1# Copyright 2016 Grist Labs, Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import ast
16import numbers
17import sys
18import token
19from ast import Module
20from typing import Callable, List, Union, cast, Optional, Tuple, TYPE_CHECKING
21
22from . import util
23from .asttokens import ASTTokens
24from .astroid_compat import astroid_node_classes as nc, BaseContainer as AstroidBaseContainer
25from .util import AstNode
26
27
28# Mapping of matching braces. To find a token here, look up token[:2].
29_matching_pairs_left = {
30 (token.OP, '('): (token.OP, ')'),
31 (token.OP, '['): (token.OP, ']'),
32 (token.OP, '{'): (token.OP, '}'),
33}
34
35_matching_pairs_right = {
36 (token.OP, ')'): (token.OP, '('),
37 (token.OP, ']'): (token.OP, '['),
38 (token.OP, '}'): (token.OP, '{'),
39}
40
41
42class MarkTokens:
43 """
44 Helper that visits all nodes in the AST tree and assigns .first_token and .last_token attributes
45 to each of them. This is the heart of the token-marking logic.
46 """
47 def __init__(self, code: ASTTokens) -> None:
48 self._code = code
49 self._methods = util.NodeMethods()
50 self._iter_children: Optional[Callable] = None
51
52 def visit_tree(self, node: Module) -> None:
53 self._iter_children = util.iter_children_func(node)
54 util.visit_tree(node, self._visit_before_children, self._visit_after_children)
55
56 def _visit_before_children(
57 self, node: AstNode, parent_token: Optional[util.Token]
58 ) -> Tuple[Optional[util.Token], Optional[util.Token]]:
59 col = getattr(node, 'col_offset', None)
60 token = self._code.get_token_from_utf8(node.lineno, col) if col is not None else None
61
62 if not token and util.is_module(node):
63 # We'll assume that a Module node starts at the start of the source code.
64 token = self._code.get_token(1, 0)
65
66 # Use our own token, or our parent's if we don't have one, to pass to child calls as
67 # parent_token argument. The second value becomes the token argument of _visit_after_children.
68 return (token or parent_token, token)
69
70 def _visit_after_children(
71 self, node: AstNode, parent_token: Optional[util.Token], token: Optional[util.Token]
72 ) -> None:
73 # This processes the node generically first, after all children have been processed.
74
75 # Get the first and last tokens that belong to children. Note how this doesn't assume that we
76 # iterate through children in order that corresponds to occurrence in source code. This
77 # assumption can fail (e.g. with return annotations).
78 first = token
79 last = None
80 for child in cast(Callable, self._iter_children)(node):
81 # astroid slices have especially wrong positions, we don't want them to corrupt their parents.
82 if util.is_empty_astroid_slice(child):
83 continue
84 if not first or child.first_token.index < first.index:
85 first = child.first_token
86 if not last or child.last_token.index > last.index:
87 last = child.last_token
88
89 # If we don't have a first token from _visit_before_children, and there were no children, then
90 # use the parent's token as the first token.
91 first = first or parent_token
92
93 # If no children, set last token to the first one.
94 last = last or first
95
96 # Statements continue to before NEWLINE. This helps cover a few different cases at once.
97 if util.is_stmt(node):
98 last = self._find_last_in_stmt(cast(util.Token, last))
99
100 # Capture any unmatched brackets.
101 first, last = self._expand_to_matching_pairs(cast(util.Token, first), cast(util.Token, last), node)
102
103 # Give a chance to node-specific methods to adjust.
104 nfirst, nlast = self._methods.get(self, node.__class__)(node, first, last)
105
106 if (nfirst, nlast) != (first, last):
107 # If anything changed, expand again to capture any unmatched brackets.
108 nfirst, nlast = self._expand_to_matching_pairs(nfirst, nlast, node)
109
110 node.first_token = nfirst
111 node.last_token = nlast
112
113 def _find_last_in_stmt(self, start_token: util.Token) -> util.Token:
114 t = start_token
115 while (not util.match_token(t, token.NEWLINE) and
116 not util.match_token(t, token.OP, ';') and
117 not token.ISEOF(t.type)):
118 t = self._code.next_token(t, include_extra=True)
119 return self._code.prev_token(t)
120
121 def _expand_to_matching_pairs(
122 self, first_token: util.Token, last_token: util.Token, node: AstNode
123 ) -> Tuple[util.Token, util.Token]:
124 """
125 Scan tokens in [first_token, last_token] range that are between node's children, and for any
126 unmatched brackets, adjust first/last tokens to include the closing pair.
127 """
128 # We look for opening parens/braces among non-child tokens (i.e. tokens between our actual
129 # child nodes). If we find any closing ones, we match them to the opens.
130 to_match_right: List[Tuple[int, str]] = []
131 to_match_left = []
132 for tok in self._code.token_range(first_token, last_token):
133 tok_info = tok[:2]
134 if to_match_right and tok_info == to_match_right[-1]:
135 to_match_right.pop()
136 elif tok_info in _matching_pairs_left:
137 to_match_right.append(_matching_pairs_left[tok_info])
138 elif tok_info in _matching_pairs_right:
139 to_match_left.append(_matching_pairs_right[tok_info])
140
141 # Once done, extend `last_token` to match any unclosed parens/braces.
142 for match in reversed(to_match_right):
143 last = self._code.next_token(last_token)
144 # Allow for trailing commas or colons (allowed in subscripts) before the closing delimiter
145 while any(util.match_token(last, token.OP, x) for x in (',', ':')):
146 last = self._code.next_token(last)
147 # Now check for the actual closing delimiter.
148 if util.match_token(last, *match):
149 last_token = last
150
151 # And extend `first_token` to match any unclosed opening parens/braces.
152 for match in to_match_left:
153 first = self._code.prev_token(first_token)
154 if util.match_token(first, *match):
155 first_token = first
156
157 return (first_token, last_token)
158
159 #----------------------------------------------------------------------
160 # Node visitors. Each takes a preliminary first and last tokens, and returns the adjusted pair
161 # that will actually be assigned.
162
163 def visit_default(
164 self, node: AstNode, first_token: util.Token, last_token: util.Token
165 ) -> Tuple[util.Token, util.Token]:
166 # pylint: disable=no-self-use
167 # By default, we don't need to adjust the token we computed earlier.
168 return (first_token, last_token)
169
170 def handle_comp(
171 self, open_brace: str, node: AstNode, first_token: util.Token, last_token: util.Token
172 ) -> Tuple[util.Token, util.Token]:
173 # For list/set/dict comprehensions, we only get the token of the first child, so adjust it to
174 # include the opening brace (the closing brace will be matched automatically).
175 before = self._code.prev_token(first_token)
176 util.expect_token(before, token.OP, open_brace)
177 return (before, last_token)
178
179 def visit_comprehension(
180 self,
181 node: AstNode,
182 first_token: util.Token,
183 last_token: util.Token,
184 ) -> Tuple[util.Token, util.Token]:
185 # The 'comprehension' node starts with 'for' but we only get first child; we search backwards
186 # to find the 'for' keyword.
187 first = self._code.find_token(first_token, token.NAME, 'for', reverse=True)
188 return (first, last_token)
189
190 def visit_if(
191 self, node: util.Token, first_token: util.Token, last_token: util.Token
192 ) -> Tuple[util.Token, util.Token]:
193 while first_token.string not in ('if', 'elif'):
194 first_token = self._code.prev_token(first_token)
195 return first_token, last_token
196
197 def visit_import(
198 self, node: AstNode, first_token: util.Token, last_token: util.Token
199 ) -> Tuple[util.Token, util.Token]:
200 # Astroid stores import aliases as tuples, not child nodes. For stdlib AST,
201 # mark the whole alias, including dotted names and an optional "as" name.
202 # Walking in source order also works before Python 3.10, when aliases did
203 # not have their own positions, and for repeated or normalized names.
204 if isinstance(node, (ast.Import, ast.ImportFrom)):
205 current = self._code.next_token(self._code.find_token(first_token, token.NAME, 'import'))
206 aliases = iter(node.names)
207 alias_node = None
208 for tok in self._code.token_range(current, last_token):
209 if util.match_token(tok, token.OP, ','):
210 alias_node = None
211 elif not (util.match_token(tok, token.OP, '(') or util.match_token(tok, token.OP, ')')):
212 if alias_node is None:
213 alias_node = cast(AstNode, next(aliases))
214 alias_node.first_token = tok
215 alias_node.last_token = tok
216 return first_token, last_token
217
218 visit_importfrom = visit_import
219
220 def handle_attr(
221 self, node: AstNode, first_token: util.Token, last_token: util.Token
222 ) -> Tuple[util.Token, util.Token]:
223 # Attribute node has ".attr" (2 tokens) after the last child.
224 dot = self._code.find_token(last_token, token.OP, '.')
225 name = self._code.next_token(dot)
226 util.expect_token(name, token.NAME)
227 return (first_token, name)
228
229 visit_attribute = handle_attr
230 visit_assignattr = handle_attr
231 visit_delattr = handle_attr
232
233 def handle_def(
234 self, node: AstNode, first_token: util.Token, last_token: util.Token
235 ) -> Tuple[util.Token, util.Token]:
236 # With astroid, nodes that start with a doc-string can have an empty body, in which case we
237 # need to adjust the last token to include the doc string.
238 if not node.body and (getattr(node, 'doc_node', None) or getattr(node, 'doc', None)): # type: ignore[union-attr]
239 last_token = self._code.find_token(last_token, token.STRING)
240
241 # Include @ from decorator
242 if first_token.index > 0:
243 prev = self._code.prev_token(first_token)
244 if util.match_token(prev, token.OP, '@'):
245 first_token = prev
246 return (first_token, last_token)
247
248 visit_classdef = handle_def
249 visit_functiondef = handle_def
250
251 def handle_following_brackets(
252 self, node: AstNode, last_token: util.Token, opening_bracket: str
253 ) -> util.Token:
254 # This is for calls and subscripts, which have a pair of brackets
255 # at the end which may contain no nodes, e.g. foo() or bar[:].
256 # We look for the opening bracket and then let the matching pair be found automatically
257 # Remember that last_token is at the end of all children,
258 # so we are not worried about encountering a bracket that belongs to a child.
259 first_child = next(cast(Callable, self._iter_children)(node))
260 call_start = self._code.find_token(first_child.last_token, token.OP, opening_bracket)
261 if call_start.index > last_token.index:
262 last_token = call_start
263 return last_token
264
265 def visit_call(
266 self, node: util.Token, first_token: util.Token, last_token: util.Token
267 ) -> Tuple[util.Token, util.Token]:
268 last_token = self.handle_following_brackets(node, last_token, '(')
269
270 # Handling a python bug with decorators with empty parens, e.g.
271 # @deco()
272 # def ...
273 if util.match_token(first_token, token.OP, '@'):
274 first_token = self._code.next_token(first_token)
275 return (first_token, last_token)
276
277 def visit_matchclass(
278 self, node: util.Token, first_token: util.Token, last_token: util.Token
279 ) -> Tuple[util.Token, util.Token]:
280 last_token = self.handle_following_brackets(node, last_token, '(')
281 return (first_token, last_token)
282
283 def visit_subscript(
284 self,
285 node: AstNode,
286 first_token: util.Token,
287 last_token: util.Token,
288 ) -> Tuple[util.Token, util.Token]:
289 last_token = self.handle_following_brackets(node, last_token, '[')
290 return (first_token, last_token)
291
292 def visit_slice(
293 self, node: AstNode, first_token: util.Token, last_token: util.Token
294 ) -> Tuple[util.Token, util.Token]:
295 # consume `:` tokens to the left and right. In Python 3.9, Slice nodes are
296 # given a col_offset, (and end_col_offset), so this will always start inside
297 # the slice, even if it is the empty slice. However, in 3.8 and below, this
298 # will only expand to the full slice if the slice contains a node with a
299 # col_offset. So x[:] will only get the correct tokens in 3.9, but x[1:] and
300 # x[:1] will even on earlier versions of Python.
301 while True:
302 prev = self._code.prev_token(first_token)
303 if prev.string != ':':
304 break
305 first_token = prev
306 while True:
307 next_ = self._code.next_token(last_token)
308 if next_.string != ':':
309 break
310 last_token = next_
311 return (first_token, last_token)
312
313 def handle_bare_tuple(
314 self, node: AstNode, first_token: util.Token, last_token: util.Token
315 ) -> Tuple[util.Token, util.Token]:
316 # A bare tuple doesn't include parens; if there is a trailing comma, make it part of the tuple.
317 maybe_comma = self._code.next_token(last_token)
318 if util.match_token(maybe_comma, token.OP, ','):
319 last_token = maybe_comma
320 return (first_token, last_token)
321
322 # In Python3.8 parsed tuples include parentheses when present.
323 def handle_tuple_nonempty(
324 self, node: AstNode, first_token: util.Token, last_token: util.Token
325 ) -> Tuple[util.Token, util.Token]:
326 assert isinstance(node, ast.Tuple) or isinstance(node, AstroidBaseContainer)
327 # It's a bare tuple if the first token belongs to the first child. The first child may
328 # include extraneous parentheses (which don't create new nodes), so account for those too.
329 child = node.elts[0]
330 if TYPE_CHECKING:
331 child = cast(AstNode, child)
332 child_first, child_last = self._gobble_parens(child.first_token, child.last_token, True)
333 if first_token == child_first:
334 return self.handle_bare_tuple(node, first_token, last_token)
335 return (first_token, last_token)
336
337 def visit_tuple(
338 self, node: AstNode, first_token: util.Token, last_token: util.Token
339 ) -> Tuple[util.Token, util.Token]:
340 assert isinstance(node, ast.Tuple) or isinstance(node, AstroidBaseContainer)
341 if not node.elts:
342 # An empty tuple is just "()", and we need no further info.
343 return (first_token, last_token)
344 return self.handle_tuple_nonempty(node, first_token, last_token)
345
346 def _gobble_parens(
347 self, first_token: util.Token, last_token: util.Token, include_all: bool = False
348 ) -> Tuple[util.Token, util.Token]:
349 # Expands a range of tokens to include one or all pairs of surrounding parentheses, and
350 # returns (first, last) tokens that include these parens.
351 while first_token.index > 0:
352 prev = self._code.prev_token(first_token)
353 next = self._code.next_token(last_token)
354 if util.match_token(prev, token.OP, '(') and util.match_token(next, token.OP, ')'):
355 first_token, last_token = prev, next
356 if include_all:
357 continue
358 break
359 return (first_token, last_token)
360
361 def visit_str(
362 self, node: AstNode, first_token: util.Token, last_token: util.Token
363 ) -> Tuple[util.Token, util.Token]:
364 return self.handle_str(first_token, last_token)
365
366 def visit_joinedstr(
367 self,
368 node: AstNode,
369 first_token: util.Token,
370 last_token: util.Token,
371 ) -> Tuple[util.Token, util.Token]:
372 if sys.version_info < (3, 12):
373 # Older versions don't tokenize the contents of f-strings
374 return self.handle_str(first_token, last_token)
375
376 last = first_token
377 while True:
378 if util.match_token(last, getattr(token, "FSTRING_START")):
379 # Python 3.12+ has tokens for the start (e.g. `f"`) and end (`"`)
380 # of the f-string. We can't just look for the next FSTRING_END
381 # because f-strings can be nested, e.g. f"{f'{x}'}", so we need
382 # to treat this like matching balanced parentheses.
383 count = 1
384 while count > 0:
385 last = self._code.next_token(last)
386 # mypy complains about token.FSTRING_START and token.FSTRING_END.
387 if util.match_token(last, getattr(token, "FSTRING_START")):
388 count += 1
389 elif util.match_token(last, getattr(token, "FSTRING_END")):
390 count -= 1
391 last_token = last
392 last = self._code.next_token(last_token)
393 elif util.match_token(last, token.STRING):
394 # Similar to handle_str, we also need to handle adjacent strings.
395 last_token = last
396 last = self._code.next_token(last_token)
397 else:
398 break
399 return (first_token, last_token)
400
401 def visit_bytes(
402 self, node: AstNode, first_token: util.Token, last_token: util.Token
403 ) -> Tuple[util.Token, util.Token]:
404 return self.handle_str(first_token, last_token)
405
406 def handle_str(
407 self, first_token: util.Token, last_token: util.Token
408 ) -> Tuple[util.Token, util.Token]:
409 # Multiple adjacent STRING tokens form a single string.
410 last = self._code.next_token(last_token)
411 while util.match_token(last, token.STRING):
412 last_token = last
413 last = self._code.next_token(last_token)
414 return (first_token, last_token)
415
416 def handle_num(
417 self,
418 node: AstNode,
419 value: Union[complex, int, numbers.Number],
420 first_token: util.Token,
421 last_token: util.Token,
422 ) -> Tuple[util.Token, util.Token]:
423 # A constant like '-1' gets turned into two tokens; this will skip the '-'.
424 while util.match_token(last_token, token.OP):
425 last_token = self._code.next_token(last_token)
426
427 if isinstance(value, complex):
428 # A complex number like -2j cannot be compared directly to 0
429 # A complex number like 1-2j is expressed as a binary operation
430 # so we don't need to worry about it
431 value = value.imag
432
433 # This makes sure that the - is included
434 if value < 0 and first_token.type == token.NUMBER: # type: ignore[operator]
435 first_token = self._code.prev_token(first_token)
436 return (first_token, last_token)
437
438 def visit_num(
439 self, node: AstNode, first_token: util.Token, last_token: util.Token
440 ) -> Tuple[util.Token, util.Token]:
441 n = node.n # type: ignore[union-attr] # ast.Num has been removed in python 3.14
442 assert isinstance(n, (complex, int, numbers.Number))
443 return self.handle_num(node, n, first_token, last_token)
444
445 def visit_const(
446 self, node: AstNode, first_token: util.Token, last_token: util.Token
447 ) -> Tuple[util.Token, util.Token]:
448 assert isinstance(node, ast.Constant) or isinstance(node, nc.Const)
449 if isinstance(node.value, numbers.Number):
450 return self.handle_num(node, node.value, first_token, last_token)
451 elif isinstance(node.value, (str, bytes)):
452 return self.visit_str(node, first_token, last_token)
453 return (first_token, last_token)
454
455 visit_constant = visit_const
456
457 def visit_keyword(
458 self, node: AstNode, first_token: util.Token, last_token: util.Token
459 ) -> Tuple[util.Token, util.Token]:
460 # Until python 3.9 (https://bugs.python.org/issue40141),
461 # ast.keyword nodes didn't have line info. Astroid has lineno None.
462 assert isinstance(node, ast.keyword) or isinstance(node, nc.Keyword)
463 if node.arg is not None and getattr(node, 'lineno', None) is None:
464 equals = self._code.find_token(first_token, token.OP, '=', reverse=True)
465 name = self._code.prev_token(equals)
466 util.expect_token(name, token.NAME, node.arg)
467 first_token = name
468 return (first_token, last_token)
469
470 def visit_starred(
471 self, node: AstNode, first_token: util.Token, last_token: util.Token
472 ) -> Tuple[util.Token, util.Token]:
473 # Astroid has 'Starred' nodes (for "foo(*bar)" type args), but they need to be adjusted.
474 if not util.match_token(first_token, token.OP, '*'):
475 star = self._code.prev_token(first_token)
476 if util.match_token(star, token.OP, '*'):
477 first_token = star
478 return (first_token, last_token)
479
480 def visit_assignname(
481 self, node: AstNode, first_token: util.Token, last_token: util.Token
482 ) -> Tuple[util.Token, util.Token]:
483 # Astroid may turn 'except' clause into AssignName, but we need to adjust it.
484 if util.match_token(first_token, token.NAME, 'except'):
485 colon = self._code.find_token(last_token, token.OP, ':')
486 first_token = last_token = self._code.prev_token(colon)
487 return (first_token, last_token)
488
489 # Async nodes should typically start with the word 'async'
490 # but Python < 3.7 doesn't put the col_offset there
491 # AsyncFunctionDef is slightly different because it might have
492 # decorators before that, which visit_functiondef handles
493 def handle_async(
494 self, node: AstNode, first_token: util.Token, last_token: util.Token
495 ) -> Tuple[util.Token, util.Token]:
496 if not first_token.string == 'async':
497 first_token = self._code.prev_token(first_token)
498 return (first_token, last_token)
499
500 visit_asyncfor = handle_async
501 visit_asyncwith = handle_async
502
503 def visit_asyncfunctiondef(
504 self,
505 node: AstNode,
506 first_token: util.Token,
507 last_token: util.Token,
508 ) -> Tuple[util.Token, util.Token]:
509 if util.match_token(first_token, token.NAME, 'def'):
510 # Include the 'async' token
511 first_token = self._code.prev_token(first_token)
512 return self.visit_functiondef(node, first_token, last_token)