Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/asttokens/util.py: 66%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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.
15import ast
16import collections
17import io
18import re
19import sys
20import token
21import tokenize
22from abc import ABCMeta
23from ast import Module, expr, AST
24from functools import lru_cache
25from typing import (
26 Callable,
27 Dict,
28 Iterable,
29 Iterator,
30 List,
31 Optional,
32 Tuple,
33 Union,
34 cast,
35 Any,
36 TYPE_CHECKING,
37 Type,
38)
40if TYPE_CHECKING: # pragma: no cover
41 from .astroid_compat import NodeNG
42else:
43 NodeNG = Any
46TokenInfo = tokenize.TokenInfo
47_lone_cr_re = re.compile(r'\r(?!\n)')
50def token_repr(tok_type: int, string: Optional[str]) -> str:
51 """Returns a human-friendly representation of a token with the given type and string."""
52 # repr() prefixes unicode with 'u' on Python2 but not Python3; strip it out for consistency.
53 return f"{token.tok_name[tok_type]}:{repr(string).lstrip('u')}"
56class Token(collections.namedtuple('Token', 'type string start end line index startpos endpos')):
57 """
58 TokenInfo is an 8-tuple containing the same 5 fields as the tokens produced by the tokenize
59 module, and 3 additional ones useful for this module:
61 - [0] .type Token type (see token.py)
62 - [1] .string Token (a string)
63 - [2] .start Starting (row, column) indices of the token (a 2-tuple of ints)
64 - [3] .end Ending (row, column) indices of the token (a 2-tuple of ints)
65 - [4] .line Original line (string)
66 - [5] .index Index of the token in the list of tokens that it belongs to.
67 - [6] .startpos Starting character offset into the input text.
68 - [7] .endpos Ending character offset into the input text.
70 The .exact_type property gives the specific type for operator tokens (for example,
71 token.LPAR for '('), and otherwise returns .type, like tokenize.TokenInfo.exact_type.
72 """
73 def __str__(self) -> str:
74 return token_repr(self.type, self.string)
76 @property
77 def exact_type(self) -> int:
78 """Return the specific operator type, or the original token type otherwise."""
79 if self.type == token.OP:
80 return token.EXACT_TOKEN_TYPES.get(self.string, self.type)
81 return self.type
84# Type class used to expand out the definition of AST to include fields added by this library
85# It's not actually used for anything other than type checking though!
86class EnhancedAST(AST):
87 # Additional attributes set by mark_tokens
88 first_token: Token = None # type: ignore
89 last_token: Token = None # type: ignore
90 lineno: int = 0
91 end_lineno: int = 0
92 end_col_offset: int = 0
95AstNode = Union[EnhancedAST, NodeNG]
98def match_token(token: Token, tok_type: int, tok_str: Optional[str] = None) -> bool:
99 """Returns true if token is of the given type and, if a string is given, has that string."""
100 return token.type == tok_type and (tok_str is None or token.string == tok_str)
103def expect_token(token: Token, tok_type: int, tok_str: Optional[str] = None) -> None:
104 """
105 Verifies that the given token is of the expected type. If tok_str is given, the token string
106 is verified too. If the token doesn't match, raises an informative ValueError.
107 """
108 if not match_token(token, tok_type, tok_str):
109 raise ValueError(
110 f"Expected token {token_repr(tok_type, tok_str)}, "
111 f"got {str(token)} on line {token.start[0]} col {token.start[1] + 1}"
112 )
115def is_non_coding_token(token_type: int) -> bool:
116 """
117 These are considered non-coding tokens, as they don't affect the syntax tree.
118 """
119 return token_type in (token.NL, token.COMMENT, token.ENCODING)
122def generate_tokens(text: str) -> Iterator[TokenInfo]:
123 """
124 Generates standard library tokens for the given code.
125 """
126 # Before Python 3.12, tokenize treats an entire line containing a lone carriage return as a
127 # non-coding NL token, even though ast.parse treats the carriage return as a line boundary.
128 # Replacing lone carriage returns is length-preserving, so token offsets still map to the
129 # original source. Keep CRLF intact because changing its length would shift later offsets.
130 text = _lone_cr_re.sub('\n', text)
131 # tokenize.generate_tokens is technically an undocumented API for Python3, but allows us to use the same API as for
132 # Python2. See https://stackoverflow.com/a/4952291/328565.
133 # FIXME: Remove cast once https://github.com/python/typeshed/issues/7003 gets fixed
134 return tokenize.generate_tokens(cast(Callable[[], str], io.StringIO(text).readline))
137def iter_children_func(node: AST) -> Callable:
138 """
139 Returns a function which yields all direct children of a AST node,
140 skipping children that are singleton nodes.
141 The function depends on whether ``node`` is from ``ast`` or from the ``astroid`` module.
142 """
143 return iter_children_astroid if hasattr(node, 'get_children') else iter_children_ast
146def iter_children_astroid(node: NodeNG, include_joined_str: bool = False) -> Union[Iterator, list]:
147 if not include_joined_str and is_joined_str(node):
148 return []
150 return node.get_children()
153SINGLETONS = {c for n, c in ast.__dict__.items() if isinstance(c, type) and
154 issubclass(c, (ast.expr_context, ast.boolop, ast.operator, ast.unaryop, ast.cmpop))}
157def iter_children_ast(node: AST, include_joined_str: bool = False) -> Iterator[Union[AST, expr]]:
158 if not include_joined_str and is_joined_str(node):
159 return
161 if isinstance(node, ast.Dict):
162 # override the iteration order: instead of <all keys>, <all values>,
163 # yield keys and values in source order (key1, value1, key2, value2, ...)
164 for (key, value) in zip(node.keys, node.values):
165 if key is not None:
166 yield key
167 yield value
168 return
170 for child in ast.iter_child_nodes(node):
171 # Skip singleton children; they don't reflect particular positions in the code and break the
172 # assumptions about the tree consisting of distinct nodes. Note that collecting classes
173 # beforehand and checking them in a set is faster than using isinstance each time.
174 if child.__class__ not in SINGLETONS:
175 yield child
178stmt_class_names = {n for n, c in ast.__dict__.items()
179 if isinstance(c, type) and issubclass(c, ast.stmt)}
180expr_class_names = ({n for n, c in ast.__dict__.items()
181 if isinstance(c, type) and issubclass(c, ast.expr)} |
182 {'AssignName', 'DelName', 'Const', 'AssignAttr', 'DelAttr'})
184# These feel hacky compared to isinstance() but allow us to work with both ast and astroid nodes
185# in the same way, and without even importing astroid.
186def is_expr(node: AstNode) -> bool:
187 """Returns whether node is an expression node."""
188 return node.__class__.__name__ in expr_class_names
190def is_stmt(node: AstNode) -> bool:
191 """Returns whether node is a statement node."""
192 return node.__class__.__name__ in stmt_class_names
194def is_module(node: AstNode) -> bool:
195 """Returns whether node is a module node."""
196 return node.__class__.__name__ == 'Module'
198def is_joined_str(node: AstNode) -> bool:
199 """Returns whether node is a JoinedStr node, used to represent f-strings."""
200 # At the moment, nodes below JoinedStr have wrong line/col info, and trying to process them only
201 # leads to errors.
202 return node.__class__.__name__ == 'JoinedStr'
205def is_expr_stmt(node: AstNode) -> bool:
206 """Returns whether node is an `Expr` node, which is a statement that is an expression."""
207 return node.__class__.__name__ == 'Expr'
211CONSTANT_CLASSES: Tuple[Type, ...] = (ast.Constant,)
212try:
213 from astroid.nodes import Const
214 CONSTANT_CLASSES += (Const,)
215except ImportError:
216 # astroid is not available
217 pass
219def is_constant(node: AstNode) -> bool:
220 """Returns whether node is a Constant node."""
221 return isinstance(node, CONSTANT_CLASSES)
224def is_ellipsis(node: AstNode) -> bool:
225 """Returns whether node is an Ellipsis node."""
226 return is_constant(node) and node.value is Ellipsis # type: ignore
229def is_starred(node: AstNode) -> bool:
230 """Returns whether node is a starred expression node."""
231 return node.__class__.__name__ == 'Starred'
234def is_slice(node: AstNode) -> bool:
235 """Returns whether node represents a slice, e.g. `1:2` in `x[1:2]`"""
236 # Before 3.9, a tuple containing a slice is an ExtSlice,
237 # but this was removed in https://bugs.python.org/issue34822
238 return (
239 node.__class__.__name__ in ('Slice', 'ExtSlice')
240 or (
241 node.__class__.__name__ == 'Tuple'
242 and any(map(is_slice, cast(ast.Tuple, node).elts))
243 )
244 )
247def is_empty_astroid_slice(node: AstNode) -> bool:
248 return (
249 node.__class__.__name__ == "Slice"
250 and not isinstance(node, ast.AST)
251 and node.lower is node.upper is node.step is None
252 )
255# Sentinel value used by visit_tree().
256_PREVISIT = object()
258def visit_tree(
259 node: Module,
260 previsit: Callable[[AstNode, Optional[Token]], Tuple[Optional[Token], Optional[Token]]],
261 postvisit: Optional[Callable[[AstNode, Optional[Token], Optional[Token]], None]]
262) -> None:
263 """
264 Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion
265 via the function call stack to avoid hitting 'maximum recursion depth exceeded' error.
267 It calls ``previsit()`` and ``postvisit()`` as follows:
269 * ``previsit(node, par_value)`` - should return ``(par_value, value)``
270 ``par_value`` is as returned from ``previsit()`` of the parent.
272 * ``postvisit(node, par_value, value)`` - should return ``value``
273 ``par_value`` is as returned from ``previsit()`` of the parent, and ``value`` is as
274 returned from ``previsit()`` of this node itself. The return ``value`` is ignored except
275 the one for the root node, which is returned from the overall ``visit_tree()`` call.
277 For the initial node, ``par_value`` is None. ``postvisit`` may be None.
278 """
279 if not postvisit:
280 postvisit = lambda node, pvalue, value: None
282 iter_children = iter_children_func(node)
283 done = set()
284 ret = None
285 stack: List[Tuple[AstNode, Optional[Token], object]] = [(node, None, _PREVISIT)]
286 while stack:
287 current, par_value, value = stack.pop()
288 if value is _PREVISIT:
289 assert current not in done # protect againt infinite loop in case of a bad tree.
290 done.add(current)
292 pvalue, post_value = previsit(current, par_value)
293 stack.append((current, par_value, post_value))
295 # Insert all children in reverse order (so that first child ends up on top of the stack).
296 ins = len(stack)
297 for n in iter_children(current):
298 stack.insert(ins, (n, pvalue, _PREVISIT))
299 else:
300 ret = postvisit(current, par_value, cast(Optional[Token], value))
301 return ret
304def walk(node: AST, include_joined_str: bool = False) -> Iterator[Union[Module, AstNode]]:
305 """
306 Recursively yield all descendant nodes in the tree starting at ``node`` (including ``node``
307 itself), using depth-first pre-order traversal (yieling parents before their children).
309 This is similar to ``ast.walk()``, but with a different order, and it works for both ``ast`` and
310 ``astroid`` trees. Also, as ``iter_children()``, it skips singleton nodes generated by ``ast``.
312 By default, ``JoinedStr`` (f-string) nodes and their contents are skipped
313 because they previously couldn't be handled. Set ``include_joined_str`` to True to include them.
314 """
315 iter_children = iter_children_func(node)
316 done = set()
317 stack = [node]
318 while stack:
319 current = stack.pop()
320 assert current not in done # protect againt infinite loop in case of a bad tree.
321 done.add(current)
323 yield current
325 # Insert all children in reverse order (so that first child ends up on top of the stack).
326 # This is faster than building a list and reversing it.
327 ins = len(stack)
328 for c in iter_children(current, include_joined_str):
329 stack.insert(ins, c)
332def replace(text: str, replacements: List[Tuple[int, int, str]]) -> str:
333 """
334 Replaces multiple slices of text with new values. This is a convenience method for making code
335 modifications of ranges e.g. as identified by ``ASTTokens.get_text_range(node)``. Replacements is
336 an iterable of ``(start, end, new_text)`` tuples.
338 For example, ``replace("this is a test", [(0, 4, "X"), (8, 9, "THE")])`` produces
339 ``"X is THE test"``.
340 """
341 p = 0
342 parts = []
343 for (start, end, new_text) in sorted(replacements):
344 parts.append(text[p:start])
345 parts.append(new_text)
346 p = end
347 parts.append(text[p:])
348 return ''.join(parts)
351class NodeMethods:
352 """
353 Helper to get `visit_{node_type}` methods given a node's class and cache the results.
354 """
355 def __init__(self) -> None:
356 self._cache: Dict[Union[ABCMeta, type], Callable[[AstNode, Token, Token], Tuple[Token, Token]]] = {}
358 def get(self, obj: Any, cls: Union[ABCMeta, type]) -> Callable:
359 """
360 Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`,
361 or `obj.visit_default` if the type-specific method is not found.
362 """
363 method = self._cache.get(cls)
364 if not method:
365 name = "visit_" + cls.__name__.lower()
366 method = getattr(obj, name, obj.visit_default)
367 self._cache[cls] = method
368 return method
371def patched_generate_tokens(original_tokens: Iterable[TokenInfo]) -> Iterator[TokenInfo]:
372 """
373 Fixes tokens yielded by `tokenize.generate_tokens` to handle more non-ASCII characters in identifiers.
374 Workaround for https://github.com/python/cpython/issues/68382.
375 Should only be used when tokenizing a string that is known to be valid syntax,
376 because it assumes that error tokens are not actually errors.
377 Combines groups of consecutive NAME, NUMBER, and/or ERRORTOKEN tokens into a single NAME token.
378 """
379 group: List[tokenize.TokenInfo] = []
380 for tok in original_tokens:
381 if (
382 tok.type in (tokenize.NAME, tokenize.ERRORTOKEN, tokenize.NUMBER)
383 # Only combine tokens if they have no whitespace in between
384 and (not group or group[-1].end == tok.start)
385 ):
386 group.append(tok)
387 else:
388 for combined_token in combine_tokens(group):
389 yield combined_token
390 group = []
391 yield tok
392 for combined_token in combine_tokens(group):
393 yield combined_token
395def combine_tokens(group: List[tokenize.TokenInfo]) -> List[tokenize.TokenInfo]:
396 if not any(tok.type == tokenize.ERRORTOKEN for tok in group) or len({tok.line for tok in group}) != 1:
397 return group
398 return [
399 tokenize.TokenInfo(
400 type=tokenize.NAME,
401 string="".join(t.string for t in group),
402 start=group[0].start,
403 end=group[-1].end,
404 line=group[0].line,
405 )
406 ]
409def last_stmt(node: AstNode) -> AstNode:
410 """
411 If the given AST node contains multiple statements, return the last one.
412 Otherwise, just return the node.
413 """
414 child_stmts = [
415 child for child in iter_children_func(node)(node)
416 if is_stmt(child) or type(child).__name__ in (
417 "excepthandler",
418 "ExceptHandler",
419 "match_case",
420 "MatchCase",
421 "TryExcept",
422 "TryFinally",
423 )
424 ]
425 if child_stmts:
426 return last_stmt(child_stmts[-1])
427 return node
431@lru_cache(maxsize=None)
432def fstring_positions_work() -> bool:
433 """
434 The positions attached to nodes inside f-string FormattedValues have some bugs
435 that were fixed in Python 3.9.7 in https://github.com/python/cpython/pull/27729.
436 This checks for those bugs more concretely without relying on the Python version.
437 Specifically this checks:
438 - Values with a format spec or conversion
439 - Repeated (i.e. identical-looking) expressions
440 - f-strings implicitly concatenated over multiple lines.
441 - Multiline, triple-quoted f-strings.
442 """
443 source = """(
444 f"a {b}{b} c {d!r} e {f:g} h {i:{j}} k {l:{m:n}}"
445 f"a {b}{b} c {d!r} e {f:g} h {i:{j}} k {l:{m:n}}"
446 f"{x + y + z} {x} {y} {z} {z} {z!a} {z:z}"
447 f'''
448 {s} {t}
449 {u} {v}
450 '''
451 )"""
452 tree = ast.parse(source)
453 name_nodes = [node for node in ast.walk(tree) if isinstance(node, ast.Name)]
454 name_positions = [(node.lineno, node.col_offset) for node in name_nodes]
455 positions_are_unique = len(set(name_positions)) == len(name_positions)
456 correct_source_segments = all(
457 ast.get_source_segment(source, node) == node.id
458 for node in name_nodes
459 )
460 return positions_are_unique and correct_source_segments
462def annotate_fstring_nodes(tree: ast.AST) -> None:
463 """
464 Add a special attribute `_broken_positions` to nodes inside f-strings
465 if the lineno/col_offset cannot be trusted.
466 """
467 if sys.version_info >= (3, 12):
468 # f-strings were weirdly implemented until https://peps.python.org/pep-0701/
469 # In Python 3.12, inner nodes have sensible positions.
470 return
471 for joinedstr in walk(tree, include_joined_str=True):
472 if not isinstance(joinedstr, ast.JoinedStr):
473 continue
474 for part in joinedstr.values:
475 # The ast positions of the FormattedValues/Constant nodes span the full f-string, which is weird.
476 setattr(part, '_broken_positions', True) # use setattr for mypy
478 if isinstance(part, ast.FormattedValue):
479 if not fstring_positions_work():
480 for child in walk(part.value):
481 setattr(child, '_broken_positions', True)
483 if part.format_spec: # this is another JoinedStr
484 # Again, the standard positions span the full f-string.
485 setattr(part.format_spec, '_broken_positions', True)