Skip to content

Commit 27b431d

Browse files
authored
Fix rendering of google-style docstring in sphinx docs (#247)
Context of this PR: llvm/llvm-project#167063 (comment) The current MLIR Python Sphinx documentation cannot handle functions that use Google-style docstrings. In this PR, we introduce support for this feature, allowing Google-style docstrings to be properly converted into reStructuredText. Before: <img width="1490" height="1147" alt="image" src="https://github.com/user-attachments/assets/79e99552-c827-41f8-b917-02a056d76edd" /> After: <img width="1514" height="1492" alt="image" src="https://github.com/user-attachments/assets/1f22ae25-fbdc-4ee1-8c32-dac58585e32e" /> Preview it at: https://mlir-python-googledocstring.surge.sh/autoapi/mlir/_mlir_libs/_mlir/ir/index.html cc @makslevental @jpienaar
1 parent 8e64ddb commit 27b431d

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

sphinx-mlir-python/conf.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,26 @@
3838

3939
import autoapi._parser as _autoapi_parser
4040
import commonmark
41+
from sphinx.ext.napoleon.docstring import GoogleDocstring
4142

43+
# Check if the docstring is google-style.
44+
# NOTE: It is pretty minimal but enough to cover current cases in MLIR Python.
45+
def is_google_docstring(doc):
46+
return any(x in doc for x in ["Args:\n", "Returns:\n", "Raises:\n"])
4247

43-
# hook the _prepare_docstring function in sphinx-autoapi,
48+
# Hook the _prepare_docstring function in sphinx-autoapi,
4449
# so that we can convert markdown to rst.
4550
_prepare_docstring = _autoapi_parser._prepare_docstring
4651
def prepare_docstring(doc):
47-
md = _prepare_docstring(doc)
48-
ast = commonmark.Parser().parse(md)
49-
rst = commonmark.ReStructuredTextRenderer().render(ast)
50-
return rst
52+
docstring = _prepare_docstring(doc)
53+
if is_google_docstring(docstring):
54+
# convert google-style docstring to rst
55+
docstring = str(GoogleDocstring(docstring))
56+
else:
57+
# convert markdown to rst
58+
ast = commonmark.Parser().parse(docstring)
59+
docstring = commonmark.ReStructuredTextRenderer().render(ast)
60+
return docstring
5161
_autoapi_parser._prepare_docstring = prepare_docstring
5262

5363
html_static_path = ['_static']

0 commit comments

Comments
 (0)