1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5"""This module renders Astroid nodes as string"""
6
7from __future__ import annotations
8
9import warnings
10from collections.abc import Iterator
11from typing import TYPE_CHECKING
12
13from astroid import nodes
14
15if TYPE_CHECKING:
16 from astroid import objects
17
18# pylint: disable=unused-argument
19
20DOC_NEWLINE = "\0"
21
22
23# Visitor pattern require argument all the time and is not better with staticmethod
24# noinspection PyUnusedLocal,PyMethodMayBeStatic
25class AsStringVisitor:
26 """Visitor to render an Astroid node as a valid python code string"""
27
28 def __init__(self, indent: str = " "):
29 self.indent: str = indent
30
31 def __call__(self, node: nodes.NodeNG) -> str:
32 """Makes this visitor behave as a simple function"""
33 return node.accept(self).replace(DOC_NEWLINE, "\n")
34
35 def _docstring(self, value: str) -> str:
36 """Render a docstring as a literal that reparses to the same text.
37
38 Emit it verbatim in triple quotes, but fall back to ``repr`` when the
39 text could terminate or escape the literal, so it round-trips.
40 """
41 if (
42 '"""' not in value
43 and not value.endswith('"')
44 and "\\" not in value
45 and "\0" not in value
46 and "\r" not in value
47 ):
48 return '"""{}"""'.format(value.replace("\n", DOC_NEWLINE))
49 return repr(value)
50
51 def _docs_dedent(self, doc_node: nodes.Const | None) -> str:
52 """Stop newlines in docs being indented by self._stmt_list"""
53 if not doc_node:
54 return ""
55
56 return "\n" + self.indent + self._docstring(doc_node.value)
57
58 def _stmt_list(self, stmts: list, indent: bool = True) -> str:
59 """return a list of nodes to string"""
60 stmts_str: str = "\n".join(
61 nstr for nstr in [n.accept(self) for n in stmts] if nstr
62 )
63 if not indent:
64 return stmts_str
65
66 return self.indent + stmts_str.replace("\n", "\n" + self.indent)
67
68 def _precedence_parens(
69 self, node: nodes.NodeNG, child: nodes.NodeNG, is_left: bool = True
70 ) -> str:
71 """Wrap child in parens only if required to keep same semantics"""
72 if self._should_wrap(node, child, is_left):
73 return f"({child.accept(self)})"
74
75 return child.accept(self)
76
77 def _should_wrap(
78 self, node: nodes.NodeNG, child: nodes.NodeNG, is_left: bool
79 ) -> bool:
80 """Wrap child if:
81 - it has lower precedence
82 - same precedence with position opposite to associativity direction
83 """
84 node_precedence = node.op_precedence()
85 child_precedence = child.op_precedence()
86
87 if node_precedence > child_precedence:
88 # 3 * (4 + 5)
89 return True
90
91 if (
92 node_precedence == child_precedence
93 and is_left != node.op_left_associative()
94 ):
95 # 3 - (4 - 5)
96 # (2**3)**4
97 return True
98
99 return False
100
101 # visit_<node> methods ###########################################
102
103 def visit_await(self, node: nodes.Await) -> str:
104 return f"await {node.value.accept(self)}"
105
106 def visit_asyncwith(self, node: nodes.AsyncWith) -> str:
107 return f"async {self.visit_with(node)}"
108
109 def visit_asyncfor(self, node: nodes.AsyncFor) -> str:
110 return f"async {self.visit_for(node)}"
111
112 def visit_arguments(self, node: nodes.Arguments) -> str:
113 """return an nodes.Arguments node as string"""
114 return node.format_args()
115
116 def visit_assignattr(self, node: nodes.AssignAttr) -> str:
117 """return an nodes.AssignAttr node as string"""
118 return self.visit_attribute(node)
119
120 def visit_assert(self, node: nodes.Assert) -> str:
121 """return an nodes.Assert node as string"""
122 if node.fail:
123 return f"assert {node.test.accept(self)}, {node.fail.accept(self)}"
124 return f"assert {node.test.accept(self)}"
125
126 def visit_assignname(self, node: nodes.AssignName) -> str:
127 """return an nodes.AssignName node as string"""
128 return node.name
129
130 def visit_assign(self, node: nodes.Assign) -> str:
131 """return an nodes.Assign node as string"""
132 lhs = " = ".join(n.accept(self) for n in node.targets)
133 return f"{lhs} = {node.value.accept(self)}"
134
135 def visit_augassign(self, node: nodes.AugAssign) -> str:
136 """return an nodes.AugAssign node as string"""
137 return f"{node.target.accept(self)} {node.op} {node.value.accept(self)}"
138
139 def visit_annassign(self, node: nodes.AnnAssign) -> str:
140 """Return an nodes.AnnAssign node as string"""
141
142 target = node.target.accept(self)
143 annotation = node.annotation.accept(self)
144 if node.value is None:
145 return f"{target}: {annotation}"
146 return f"{target}: {annotation} = {node.value.accept(self)}"
147
148 def visit_binop(self, node: nodes.BinOp) -> str:
149 """return an nodes.BinOp node as string"""
150 left = self._precedence_parens(node, node.left)
151 right = self._precedence_parens(node, node.right, is_left=False)
152 if node.op == "**":
153 return f"{left}{node.op}{right}"
154
155 return f"{left} {node.op} {right}"
156
157 def visit_boolop(self, node: nodes.BoolOp) -> str:
158 """return an nodes.BoolOp node as string"""
159 values = [f"{self._precedence_parens(node, n)}" for n in node.values]
160 return (f" {node.op} ").join(values)
161
162 def visit_break(self, node: nodes.Break) -> str:
163 """return an nodes.Break node as string"""
164 return "break"
165
166 def visit_call(self, node: nodes.Call) -> str:
167 """return an nodes.Call node as string"""
168 expr_str = self._precedence_parens(node, node.func)
169 args = [arg.accept(self) for arg in node.args]
170 if node.keywords:
171 keywords = [kwarg.accept(self) for kwarg in node.keywords]
172 else:
173 keywords = []
174
175 args.extend(keywords)
176 return f"{expr_str}({', '.join(args)})"
177
178 def _handle_type_params(
179 self, type_params: list[nodes.TypeVar | nodes.ParamSpec | nodes.TypeVarTuple]
180 ) -> str:
181 return (
182 f"[{', '.join(tp.accept(self) for tp in type_params)}]"
183 if type_params
184 else ""
185 )
186
187 def visit_classdef(self, node: nodes.ClassDef) -> str:
188 """return an nodes.ClassDef node as string"""
189 decorate = node.decorators.accept(self) if node.decorators else ""
190 type_params = self._handle_type_params(node.type_params)
191 args = [n.accept(self) for n in node.bases]
192 if node._metaclass and not node.has_metaclass_hack():
193 args.append("metaclass=" + node._metaclass.accept(self))
194 args += [n.accept(self) for n in node.keywords]
195 args_str = f"({', '.join(args)})" if args else ""
196 docs = self._docs_dedent(node.doc_node)
197 body = self._stmt_list(node.body)
198 return (
199 f"\n\n{decorate}class {node.name}{type_params}{args_str}:{docs}\n{body}\n"
200 )
201
202 def visit_compare(self, node: nodes.Compare) -> str:
203 """return an nodes.Compare node as string"""
204 rhs_str = " ".join(
205 f"{op} {self._precedence_parens(node, expr, is_left=False)}"
206 for op, expr in node.ops
207 )
208 return f"{self._precedence_parens(node, node.left)} {rhs_str}"
209
210 def visit_comprehension(self, node: nodes.Comprehension) -> str:
211 """return an nodes.Comprehension node as string"""
212 ifs = "".join(f" if {n.accept(self)}" for n in node.ifs)
213 generated = f"for {node.target.accept(self)} in {node.iter.accept(self)}{ifs}"
214 return f"{'async ' if node.is_async else ''}{generated}"
215
216 def visit_const(self, node: nodes.Const) -> str:
217 """return an nodes.Const node as string"""
218 if node.value is Ellipsis:
219 return "..."
220 try:
221 return repr(node.value)
222 except ValueError:
223 # repr() of an int past sys.get_int_max_str_digits() raises;
224 # hex() is exempt from that limit and round-trips as source.
225 return hex(node.value)
226
227 def visit_continue(self, node: nodes.Continue) -> str:
228 """return an nodes.Continue node as string"""
229 return "continue"
230
231 def visit_delete(self, node: nodes.Delete) -> str:
232 """return an nodes.Delete node as string"""
233 return f"del {', '.join(child.accept(self) for child in node.targets)}"
234
235 def visit_delattr(self, node: nodes.DelAttr) -> str:
236 """return an nodes.DelAttr node as string"""
237 return self.visit_attribute(node)
238
239 def visit_delname(self, node: nodes.DelName) -> str:
240 """return an nodes.DelName node as string"""
241 return node.name
242
243 def visit_decorators(self, node: nodes.Decorators) -> str:
244 """return an nodes.Decorators node as string"""
245 joined = "\n@".join(item.accept(self) for item in node.nodes)
246 return f"@{joined}\n"
247
248 def visit_dict(self, node: nodes.Dict) -> str:
249 """return an nodes.Dict node as string"""
250 return f"{{{', '.join(self._visit_dict(node))}}}"
251
252 def _visit_dict(self, node: nodes.Dict) -> Iterator[str]:
253 for key, value in node.items:
254 key = key.accept(self)
255 value = value.accept(self)
256 if key == "**":
257 # It can only be a DictUnpack node.
258 yield key + value
259 else:
260 yield f"{key}: {value}"
261
262 def visit_dictunpack(self, node: nodes.DictUnpack) -> str:
263 return "**"
264
265 def visit_dictcomp(self, node: nodes.DictComp) -> str:
266 """return an nodes.DictComp node as string"""
267 key = node.key.accept(self)
268 value = node.value.accept(self)
269 generators = " ".join(n.accept(self) for n in node.generators)
270 if key == "**":
271 # PEP 798 dict-comprehension unpacking, e.g. ``{**d for d in dicts}``.
272 return f"{{{key}{value} {generators}}}"
273 return f"{{{key}: {value} {generators}}}"
274
275 def visit_expr(self, node: nodes.Expr) -> str:
276 """return an nodes.Expr node as string"""
277 return node.value.accept(self)
278
279 def visit_emptynode(self, node: nodes.EmptyNode) -> str:
280 """dummy method for visiting an EmptyNode"""
281 return ""
282
283 def visit_excepthandler(self, node: nodes.ExceptHandler) -> str:
284 n = "except"
285 if isinstance(getattr(node, "parent", None), nodes.TryStar):
286 n = "except*"
287 if node.type:
288 if node.name:
289 excs = f"{n} {node.type.accept(self)} as {node.name.accept(self)}"
290 else:
291 excs = f"{n} {node.type.accept(self)}"
292 else:
293 excs = f"{n}"
294 return f"{excs}:\n{self._stmt_list(node.body)}"
295
296 def visit_empty(self, node: nodes.EmptyNode) -> str:
297 """return an EmptyNode as string"""
298 return ""
299
300 def visit_for(self, node: nodes.For) -> str:
301 """return an nodes.For node as string"""
302 fors = f"for {node.target.accept(self)} in {node.iter.accept(self)}:\n{self._stmt_list(node.body)}"
303 if node.orelse:
304 fors = f"{fors}\nelse:\n{self._stmt_list(node.orelse)}"
305 return fors
306
307 def visit_importfrom(self, node: nodes.ImportFrom) -> str:
308 """return an nodes.ImportFrom node as string"""
309 lazy = "lazy " if node.is_lazy else ""
310 return "{}from {} import {}".format(
311 lazy, "." * (node.level or 0) + node.modname, _import_string(node.names)
312 )
313
314 def visit_joinedstr(self, node: nodes.JoinedStr) -> str:
315 string = "".join(
316 # Use repr on the string literal parts
317 # to get proper escapes, e.g. \n, \\, \"
318 # But strip the quotes off the ends
319 # (they will always be one character: ' or ")
320 (
321 repr(value.value)[1:-1]
322 # Literal braces must be doubled to escape them
323 .replace("{", "{{").replace("}", "}}")
324 # Each value in values is either a string literal (Const)
325 # or a FormattedValue
326 if type(value).__name__ == "Const"
327 else value.accept(self)
328 )
329 for value in node.values
330 )
331
332 # Try to find surrounding quotes that don't appear at all in the string.
333 # Because the formatted values inside {} can't contain backslash (\)
334 # using a triple quote is sometimes necessary.
335 for quote in ("'", '"', '"""', "'''"):
336 if quote not in string:
337 return "f" + quote + string + quote
338
339 # Every candidate quote is present in the body. Pick a delimiter absent
340 # from the {expression} parts (which cannot hold a backslash) and
341 # escape it in the literal parts so the f-string cannot terminate early.
342 formatted = "".join(
343 value.accept(self)
344 for value in node.values
345 if not isinstance(value, nodes.Const)
346 )
347 quote = next(
348 (q for q in ("'", '"', "'''", '"""') if q not in formatted),
349 # Unrepresentable: every delimiter occurs in an expression part.
350 "'''",
351 )
352 string = "".join(
353 (
354 _escaped_fstring_literal(value.value, quote[0])
355 if isinstance(value, nodes.Const)
356 else value.accept(self)
357 )
358 for value in node.values
359 )
360 return "f" + quote + string + quote
361
362 def visit_formattedvalue(self, node: nodes.FormattedValue) -> str:
363 result = node.value.accept(self)
364 if node.conversion and node.conversion >= 0:
365 # e.g. if node.conversion == 114: result += "!r"
366 result += "!" + chr(node.conversion)
367 if node.format_spec:
368 # The format spec is itself a JoinedString, i.e. an f-string
369 # We strip the f and quotes of the ends
370 result += ":" + node.format_spec.accept(self)[2:-1]
371 return f"{{{result}}}"
372
373 def handle_functiondef(self, node: nodes.FunctionDef, keyword: str) -> str:
374 """return a (possibly async) function definition node as string"""
375 decorate = node.decorators.accept(self) if node.decorators else ""
376 type_params = self._handle_type_params(node.type_params)
377 docs = self._docs_dedent(node.doc_node)
378 trailer = ":"
379 if node.returns:
380 return_annotation = " -> " + node.returns.as_string()
381 trailer = return_annotation + ":"
382 def_format = "\n%s%s %s%s(%s)%s%s\n%s"
383 return def_format % (
384 decorate,
385 keyword,
386 node.name,
387 type_params,
388 node.args.accept(self),
389 trailer,
390 docs,
391 self._stmt_list(node.body),
392 )
393
394 def visit_functiondef(self, node: nodes.FunctionDef) -> str:
395 """return an nodes.FunctionDef node as string"""
396 return self.handle_functiondef(node, "def")
397
398 def visit_asyncfunctiondef(self, node: nodes.AsyncFunctionDef) -> str:
399 """return an nodes.AsyncFunction node as string"""
400 return self.handle_functiondef(node, "async def")
401
402 def visit_generatorexp(self, node: nodes.GeneratorExp) -> str:
403 """return an nodes.GeneratorExp node as string"""
404 return "({} {})".format(
405 node.elt.accept(self), " ".join(n.accept(self) for n in node.generators)
406 )
407
408 def visit_attribute(
409 self, node: nodes.Attribute | nodes.AssignAttr | nodes.DelAttr
410 ) -> str:
411 """return an nodes.Attribute node as string"""
412 try:
413 left = self._precedence_parens(node, node.expr)
414 except RecursionError:
415 warnings.warn(
416 "Recursion limit exhausted; defaulting to adding parentheses.",
417 UserWarning,
418 stacklevel=2,
419 )
420 left = f"({node.expr.accept(self)})"
421 if left.isdigit():
422 left = f"({left})"
423 return f"{left}.{node.attrname}"
424
425 def visit_global(self, node: nodes.Global) -> str:
426 """return an nodes.Global node as string"""
427 return f"global {', '.join(node.names)}"
428
429 def visit_if(self, node: nodes.If) -> str:
430 """return an nodes.If node as string"""
431 ifs = [f"if {node.test.accept(self)}:\n{self._stmt_list(node.body)}"]
432 if node.has_elif_block():
433 ifs.append(f"el{self._stmt_list(node.orelse, indent=False)}")
434 elif node.orelse:
435 ifs.append(f"else:\n{self._stmt_list(node.orelse)}")
436 return "\n".join(ifs)
437
438 def visit_ifexp(self, node: nodes.IfExp) -> str:
439 """return an nodes.IfExp node as string"""
440 body = self._precedence_parens(node, node.body, is_left=True)
441 test = self._precedence_parens(node, node.test, is_left=True)
442 orelse = self._precedence_parens(node, node.orelse, is_left=False)
443 return f"{body} if {test} else {orelse}"
444
445 def visit_import(self, node: nodes.Import) -> str:
446 """return an nodes.Import node as string"""
447 lazy = "lazy " if node.is_lazy else ""
448 return f"{lazy}import {_import_string(node.names)}"
449
450 def visit_keyword(self, node: nodes.Keyword) -> str:
451 """return an nodes.Keyword node as string"""
452 if node.arg is None:
453 return f"**{node.value.accept(self)}"
454 return f"{node.arg}={node.value.accept(self)}"
455
456 def visit_lambda(self, node: nodes.Lambda) -> str:
457 """return an nodes.Lambda node as string"""
458 args = node.args.accept(self)
459 body = node.body.accept(self)
460 if args:
461 return f"lambda {args}: {body}"
462
463 return f"lambda: {body}"
464
465 def visit_list(self, node: nodes.List) -> str:
466 """return an nodes.List node as string"""
467 return f"[{', '.join(child.accept(self) for child in node.elts)}]"
468
469 def visit_listcomp(self, node: nodes.ListComp) -> str:
470 """return an nodes.ListComp node as string"""
471 return "[{} {}]".format(
472 node.elt.accept(self), " ".join(n.accept(self) for n in node.generators)
473 )
474
475 def visit_module(self, node: nodes.Module) -> str:
476 """return an nodes.Module node as string"""
477 docs = f"{self._docstring(node.doc_node.value)}\n\n" if node.doc_node else ""
478 return docs + "\n".join(n.accept(self) for n in node.body) + "\n\n"
479
480 def visit_name(self, node: nodes.Name) -> str:
481 """return an nodes.Name node as string"""
482 return node.name
483
484 def visit_namedexpr(self, node: nodes.NamedExpr) -> str:
485 """Return an assignment expression node as string, always parenthesized."""
486 target = node.target.accept(self)
487 value = node.value.accept(self)
488 if isinstance(node.parent, nodes.Compare):
489 return f"{target} := {value}"
490 return f"({target} := {value})"
491
492 def visit_nonlocal(self, node: nodes.Nonlocal) -> str:
493 """return an nodes.Nonlocal node as string"""
494 return f"nonlocal {', '.join(node.names)}"
495
496 def visit_paramspec(self, node: nodes.ParamSpec) -> str:
497 """return an nodes.ParamSpec node as string"""
498 default_value_str = (
499 f" = {node.default_value.accept(self)}" if node.default_value else ""
500 )
501 return f"**{node.name.accept(self)}{default_value_str}"
502
503 def visit_pass(self, node: nodes.Pass) -> str:
504 """return an nodes.Pass node as string"""
505 return "pass"
506
507 def visit_partialfunction(self, node: objects.PartialFunction) -> str:
508 """Return an objects.PartialFunction as string."""
509 return self.visit_functiondef(node)
510
511 def visit_raise(self, node: nodes.Raise) -> str:
512 """return an nodes.Raise node as string"""
513 if node.exc:
514 if node.cause:
515 return f"raise {node.exc.accept(self)} from {node.cause.accept(self)}"
516 return f"raise {node.exc.accept(self)}"
517 return "raise"
518
519 def visit_return(self, node: nodes.Return) -> str:
520 """return an nodes.Return node as string"""
521 if node.is_tuple_return() and len(node.value.elts) > 1:
522 elts = [child.accept(self) for child in node.value.elts]
523 return f"return {', '.join(elts)}"
524
525 if node.value:
526 return f"return {node.value.accept(self)}"
527
528 return "return"
529
530 def visit_set(self, node: nodes.Set) -> str:
531 """return an nodes.Set node as string"""
532 return f"{{{', '.join(child.accept(self) for child in node.elts)}}}"
533
534 def visit_setcomp(self, node: nodes.SetComp) -> str:
535 """return an nodes.SetComp node as string"""
536 return "{{{} {}}}".format(
537 node.elt.accept(self), " ".join(n.accept(self) for n in node.generators)
538 )
539
540 def visit_slice(self, node: nodes.Slice) -> str:
541 """return an nodes.Slice node as string"""
542 lower = node.lower.accept(self) if node.lower else ""
543 upper = node.upper.accept(self) if node.upper else ""
544 step = node.step.accept(self) if node.step else ""
545 if step:
546 return f"{lower}:{upper}:{step}"
547 return f"{lower}:{upper}"
548
549 def visit_subscript(self, node: nodes.Subscript) -> str:
550 """return an nodes.Subscript node as string"""
551 idx = node.slice
552 if idx.__class__.__name__.lower() == "index":
553 idx = idx.value
554 idxstr = idx.accept(self)
555 if idx.__class__.__name__.lower() == "tuple" and idx.elts:
556 # Remove parenthesis in tuple and extended slice.
557 # a[(::1, 1:)] is not valid syntax.
558 idxstr = idxstr[1:-1]
559 return f"{self._precedence_parens(node, node.value)}[{idxstr}]"
560
561 def visit_try(self, node: nodes.Try) -> str:
562 """return an nodes.Try node as string"""
563 trys = [f"try:\n{self._stmt_list(node.body)}"]
564 for handler in node.handlers:
565 trys.append(handler.accept(self))
566 if node.orelse:
567 trys.append(f"else:\n{self._stmt_list(node.orelse)}")
568 if node.finalbody:
569 trys.append(f"finally:\n{self._stmt_list(node.finalbody)}")
570 return "\n".join(trys)
571
572 def visit_trystar(self, node: nodes.TryStar) -> str:
573 """return an nodes.TryStar node as string"""
574 trys = [f"try:\n{self._stmt_list(node.body)}"]
575 for handler in node.handlers:
576 trys.append(handler.accept(self))
577 if node.orelse:
578 trys.append(f"else:\n{self._stmt_list(node.orelse)}")
579 if node.finalbody:
580 trys.append(f"finally:\n{self._stmt_list(node.finalbody)}")
581 return "\n".join(trys)
582
583 def visit_tuple(self, node: nodes.Tuple) -> str:
584 """return an nodes.Tuple node as string"""
585 if len(node.elts) == 1:
586 return f"({node.elts[0].accept(self)}, )"
587 return f"({', '.join(child.accept(self) for child in node.elts)})"
588
589 def visit_typealias(self, node: nodes.TypeAlias) -> str:
590 """return an nodes.TypeAlias node as string"""
591 type_params = self._handle_type_params(node.type_params)
592 return f"type {node.name.accept(self)}{type_params} = {node.value.accept(self)}"
593
594 def visit_typevar(self, node: nodes.TypeVar) -> str:
595 """return an nodes.TypeVar node as string"""
596 bound_str = f": {node.bound.accept(self)}" if node.bound else ""
597 default_value_str = (
598 f" = {node.default_value.accept(self)}" if node.default_value else ""
599 )
600 return f"{node.name.accept(self)}{bound_str}{default_value_str}"
601
602 def visit_typevartuple(self, node: nodes.TypeVarTuple) -> str:
603 """return an nodes.TypeVarTuple node as string"""
604 default_value_str = (
605 f" = {node.default_value.accept(self)}" if node.default_value else ""
606 )
607 return f"*{node.name.accept(self)}{default_value_str}"
608
609 def visit_unaryop(self, node: nodes.UnaryOp) -> str:
610 """return an nodes.UnaryOp node as string"""
611 if node.op == "not":
612 operator = "not "
613 else:
614 operator = node.op
615 return f"{operator}{self._precedence_parens(node, node.operand)}"
616
617 def visit_while(self, node: nodes.While) -> str:
618 """return an nodes.While node as string"""
619 whiles = f"while {node.test.accept(self)}:\n{self._stmt_list(node.body)}"
620 if node.orelse:
621 whiles = f"{whiles}\nelse:\n{self._stmt_list(node.orelse)}"
622 return whiles
623
624 def visit_with(self, node: nodes.With) -> str: # 'with' without 'as' is possible
625 """return an nodes.With node as string"""
626 items = ", ".join(
627 f"{expr.accept(self)}" + ((v and f" as {v.accept(self)}") or "")
628 for expr, v in node.items
629 )
630 return f"with {items}:\n{self._stmt_list(node.body)}"
631
632 def visit_yield(self, node: nodes.Yield) -> str:
633 """yield an ast.Yield node as string"""
634 yi_val = (" " + node.value.accept(self)) if node.value else ""
635 expr = "yield" + yi_val
636 if node.parent.is_statement:
637 return expr
638
639 return f"({expr})"
640
641 def visit_yieldfrom(self, node: nodes.YieldFrom) -> str:
642 """Return an nodes.YieldFrom node as string."""
643 yi_val = (" " + node.value.accept(self)) if node.value else ""
644 expr = "yield from" + yi_val
645 if node.parent.is_statement:
646 return expr
647
648 return f"({expr})"
649
650 def visit_starred(self, node: nodes.Starred) -> str:
651 """return Starred node as string"""
652 return "*" + node.value.accept(self)
653
654 def visit_match(self, node: nodes.Match) -> str:
655 """Return an nodes.Match node as string."""
656 return f"match {node.subject.accept(self)}:\n{self._stmt_list(node.cases)}"
657
658 def visit_matchcase(self, node: nodes.MatchCase) -> str:
659 """Return an nodes.MatchCase node as string."""
660 guard_str = f" if {node.guard.accept(self)}" if node.guard else ""
661 return (
662 f"case {node.pattern.accept(self)}{guard_str}:\n"
663 f"{self._stmt_list(node.body)}"
664 )
665
666 def visit_matchvalue(self, node: nodes.MatchValue) -> str:
667 """Return an nodes.MatchValue node as string."""
668 return node.value.accept(self)
669
670 @staticmethod
671 def visit_matchsingleton(node: nodes.MatchSingleton) -> str:
672 """Return an nodes.MatchSingleton node as string."""
673 return str(node.value)
674
675 def visit_matchsequence(self, node: nodes.MatchSequence) -> str:
676 """Return an nodes.MatchSequence node as string."""
677 if node.patterns is None:
678 return "[]"
679 return f"[{', '.join(p.accept(self) for p in node.patterns)}]"
680
681 def visit_matchmapping(self, node: nodes.MatchMapping) -> str:
682 """Return an nodes..MatchMapping node as string."""
683 mapping_strings: list[str] = []
684 if node.keys and node.patterns:
685 mapping_strings.extend(
686 f"{key.accept(self)}: {p.accept(self)}"
687 for key, p in zip(node.keys, node.patterns)
688 )
689 if node.rest:
690 mapping_strings.append(f"**{node.rest.accept(self)}")
691 return f"{'{'}{', '.join(mapping_strings)}{'}'}"
692
693 def visit_matchclass(self, node: nodes.MatchClass) -> str:
694 """Return an nodes..MatchClass node as string."""
695 if node.cls is None:
696 raise AssertionError(f"{node} does not have a 'cls' node")
697 class_strings: list[str] = []
698 if node.patterns:
699 class_strings.extend(p.accept(self) for p in node.patterns)
700 if node.kwd_attrs and node.kwd_patterns:
701 for attr, pattern in zip(node.kwd_attrs, node.kwd_patterns):
702 class_strings.append(f"{attr}={pattern.accept(self)}")
703 return f"{node.cls.accept(self)}({', '.join(class_strings)})"
704
705 def visit_matchstar(self, node: nodes.MatchStar) -> str:
706 """Return an nodes..MatchStar node as string."""
707 return f"*{node.name.accept(self) if node.name else '_'}"
708
709 def visit_matchas(self, node: nodes.MatchAs) -> str:
710 """Return an nodes..MatchAs node as string."""
711 if isinstance(
712 node.parent, (nodes.MatchSequence, nodes.MatchMapping, nodes.MatchClass)
713 ):
714 return node.name.accept(self) if node.name else "_"
715 return (
716 f"{node.pattern.accept(self) if node.pattern else '_'}"
717 f"{f' as {node.name.accept(self)}' if node.name else ''}"
718 )
719
720 def visit_matchor(self, node: nodes.MatchOr) -> str:
721 """Return an nodes.MatchOr node as string."""
722 if node.patterns is None:
723 raise AssertionError(f"{node} does not have pattern nodes")
724 return " | ".join(p.accept(self) for p in node.patterns)
725
726 def visit_templatestr(self, node: nodes.TemplateStr) -> str:
727 """Return an nodes.TemplateStr node as string."""
728 string = ""
729 for value in node.values:
730 match value:
731 case nodes.Interpolation():
732 string += "{" + value.accept(self) + "}"
733 case _:
734 string += value.accept(self)[1:-1]
735 for quote in ("'", '"', '"""', "'''"):
736 if quote not in string:
737 break
738 return "t" + quote + string + quote
739
740 def visit_interpolation(self, node: nodes.Interpolation) -> str:
741 """Return an nodes.Interpolation node as string."""
742 result = f"{node.str}"
743 if node.conversion and node.conversion >= 0:
744 # e.g. if node.conversion == 114: result += "!r"
745 result += "!" + chr(node.conversion)
746 if node.format_spec:
747 # The format spec is itself a JoinedString, i.e. an f-string
748 # We strip the f and quotes of the ends
749 result += ":" + node.format_spec.accept(self)[2:-1]
750 return result
751
752 # These aren't for real AST nodes, but for inference objects.
753
754 def visit_frozenset(self, node: objects.FrozenSet) -> str:
755 return node.parent.accept(self)
756
757 def visit_super(self, node: objects.Super) -> str:
758 return node.parent.accept(self)
759
760 def visit_uninferable(self, node) -> str:
761 return str(node)
762
763 def visit_property(self, node: objects.Property) -> str:
764 return node.function.accept(self)
765
766 def visit_evaluatedobject(self, node: nodes.EvaluatedObject) -> str:
767 return node.original.accept(self)
768
769 def visit_unknown(self, node: nodes.Unknown) -> str:
770 return str(node)
771
772
773def _escaped_fstring_literal(value: str, quote: str) -> str:
774 """Return the inner text of an f-string literal part delimited by *quote*
775 (a single quote character), escaping *quote* and doubling braces."""
776 literal = repr(value)
777 if literal[0] == quote:
778 body = literal[1:-1]
779 else:
780 # repr escapes only its own quote; unescape it and escape *quote*.
781 body = literal[1:-1].replace("\\" + literal[0], literal[0])
782 body = body.replace(quote, "\\" + quote)
783 return body.replace("{", "{{").replace("}", "}}")
784
785
786def _import_string(names: list[tuple[str, str | None]]) -> str:
787 """return a list of (name, asname) formatted as a string"""
788 _names = []
789 for name, asname in names:
790 if asname is not None:
791 _names.append(f"{name} as {asname}")
792 else:
793 _names.append(name)
794 return ", ".join(_names)
795
796
797# This sets the default indent to 4 spaces.
798to_code = AsStringVisitor(" ")