MCPcopy
hub / github.com/psf/black / generate_comments

Function generate_comments

src/black/comments.py:60–86  ·  view source on GitHub ↗

Clean the prefix of the `leaf` and generate comments from it, if any. Comments in lib2to3 are shoved into the whitespace prefix. This happens in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation move because it does away with modifying the grammar to include

(leaf: LN, mode: Mode)

Source from the content-addressed store, hash-verified

58
59
60def generate_comments(leaf: LN, mode: Mode) -> Iterator[Leaf]:
61 """Clean the prefix of the `leaf` and generate comments from it, if any.
62
63 Comments in lib2to3 are shoved into the whitespace prefix. This happens
64 in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation
65 move because it does away with modifying the grammar to include all the
66 possible places in which comments can be placed.
67
68 The sad consequence for us though is that comments don't "belong" anywhere.
69 This is why this function generates simple parentless Leaf objects for
70 comments. We simply don't know what the correct parent should be.
71
72 No matter though, we can live without this. We really only need to
73 differentiate between inline and standalone comments. The latter don't
74 share the line with any code.
75
76 Inline comments are emitted as regular token.COMMENT leaves. Standalone
77 are emitted with a fake STANDALONE_COMMENT token identifier.
78 """
79 total_consumed = 0
80 for pc in list_comments(
81 leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER, mode=mode
82 ):
83 total_consumed = pc.consumed
84 prefix = make_simple_prefix(pc.newlines, pc.form_feed)
85 yield Leaf(pc.type, pc.value, prefix=prefix)
86 normalize_trailing_prefix(leaf, total_consumed)
87
88
89@lru_cache(maxsize=4096)

Callers 2

visit_defaultMethod · 0.90

Calls 4

make_simple_prefixFunction · 0.90
LeafClass · 0.90
list_commentsFunction · 0.85

Tested by

no test coverage detected