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