Debian Codegraph @

src/graphql/language/printer.py

raw
1 from typing import Any, Collection, Optional
2
3 from ..language.ast import Node, OperationType
4 from .block_string import print_block_string
5 from .print_string import print_string
6 from .visitor import visit, Visitor
7
8 __all__ = ["print_ast"]
9
10
11 MAX_LINE_LENGTH = 80
12
13 Strings = Collection[str]
14
15
16 class PrintedNode:
17 """A union type for all nodes that have been processed by the printer."""
18
19 alias: str
20 argument_name: str
21 arguments: Strings
22 block: bool
23 default_value: str
24 definitions: Strings
25 description: str
26 directives: str
27 field_name: str
28 fields: Strings
29 interfaces: Strings
30 locations: Strings
31 member_name: str
32 name: str
33 operation: OperationType
34 operation_types: Strings
35 repeatable: bool
36 selection_set: str
37 selections: Strings
38 type: str
39 type_condition: str
40 types: Strings
41 value: str
42 values: Strings
43 variable: str
44 variable_definitions: Strings
45
46
47 def print_ast(ast: Node) -> str:
48 """Convert an AST into a string.
49
50 The conversion is done using a set of reasonable formatting rules.
51 """
52 return visit(ast, PrintAstVisitor())
53
54
55 class PrintAstVisitor(Visitor):
56 @staticmethod
57 def leave_name(node: PrintedNode, *_args: Any) -> str:
58 return node.value
59
60 @staticmethod
61 def leave_variable(node: PrintedNode, *_args: Any) -> str:
62 return f"${node.name}"
63
64 # Document
65
66 @staticmethod
67 def leave_document(node: PrintedNode, *_args: Any) -> str:
68 return join(node.definitions, "\n\n")
69
70 @staticmethod
71 def leave_operation_definition(node: PrintedNode, *_args: Any) -> str:
72 var_defs = (
73 wrap("(\n", join(node.variable_definitions, "\n"), "\n)")
74 if has_multiline_items(node.variable_definitions)
75 else wrap("(", join(node.variable_definitions, ", "), ")")
76 )
77 prefix = wrap("", node.description, "\n") + join(
78 (
79 node.operation.value,
80 join((node.name, var_defs)),
81 join(node.directives, " "),
82 ),
83 " ",
84 )
85 # Anonymous queries with no directives or variable definitions can use the
86 # query short form.
87 return ("" if prefix == "query" else prefix + " ") + node.selection_set
88
89 @staticmethod
90 def leave_variable_definition(node: PrintedNode, *_args: Any) -> str:
91 return (
92 wrap("", node.description, "\n") + f"{node.variable}: {node.type}"
93 f"{wrap(' = ', node.default_value)}"
94 f"{wrap(' ', join(node.directives, ' '))}"
95 )
96
97 @staticmethod
98 def leave_selection_set(node: PrintedNode, *_args: Any) -> str:
99 return block(node.selections)
100
101 @staticmethod
102 def leave_field(node: PrintedNode, *_args: Any) -> str:
103 prefix = wrap("", node.alias, ": ") + node.name
104 args_line = prefix + wrap("(", join(node.arguments, ", "), ")")
105
106 if len(args_line) > MAX_LINE_LENGTH:
107 args_line = prefix + wrap("(\n", indent(join(node.arguments, "\n")), "\n)")
108
109 return join((args_line, join(node.directives, " "), node.selection_set), " ")
110
111 @staticmethod
112 def leave_argument(node: PrintedNode, *_args: Any) -> str:
113 return f"{node.name}: {node.value}"
114
115 # Fragments
116
117 @staticmethod
118 def leave_fragment_spread(node: PrintedNode, *_args: Any) -> str:
119 return f"...{node.name}{wrap(' ', join(node.directives, ' '))}"
120
121 @staticmethod
122 def leave_inline_fragment(node: PrintedNode, *_args: Any) -> str:
123 return join(
124 (
125 "...",
126 wrap("on ", node.type_condition),
127 join(node.directives, " "),
128 node.selection_set,
129 ),
130 " ",
131 )
132
133 @staticmethod
134 def leave_fragment_definition(node: PrintedNode, *_args: Any) -> str:
135 # Note: fragment variable definitions are deprecated and will be removed in v3.3
136 return (
137 wrap("", node.description, "\n") + f"fragment {node.name}"
138 f"{wrap('(', join(node.variable_definitions, ', '), ')')}"
139 f" on {node.type_condition}"
140 f" {wrap('', join(node.directives, ' '), ' ')}"
141 f"{node.selection_set}"
142 )
143
144 # Value
145
146 @staticmethod
147 def leave_int_value(node: PrintedNode, *_args: Any) -> str:
148 return node.value
149
150 @staticmethod
151 def leave_float_value(node: PrintedNode, *_args: Any) -> str:
152 return node.value
153
154 @staticmethod
155 def leave_string_value(node: PrintedNode, *_args: Any) -> str:
156 if node.block:
157 return print_block_string(node.value)
158 return print_string(node.value)
159
160 @staticmethod
161 def leave_boolean_value(node: PrintedNode, *_args: Any) -> str:
162 return "true" if node.value else "false"
163
164 @staticmethod
165 def leave_null_value(_node: PrintedNode, *_args: Any) -> str:
166 return "null"
167
168 @staticmethod
169 def leave_enum_value(node: PrintedNode, *_args: Any) -> str:
170 return node.value
171
172 @staticmethod
173 def leave_list_value(node: PrintedNode, *_args: Any) -> str:
174 return f"[{join(node.values, ', ')}]"
175
176 @staticmethod
177 def leave_object_value(node: PrintedNode, *_args: Any) -> str:
178 return f"{{{join(node.fields, ', ')}}}"
179
180 @staticmethod
181 def leave_object_field(node: PrintedNode, *_args: Any) -> str:
182 return f"{node.name}: {node.value}"
183
184 # Directive
185
186 @staticmethod
187 def leave_directive(node: PrintedNode, *_args: Any) -> str:
188 return f"@{node.name}{wrap('(', join(node.arguments, ', '), ')')}"
189
190 # Type
191
192 @staticmethod
193 def leave_named_type(node: PrintedNode, *_args: Any) -> str:
194 return node.name
195
196 @staticmethod
197 def leave_list_type(node: PrintedNode, *_args: Any) -> str:
198 return f"[{node.type}]"
199
200 @staticmethod
201 def leave_non_null_type(node: PrintedNode, *_args: Any) -> str:
202 return f"{node.type}!"
203
204 # Type System Definitions
205
206 @staticmethod
207 def leave_schema_definition(node: PrintedNode, *_args: Any) -> str:
208 return wrap("", node.description, "\n") + join(
209 (
210 "schema",
211 join(node.directives, " "),
212 block(node.operation_types),
213 ),
214 " ",
215 )
216
217 @staticmethod
218 def leave_operation_type_definition(node: PrintedNode, *_args: Any) -> str:
219 return f"{node.operation.value}: {node.type}"
220
221 @staticmethod
222 def leave_scalar_type_definition(node: PrintedNode, *_args: Any) -> str:
223 return wrap("", node.description, "\n") + join(
224 (
225 "scalar",
226 node.name,
227 join(node.directives, " "),
228 ),
229 " ",
230 )
231
232 @staticmethod
233 def leave_object_type_definition(node: PrintedNode, *_args: Any) -> str:
234 return wrap("", node.description, "\n") + join(
235 (
236 "type",
237 node.name,
238 wrap("implements ", join(node.interfaces, " & ")),
239 join(node.directives, " "),
240 block(node.fields),
241 ),
242 " ",
243 )
244
245 @staticmethod
246 def leave_field_definition(node: PrintedNode, *_args: Any) -> str:
247 args = node.arguments
248 args = (
249 wrap("(\n", indent(join(args, "\n")), "\n)")
250 if has_multiline_items(args)
251 else wrap("(", join(args, ", "), ")")
252 )
253 directives = wrap(" ", join(node.directives, " "))
254 return (
255 wrap("", node.description, "\n")
256 + f"{node.name}{args}: {node.type}{directives}"
257 )
258
259 @staticmethod
260 def leave_input_value_definition(node: PrintedNode, *_args: Any) -> str:
261 return wrap("", node.description, "\n") + join(
262 (
263 f"{node.name}: {node.type}",
264 wrap("= ", node.default_value),
265 join(node.directives, " "),
266 ),
267 " ",
268 )
269
270 @staticmethod
271 def leave_interface_type_definition(node: PrintedNode, *_args: Any) -> str:
272 return wrap("", node.description, "\n") + join(
273 (
274 "interface",
275 node.name,
276 wrap("implements ", join(node.interfaces, " & ")),
277 join(node.directives, " "),
278 block(node.fields),
279 ),
280 " ",
281 )
282
283 @staticmethod
284 def leave_union_type_definition(node: PrintedNode, *_args: Any) -> str:
285 return wrap("", node.description, "\n") + join(
286 (
287 "union",
288 node.name,
289 join(node.directives, " "),
290 wrap("= ", join(node.types, " | ")),
291 ),
292 " ",
293 )
294
295 @staticmethod
296 def leave_enum_type_definition(node: PrintedNode, *_args: Any) -> str:
297 return wrap("", node.description, "\n") + join(
298 ("enum", node.name, join(node.directives, " "), block(node.values)), " "
299 )
300
301 @staticmethod
302 def leave_enum_value_definition(node: PrintedNode, *_args: Any) -> str:
303 return wrap("", node.description, "\n") + join(
304 (node.name, join(node.directives, " ")), " "
305 )
306
307 @staticmethod
308 def leave_input_object_type_definition(node: PrintedNode, *_args: Any) -> str:
309 return wrap("", node.description, "\n") + join(
310 ("input", node.name, join(node.directives, " "), block(node.fields)), " "
311 )
312
313 @staticmethod
314 def leave_directive_definition(node: PrintedNode, *_args: Any) -> str:
315 args = node.arguments
316 args = (
317 wrap("(\n", indent(join(args, "\n")), "\n)")
318 if has_multiline_items(args)
319 else wrap("(", join(args, ", "), ")")
320 )
321 directives = wrap(" ", join(node.directives, " "))
322 repeatable = " repeatable" if node.repeatable else ""
323 locations = join(node.locations, " | ")
324 return (
325 wrap("", node.description, "\n")
326 + f"directive @{node.name}{args}{directives}{repeatable} on {locations}"
327 )
328
329 @staticmethod
330 def leave_schema_extension(node: PrintedNode, *_args: Any) -> str:
331 return join(
332 ("extend schema", join(node.directives, " "), block(node.operation_types)),
333 " ",
334 )
335
336 @staticmethod
337 def leave_directive_extension(node: PrintedNode, *_args: Any) -> str:
338 return join((f"extend directive @{node.name}", join(node.directives, " ")), " ")
339
340 @staticmethod
341 def leave_scalar_type_extension(node: PrintedNode, *_args: Any) -> str:
342 return join(("extend scalar", node.name, join(node.directives, " ")), " ")
343
344 @staticmethod
345 def leave_object_type_extension(node: PrintedNode, *_args: Any) -> str:
346 return join(
347 (
348 "extend type",
349 node.name,
350 wrap("implements ", join(node.interfaces, " & ")),
351 join(node.directives, " "),
352 block(node.fields),
353 ),
354 " ",
355 )
356
357 @staticmethod
358 def leave_interface_type_extension(node: PrintedNode, *_args: Any) -> str:
359 return join(
360 (
361 "extend interface",
362 node.name,
363 wrap("implements ", join(node.interfaces, " & ")),
364 join(node.directives, " "),
365 block(node.fields),
366 ),
367 " ",
368 )
369
370 @staticmethod
371 def leave_union_type_extension(node: PrintedNode, *_args: Any) -> str:
372 return join(
373 (
374 "extend union",
375 node.name,
376 join(node.directives, " "),
377 wrap("= ", join(node.types, " | ")),
378 ),
379 " ",
380 )
381
382 @staticmethod
383 def leave_enum_type_extension(node: PrintedNode, *_args: Any) -> str:
384 return join(
385 ("extend enum", node.name, join(node.directives, " "), block(node.values)),
386 " ",
387 )
388
389 @staticmethod
390 def leave_input_object_type_extension(node: PrintedNode, *_args: Any) -> str:
391 return join(
392 ("extend input", node.name, join(node.directives, " "), block(node.fields)),
393 " ",
394 )
395
396 # Schema Coordinates
397
398 @staticmethod
399 def leave_type_coordinate(node: PrintedNode, *_args: Any) -> str:
400 return node.name
401
402 @staticmethod
403 def leave_member_coordinate(node: PrintedNode, *_args: Any) -> str:
404 return join((node.name, wrap(".", node.member_name)))
405
406 @staticmethod
407 def leave_argument_coordinate(node: PrintedNode, *_args: Any) -> str:
408 return join(
409 (node.name, wrap(".", node.field_name), wrap("(", node.argument_name, ":)"))
410 )
411
412 @staticmethod
413 def leave_directive_coordinate(node: PrintedNode, *_args: Any) -> str:
414 return f"@{node.name}"
415
416 @staticmethod
417 def leave_directive_argument_coordinate(node: PrintedNode, *_args: Any) -> str:
418 return f"@{node.name}{wrap('(', node.argument_name, ':)')}"
419
420
421 def join(strings: Optional[Strings], separator: str = "") -> str:
422 """Join strings in a given collection.
423
424 Return an empty string if it is None or empty, otherwise join all items together
425 separated by separator if provided.
426 """
427 return separator.join(s for s in strings if s) if strings else ""
428
429
430 def block(strings: Optional[Strings]) -> str:
431 """Return strings inside a block.
432
433 Given a collection of strings, return a string with each item on its own line,
434 wrapped in an indented "{ }" block.
435 """
436 return wrap("{\n", indent(join(strings, "\n")), "\n}")
437
438
439 def wrap(start: str, string: Optional[str], end: str = "") -> str:
440 """Wrap string inside other strings at start and end.
441
442 If the string is not None or empty, then wrap with start and end, otherwise return
443 an empty string.
444 """
445 return f"{start}{string}{end}" if string else ""
446
447
448 def indent(string: str) -> str:
449 """Indent string with two spaces.
450
451 If the string is not None or empty, add two spaces at the beginning of every line
452 inside the string.
453 """
454 return wrap(" ", string.replace("\n", "\n "))
455
456
457 def is_multiline(string: str) -> bool:
458 """Check whether a string consists of multiple lines."""
459 return "\n" in string
460
461
462 def has_multiline_items(strings: Optional[Strings]) -> bool:
463 """Check whether one of the items in the list has multiple lines."""
464 return any(is_multiline(item) for item in strings) if strings else False