Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/gast/gast.py: 30%
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
1import sys as _sys
2import ast as _ast
3from ast import boolop, cmpop, excepthandler, expr, expr_context, operator
4from ast import slice, stmt, unaryop, mod, AST
5from ast import iter_child_nodes, walk
7try:
8 from ast import TypeIgnore
9except ImportError:
10 class TypeIgnore(AST):
11 pass
13try:
14 from ast import pattern
15except ImportError:
16 class pattern(AST):
17 pass
20try:
21 from ast import type_param
22except ImportError:
23 class type_param(AST):
24 pass
27def _make_node(Name, Fields, Attributes, Bases):
29 # This constructor is used a lot during conversion from ast to gast,
30 # then as the primary way to build ast nodes. So we tried to optimized it
31 # for speed and not for readability.
32 def create_node(self, *args, **kwargs):
33 if len(args) > len(Fields):
34 raise TypeError(
35 "{} constructor takes at most {} positional arguments".
36 format(Name, len(Fields)))
38 # it's faster to iterate rather than zipping or enumerate
39 for i in range(len(args)):
40 setattr(self, Fields[i], args[i])
41 if kwargs: # cold branch
42 self.__dict__.update(kwargs)
44 setattr(_sys.modules[__name__],
45 Name,
46 type(Name,
47 Bases,
48 {'__init__': create_node,
49 '_fields': Fields,
50 '_field_types': {},
51 '_attributes': Attributes}))
53def _fill_field_types(Name, FieldTypes):
54 node = getattr(_sys.modules[__name__], Name)
55 assert len(node._fields) == len(FieldTypes), Name
56 node._field_types.update(zip(node._fields, FieldTypes))
58_nodes = (
59 # mod
60 ('Module', (('body', 'type_ignores'), (), (mod,))),
61 ('Interactive', (('body',), (), (mod,))),
62 ('Expression', (('body',), (), (mod,))),
63 ('FunctionType', (('argtypes', 'returns'), (), (mod,))),
64 ('Suite', (('body',), (), (mod,))),
66 # stmt
67 ('FunctionDef', (('name', 'args', 'body', 'decorator_list', 'returns',
68 'type_comment', 'type_params'),
69 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
70 (stmt,))),
71 ('AsyncFunctionDef', (('name', 'args', 'body', 'decorator_list', 'returns',
72 'type_comment', 'type_params',),
73 ('lineno', 'col_offset',
74 'end_lineno', 'end_col_offset',),
75 (stmt,))),
76 ('ClassDef', (('name', 'bases', 'keywords', 'body', 'decorator_list',
77 'type_params',),
78 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
79 (stmt,))),
80 ('Return', (('value',),
81 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
82 (stmt,))),
83 ('Delete', (('targets',),
84 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
85 (stmt,))),
86 ('Assign', (('targets', 'value', 'type_comment'),
87 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
88 (stmt,))),
89 ('TypeAlias', (('name', 'type_params', 'value'),
90 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
91 (stmt,))),
92 ('AugAssign', (('target', 'op', 'value',),
93 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
94 (stmt,))),
95 ('AnnAssign', (('target', 'annotation', 'value', 'simple',),
96 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
97 (stmt,))),
98 ('Print', (('dest', 'values', 'nl',),
99 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
100 (stmt,))),
101 ('For', (('target', 'iter', 'body', 'orelse', 'type_comment'),
102 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
103 (stmt,))),
104 ('AsyncFor', (('target', 'iter', 'body', 'orelse', 'type_comment'),
105 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
106 (stmt,))),
107 ('While', (('test', 'body', 'orelse',),
108 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
109 (stmt,))),
110 ('If', (('test', 'body', 'orelse',),
111 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
112 (stmt,))),
113 ('With', (('items', 'body', 'type_comment'),
114 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
115 (stmt,))),
116 ('AsyncWith', (('items', 'body', 'type_comment'),
117 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
118 (stmt,))),
119 ('Match', (('subject', 'cases'),
120 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
121 (stmt,))),
122 ('Raise', (('exc', 'cause',),
123 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
124 (stmt,))),
125 ('Try', (('body', 'handlers', 'orelse', 'finalbody',),
126 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
127 (stmt,))),
128 ('TryStar', (('body', 'handlers', 'orelse', 'finalbody',),
129 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
130 (stmt,))),
131 ('Assert', (('test', 'msg',),
132 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
133 (stmt,))),
134 ('Import', (('names',),
135 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
136 (stmt,))),
137 ('ImportFrom', (('module', 'names', 'level',),
138 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
139 (stmt,))),
140 ('Exec', (('body', 'globals', 'locals',),
141 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
142 (stmt,))),
143 ('Global', (('names',),
144 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
145 (stmt,))),
146 ('Nonlocal', (('names',),
147 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
148 (stmt,))),
149 ('Expr', (('value',),
150 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
151 (stmt,))),
152 ('Pass', ((), ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
153 (stmt,))),
154 ('Break', ((), ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
155 (stmt,))),
156 ('Continue', ((),
157 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
158 (stmt,))),
160 # expr
162 ('BoolOp', (('op', 'values',),
163 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
164 (expr,))),
165 ('NamedExpr', (('target', 'value',),
166 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
167 (expr,))),
168 ('BinOp', (('left', 'op', 'right',),
169 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
170 (expr,))),
171 ('UnaryOp', (('op', 'operand',),
172 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
173 (expr,))),
174 ('Lambda', (('args', 'body',),
175 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
176 (expr,))),
177 ('IfExp', (('test', 'body', 'orelse',),
178 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
179 (expr,))),
180 ('Dict', (('keys', 'values',),
181 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
182 (expr,))),
183 ('Set', (('elts',),
184 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
185 (expr,))),
186 ('ListComp', (('elt', 'generators',),
187 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
188 (expr,))),
189 ('SetComp', (('elt', 'generators',),
190 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
191 (expr,))),
192 ('DictComp', (('key', 'value', 'generators',),
193 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
194 (expr,))),
195 ('GeneratorExp', (('elt', 'generators',),
196 ('lineno', 'col_offset',
197 'end_lineno', 'end_col_offset',),
198 (expr,))),
199 ('Await', (('value',),
200 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
201 (expr,))),
202 ('Yield', (('value',),
203 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
204 (expr,))),
205 ('YieldFrom', (('value',),
206 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
207 (expr,))),
208 ('Compare', (('left', 'ops', 'comparators',),
209 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
210 (expr,))),
211 ('Call', (('func', 'args', 'keywords',),
212 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
213 (expr,))),
214 ('Repr', (('value',),
215 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
216 (expr,))),
217 ('FormattedValue', (('value', 'conversion', 'format_spec',),
218 ('lineno', 'col_offset',
219 'end_lineno', 'end_col_offset',),
220 (expr,))),
221 ('JoinedStr', (('values',),
222 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
223 (expr,))),
224 ('Constant', (('value', 'kind'),
225 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
226 (expr,))),
227 ('Attribute', (('value', 'attr', 'ctx',),
228 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
229 (expr,))),
230 ('Subscript', (('value', 'slice', 'ctx',),
231 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
232 (expr,))),
233 ('Starred', (('value', 'ctx',),
234 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
235 (expr,))),
236 ('Name', (('id', 'ctx', 'annotation', 'type_comment'),
237 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
238 (expr,))),
239 ('List', (('elts', 'ctx',),
240 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
241 (expr,))),
242 ('Tuple', (('elts', 'ctx',),
243 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
244 (expr,))),
246 # expr_context
247 ('Load', ((), (), (expr_context,))),
248 ('Store', ((), (), (expr_context,))),
249 ('Del', ((), (), (expr_context,))),
250 ('AugLoad', ((), (), (expr_context,))),
251 ('AugStore', ((), (), (expr_context,))),
252 ('Param', ((), (), (expr_context,))),
254 # slice
255 ('Slice', (('lower', 'upper', 'step'),
256 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset',),
257 (slice,))),
259 # boolop
260 ('And', ((), (), (boolop,))),
261 ('Or', ((), (), (boolop,))),
263 # operator
264 ('Add', ((), (), (operator,))),
265 ('Sub', ((), (), (operator,))),
266 ('Mult', ((), (), (operator,))),
267 ('MatMult', ((), (), (operator,))),
268 ('Div', ((), (), (operator,))),
269 ('Mod', ((), (), (operator,))),
270 ('Pow', ((), (), (operator,))),
271 ('LShift', ((), (), (operator,))),
272 ('RShift', ((), (), (operator,))),
273 ('BitOr', ((), (), (operator,))),
274 ('BitXor', ((), (), (operator,))),
275 ('BitAnd', ((), (), (operator,))),
276 ('FloorDiv', ((), (), (operator,))),
278 # unaryop
279 ('Invert', ((), (), (unaryop, AST,))),
280 ('Not', ((), (), (unaryop, AST,))),
281 ('UAdd', ((), (), (unaryop, AST,))),
282 ('USub', ((), (), (unaryop, AST,))),
284 # cmpop
285 ('Eq', ((), (), (cmpop,))),
286 ('NotEq', ((), (), (cmpop,))),
287 ('Lt', ((), (), (cmpop,))),
288 ('LtE', ((), (), (cmpop,))),
289 ('Gt', ((), (), (cmpop,))),
290 ('GtE', ((), (), (cmpop,))),
291 ('Is', ((), (), (cmpop,))),
292 ('IsNot', ((), (), (cmpop,))),
293 ('In', ((), (), (cmpop,))),
294 ('NotIn', ((), (), (cmpop,))),
296 # comprehension
297 ('comprehension', (('target', 'iter', 'ifs', 'is_async'), (), (AST,))),
299 # excepthandler
300 ('ExceptHandler', (('type', 'name', 'body'),
301 ('lineno', 'col_offset',
302 'end_lineno', 'end_col_offset'),
303 (excepthandler,))),
305 # arguments
306 ('arguments', (('args', 'posonlyargs', 'vararg', 'kwonlyargs',
307 'kw_defaults', 'kwarg', 'defaults'), (), (AST,))),
309 # keyword
310 ('keyword', (('arg', 'value'),
311 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset'),
312 (AST,))),
314 # alias
315 ('alias', (('name', 'asname'),
316 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset'),
317 (AST,))),
319 # withitem
320 ('withitem', (('context_expr', 'optional_vars'), (), (AST,))),
322 # match_case
323 ('match_case', (('pattern', 'guard', 'body'), (), (AST,))),
325 # pattern
326 ('MatchValue', (('value',),
327 ('lineno', 'col_offset', 'end_lineno', 'end_col_offset'),
328 (pattern,))),
329 ('MatchSingleton', (('value',),
330 ('lineno', 'col_offset',
331 'end_lineno', 'end_col_offset'),
332 (pattern,))),
333 ('MatchSequence', (('patterns',),
334 ('lineno', 'col_offset',
335 'end_lineno', 'end_col_offset'),
336 (pattern,))),
337 ('MatchMapping', (('keys', 'patterns', 'rest'),
338 ('lineno', 'col_offset',
339 'end_lineno', 'end_col_offset'),
340 (pattern,))),
341 ('MatchClass', (('cls', 'patterns', 'kwd_attrs', 'kwd_patterns'),
342 ('lineno', 'col_offset',
343 'end_lineno', 'end_col_offset'),
344 (pattern,))),
345 ('MatchStar', (('name',),
346 ('lineno', 'col_offset',
347 'end_lineno', 'end_col_offset'),
348 (pattern,))),
349 ('MatchAs', (('pattern', 'name'),
350 ('lineno', 'col_offset',
351 'end_lineno', 'end_col_offset'),
352 (pattern,))),
353 ('MatchOr', (('patterns',),
354 ('lineno', 'col_offset',
355 'end_lineno', 'end_col_offset'),
356 (pattern,))),
358 # type_ignore
359 ('type_ignore', ((), ('lineno', 'tag'), (TypeIgnore,))),
361 # type_param
362 ('TypeVar', (('name', 'bound',),
363 ('lineno', 'col_offset',
364 'end_lineno', 'end_col_offset'),
365 (type_param,))),
366 ('ParamSpec', (('name',),
367 ('lineno', 'col_offset',
368 'end_lineno', 'end_col_offset'),
369 (type_param,))),
370 ('TypeVarTuple', (('name',),
371 ('lineno', 'col_offset',
372 'end_lineno', 'end_col_offset'),
373 (type_param,))),
374 )
376for _name, _descr in _nodes:
377 _make_node(_name, *_descr)
379# As an exception to gast rule that states that all nodes are identical for all
380# python version, we don't fill the field type for python with a version lower
381# than 3.10. Those version lack type support to be compatible with the more
382# modern representation anyway. The _field_types still exists though, but it's
383# always empty.
384if _sys.version_info >= (3, 10):
386 _node_types = (
387 # mod
388 ('Module', (list[stmt], list[type_ignore])),
389 ('Interactive', (list[stmt],)),
390 ('Expression', (expr,)),
391 ('FunctionType', ('argtypes', 'returns'),),
392 ('Suite', (list[stmt],),),
394 # stmt
395 ('FunctionDef', (str, arguments, list[stmt], list[expr], expr | None, str | None, list[type_param]),),
396 ('AsyncFunctionDef', (str, arguments, list[stmt], list[expr], expr | None, str | None, list[type_param]),),
397 ('ClassDef', (str, list[expr], list[keyword], list[stmt], list[expr], list[type_param])),
398 ('Return', (expr | None,)),
399 ('Delete', (list[expr],)),
400 ('Assign', (list[expr], expr, str | None),),
401 ('TypeAlias', (expr, list[type_param], expr),),
402 ('AugAssign', (expr, operator, expr), ),
403 ('AnnAssign', (expr, expr, expr | None, int), ),
404 ('Print', (expr | None, list[expr], bool), ),
405 ('For', (expr, expr, list[stmt], list[stmt], str | None), ),
406 ('AsyncFor', (expr, expr, list[stmt], list[stmt], str | None), ),
407 ('While', (expr, list[stmt], list[stmt]), ),
408 ('If', (expr, list[stmt], list[stmt]), ),
409 ('With', (list[withitem], list[stmt], str | None), ),
410 ('AsyncWith', (list[withitem], list[stmt], str | None), ),
411 ('Match', (expr, match_case), ),
412 ('Raise', (expr | None, expr | None), ),
413 ('Try', (list[stmt], list[excepthandler], list[stmt], list[stmt]), ),
414 ('TryStar', (list[stmt], list[excepthandler], list[stmt], list[stmt]), ),
415 ('Assert', (expr, expr | None), ),
416 ('Import', (list[alias],), ),
417 ('ImportFrom', (str|None, list[alias], int | None), ),
418 ('Exec', (expr, expr | None, expr | None), ),
419 ('Global', (list[str],), ),
420 ('Nonlocal', (list[str],), ),
421 ('Expr', (expr,), ),
423 # expr
425 ('BoolOp', (boolop, list[expr]), ),
426 ('NamedExpr', (expr, expr), ),
427 ('BinOp', (expr, operator, expr), ),
428 ('UnaryOp', (unaryop, expr), ),
429 ('Lambda', (arguments, expr), ),
430 ('IfExp', (expr, expr, expr), ),
431 ('Dict', (list[expr], list[expr]), ),
432 ('Set', (list[expr],), ),
433 ('ListComp', (expr, list[comprehension]), ),
434 ('SetComp', (expr, list[comprehension]), ),
435 ('DictComp', (expr, expr, list[comprehension]), ),
436 ('GeneratorExp', (expr, list[comprehension]), ),
437 ('Await', (expr,), ),
438 ('Yield', (expr | None,), ),
439 ('YieldFrom', (expr,), ),
440 ('Compare', (expr, list[cmpop], list[expr]), ),
441 ('Call', (expr, list[expr], list[keyword]), ),
442 ('Repr', (expr,), ),
443 ('FormattedValue', (expr, int, expr | None), ),
444 ('JoinedStr', (list[expr],), ),
445 ('Constant', (object, str | None), ),
446 ('Attribute', (expr, str, expr_context), ),
447 ('Subscript', (expr, expr, expr_context), ),
448 ('Starred', (expr, expr_context), ),
449 ('Name', (str, expr_context, expr, str | None), ),
450 ('List', (list[expr], expr_context), ),
451 ('Tuple', (list[expr], expr_context), ),
452 ('Slice', (expr | None, expr | None, expr | None), ),
454 # comprehension
455 ('comprehension', (expr, expr, list[expr], int), ),
457 # excepthandler
458 ('ExceptHandler', (expr | None, str | None, list[stmt]), ),
460 # arguments
461 ('arguments', (list[expr], list[expr], expr | None, list[expr], list[expr], expr | None, list[expr]), ),
463 # keyword
464 ('keyword', (str | None, expr), ),
466 # alias
467 ('alias', (str, str | None), ),
469 # withitem
470 ('withitem', (expr, expr | None), ),
472 # match_case
473 ('match_case', (pattern, expr, list[stmt]), ),
475 # pattern
476 ('MatchValue', (expr,), ),
477 ('MatchSingleton', (object,), ),
478 ('MatchSequence', (list[pattern],), ),
479 ('MatchMapping', (list[expr], list[pattern], str | None), ),
480 ('MatchClass', (expr, list[pattern], list[str], list[pattern]), ),
481 ('MatchStar', (str | None,), ),
482 ('MatchAs', (pattern | None, str | None), ),
483 ('MatchOr', (list[pattern],), ),
485 # type_param
486 ('TypeVar', (str, expr | None), ),
487 ('ParamSpec', (str,), ),
488 ('TypeVarTuple', (str,), ),
489 )
491 for _name, _types in _node_types:
492 _fill_field_types(_name, _types)
494if _sys.version_info.major == 2:
495 from .ast2 import ast_to_gast, gast_to_ast
496if _sys.version_info.major == 3:
497 from .ast3 import ast_to_gast, gast_to_ast
500def parse(*args, **kwargs):
501 return ast_to_gast(_ast.parse(*args, **kwargs))
504def unparse(gast_obj):
505 from .unparser import unparse
506 return unparse(gast_obj)
509def literal_eval(node_or_string):
510 if isinstance(node_or_string, AST):
511 node_or_string = gast_to_ast(node_or_string)
512 return _ast.literal_eval(node_or_string)
515def get_docstring(node, clean=True):
516 if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
517 raise TypeError("%r can't have docstrings" % node.__class__.__name__)
518 if not(node.body and isinstance(node.body[0], Expr)):
519 return None
520 node = node.body[0].value
521 if isinstance(node, Constant) and isinstance(node.value, str):
522 text = node.value
523 else:
524 return None
525 if clean:
526 import inspect
527 text = inspect.cleandoc(text)
528 return text
531# the following are directly imported from python3.8's Lib/ast.py #
533def copy_location(new_node, old_node):
534 """
535 Copy source location (`lineno`, `col_offset`, `end_lineno`, and
536 `end_col_offset` attributes) from *old_node* to *new_node* if possible,
537 and return *new_node*.
538 """
539 for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
540 if attr in old_node._attributes and attr in new_node._attributes \
541 and hasattr(old_node, attr):
542 setattr(new_node, attr, getattr(old_node, attr))
543 return new_node
546def fix_missing_locations(node):
547 """
548 When you compile a node tree with compile(), the compiler expects lineno
549 and col_offset attributes for every node that supports them. This is
550 rather tedious to fill in for generated nodes, so this helper adds these
551 attributes recursively where not already set, by setting them to the values
552 of the parent node. It works recursively starting at *node*.
553 """
554 def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
555 if 'lineno' in node._attributes:
556 if not hasattr(node, 'lineno'):
557 node.lineno = lineno
558 else:
559 lineno = node.lineno
560 if 'end_lineno' in node._attributes:
561 if not hasattr(node, 'end_lineno'):
562 node.end_lineno = end_lineno
563 else:
564 end_lineno = node.end_lineno
565 if 'col_offset' in node._attributes:
566 if not hasattr(node, 'col_offset'):
567 node.col_offset = col_offset
568 else:
569 col_offset = node.col_offset
570 if 'end_col_offset' in node._attributes:
571 if not hasattr(node, 'end_col_offset'):
572 node.end_col_offset = end_col_offset
573 else:
574 end_col_offset = node.end_col_offset
575 for child in iter_child_nodes(node):
576 _fix(child, lineno, col_offset, end_lineno, end_col_offset)
577 _fix(node, 1, 0, 1, 0)
578 return node
581if _sys.version_info.major == 3 and _sys.version_info.minor >= 8:
582 get_source_segment = _ast.get_source_segment
583else:
584 # No end_lineno no end_col_offset info set for those version, so always
585 # return None
586 def get_source_segment(source, node, padded=False):
587 return None
590def increment_lineno(node, n=1):
591 """
592 Increment the line number and end line number of each node in the tree
593 starting at *node* by *n*. This is useful to "move code" to a different
594 location in a file.
595 """
596 for child in walk(node):
597 if 'lineno' in child._attributes:
598 child.lineno = (getattr(child, 'lineno', 0) or 0) + n
599 if 'end_lineno' in child._attributes:
600 child.end_lineno = (getattr(child, 'end_lineno', 0) or 0) + n
601 return node
603# Code import from Lib/ast.py
604#
605# minor changes: getattr(x, y, ...) is None => getattr(x, y, 42) is None
606#
607def dump(
608 node, annotate_fields=True, include_attributes=False,
609 # *, # removed for compatibility with python2 :-/
610 indent=None, show_empty=False,
611):
612 """
613 Return a formatted dump of the tree in node. This is mainly useful for
614 debugging purposes. If annotate_fields is true (by default),
615 the returned string will show the names and the values for fields.
616 If annotate_fields is false, the result string will be more compact by
617 omitting unambiguous field names. Attributes such as line
618 numbers and column offsets are not dumped by default. If this is wanted,
619 include_attributes can be set to true. If indent is a non-negative
620 integer or string, then the tree will be pretty-printed with that indent
621 level. None (the default) selects the single line representation.
622 If show_empty is False, then empty lists and fields that are None
623 will be omitted from the output for better readability.
624 """
625 def _format(node, level=0):
626 if indent is not None:
627 level += 1
628 prefix = '\n' + indent * level
629 sep = ',\n' + indent * level
630 else:
631 prefix = ''
632 sep = ', '
633 if isinstance(node, AST):
634 cls = type(node)
635 args = []
636 args_buffer = []
637 allsimple = True
638 keywords = annotate_fields
639 for name in node._fields:
640 try:
641 value = getattr(node, name)
642 except AttributeError:
643 keywords = True
644 continue
645 if value is None and getattr(cls, name, 42) is None:
646 keywords = True
647 continue
648 if not show_empty:
649 if value == []:
650 if not keywords:
651 args_buffer.append(repr(value))
652 continue
653 if not keywords:
654 args.extend(args_buffer)
655 args_buffer = []
656 value, simple = _format(value, level)
657 allsimple = allsimple and simple
658 if keywords:
659 args.append('%s=%s' % (name, value))
660 else:
661 args.append(value)
662 if include_attributes and node._attributes:
663 for name in node._attributes:
664 try:
665 value = getattr(node, name)
666 except AttributeError:
667 continue
668 if value is None and getattr(cls, name, 42) is None:
669 continue
670 value, simple = _format(value, level)
671 allsimple = allsimple and simple
672 args.append('%s=%s' % (name, value))
673 if allsimple and len(args) <= 3:
674 return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
675 return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
676 elif isinstance(node, list):
677 if not node:
678 return '[]', True
679 return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
680 return repr(node), True
682 if not isinstance(node, AST):
683 raise TypeError('expected AST, got %r' % node.__class__.__name__)
684 if indent is not None and not isinstance(indent, str):
685 indent = ' ' * indent
686 return _format(node)[0]