Python source code parser to pick up comments after assignments. This parser takes code which starts with an assignment statement, and returns the comment for the variable if one exists.
| 187 | |
| 188 | |
| 189 | class AfterCommentParser(TokenProcessor): |
| 190 | """Python source code parser to pick up comments after assignments. |
| 191 | |
| 192 | This parser takes code which starts with an assignment statement, |
| 193 | and returns the comment for the variable if one exists. |
| 194 | """ |
| 195 | |
| 196 | def __init__(self, lines: list[str]) -> None: |
| 197 | super().__init__(lines) |
| 198 | self.comment: str | None = None |
| 199 | |
| 200 | def fetch_rvalue(self) -> list[Token]: |
| 201 | """Fetch right-hand value of assignment.""" |
| 202 | tokens = [] |
| 203 | while current := self.fetch_token(): |
| 204 | tokens.append(current) |
| 205 | if current == [OP, '(']: |
| 206 | tokens += self.fetch_until([OP, ')']) |
| 207 | elif current == [OP, '{']: |
| 208 | tokens += self.fetch_until([OP, '}']) |
| 209 | elif current == [OP, '[']: |
| 210 | tokens += self.fetch_until([OP, ']']) |
| 211 | elif current == INDENT: |
| 212 | tokens += self.fetch_until(DEDENT) |
| 213 | elif current == [OP, ';']: # NoQA: SIM114 |
| 214 | break |
| 215 | elif current and current.kind not in {OP, NAME, NUMBER, STRING}: |
| 216 | break |
| 217 | |
| 218 | return tokens |
| 219 | |
| 220 | def parse(self) -> None: |
| 221 | """Parse the code and obtain comment after assignment.""" |
| 222 | # skip lvalue (or whole of AnnAssign) |
| 223 | while (tok := self.fetch_token()) and not tok.match( |
| 224 | [OP, '='], NEWLINE, COMMENT |
| 225 | ): |
| 226 | assert tok |
| 227 | assert tok is not None |
| 228 | |
| 229 | # skip rvalue (if exists) |
| 230 | if tok == [OP, '=']: |
| 231 | self.fetch_rvalue() |
| 232 | tok = self.current |
| 233 | assert tok is not None |
| 234 | |
| 235 | if tok == COMMENT: |
| 236 | self.comment = tok.value |
| 237 | |
| 238 | |
| 239 | class VariableCommentPicker(ast.NodeVisitor): |
no outgoing calls
no test coverage detected
searching dependent graphs…