Debian Codegraph @

src/graphql/utilities/strip_ignored_characters.py

raw
1 from typing import Union, cast
2
3 from ..language import Lexer, TokenKind
4 from ..language.source import Source, is_source
5 from ..language.block_string import print_block_string
6 from ..language.lexer import is_punctuator_token_kind
7
8 __all__ = ["strip_ignored_characters"]
9
10
11 def strip_ignored_characters(source: Union[str, Source]) -> str:
12 """Strip characters that are ignored anyway.
13
14 Strips characters that are not significant to the validity or execution
15 of a GraphQL document:
16
17 - UnicodeBOM
18 - WhiteSpace
19 - LineTerminator
20 - Comment
21 - Comma
22 - BlockString indentation
23
24 Note: It is required to have a delimiter character between neighboring
25 non-punctuator tokes and this function always uses single space as delimiter.
26
27 It is guaranteed that both input and output documents if parsed would result
28 in the exact same AST except for nodes location.
29
30 Warning: It is guaranteed that this function will always produce stable results.
31 However, it's not guaranteed that it will stay the same between different
32 releases due to bugfixes or changes in the GraphQL specification.
33 """ '''
34
35 Query example::
36
37 query SomeQuery($foo: String!, $bar: String) {
38 someField(foo: $foo, bar: $bar) {
39 a
40 b {
41 c
42 d
43 }
44 }
45 }
46
47 Becomes::
48
49 query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}}
50
51 SDL example::
52
53 """
54 Type description
55 """
56 type Foo {
57 """
58 Field description
59 """
60 bar: String
61 }
62
63 Becomes::
64
65 """Type description""" type Foo{"""Field description""" bar:String}
66 '''
67 source = cast(Source, source) if is_source(source) else Source(cast(str, source))
68
69 body = source.body
70 lexer = Lexer(source)
71 stripped_body = ""
72 was_last_added_token_non_punctuator = False
73 while lexer.advance().kind != TokenKind.EOF:
74 current_token = lexer.token
75 token_kind = current_token.kind
76
77 # Every two non-punctuator tokens should have space between them.
78 # Also prevent case of non-punctuator token following by spread resulting
79 # in invalid token (e.g.`1...` is invalid Float token).
80 is_non_punctuator = not is_punctuator_token_kind(current_token.kind)
81 if was_last_added_token_non_punctuator and (
82 is_non_punctuator or current_token.kind == TokenKind.SPREAD
83 ):
84 stripped_body += " "
85
86 token_body = body[current_token.start : current_token.end]
87 if token_kind == TokenKind.BLOCK_STRING:
88 stripped_body += print_block_string(
89 current_token.value or "", minimize=True
90 )
91 else:
92 stripped_body += token_body
93
94 was_last_added_token_non_punctuator = is_non_punctuator
95
96 return stripped_body