Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/xliff/parse_xcode.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 Iterator
18 from dataclasses import dataclass
19 from re import compile
20 from typing import NoReturn
21
22 from lxml import etree
23
24 from ...message import (
25 CatchallKey,
26 Expression,
27 FunctionAnnotation,
28 SelectMessage,
29 VariableRef,
30 Variants,
31 )
32 from ..data import Entry, Metadata
33 from .common import attrib_as_metadata
34
35
36 @dataclass
37 class XcodePluralElements:
38 unit: etree._Element
39 source: etree._Element
40 target: etree._Element | None
41
42
43 @dataclass
44 class XcodePlural:
45 var_name: str
46 format_key: XcodePluralElements | None
47 variants: dict[str, XcodePluralElements]
48
49
50 plural_categories = ("zero", "one", "two", "few", "many", "other")
51 variant_key = compile(r"%#@([a-zA-Z_]\w*)@")
52 # https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
53 printf = compile(
54 r"%([1-9]\$)?[-#+ 0,]?[0-9.]*(?:(?:hh?|ll?|qztj)[douxX]|L[aAeEfFgG]|[@%aAcCdDeEfFgGoOspSuUxX])"
55 )
56
57
58 def parse_xliff_stringsdict(
59 ns: str, body: etree._Element
60 ) -> list[Entry[SelectMessage, str]] | None:
61 plurals: dict[str, XcodePlural] = {}
62 for unit in body:
63 if unit.tag != f"{ns}trans-unit":
64 return None
65 if unit.text and not unit.text.isspace():
66 raise ValueError(f"Unexpected text in <trans-unit>: {unit.text}")
67 id = unit.attrib.get("id", None)
68 if id and id.startswith("/") and id.endswith(":dict/:string"):
69 # If we get this far, this is clearly trying to be an Xcode plural.
70 # Therefore, treat any further deviations as errors.
71 parse_xliff_stringsdict_unit(ns, plurals, unit)
72 else:
73 return None
74
75 entries = []
76 for msg_id, plural in plurals.items():
77 selector = Expression(
78 VariableRef(plural.var_name),
79 FunctionAnnotation("number"),
80 {"source": plural.format_key.source.text if plural.format_key else None},
81 )
82 meta: list[Metadata[str]] = []
83 if plural.format_key:
84 meta += attrib_as_metadata(plural.format_key.unit, "format", ("id",))
85 if plural.format_key.target is not None:
86 meta += attrib_as_metadata(plural.format_key.target, "format/target")
87 variants: Variants = {}
88 for key, variant in plural.variants.items():
89 meta += attrib_as_metadata(variant.unit, key, ("id",))
90 meta.append(Metadata(f"{key}/source", variant.source.text or ""))
91 if variant.target is None:
92 pattern_src = None
93 else:
94 meta += attrib_as_metadata(variant.target, f"{key}/target")
95 pattern_src = variant.target.text
96 variants[(CatchallKey("other") if key == "other" else key,)] = list(
97 parse_pattern(pattern_src)
98 )
99 entries.append(Entry((msg_id,), SelectMessage([selector], variants), meta=meta))
100 return entries
101
102
103 def parse_xliff_stringsdict_unit(
104 ns: str, plurals: dict[str, XcodePlural], unit: etree._Element
105 ) -> None:
106 id_parts = unit.attrib["id"].split(":dict/")
107 msg_id = id_parts[0][1:]
108
109 def error(message: str) -> NoReturn:
110 raise ValueError(f"{message} in Xcode plural definition {unit.attrib['id']}")
111
112 source = None
113 target = None
114 for el in unit:
115 if len(el) > 0:
116 error(f"Unexpected child elements of <{el.tag}>")
117 if el.tag == f"{ns}source":
118 if el.attrib:
119 error("Unexpected attributes of <source>")
120 if source is None:
121 source = el
122 else:
123 error("Duplicate <source>")
124 elif el.tag == f"{ns}target":
125 if target is None:
126 target = el
127 else:
128 error("Duplicate <target>")
129 elif el.tag == f"{ns}note":
130 if el.attrib or el.text:
131 error("Unexpected not-empty <note>")
132 else:
133 error(f"Unexpected <{el.tag}>")
134 if el.tail and not el.tail.isspace():
135 raise ValueError(f"Unexpected text in <trans-unit>: {el.tail}")
136 if source is None:
137 error("Missing <source>")
138 var_data = XcodePluralElements(unit, source, target)
139
140 if id_parts[1] == "NSStringLocalizedFormatKey":
141 if len(id_parts) != 3:
142 error("Unexpected Xcode plurals id")
143 var_match = variant_key.search(source.text or "")
144 if var_match is None:
145 error("Unexpected <source> value")
146 if msg_id in plurals:
147 prev = plurals[msg_id]
148 if prev.format_key is None:
149 prev.format_key = var_data
150 else:
151 error("Duplicate NSStringLocalizedFormatKey")
152 if var_match[1] != prev.var_name:
153 error("Mismatching key values")
154 else:
155 plurals[msg_id] = XcodePlural(var_match[1], var_data, {})
156 else:
157 if len(id_parts) != 4:
158 error("Unexpected Xcode plurals id")
159 var_name = id_parts[1]
160 plural_cat = id_parts[2]
161 if plural_cat not in plural_categories:
162 error("Invalid plural category")
163 if msg_id in plurals:
164 prev = plurals[msg_id]
165 if var_name != prev.var_name:
166 error("Mismatching key values")
167 if plural_cat in prev.variants:
168 error(f"Duplicate {plural_cat}")
169 prev.variants[plural_cat] = var_data
170 else:
171 plurals[msg_id] = XcodePlural(
172 var_name, None, variants={plural_cat: var_data}
173 )
174
175
176 def parse_pattern(src: str | None) -> Iterator[str | Expression]:
177 if not src:
178 return
179 pos = 0
180 for m in printf.finditer(src):
181 start = m.start()
182 if start > pos:
183 yield src[pos:start]
184 source = m[0]
185 format = source[-1]
186 if format == "%":
187 yield Expression("%", attributes={"source": source})
188 else:
189 name: str
190 func: str | None
191 # TODO post-py38: should be a match
192 if format in {"c", "C", "s", "S"}:
193 name = "str"
194 func = "string"
195 elif format in {"d", "D", "o", "O", "p", "u", "U", "x", "X"}:
196 name = "int"
197 func = "integer"
198 elif format in {"a", "A", "e", "E", "f", "g", "G"}:
199 name = "num"
200 func = "number"
201 else:
202 name = "arg"
203 func = None
204 if m[1]:
205 name += m[1][0]
206 yield Expression(
207 VariableRef(name),
208 FunctionAnnotation(func) if func else None,
209 attributes={"source": source},
210 )
211 pos = m.end()
212 if pos < len(src):
213 yield src[pos:]