Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/util.py

raw
1 import textwrap
2
3 import fluent.syntax.ast as FTL
4 from fluent.syntax.parser import FluentParser, FluentParserStream
5
6
7 fluent_parser = FluentParser(with_spans=False)
8
9
10 def parse(Parser, string):
11 if Parser is FluentParser:
12 return fluent_parser.parse(string)
13
14 # Parsing a legacy resource.
15
16 # Parse the string into the internal Context.
17 parser = Parser()
18 # compare-locales expects ASCII strings.
19 parser.readContents(string.encode("utf8"))
20 # Transform the parsed result which is an iterator into a dict.
21 return {ent.key: ent for ent in parser}
22
23
24 def ftl_resource_to_ast(code):
25 return fluent_parser.parse(ftl(code))
26
27
28 def ftl_resource_to_json(code):
29 return fluent_parser.parse(ftl(code)).to_json()
30
31
32 def ftl_pattern_to_json(code):
33 ps = FluentParserStream(ftl(code))
34 return fluent_parser.maybe_get_pattern(ps).to_json()
35
36
37 def to_json(merged_iter):
38 return {path: resource.to_json() for path, resource in merged_iter}
39
40
41 LOCALIZABLE_ENTRIES = (FTL.Message, FTL.Term)
42
43
44 def get_message(body, ident):
45 """Get message called `ident` from the `body` iterable."""
46 for entity in body:
47 if isinstance(entity, LOCALIZABLE_ENTRIES) and entity.id.name == ident:
48 return entity
49
50
51 def get_transform(body, ident):
52 """Get entity called `ident` from the `body` iterable."""
53 for transform in body:
54 if transform.id.name == ident:
55 return transform
56
57
58 def skeleton(node):
59 """Create a skeleton copy of the given node.
60
61 For localizable entries, the value is None and the attributes are {}.
62 That's not a valid Fluent entry, so it requires further manipulation to
63 set values and/or attributes.
64 """
65 if isinstance(node, LOCALIZABLE_ENTRIES):
66 return type(node)(id=node.id.clone(), value=None)
67 return node.clone()
68
69
70 def ftl(code):
71 """Nicer indentation for FTL code.
72
73 The code returned by this function is meant to be compared against the
74 output of the FTL Serializer. The input code will end with a newline to
75 match the output of the serializer.
76 """
77
78 # The code might be triple-quoted.
79 code = code.lstrip("\n")
80
81 return textwrap.dedent(code)
82
83
84 def fold(fun, node, init):
85 """Reduce `node` to a single value using `fun`.
86
87 Apply `fun` against an accumulator and each subnode of `node` (in postorder
88 traversal) to reduce it to a single value.
89 """
90
91 def fold_(vals, acc):
92 if not vals:
93 return acc
94
95 head = list(vals)[0]
96 tail = list(vals)[1:]
97
98 if isinstance(head, FTL.BaseNode):
99 acc = fold(fun, head, acc)
100 if isinstance(head, list):
101 acc = fold_(head, acc)
102 if isinstance(head, dict):
103 acc = fold_(head.values(), acc)
104
105 return fold_(tail, fun(acc, head))
106
107 return fold_(vars(node).values(), init)