Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/fluent/serialize.py

raw
1 # Copyright Mozilla Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from __future__ import annotations
16
17 from collections.abc import Callable
18 from re import fullmatch
19 from typing import Any, Iterator
20
21 from fluent.syntax import FluentSerializer
22 from fluent.syntax import ast as ftl
23
24 from ... import message as msg
25 from .. import data as res
26
27
28 def fluent_serialize(
29 resource: (
30 res.Resource[str, res.M]
31 | res.Resource[msg.Message, res.M]
32 | res.Resource[ftl.Pattern, res.M]
33 ),
34 serialize_metadata: Callable[[res.Metadata[res.M]], str | None] | None = None,
35 trim_comments: bool = False,
36 ) -> Iterator[str]:
37 """
38 Serialize a resource as the contents of a Fluent FTL file.
39
40 Section identifiers are not supported.
41 Single-part message identifiers are treated as message values,
42 while two-part message identifiers are considered message attributes.
43
44 Function names are upper-cased, and annotations with the `message` function
45 are mapped to message and term references.
46
47 Yields each entry and comment separately.
48 If the resource includes any metadata, a `serialize_metadata` callable must be provided
49 to map each field into a comment value, or to discard it by returning an empty value.
50 """
51 ftl_ast = fluent_astify(resource, serialize_metadata, trim_comments)
52 serializer = FluentSerializer()
53 nl_prefix = 0
54 for entry in ftl_ast.body:
55 yield serializer.serialize_entry(entry, nl_prefix)
56 if not nl_prefix:
57 nl_prefix = 1
58
59
60 def fluent_astify(
61 resource: (
62 res.Resource[str, res.M]
63 | res.Resource[msg.Message, res.M]
64 | res.Resource[ftl.Pattern, res.M]
65 ),
66 serialize_metadata: Callable[[res.Metadata[res.M]], str | None] | None = None,
67 trim_comments: bool = False,
68 ) -> ftl.Resource:
69 """
70 Transform a resource into a corresponding Fluent AST structure.
71
72 Section identifiers are not supported.
73 Single-part message identifiers are treated as message values,
74 while two-part message identifiers are considered message attributes.
75
76 Function names are upper-cased, and annotations with the `message` function
77 are mapped to message and term references.
78
79 If the resource includes any metadata other than a string resource `info` value,
80 a `serialize_metadata` callable must be provided
81 to map each field into a comment value, or to discard it by returning an empty value.
82 """
83
84 def comment(
85 node: (
86 res.Resource[Any, Any]
87 | res.Section[Any, Any]
88 | res.Entry[Any, Any]
89 | res.Comment
90 ),
91 ) -> str:
92 if trim_comments:
93 return ""
94 cs = node.comment.rstrip()
95 if not isinstance(node, res.Comment) and node.meta:
96 if not serialize_metadata:
97 raise ValueError("Metadata requires serialize_metadata parameter")
98 for field in node.meta:
99 if (
100 isinstance(node, res.Resource)
101 and field.key == "info"
102 and field == node.meta[0]
103 ):
104 continue
105 meta_str = serialize_metadata(field)
106 if meta_str:
107 ms = meta_str.strip("\n")
108 cs = f"{cs}\n{ms}" if cs else ms
109 return cs
110
111 body: list[ftl.EntryType] = []
112 res_info = resource.meta[0] if resource.meta else None
113 if (
114 not trim_comments
115 and res_info
116 and res_info.key == "info"
117 and isinstance(res_info.value, str)
118 and res_info.value
119 ):
120 body.append(ftl.Comment(res_info.value))
121 res_comment = resource.comment.rstrip()
122 else:
123 res_comment = comment(resource)
124 if res_comment:
125 body.append(ftl.ResourceComment(res_comment))
126 for idx, section in enumerate(resource.sections):
127 section_comment = comment(section) # type: ignore[arg-type]
128 if not trim_comments and idx != 0 or section_comment:
129 body.append(ftl.GroupComment(section_comment))
130 cur: ftl.Message | ftl.Term | None = None
131 cur_id = ""
132 for entry in section.entries: # type: ignore[attr-defined]
133 if isinstance(entry, res.Comment):
134 if not trim_comments:
135 body.append(ftl.Comment(entry.comment))
136 cur = None
137 else:
138 value = (
139 entry.value
140 if isinstance(entry.value, ftl.Pattern)
141 else fluent_astify_message(entry.value)
142 )
143 entry_comment = comment(entry)
144 if len(entry.id) == 1: # value
145 cur_id = entry.id[0]
146 cur = (
147 ftl.Term(ftl.Identifier(cur_id[1:]), value)
148 if cur_id.startswith("-")
149 else ftl.Message(ftl.Identifier(cur_id), value)
150 )
151 if entry_comment:
152 cur.comment = ftl.Comment(entry_comment)
153 body.append(cur)
154 elif len(entry.id) == 2: # attribute
155 if cur is None or entry.id[0] != cur_id:
156 cur_id = entry.id[0]
157 if cur_id.startswith("-"):
158 value = ftl.Pattern([ftl.Placeable(ftl.StringLiteral(""))])
159 cur = ftl.Term(ftl.Identifier(cur_id[1:]), value)
160 else:
161 cur = ftl.Message(ftl.Identifier(cur_id))
162 if entry_comment:
163 cur.comment = ftl.Comment(entry_comment)
164 body.append(cur)
165 elif entry_comment:
166 attr_comment = f"{entry.id[1]}:\n{entry_comment}"
167 if cur.comment:
168 cur.comment.content = (
169 str(cur.comment.content) + "\n\n" + attr_comment
170 )
171 else:
172 cur.comment = ftl.Comment(attr_comment)
173 cur.attributes.append(
174 ftl.Attribute(ftl.Identifier(entry.id[1]), value)
175 )
176 else:
177 raise ValueError(f"Unsupported message id: {entry.id}")
178 return ftl.Resource(body)
179
180
181 def fluent_astify_message(message: str | msg.Message) -> ftl.Pattern:
182 """
183 Transform a message into a corresponding Fluent AST pattern.
184
185 Function names are upper-cased, and annotations with the `message` function
186 are mapped to message and term references.
187 """
188
189 if isinstance(message, str):
190 return ftl.Pattern([ftl.TextElement(message)])
191 if not isinstance(message, (msg.PatternMessage, msg.SelectMessage)):
192 raise ValueError(f"Unsupported message: {message}")
193 decl = [d for d in message.declarations if isinstance(d, msg.Declaration)]
194 if len(decl) != len(message.declarations):
195 raise ValueError("Unsupported statements are not supported")
196 if isinstance(message, msg.PatternMessage):
197 return flat_pattern(decl, message.pattern)
198
199 # It gets a bit complicated for SelectMessage. We'll be modifying this list,
200 # building select expressions for each selector starting from the last one
201 # until this list has only one entry `[[], pattern]`.
202 #
203 # We rely on the variants being in order, so that a variant with N keys
204 # will be next to all other variants for which the first N-1 keys are equal.
205 variants = [
206 (list(keys), flat_pattern(decl, value))
207 for keys, value in message.variants.items()
208 ]
209
210 other = fallback_name(message.variants)
211 keys0 = variants[0][0]
212 while keys0:
213 selector = expression(decl, message.selectors[len(keys0) - 1])
214 if (
215 isinstance(selector, ftl.FunctionReference)
216 and selector.id.name == "NUMBER"
217 and selector.arguments.positional
218 and isinstance(selector.arguments.positional[0], ftl.VariableReference)
219 and not selector.arguments.named
220 ):
221 selector = selector.arguments.positional[0]
222 base_keys = []
223 sel_exp = None
224 i = 0
225 while i < len(variants):
226 keys, pattern = variants[i]
227 key = keys.pop() # Ultimately modifies keys0
228 ftl_variant = ftl.Variant(
229 variant_key(key, other), pattern, isinstance(key, msg.CatchallKey)
230 )
231 if sel_exp and keys == base_keys:
232 sel_exp.variants.append(ftl_variant)
233 variants.pop(i)
234 else:
235 base_keys = keys
236 sel_exp = ftl.SelectExpression(selector.clone(), [ftl_variant])
237 variants[i] = (keys, ftl.Pattern([ftl.Placeable(sel_exp)]))
238 i += 1
239 if len(variants) != 1:
240 raise ValueError(f"Error resolving select message variants (n={len(variants)})")
241 return variants[0][1]
242
243
244 def fallback_name(variants: msg.Variants) -> str:
245 """
246 Try `other`, `other1`, `other2`, ... until a free one is found.
247 """
248 i = 0
249 key = root = "other"
250 while any(
251 key == (k.value if isinstance(k, msg.CatchallKey) else k)
252 for keys in variants
253 for k in keys
254 ):
255 i += 1
256 key = f"{root}{i}"
257 return key
258
259
260 def variant_key(
261 key: str | msg.CatchallKey, other: str
262 ) -> ftl.NumberLiteral | ftl.Identifier:
263 kv = key.value or other if isinstance(key, msg.CatchallKey) else key
264 try:
265 float(kv)
266 return ftl.NumberLiteral(kv)
267 except Exception:
268 if fullmatch(r"[a-zA-Z][\w-]*", kv):
269 return ftl.Identifier(kv)
270 raise ValueError(f"Unsupported variant key: {kv}")
271
272
273 def flat_pattern(decl: list[msg.Declaration], pattern: msg.Pattern) -> ftl.Pattern:
274 elements: list[ftl.TextElement | ftl.Placeable] = []
275 for el in pattern:
276 if isinstance(el, str):
277 elements.append(ftl.TextElement(el))
278 elif isinstance(el, msg.Expression):
279 elements.append(ftl.Placeable(expression(decl, el)))
280 else:
281 raise ValueError(f"Conversion to Fluent not supported: {el}")
282 return ftl.Pattern(elements)
283
284
285 def expression(
286 decl: list[msg.Declaration], expr: msg.Expression
287 ) -> ftl.InlineExpression:
288 arg = value(decl, expr.arg) if expr.arg is not None else None
289 if isinstance(expr.annotation, msg.FunctionAnnotation):
290 return function_ref(decl, arg, expr.annotation)
291 elif expr.annotation:
292 raise ValueError("Unsupported annotations are not supported")
293 if arg:
294 return arg
295 raise ValueError("Invalid empty expression")
296
297
298 def function_ref(
299 decl: list[msg.Declaration],
300 arg: ftl.InlineExpression | None,
301 annotation: msg.FunctionAnnotation,
302 ) -> ftl.InlineExpression:
303 named: list[ftl.NamedArgument] = []
304 for name, val in annotation.options.items():
305 ftl_val = value(decl, val)
306 if isinstance(ftl_val, ftl.Literal):
307 named.append(ftl.NamedArgument(ftl.Identifier(name), ftl_val))
308 else:
309 raise ValueError(f"Fluent option value not literal for {name}: {ftl_val}")
310
311 if annotation.name == "string":
312 if not arg:
313 raise ValueError("Argument required for :string")
314 if named:
315 raise ValueError("Options on :string are not supported")
316 return arg
317 if annotation.name == "number" and isinstance(arg, ftl.NumberLiteral) and not named:
318 return arg
319 if annotation.name == "message":
320 if not isinstance(arg, ftl.Literal):
321 raise ValueError(
322 "Message and term references must have a literal message identifier"
323 )
324 match = fullmatch(r"(-?[a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?", arg.value)
325 if not match:
326 raise ValueError(f"Invalid message or term identifier: {arg.value}")
327 msg_id = match[1]
328 msg_attr = match[2]
329 attr = ftl.Identifier(msg_attr) if msg_attr else None
330 if msg_id[0] == "-":
331 args = ftl.CallArguments(named=named) if named else None
332 return ftl.TermReference(ftl.Identifier(msg_id[1:]), attr, args)
333 elif named:
334 raise ValueError("Options on message references are not supported")
335 else:
336 return ftl.MessageReference(ftl.Identifier(msg_id), attr)
337
338 args = ftl.CallArguments([arg] if arg else None, named)
339 return ftl.FunctionReference(ftl.Identifier(annotation.name.upper()), args)
340
341
342 # Non-printable ASCII C0 & C1 / Unicode Cc characters
343 esc_cc = {n: f"\\u{n:04X}" for r in (range(0, 32), range(127, 160)) for n in r}
344
345
346 def value(
347 decl: list[msg.Declaration], val: str | msg.VariableRef
348 ) -> ftl.InlineExpression:
349 if isinstance(val, str):
350 try:
351 float(val)
352 return ftl.NumberLiteral(val)
353 except Exception:
354 return ftl.StringLiteral(val.translate(esc_cc))
355 else:
356 local = next((d for d in decl if d.name == val.name), None)
357 return (
358 expression(decl, local.value)
359 if local
360 else ftl.VariableReference(ftl.Identifier(val.name))
361 )