Debian Codegraph @

third_party/python/fluent.syntax/fluent/syntax/serializer.py

raw
1 from typing import List, Union
2 from . import ast
3
4
5 def indent_except_first_line(content: str) -> str:
6 return " ".join(
7 content.splitlines(True)
8 )
9
10
11 def includes_new_line(elem: Union[ast.TextElement, ast.Placeable]) -> bool:
12 return isinstance(elem, ast.TextElement) and "\n" in elem.value
13
14
15 def is_select_expr(elem: Union[ast.TextElement, ast.Placeable]) -> bool:
16 return (
17 isinstance(elem, ast.Placeable) and
18 isinstance(elem.expression, ast.SelectExpression))
19
20
21 def should_start_on_new_line(pattern: ast.Pattern) -> bool:
22 is_multiline = any(is_select_expr(elem) for elem in pattern.elements) \
23 or any(includes_new_line(elem) for elem in pattern.elements)
24
25 if is_multiline:
26 first_element = pattern.elements[0]
27 if isinstance(first_element, ast.TextElement):
28 first_char = first_element.value[0]
29 if first_char in ("[", ".", "*"):
30 return False
31 return True
32 return False
33
34
35 class FluentSerializer:
36 """FluentSerializer converts :class:`.ast.SyntaxNode` objects to unicode strings.
37
38 `with_junk` controls if parse errors are written back or not.
39 """
40 HAS_ENTRIES = 1
41
42 def __init__(self, with_junk: bool = False):
43 self.with_junk = with_junk
44
45 def serialize(self, resource: ast.Resource) -> str:
46 "Serialize a :class:`.ast.Resource` to a string."
47 if not isinstance(resource, ast.Resource):
48 raise Exception('Unknown resource type: {}'.format(type(resource)))
49
50 state = 0
51
52 parts: List[str] = []
53 for entry in resource.body:
54 if not isinstance(entry, ast.Junk) or self.with_junk:
55 parts.append(self.serialize_entry(entry, state))
56 if not state & self.HAS_ENTRIES:
57 state |= self.HAS_ENTRIES
58
59 return "".join(parts)
60
61 def serialize_entry(self, entry: ast.EntryType, state: int = 0) -> str:
62 "Serialize an :class:`.ast.Entry` to a string."
63 if isinstance(entry, ast.Message):
64 return serialize_message(entry)
65 if isinstance(entry, ast.Term):
66 return serialize_term(entry)
67 if isinstance(entry, ast.Comment):
68 if state & self.HAS_ENTRIES:
69 return "\n{}\n".format(serialize_comment(entry, "#"))
70 return "{}\n".format(serialize_comment(entry, "#"))
71 if isinstance(entry, ast.GroupComment):
72 if state & self.HAS_ENTRIES:
73 return "\n{}\n".format(serialize_comment(entry, "##"))
74 return "{}\n".format(serialize_comment(entry, "##"))
75 if isinstance(entry, ast.ResourceComment):
76 if state & self.HAS_ENTRIES:
77 return "\n{}\n".format(serialize_comment(entry, "###"))
78 return "{}\n".format(serialize_comment(entry, "###"))
79 if isinstance(entry, ast.Junk):
80 return serialize_junk(entry)
81 raise Exception('Unknown entry type: {}'.format(type(entry)))
82
83
84 def serialize_comment(comment: Union[ast.Comment, ast.GroupComment, ast.ResourceComment], prefix: str = "#") -> str:
85 if not comment.content:
86 return f'{prefix}\n'
87
88 prefixed = "\n".join([
89 prefix if len(line) == 0 else f"{prefix} {line}"
90 for line in comment.content.split("\n")
91 ])
92 # Add the trailing line break.
93 return f'{prefixed}\n'
94
95
96 def serialize_junk(junk: ast.Junk) -> str:
97 return junk.content or ''
98
99
100 def serialize_message(message: ast.Message) -> str:
101 parts: List[str] = []
102
103 if message.comment:
104 parts.append(serialize_comment(message.comment))
105
106 parts.append(f"{message.id.name} =")
107
108 if message.value:
109 parts.append(serialize_pattern(message.value))
110
111 if message.attributes:
112 for attribute in message.attributes:
113 parts.append(serialize_attribute(attribute))
114
115 parts.append("\n")
116 return ''.join(parts)
117
118
119 def serialize_term(term: ast.Term) -> str:
120 parts: List[str] = []
121
122 if term.comment:
123 parts.append(serialize_comment(term.comment))
124
125 parts.append(f"-{term.id.name} =")
126 parts.append(serialize_pattern(term.value))
127
128 if term.attributes:
129 for attribute in term.attributes:
130 parts.append(serialize_attribute(attribute))
131
132 parts.append("\n")
133 return ''.join(parts)
134
135
136 def serialize_attribute(attribute: ast.Attribute) -> str:
137 return "\n .{} ={}".format(
138 attribute.id.name,
139 indent_except_first_line(serialize_pattern(attribute.value))
140 )
141
142
143 def serialize_pattern(pattern: ast.Pattern) -> str:
144 content = "".join(serialize_element(elem) for elem in pattern.elements)
145 content = indent_except_first_line(content)
146
147 if should_start_on_new_line(pattern):
148 return f'\n {content}'
149
150 return f' {content}'
151
152
153 def serialize_element(element: ast.PatternElement) -> str:
154 if isinstance(element, ast.TextElement):
155 return element.value
156 if isinstance(element, ast.Placeable):
157 return serialize_placeable(element)
158 raise Exception('Unknown element type: {}'.format(type(element)))
159
160
161 def serialize_placeable(placeable: ast.Placeable) -> str:
162 expr = placeable.expression
163 if isinstance(expr, ast.Placeable):
164 return "{{{}}}".format(serialize_placeable(expr))
165 if isinstance(expr, ast.SelectExpression):
166 # Special-case select expressions to control the withespace around the
167 # opening and the closing brace.
168 return "{{ {}}}".format(serialize_expression(expr))
169 if isinstance(expr, ast.Expression):
170 return "{{ {} }}".format(serialize_expression(expr))
171 raise Exception('Unknown expression type: {}'.format(type(expr)))
172
173
174 def serialize_expression(expression: Union[ast.Expression, ast.Placeable]) -> str:
175 if isinstance(expression, ast.StringLiteral):
176 return f'"{expression.value}"'
177 if isinstance(expression, ast.NumberLiteral):
178 return expression.value
179 if isinstance(expression, ast.VariableReference):
180 return f"${expression.id.name}"
181 if isinstance(expression, ast.TermReference):
182 out = f"-{expression.id.name}"
183 if expression.attribute is not None:
184 out += f".{expression.attribute.name}"
185 if expression.arguments is not None:
186 out += serialize_call_arguments(expression.arguments)
187 return out
188 if isinstance(expression, ast.MessageReference):
189 out = expression.id.name
190 if expression.attribute is not None:
191 out += f".{expression.attribute.name}"
192 return out
193 if isinstance(expression, ast.FunctionReference):
194 args = serialize_call_arguments(expression.arguments)
195 return f"{expression.id.name}{args}"
196 if isinstance(expression, ast.SelectExpression):
197 out = "{} ->".format(
198 serialize_expression(expression.selector))
199 for variant in expression.variants:
200 out += serialize_variant(variant)
201 return f"{out}\n"
202 if isinstance(expression, ast.Placeable):
203 return serialize_placeable(expression)
204 raise Exception('Unknown expression type: {}'.format(type(expression)))
205
206
207 def serialize_variant(variant: ast.Variant) -> str:
208 return "\n{}[{}]{}".format(
209 " *" if variant.default else " ",
210 serialize_variant_key(variant.key),
211 indent_except_first_line(serialize_pattern(variant.value))
212 )
213
214
215 def serialize_call_arguments(expr: ast.CallArguments) -> str:
216 positional = ", ".join(
217 serialize_expression(arg) for arg in expr.positional)
218 named = ", ".join(
219 serialize_named_argument(arg) for arg in expr.named)
220 if len(expr.positional) > 0 and len(expr.named) > 0:
221 return f'({positional}, {named})'
222 return '({})'.format(positional or named)
223
224
225 def serialize_named_argument(arg: ast.NamedArgument) -> str:
226 return "{}: {}".format(
227 arg.name.name,
228 serialize_expression(arg.value)
229 )
230
231
232 def serialize_variant_key(key: Union[ast.Identifier, ast.NumberLiteral]) -> str:
233 if isinstance(key, ast.Identifier):
234 return key.name
235 if isinstance(key, ast.NumberLiteral):
236 return key.value
237 raise Exception('Unknown variant key type: {}'.format(type(key)))