Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/transforms.py

raw
1 """Migration Transforms.
2
3 Transforms are AST nodes which describe how legacy translations should be
4 migrated. They are created inert and only return the migrated AST nodes when
5 they are evaluated by a MigrationContext.
6
7 All Transforms evaluate to Fluent Patterns. This makes them suitable for
8 defining migrations of values of message, attributes and variants. The special
9 CONCAT Transform is capable of joining multiple Patterns returned by evaluating
10 other Transforms into a single Pattern. It can also concatenate Pattern
11 elements: TextElements and Placeables.
12
13 The COPY, REPLACE and PLURALS Transforms inherit from Source which is a special
14 AST Node defining the location (the file path and the id) of the legacy
15 translation. During the migration, the current MigrationContext scans the
16 migration spec for Source nodes and extracts the information about all legacy
17 translations being migrated. For instance,
18
19 COPY('file.dtd', 'hello')
20
21 is equivalent to:
22
23 FTL.Pattern([
24 Source('file.dtd', 'hello')
25 ])
26
27 Sometimes it's useful to work with text rather than (path, key) source
28 definitions. This is the case when the migrated translation requires some
29 hardcoded text, e.g. <a> and </a> when multiple translations become a single
30 one with a DOM overlay. In such cases it's best to use FTL.TextElements:
31
32 FTL.Message(
33 id=FTL.Identifier('update-failed'),
34 value=CONCAT(
35 COPY('aboutDialog.dtd', 'update.failed.start'),
36 FTL.TextElement('<a>'),
37 COPY('aboutDialog.dtd', 'update.failed.linkText'),
38 FTL.TextElement('</a>'),
39 COPY('aboutDialog.dtd', 'update.failed.end'),
40 )
41 )
42
43 The REPLACE_IN_TEXT Transform also takes TextElements as input, making it
44 possible to pass it as the foreach function of the PLURALS Transform. In the
45 example below, each slice of the plural string is converted into a
46 TextElement by PLURALS and then run through the REPLACE_IN_TEXT transform.
47
48 FTL.Message(
49 FTL.Identifier('delete-all'),
50 value=PLURALS(
51 'aboutDownloads.dtd',
52 'deleteAll',
53 VARIABLE_REFERENCE('num'),
54 lambda text: REPLACE_IN_TEXT(
55 text,
56 {
57 '#1': VARIABLE_REFERENCE('num')
58 }
59 )
60 )
61 )
62 """
63
64 import re
65
66 from fluent.syntax import ast as FTL
67 from fluent.syntax.visitor import Transformer
68 from .errors import NotSupportedError
69
70
71 def chain_elements(elements):
72 """Flatten a list of FTL nodes into an iterator over PatternElements."""
73 for element in elements:
74 if isinstance(element, FTL.Pattern):
75 # PY3 yield from element.elements
76 yield from element.elements
77 elif isinstance(element, FTL.PatternElement):
78 yield element
79 elif isinstance(element, FTL.Expression):
80 yield FTL.Placeable(element)
81 else:
82 raise RuntimeError("Expected Pattern, PatternElement or Expression")
83
84
85 re_leading_ws = re.compile(
86 r"\A(?:(?P<whitespace> +)(?P<text>.*?)|(?P<block_text>\n.*?))\Z",
87 re.S,
88 )
89 re_trailing_ws = re.compile(
90 r"\A(?:(?P<text>.*?)(?P<whitespace> +)|(?P<block_text>.*\n))\Z", re.S
91 )
92
93
94 def extract_whitespace(regex, element):
95 """Extract leading or trailing whitespace from a TextElement.
96
97 Return a tuple of (Placeable, TextElement) in which the Placeable
98 encodes the extracted whitespace as a StringLiteral and the
99 TextElement has the same amount of whitespace removed. The
100 Placeable with the extracted whitespace is always returned first.
101 If the element starts or ends with a newline, add an empty
102 StringLiteral.
103 """
104 match = re.search(regex, element.value)
105 if match:
106 # If white-space is None, we're a newline. Add an
107 # empty { "" }
108 whitespace = match.group("whitespace") or ""
109 placeable = FTL.Placeable(FTL.StringLiteral(whitespace))
110 if whitespace == element.value:
111 return placeable, None
112 else:
113 # Either text or block_text matched the rest.
114 text = match.group("text") or match.group("block_text")
115 return placeable, FTL.TextElement(text)
116 else:
117 return None, element
118
119
120 class Transform(FTL.BaseNode):
121 def __call__(self, ctx):
122 raise NotImplementedError
123
124 @staticmethod
125 def pattern_of(*elements):
126 normalized = []
127
128 # Normalize text content: convert text content to TextElements, join
129 # adjacent text and prune empty. Text content is either existing
130 # TextElements or whitespace-only StringLiterals. This may result in
131 # leading and trailing whitespace being put back into TextElements if
132 # the new Pattern is built from existing Patterns (CONCAT(COPY...)).
133 # The leading and trailing whitespace of the new Pattern will be
134 # extracted later into new StringLiterals.
135 for element in chain_elements(elements):
136 if isinstance(element, FTL.TextElement):
137 text_content = element.value
138 elif (
139 isinstance(element, FTL.Placeable)
140 and isinstance(element.expression, FTL.StringLiteral)
141 and re.match(r"^ *$", element.expression.value)
142 ):
143 text_content = element.expression.value
144 else:
145 # The element does not contain text content which should be
146 # normalized. It may be a number, a reference, or
147 # a StringLiteral which should be preserved in the Pattern.
148 normalized.append(element)
149 continue
150
151 previous = normalized[-1] if len(normalized) else None
152 if isinstance(previous, FTL.TextElement):
153 # Join adjacent TextElements.
154 previous.value += text_content
155 elif len(text_content) > 0:
156 # Normalize non-empty text to a TextElement.
157 normalized.append(FTL.TextElement(text_content))
158 else:
159 # Prune empty text.
160 pass
161
162 # Store empty values explicitly as {""}.
163 if len(normalized) == 0:
164 empty = FTL.Placeable(FTL.StringLiteral(""))
165 return FTL.Pattern([empty])
166
167 # Extract explicit leading whitespace into a StringLiteral.
168 if isinstance(normalized[0], FTL.TextElement):
169 ws, text = extract_whitespace(re_leading_ws, normalized[0])
170 normalized[:1] = [ws, text]
171
172 # Extract explicit trailing whitespace into a StringLiteral.
173 if isinstance(normalized[-1], FTL.TextElement):
174 ws, text = extract_whitespace(re_trailing_ws, normalized[-1])
175 normalized[-1:] = [text, ws]
176
177 return FTL.Pattern([element for element in normalized if element is not None])
178
179
180 class Source(Transform):
181 """Base class for Transforms that get translations from source files.
182
183 The contract is that the first argument is the source path, and the
184 second is a key representing legacy string IDs, or Fluent id.attr.
185 """
186
187 def __init__(self, path, key):
188 self.path = path
189 self.key = key
190
191
192 class FluentSource(Source):
193 """Declare a Fluent source translation to be copied over.
194
195 When evaluated, it clones the Pattern of the parsed source.
196 """
197
198 def __init__(self, path, key):
199 if not path.endswith(".ftl"):
200 raise NotSupportedError(
201 "Please use COPY to migrate from legacy files " "({})".format(path)
202 )
203 if key[0] == "-" and "." in key:
204 raise NotSupportedError(
205 "Cannot migrate from Term Attributes, as they are"
206 "locale-dependent ({})".format(path)
207 )
208 super().__init__(path, key)
209
210 def __call__(self, ctx):
211 pattern = ctx.get_fluent_source_pattern(self.path, self.key)
212 return pattern.clone()
213
214
215 class COPY_PATTERN(FluentSource):
216 """Create a Pattern with the translation value from the given source.
217
218 The given key can be a Message ID, Message ID.attribute_name, or
219 Term ID. Accessing Term attributes is not supported, as they're internal
220 to the localization.
221 """
222
223 pass
224
225
226 class TransformPattern(FluentSource, Transformer):
227 """Base class for modifying a Fluent pattern as part of a migration.
228
229 Implement visit_* methods of the Transformer pattern to do the
230 actual modifications.
231 """
232
233 def __call__(self, ctx):
234 pattern = super().__call__(ctx)
235 return self.visit(pattern)
236
237 def visit_Pattern(self, node):
238 # Make sure we're creating valid Patterns after restructuring
239 # transforms.
240 node = self.generic_visit(node)
241 pattern = Transform.pattern_of(*node.elements)
242 return pattern
243
244 def visit_Placeable(self, node):
245 # Ensure we have a Placeable with an expression still.
246 # Transforms could have replaced the expression with
247 # a Pattern or PatternElement, in which case we
248 # just pass that through.
249 # Patterns then get flattened by visit_Pattern.
250 node = self.generic_visit(node)
251 if isinstance(node.expression, (FTL.Pattern, FTL.PatternElement)):
252 return node.expression
253 return node
254
255
256 class LegacySource(Source):
257 """Declare the source translation to be migrated with other transforms.
258
259 When evaluated, `Source` returns a TextElement with the content from the
260 source translation. Escaped characters are unescaped by the
261 compare-locales parser according to the file format:
262
263 - in properties files: \\uXXXX,
264 - in DTD files: known named, decimal, and hexadecimal HTML entities.
265
266 Consult the following files for the list of known named HTML entities:
267
268 https://github.com/python/cpython/blob/2.7/Lib/htmlentitydefs.py
269 https://github.com/python/cpython/blob/3.6/Lib/html/entities.py
270
271 By default, leading and trailing whitespace on each line as well as
272 leading and trailing empty lines will be stripped from the source
273 translation's content. Set `trim=False` to disable this behavior.
274 """
275
276 def __init__(self, path, key, trim=None):
277 if path.endswith(".ftl"):
278 raise NotSupportedError(
279 "Please use COPY_PATTERN to migrate from Fluent files "
280 "({})".format(path)
281 )
282
283 super().__init__(path, key)
284 self.trim = trim
285
286 def get_text(self, ctx):
287 return ctx.get_legacy_source(self.path, self.key)
288
289 @staticmethod
290 def trim_text(text):
291 # strip leading white-space from each line
292 text = re.sub("^[ \t]+", "", text, flags=re.M)
293 # strip trailing white-space from each line
294 text = re.sub("[ \t]+$", "", text, flags=re.M)
295 # strip leading and trailing empty lines
296 text = text.strip("\r\n")
297 return text
298
299 def __call__(self, ctx):
300 text = self.get_text(ctx)
301 if self.trim is not False:
302 text = self.trim_text(text)
303 return FTL.TextElement(text)
304
305
306 class COPY(LegacySource):
307 """Create a Pattern with the translation value from the given source."""
308
309 def __call__(self, ctx):
310 element = super().__call__(ctx)
311 return Transform.pattern_of(element)
312
313
314 PRINTF = re.compile(
315 r"%(?P<good>%|"
316 r"(?:(?P<number>[1-9][0-9]*)\$)?"
317 r"(?P<width>\*|[0-9]+)?"
318 r"(?P<prec>\.(?:\*|[0-9]+)?)?"
319 r"(?P<spec>[duxXosScpfg]))"
320 )
321
322
323 def number():
324 i = 1
325 while True:
326 yield i
327 i += 1
328
329
330 def normalize_printf(text):
331 """Normalize printf arguments so that they're all numbered.
332 Gecko forbids mixing unnumbered and numbered ones, so
333 we just need to convert unnumbered to numbered ones.
334 Also remove ones that have zero width, as they're intended
335 to be removed from the output by the localizer.
336 """
337 next_number = number()
338
339 def normalized(match):
340 if match.group("good") == "%":
341 return "%"
342 hidden = match.group("width") == "0"
343 if match.group("number"):
344 return "" if hidden else match.group()
345 num = next(next_number)
346 return "" if hidden else "%{}${}".format(num, match.group("spec"))
347
348 return PRINTF.sub(normalized, text)
349
350
351 class REPLACE_IN_TEXT(Transform):
352 """Create a Pattern from a TextElement and replace legacy placeables.
353
354 The original placeables are defined as keys on the `replacements` dict.
355 For each key the value must be defined as a FTL Pattern, Placeable,
356 TextElement or Expression to be interpolated.
357 """
358
359 def __init__(self, element, replacements, normalize_printf=False):
360 self.element = element
361 self.replacements = replacements
362 self.normalize_printf = normalize_printf
363
364 def __call__(self, ctx):
365 # For each specified replacement, find all indices of the original
366 # placeable in the source translation. If missing, the list of indices
367 # will be empty.
368 value = self.element.value
369 if self.normalize_printf:
370 value = normalize_printf(value)
371 key_indices = {
372 key: [m.start() for m in re.finditer(re.escape(key), value)]
373 for key in self.replacements.keys()
374 }
375
376 # Build a dict of indices to replacement keys.
377 keys_indexed = {}
378 for key, indices in key_indices.items():
379 for index in indices:
380 keys_indexed[index] = key
381
382 # Order the replacements by the position of the original placeable in
383 # the translation.
384 replacements = (
385 (key, ctx.evaluate(self.replacements[key]))
386 for index, key in sorted(keys_indexed.items(), key=lambda x: x[0])
387 )
388
389 # A list of PatternElements built from the legacy translation and the
390 # FTL replacements. It may contain empty or adjacent TextElements.
391 elements = []
392 tail = value
393
394 # Convert original placeables and text into FTL Nodes. For each
395 # original placeable the translation will be partitioned around it and
396 # the text before it will be converted into an `FTL.TextElement` and
397 # the placeable will be replaced with its replacement.
398 for key, node in replacements:
399 before, key, tail = tail.partition(key)
400 elements.append(FTL.TextElement(before))
401 elements.append(node)
402
403 # Don't forget about the tail after the loop ends.
404 elements.append(FTL.TextElement(tail))
405 return Transform.pattern_of(*elements)
406
407
408 class REPLACE(LegacySource):
409 """Create a Pattern with interpolations from given source.
410
411 Interpolations in the translation value from the given source will be
412 replaced with FTL placeables using the `REPLACE_IN_TEXT` transform.
413 """
414
415 def __init__(self, path, key, replacements, **kwargs):
416 # We default normalize_printf to False except for .properties files.
417 # We still allow the caller to override the default value.
418 normalize_printf = False
419 if "normalize_printf" in kwargs:
420 normalize_printf = kwargs["normalize_printf"]
421 del kwargs["normalize_printf"]
422 elif path.endswith(".properties"):
423 normalize_printf = True
424
425 super().__init__(path, key, **kwargs)
426 self.replacements = replacements
427 self.normalize_printf = normalize_printf
428
429 def __call__(self, ctx):
430 element = super().__call__(ctx)
431 return REPLACE_IN_TEXT(
432 element, self.replacements, normalize_printf=self.normalize_printf
433 )(ctx)
434
435
436 class PLURALS(LegacySource):
437 """Create a Pattern with plurals from given source.
438
439 Build an `FTL.SelectExpression` with the supplied `selector` and variants
440 extracted from the source. The original translation should be a
441 semicolon-separated list of plural forms. Each form will be converted
442 into a TextElement and run through the `foreach` function, which should
443 return an `FTL.Node` or a `Transform`. By default, the `foreach` function
444 creates a valid Pattern from the TextElement passed into it.
445 """
446
447 DEFAULT_ORDER = ("zero", "one", "two", "few", "many", "other")
448
449 def __init__(self, path, key, selector, foreach=Transform.pattern_of, **kwargs):
450 super().__init__(path, key, **kwargs)
451 self.selector = selector
452 self.foreach = foreach
453
454 def __call__(self, ctx):
455 element = super().__call__(ctx)
456 selector = ctx.evaluate(self.selector)
457 keys = ctx.plural_categories
458 forms = [FTL.TextElement(part.strip()) for part in element.value.split(";")]
459
460 # The default CLDR form should be the last we have in DEFAULT_ORDER,
461 # usually `other`, but in some cases `many`. If we don't have a variant
462 # for that, we'll append one, using the, in CLDR order, last existing
463 # variant in the legacy translation. That may or may not be the last
464 # variant.
465 default_key = [key for key in reversed(self.DEFAULT_ORDER) if key in keys][0]
466
467 # Match keys to legacy forms in the order they are defined in Gecko's
468 # PluralForm.jsm. Filter out empty forms.
469 pairs = [(key, var) for key, var in zip(keys, forms) if var.value]
470
471 # A special case for legacy translations which don't define any
472 # plural forms.
473 if len(pairs) == 0:
474 return Transform.pattern_of()
475
476 # A special case for languages with one plural category or one legacy
477 # variant. We don't need to insert a SelectExpression for them.
478 if len(pairs) == 1:
479 _, only_form = pairs[0]
480 only_variant = ctx.evaluate(self.foreach(only_form))
481 return Transform.pattern_of(only_variant)
482
483 # Make sure the default key is defined. If it's missing, use the last
484 # form (in CLDR order) found in the legacy translation.
485 pairs.sort(key=lambda pair: self.DEFAULT_ORDER.index(pair[0]))
486 last_key, last_form = pairs[-1]
487 if last_key != default_key:
488 pairs.append((default_key, last_form))
489
490 def createVariant(key, form):
491 # Run the legacy plural form through `foreach` which returns an
492 # `FTL.Node` describing the transformation required for each
493 # variant. Then evaluate it to a migrated FTL node.
494 value = ctx.evaluate(self.foreach(form))
495 return FTL.Variant(
496 key=FTL.Identifier(key), value=value, default=key == default_key
497 )
498
499 select = FTL.SelectExpression(
500 selector=selector,
501 variants=[createVariant(key, form) for key, form in pairs],
502 )
503
504 return Transform.pattern_of(select)
505
506
507 class CONCAT(Transform):
508 """Create a new Pattern from Patterns, PatternElements and Expressions.
509
510 When called with at least two elements, `CONCAT` disables the trimming
511 behavior of the elements which are subclasses of `LegacySource` by
512 setting `trim=False`, unless `trim` has already been set explicitly. The
513 following two `CONCAT` calls are equivalent:
514
515 CONCAT(
516 FTL.TextElement("Hello"),
517 COPY("file.properties", "hello")
518 )
519
520 CONCAT(
521 FTL.TextElement("Hello"),
522 COPY("file.properties", "hello", trim=False)
523 )
524
525 Set `trim=True` explicitly to force trimming:
526
527 CONCAT(
528 FTL.TextElement("Hello "),
529 COPY("file.properties", "hello", trim=True)
530 )
531
532 When called with a single element and when the element is a subclass of
533 `LegacySource`, the trimming behavior is not changed. The following two
534 transforms are equivalent:
535
536 CONCAT(COPY("file.properties", "hello"))
537
538 COPY("file.properties", "hello")
539 """
540
541 def __init__(self, *elements, **kwargs):
542 # We want to support both passing elements as *elements in the
543 # migration specs and as elements=[]. The latter is used by
544 # FTL.BaseNode.traverse when it recreates the traversed node using its
545 # attributes as kwargs.
546 self.elements = list(kwargs.get("elements", elements))
547
548 # We want to make CONCAT(COPY()) equivalent to COPY() so that it's
549 # always safe (no-op) to wrap transforms in a CONCAT. This is used by
550 # the implementation of transforms_from.
551 if len(self.elements) > 1:
552 for elem in self.elements:
553 # Only change trim if it hasn't been set explicitly.
554 if isinstance(elem, LegacySource) and elem.trim is None:
555 elem.trim = False
556
557 def __call__(self, ctx):
558 return Transform.pattern_of(*self.elements)