Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sphinx Doc-comments support #804

Open
wants to merge 61 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 50 commits
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
86ba1e7
Refactor the ASTBuilder to get rif of the currentAttr attribute.
tristanlatr May 20, 2022
31b47b1
Continue a bit of refactor
tristanlatr May 20, 2022
f34040d
Update pydoctor/astbuilder.py
tristanlatr May 26, 2022
3b00c3e
Merge branch 'master' into experimental-refactor-astbuilder
tristanlatr May 31, 2022
0d60f57
Trigger a warning when several docstrings are detected
tristanlatr Jun 20, 2024
468850f
Fix pyflakes
tristanlatr Jun 20, 2024
0330265
Forgot the test file
tristanlatr Jun 20, 2024
a7d3aa3
Add some soce from sphinx to support doc comments.
tristanlatr Jun 20, 2024
537fb05
Add comment
tristanlatr Jun 25, 2024
f93e09a
Hook the sphinx code into the astbuiler.
tristanlatr Jun 26, 2024
d3f343a
Do not require the comnent to be indeted, idl why it's like this in s…
tristanlatr Jun 26, 2024
81b1a4d
Merge commit '537fb051c60de2b83b9d35e9100580b178af2f85' into 800-doc-…
tristanlatr Jun 27, 2024
c00e68c
Fix test
tristanlatr Jun 27, 2024
8252d36
Add proper sphinx license
tristanlatr Jun 27, 2024
5ef6dc4
Add readme entry
tristanlatr Jun 27, 2024
c4a46a1
Decode source files before calling splitlines()
tristanlatr Jun 28, 2024
0177b9e
Simpler approach
tristanlatr Jun 28, 2024
a5620f3
Add a test for a not-utf8 encoded file
tristanlatr Jun 28, 2024
5ebcfc8
Fix test
tristanlatr Jun 28, 2024
6b7e070
Merge branch 'master' into 800-doc-comments-support
tristanlatr Jul 4, 2024
9a0862b
Merge branch '800-doc-comments-support' of github.com:twisted/pydocto…
tristanlatr Jul 8, 2024
fab08ee
Fix the aliasing/doc-comment interactio issue
tristanlatr Aug 20, 2024
32181af
Auto-detect source code encoding
tristanlatr Aug 20, 2024
bf165a5
Fix test
tristanlatr Aug 20, 2024
45ee089
Fix test
tristanlatr Aug 20, 2024
2d335b8
Merge branch 'master' into 800-doc-comments-support
tristanlatr Aug 20, 2024
e027a73
Merge branch '800-doc-comments-support' of github.com:twisted/pydocto…
tristanlatr Aug 20, 2024
d37df78
Add clear documentation regarding the doc-comments.
tristanlatr Sep 13, 2024
43f12bb
Fix a couple of mypy errors...
tristanlatr Sep 13, 2024
8e4390e
Merge branch 'master' into experimental-refactor-astbuilder
tristanlatr Sep 13, 2024
c288a96
cleanup
tristanlatr Sep 13, 2024
f366f07
Merge branch 'master' into experimental-refactor-astbuilder
tristanlatr Sep 13, 2024
c44b3c8
Use a control flow exception in order to control whether to look for …
tristanlatr Sep 13, 2024
9081331
Merge branch 'experimental-refactor-astbuilder' of github.com:twisted…
tristanlatr Sep 13, 2024
daf7f63
Fix unjandled control flow error
tristanlatr Sep 13, 2024
e7d7826
add few tests
tristanlatr Sep 13, 2024
674ce69
Fix typing.
tristanlatr Sep 13, 2024
a38c793
Fix docstring and add indicative exception messages
tristanlatr Sep 14, 2024
b9e7ed2
Fix the test case
tristanlatr Sep 14, 2024
54cdd9b
fix typing
tristanlatr Sep 14, 2024
8c60beb
Add few test cases in order to cover all new lines of code.
tristanlatr Sep 15, 2024
53c4e70
Try to cover all branches...
tristanlatr Sep 15, 2024
5a0baec
Merge branch 'master' into experimental-refactor-astbuilder
tristanlatr Sep 15, 2024
4613459
Remove comment
tristanlatr Sep 15, 2024
87ff39c
Fix crash
tristanlatr Sep 16, 2024
ae2d93c
Merge commit '4613459674f810c9932140958362f79a16c284d4' into 800-doc-…
tristanlatr Sep 16, 2024
415c7d9
Remove duplicate docs
tristanlatr Sep 16, 2024
28f01e7
Fix typing
tristanlatr Sep 16, 2024
ec682e5
Add missing future import
tristanlatr Sep 16, 2024
ba2a314
Merge commit '5be689891dd89ddae7da4f0a3d291aa2840be64d' into 800-doc-…
tristanlatr Sep 22, 2024
1f7a3ec
We’re not kissing support for other encodings.
tristanlatr Sep 24, 2024
39d6d33
Merge branch 'master' into 800-doc-comments-support
tristanlatr Sep 26, 2024
9918d19
Merge branch 'master' into 800-doc-comments-support
tristanlatr Oct 15, 2024
ede0135
Merge branch 'master' into 800-doc-comments-support
tristanlatr Oct 21, 2024
ad12b3e
Merge branch 'master' into 800-doc-comments-support
tristanlatr Nov 10, 2024
4493bf1
Merge branch 'master' into 800-doc-comments-support
tristanlatr Nov 18, 2024
0e4902e
Merge branch 'master' into 800-doc-comments-support
tristanlatr Nov 26, 2024
7d3c364
Merge branch 'master' into 800-doc-comments-support
tristanlatr Jan 13, 2025
6f5bcd0
Remove unused import
tristanlatr Jan 14, 2025
29c09fe
Merge branch 'master' into 800-doc-comments-support
tristanlatr Jan 14, 2025
6f12061
Small typing arrangments
tristanlatr Jan 14, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,67 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


Support for token processing and doc-comments has been adapted from the Sphinx project -
as well as many other docstring parsing related helpers and features.
Sphinx is licensed as follows:


Copyright (c) 2007-2024 by the Sphinx team (see AUTHORS file).
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


The implementation of numpydoc docstring preprocessor
was derived from Sphinx's which itselft is partially derived
from code under the following license:

-------------------------------------------------------------------------------

Copyright (C) 2008 Stefan van der Walt <[email protected]>, Pauli Virtanen <[email protected]>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ in development
^^^^^^^^^^^^^^

* Drop Python 3.7 and support Python 3.13.
* Add support for doc-comments as found in Sphinx. Use the special comment formatting ``#:`` to start the comment instead of just ``#``.
Comments need to be either on a line of their own before the definition, or immediately after the assignment on the same line.
tristanlatr marked this conversation as resolved.
Show resolved Hide resolved
* Trigger a warning when several docstrings are detected for the same object.
* Improve typing of docutils related code.
* Run unit tests on all supported combinations of Python versions and platforms, including PyPy for Windows. Previously, tests where ran on all supported Python version for Linux, but not for MacOS and Windows.
Expand Down
22 changes: 22 additions & 0 deletions docs/source/codedoc.rst
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,28 @@ Assignments to ``__doc__`` inside functions are ignored by pydoctor. This can be

Augmented assignments like ``+=`` are currently ignored as well, but that is an implementation limitation rather than a design decision, so this might change in the future.

Doc-comments
------------

Documentation can also be put into a comment with special formatting, using a ``#:`` to start the comment instead of just ``#``.
Comments need to be either on their own before the definition, OR immediately after the assignment on the same line.
The latter form is restricted to one line only.::

var = True #: Doc comment for module attribute.

class Foo:

#: Doc comment for class attribute Foo.bar.
#: It can have multiple lines.
#: @type: int
bar = 1

flox = 1.5 #: Doc comment for Foo.flox. One line only.

def __init__(self):
#: Doc comment for instance attribute qux.
self.qux = 3

Constants
---------

Expand Down
55 changes: 43 additions & 12 deletions pydoctor/astbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import ast
import tokenize
import sys

from functools import partial
Expand All @@ -17,14 +18,17 @@
from pydoctor.epydoc.markup._pyval_repr import colorize_inline_pyval
from pydoctor.astutils import (is_none_literal, is_typing_annotation, is_using_annotations, is_using_typing_final, node2dottedname, node2fullname,
is__name__equals__main__, unstring_annotation, upgrade_annotation, iterassign, extract_docstring_linenum, infer_type, get_parents,
get_docstring_node, get_assign_docstring_node, unparse, NodeVisitor, Parentage, Str)
get_docstring_node, get_assign_docstring_node, extract_doc_comment_before, extract_doc_comment_after, unparse, NodeVisitor, Parentage, Str)

def parseFile(path: Path) -> tuple[ast.Module, Sequence[str]]:
"""
Parse the contents of a Python source file.

def parseFile(path: Path) -> ast.Module:
"""Parse the contents of a Python source file."""
with open(path, 'rb') as f:
src = f.read() + b'\n'
return _parse(src, filename=str(path))
@returns: Tuple: ast module, sequence of source code lines.
"""
with tokenize.open(path) as f:
src = f.read() + '\n'
return _parse(src, filename=str(path)), src.splitlines(keepends=True)

if sys.version_info >= (3,8):
_parse = partial(ast.parse, type_comments=True)
Expand Down Expand Up @@ -747,6 +751,25 @@ def _handleAssignment(self,
else:
raise IgnoreAssignment()

def _handleDocComment(self, node: ast.Assign | ast.AnnAssign, target: ast.expr) -> None:
# Process the doc-comments, this is very similiar to the inline docstrings.
try:
parent, name = self._contextualizeTarget(target)
except ValueError:
return

# fetch the target of the doc-comment
if (attr:=parent.contents.get(name)) is None:
return

lines = self.builder.lines_collection[self.module]
if lines:
for doc_comment in [extract_doc_comment_before(node, lines),
extract_doc_comment_after(node, lines)]:
if doc_comment:
attr._setDocstringValue(doc_comment[1], doc_comment[0])


def visit_Assign(self, node: ast.Assign) -> None:
lineno = node.lineno
expr = node.value
Expand Down Expand Up @@ -774,9 +797,11 @@ def visit_Assign(self, node: ast.Assign) -> None:
continue
else:
if not isTupleAssignment:
self._handleDocComment(node, target)
self._handleInlineDocstrings(node, target)
else:
for elem in cast(ast.Tuple, target).elts: # mypy is not as smart as pyright yet.
self._handleDocComment(node, elem)
self._handleInlineDocstrings(node, elem)

def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
Expand All @@ -787,6 +812,7 @@ def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
except IgnoreAssignment:
return
else:
self._handleDocComment(node, node.target)
self._handleInlineDocstrings(node, node.target)

def _getClassFromMethodContext(self) -> Optional[model.Class]:
Expand Down Expand Up @@ -1133,11 +1159,12 @@ class ASTBuilder:
def __init__(self, system: model.System):
self.system = system

self.current = cast(model.Documentable, None) # current visited object.
self.currentMod: Optional[model.Module] = None # current module, set when visiting ast.Module.
self.current = cast(model.Documentable, None) #: current visited object
self.currentMod: Optional[model.Module] = None #: module, set when visiting ast.Module

self._stack: List[model.Documentable] = []
self.ast_cache: Dict[Path, Optional[ast.Module]] = {}
self.ast_cache: Dict[Path, Optional[ast.Module]] = {} #: avoids calling parse() twice for the same path
self.lines_collection: dict[model.Module, Sequence[str] | None] = {} #: mapping from modules to source code lines

def _push(self,
cls: Type[DocumentableT],
Expand Down Expand Up @@ -1248,20 +1275,24 @@ def parseFile(self, path: Path, ctx: model.Module) -> Optional[ast.Module]:
return self.ast_cache[path]
except KeyError:
mod: Optional[ast.Module] = None
lines: Sequence[str] | None = None
try:
mod = parseFile(path)
mod, lines = parseFile(path)
except (SyntaxError, ValueError) as e:
ctx.report(f"cannot parse file, {e}")

self.ast_cache[path] = mod
self.lines_collection[ctx] = lines
return mod

def parseString(self, py_string:str, ctx: model.Module) -> Optional[ast.Module]:
mod = None
mod: Optional[ast.Module] = None
lines: Sequence[str] | None = None
try:
mod = _parse(py_string)
mod, lines = _parse(py_string), py_string.splitlines(keepends=True)
except (SyntaxError, ValueError):
ctx.report("cannot parse string")
self.lines_collection[ctx] = lines
return mod

model.System.defaultBuilder = ASTBuilder
Expand Down
Loading
Loading