| 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, Iterable, Iterator |
| 18 |
from re import compile |
| 19 |
|
| 20 |
from lxml import etree |
| 21 |
|
| 22 |
from ...message import ( |
| 23 |
CatchallKey, |
| 24 |
Expression, |
| 25 |
FunctionAnnotation, |
| 26 |
Markup, |
| 27 |
Message, |
| 28 |
PatternMessage, |
| 29 |
SelectMessage, |
| 30 |
VariableRef, |
| 31 |
) |
| 32 |
from ..data import Comment, Entry, Metadata, Resource, Section |
| 33 |
from ..format import Format |
| 34 |
|
| 35 |
plural_categories = ("zero", "one", "two", "few", "many", "other") |
| 36 |
xliff_ns = "urn:oasis:names:tc:xliff:document:1.2" |
| 37 |
xliff_g = f"{{{xliff_ns}}}g" |
| 38 |
|
| 39 |
# Exclude : for compatibility with MF2 |
| 40 |
xml_name_start = r"A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF" |
| 41 |
xml_name_rest = r".0-9\xB7\u0300-\u036F\u203F-\u2040-" |
| 42 |
xml_name = compile(f"[{xml_name_start}][{xml_name_start}{xml_name_rest}]*") |
| 43 |
|
| 44 |
# Android string resources contain four different kinds of localizable values: |
| 45 |
# |
| 46 |
# - HTML entity declarations, |
| 47 |
# which will be inserted into other strings during XML parsing. |
| 48 |
# - Strings with printf-style variables, |
| 49 |
# which also use "quotes" for special escaping behaviour. |
| 50 |
# These may include HTML as escaped string contents, |
| 51 |
# which will require fromHtml(String) processing |
| 52 |
# after being initially formatted with getString(int, Object...) |
| 53 |
# - Strings with HTML contents, which can't include variables, |
| 54 |
# and are generally used via setText(java.lang.CharSequence). |
| 55 |
# - Strings with ICU MessageFormat contents. |
| 56 |
# These also use "quotes" for special escaping behaviour. |
| 57 |
# ICU MessageFormat strings are not currently detected by this library. |
| 58 |
# |
| 59 |
# The source contents of each of the above needs to be parsed differently, |
| 60 |
# and message strings can be found in <string>, <string-array>, and <plurals> |
| 61 |
# elements, each of which also needs different parsing. |
| 62 |
# |
| 63 |
# For more information, see: |
| 64 |
# https://developer.android.com/guide/topics/resources/string-resource |
| 65 |
# https://developer.android.com/guide/topics/resources/localization#mark-message-parts |
| 66 |
|
| 67 |
|
| 68 |
def android_parse(source: str | bytes) -> Resource[Message, str]: |
| 69 |
""" |
| 70 |
Parse an Android strings XML file into a message resource. |
| 71 |
|
| 72 |
If any internal DOCTYPE entities are declared, |
| 73 |
they are included as messages in an "!ENTITY" section. |
| 74 |
|
| 75 |
Resource and entry attributes are parsed as metadata. |
| 76 |
|
| 77 |
All XML, Android, and printf escapes are unescaped |
| 78 |
except for %n, which has a platform-dependent meaning. |
| 79 |
|
| 80 |
Spans of text and entities wrapped in an <xliff:g> |
| 81 |
will be parsed as expressions with a "translate": "no" attribute. |
| 82 |
Spans including elements will be wrapped with open/close markup |
| 83 |
with a similar attribute. |
| 84 |
""" |
| 85 |
parser = etree.XMLParser(resolve_entities=False) |
| 86 |
root = etree.fromstring( |
| 87 |
source.encode() if isinstance(source, str) else source, parser |
| 88 |
) |
| 89 |
if root.tag != "resources": |
| 90 |
raise ValueError(f"Unsupported root node: {root}") |
| 91 |
if root.text and not root.text.isspace(): |
| 92 |
raise ValueError(f"Unexpected text in resource: {root.text}") |
| 93 |
res: Resource[Message, str] = Resource(Format.android, [Section((), [])]) |
| 94 |
root_comments = [c.text for c in root.itersiblings(etree.Comment, preceding=True)] |
| 95 |
if root_comments: |
| 96 |
root_comments.reverse() |
| 97 |
res.comment = comment_str(root_comments) |
| 98 |
res.meta = [Metadata(k, v) for k, v in root.attrib.items()] |
| 99 |
for ns, url in root.nsmap.items(): |
| 100 |
res.meta.append(Metadata(f"xmlns:{ns}" if ns else "xmlns", url)) |
| 101 |
entries = res.sections[0].entries |
| 102 |
|
| 103 |
dtd = root.getroottree().docinfo.internalDTD |
| 104 |
if dtd: |
| 105 |
entities: list[Entry[Message, str] | Comment] = [] |
| 106 |
for entity in dtd.iterentities(): |
| 107 |
name = entity.name |
| 108 |
if not name: |
| 109 |
raise ValueError(f"Unnamed entity: {entity}") |
| 110 |
value: Message = PatternMessage(list(parse_entity_value(entity.content))) |
| 111 |
entities.append(Entry((name,), value)) |
| 112 |
if entities: |
| 113 |
res.sections.insert(0, Section(("!ENTITY",), entities)) |
| 114 |
|
| 115 |
comment: list[str | None] = [] # TODO: should be list[str] |
| 116 |
for el in root: |
| 117 |
if el.tail and not el.tail.isspace(): |
| 118 |
raise ValueError(f"Unexpected text in resource: {el.tail}") |
| 119 |
if isinstance(el, etree._Comment): |
| 120 |
comment.append(el.text) |
| 121 |
if el.tail and el.tail.count("\n") > 1 and comment: |
| 122 |
entries.append(Comment(comment_str(comment))) |
| 123 |
comment.clear() |
| 124 |
else: |
| 125 |
name = el.attrib.get("name", None) |
| 126 |
if not name: |
| 127 |
raise ValueError(f"Unnamed {el.tag} entry: {el}") |
| 128 |
meta = [Metadata(k, v) for k, v in el.attrib.items() if k != "name"] |
| 129 |
|
| 130 |
if el.tag == "string": |
| 131 |
value = PatternMessage(list(parse_pattern(el))) |
| 132 |
entries.append(Entry((name,), value, comment_str(comment), meta)) |
| 133 |
|
| 134 |
elif el.tag == "plurals": |
| 135 |
if el.text and not el.text.isspace(): |
| 136 |
raise ValueError(f"Unexpected text in {name} plurals: {el.text}") |
| 137 |
value = parse_plurals(name, el, comment.extend) |
| 138 |
entries.append(Entry((name,), value, comment_str(comment), meta)) |
| 139 |
|
| 140 |
elif el.tag == "string-array": |
| 141 |
if el.text and not el.text.isspace(): |
| 142 |
raise ValueError( |
| 143 |
f"Unexpected text in {name} string-array: {el.text}" |
| 144 |
) |
| 145 |
idx = 0 |
| 146 |
for item in el: |
| 147 |
if isinstance(item, etree._Comment): |
| 148 |
comment.append(item.text) |
| 149 |
elif item.tag == "item": |
| 150 |
value = PatternMessage(list(parse_pattern(item))) |
| 151 |
ic = comment_str(comment) |
| 152 |
entries.append(Entry((name, str(idx)), value, ic, meta[:])) |
| 153 |
comment.clear() |
| 154 |
idx += 1 |
| 155 |
else: |
| 156 |
cs = etree.tostring(item, encoding="unicode") |
| 157 |
raise ValueError(f"Unsupported {name} string-array child: {cs}") |
| 158 |
if item.tail and not item.tail.isspace(): |
| 159 |
raise ValueError( |
| 160 |
f"Unexpected text in {name} string-array: {item.tail}" |
| 161 |
) |
| 162 |
|
| 163 |
else: |
| 164 |
es = etree.tostring(el, encoding="unicode") |
| 165 |
raise ValueError(f"Unsupported entry: {es}") |
| 166 |
if comment: |
| 167 |
comment.clear() |
| 168 |
return res |
| 169 |
|
| 170 |
|
| 171 |
dash_indent = compile(r" .+(\n - .*)+ ") |
| 172 |
|
| 173 |
|
| 174 |
def comment_str(body: list[str | None]) -> str: |
| 175 |
lines: list[str] = [] |
| 176 |
for comment in body: |
| 177 |
if comment: |
| 178 |
if dash_indent.fullmatch(comment): |
| 179 |
# A dash is considered as a part of the indent if it's aligned |
| 180 |
# with the last dash of <!-- in a top-level comment. |
| 181 |
lines.append(comment.replace("\n - ", "\n").strip(" ")) |
| 182 |
else: |
| 183 |
lines.append( |
| 184 |
"\n".join(line.strip() for line in comment.splitlines()).strip("\n") |
| 185 |
) |
| 186 |
return "\n\n".join(lines).strip("\n") |
| 187 |
|
| 188 |
|
| 189 |
entity_ref = compile(f"&({xml_name.pattern});") |
| 190 |
|
| 191 |
|
| 192 |
def parse_entity_value(src: str | None) -> Iterator[str | Expression]: |
| 193 |
if src: |
| 194 |
pos = 0 |
| 195 |
for m in entity_ref.finditer(src): |
| 196 |
start = m.start() |
| 197 |
if start > pos: |
| 198 |
yield src[pos:start] |
| 199 |
yield Expression(VariableRef(m[1]), FunctionAnnotation("entity")) |
| 200 |
pos = m.end() |
| 201 |
if pos < len(src): |
| 202 |
yield src[pos:] |
| 203 |
|
| 204 |
|
| 205 |
def parse_plurals( |
| 206 |
name: str, el: etree._Element, add_comment: Callable[[Iterable[str | None]], None] |
| 207 |
) -> SelectMessage: |
| 208 |
sel = Expression(VariableRef("quantity"), FunctionAnnotation("number")) |
| 209 |
msg = SelectMessage([sel], {}) |
| 210 |
var_comment: list[str | None] = [] |
| 211 |
for item in el: |
| 212 |
if isinstance(item, etree._Comment): |
| 213 |
var_comment.append(item.text) |
| 214 |
elif item.tag == "item": |
| 215 |
key = item.attrib.get("quantity", None) |
| 216 |
if key not in plural_categories: |
| 217 |
raise ValueError(f"Invalid quantity for {name} plurals item: {key}") |
| 218 |
if var_comment: |
| 219 |
add_comment( |
| 220 |
(f"{key}: {c}" for c in var_comment if c) |
| 221 |
if msg.variants |
| 222 |
else var_comment |
| 223 |
) |
| 224 |
var_comment.clear() |
| 225 |
msg.variants[(CatchallKey(key) if key == "other" else key,)] = list( |
| 226 |
parse_pattern(item) |
| 227 |
) |
| 228 |
else: |
| 229 |
cs = etree.tostring(item, encoding="unicode") |
| 230 |
raise ValueError(f"Unsupported {name} plurals child: {cs}") |
| 231 |
if item.tail and not item.tail.isspace(): |
| 232 |
raise ValueError(f"Unexpected text in {name} plurals: {item.tail}") |
| 233 |
return msg |
| 234 |
|
| 235 |
|
| 236 |
resource_ref = compile(r"@(?:\w+:)?\w+/\w+|\?(?:\w+:)?(\w+/)?\w+") |
| 237 |
|
| 238 |
|
| 239 |
def parse_pattern(el: etree._Element) -> Iterator[str | Expression | Markup]: |
| 240 |
if len(el) == 0 and el.text and resource_ref.fullmatch(el.text): |
| 241 |
# https://developer.android.com/guide/topics/resources/providing-resources#ResourcesFromXml |
| 242 |
yield Expression(el.text, FunctionAnnotation("reference")) |
| 243 |
else: |
| 244 |
flat = flatten(el) |
| 245 |
spaced = parse_quotes(flat) |
| 246 |
yield from parse_inline(spaced) |
| 247 |
|
| 248 |
|
| 249 |
def flatten(el: etree._Element) -> Iterator[str | Expression | Markup]: |
| 250 |
if el.text: |
| 251 |
yield el.text |
| 252 |
for child in el: |
| 253 |
if isinstance(child, etree._Entity): |
| 254 |
yield Expression(VariableRef(child.name), FunctionAnnotation("entity")) |
| 255 |
else: |
| 256 |
name = ( |
| 257 |
f"{child.prefix}:{etree.QName(child.tag).localname}" |
| 258 |
if child.prefix |
| 259 |
else child.tag |
| 260 |
) |
| 261 |
if child.tag == xliff_g: |
| 262 |
body = list(flatten(child)) |
| 263 |
if any( |
| 264 |
isinstance(gc, Expression) |
| 265 |
and gc.attributes.get("translate", None) == "no" |
| 266 |
or isinstance(gc, Markup) |
| 267 |
for gc in body |
| 268 |
): |
| 269 |
# Any <xliff:g> around elements needs to be rendered explicitly |
| 270 |
yield Markup("open", name, dict(child.attrib), {"translate": "no"}) |
| 271 |
yield from body |
| 272 |
yield Markup("close", name, attributes={"translate": "no"}) |
| 273 |
else: |
| 274 |
id = child.get("id", None) |
| 275 |
for gc in body: |
| 276 |
if isinstance(gc, str): |
| 277 |
options: dict[str, str | VariableRef] = dict(child.attrib) |
| 278 |
attr: dict[str, str | VariableRef | None] = { |
| 279 |
"translate": "no" |
| 280 |
} |
| 281 |
arg: str | VariableRef | None |
| 282 |
if id: |
| 283 |
arg = VariableRef(get_var_name(id)) |
| 284 |
attr["source"] = gc |
| 285 |
elif gc.startswith(("%", "{")): |
| 286 |
arg = VariableRef(get_var_name(gc)) |
| 287 |
attr["source"] = gc |
| 288 |
else: |
| 289 |
arg = gc |
| 290 |
yield Expression( |
| 291 |
arg, |
| 292 |
FunctionAnnotation(name, options) if options else None, |
| 293 |
attr, |
| 294 |
) |
| 295 |
else: |
| 296 |
gc.attributes["translate"] = "no" |
| 297 |
gc.annotation.options = dict(child.attrib) # type: ignore[union-attr] |
| 298 |
yield gc |
| 299 |
else: |
| 300 |
yield Markup("open", name, options=dict(child.attrib)) |
| 301 |
yield from flatten(child) |
| 302 |
yield Markup("close", name) |
| 303 |
if child.tail: |
| 304 |
yield child.tail |
| 305 |
|
| 306 |
|
| 307 |
double_quote = compile(r'(?<!\\)"') |
| 308 |
spaces = compile(r"\s+") |
| 309 |
|
| 310 |
|
| 311 |
def parse_quotes( |
| 312 |
iter: Iterator[str | Expression | Markup], |
| 313 |
) -> Iterator[str | Expression | Markup]: |
| 314 |
stack: list[str | Expression] = [] |
| 315 |
|
| 316 |
def collapse_stack() -> Iterator[str | Expression | Markup]: |
| 317 |
yield '"' |
| 318 |
for part in stack: |
| 319 |
yield spaces.sub(" ", part) if isinstance(part, str) else part |
| 320 |
|
| 321 |
for part in iter: |
| 322 |
if isinstance(part, str): |
| 323 |
pos = 0 |
| 324 |
quoted = bool(stack) |
| 325 |
for m in double_quote.finditer(part): |
| 326 |
prev = part[pos : m.start()] |
| 327 |
if quoted: |
| 328 |
if stack: |
| 329 |
yield from stack |
| 330 |
stack.clear() |
| 331 |
if prev: |
| 332 |
yield prev |
| 333 |
elif prev: |
| 334 |
yield spaces.sub(" ", prev) |
| 335 |
quoted = not quoted |
| 336 |
pos = m.end() |
| 337 |
last = part[pos:] |
| 338 |
if quoted: |
| 339 |
stack.append(last) |
| 340 |
elif last: |
| 341 |
yield spaces.sub(" ", last) |
| 342 |
elif stack: |
| 343 |
if ( |
| 344 |
isinstance(part, Markup) |
| 345 |
or part.attributes.get("translate", None) == "no" |
| 346 |
): |
| 347 |
yield from collapse_stack() |
| 348 |
stack.clear() |
| 349 |
yield part |
| 350 |
else: # Expression |
| 351 |
stack.append(part) |
| 352 |
else: |
| 353 |
yield part |
| 354 |
if stack: |
| 355 |
yield from collapse_stack() |
| 356 |
|
| 357 |
|
| 358 |
inline_re = compile( |
| 359 |
r"""\\([@?nt'"\\])|""" |
| 360 |
r"\\u([0-9]{4})|" |
| 361 |
r"(<[^%>]+>)|" |
| 362 |
r"(%(?:[1-9]\$)?[-#+ 0,(]?[0-9.]*([a-su-zA-SU-Z%]|[tT][a-zA-Z]))" |
| 363 |
) |
| 364 |
|
| 365 |
|
| 366 |
def parse_inline( |
| 367 |
iter: Iterator[str | Expression | Markup], |
| 368 |
) -> Iterator[str | Expression | Markup]: |
| 369 |
acc = "" |
| 370 |
for part in iter: |
| 371 |
if not isinstance(part, str): |
| 372 |
if acc: |
| 373 |
yield acc |
| 374 |
acc = "" |
| 375 |
yield part |
| 376 |
else: |
| 377 |
pos = 0 |
| 378 |
for m in inline_re.finditer(part): |
| 379 |
start = m.start() |
| 380 |
if start > pos: |
| 381 |
acc += part[pos:start] |
| 382 |
if m[1]: |
| 383 |
# Special character |
| 384 |
c = m[1] |
| 385 |
acc += "\n" if c == "n" else "\t" if c == "t" else c |
| 386 |
elif m[2]: |
| 387 |
# Unicode escape |
| 388 |
acc += chr(int(m[2])) |
| 389 |
elif m[3]: |
| 390 |
# Escaped HTML element, e.g. <b> |
| 391 |
# HTML elements containing internal % formatting are not wrapped as literals |
| 392 |
if acc: |
| 393 |
yield acc |
| 394 |
acc = "" |
| 395 |
yield Expression(m[3], FunctionAnnotation("html")) |
| 396 |
else: |
| 397 |
if acc: |
| 398 |
yield acc |
| 399 |
acc = "" |
| 400 |
conversion = m[5] |
| 401 |
if conversion == "%": |
| 402 |
# Literal % |
| 403 |
yield Expression("%", attributes={"source": m[4]}) |
| 404 |
else: |
| 405 |
# Placeholder |
| 406 |
func: str | None |
| 407 |
# TODO post-py38: should be a match |
| 408 |
if conversion in {"b", "B"}: |
| 409 |
func = "boolean" |
| 410 |
elif conversion in {"c", "C", "s", "S"}: |
| 411 |
func = "string" |
| 412 |
elif conversion in {"d", "h", "H", "o", "x", "X"}: |
| 413 |
func = "integer" |
| 414 |
elif conversion in {"a", "A", "e", "E", "f", "g", "G"}: |
| 415 |
func = "number" |
| 416 |
else: |
| 417 |
c0 = conversion[0] |
| 418 |
func = "datetime" if c0 == "t" or c0 == "T" else None |
| 419 |
name = get_var_name(m[4]) |
| 420 |
yield Expression( |
| 421 |
VariableRef(name), |
| 422 |
FunctionAnnotation(func) if func else None, |
| 423 |
{"source": m[4]}, |
| 424 |
) |
| 425 |
pos = m.end() |
| 426 |
acc += part[pos:] |
| 427 |
if acc: |
| 428 |
yield acc |
| 429 |
|
| 430 |
|
| 431 |
printf = compile(r"%([1-9]\$)?") |
| 432 |
not_name_char = compile(f"[^{xml_name_start}{xml_name_rest}]") |
| 433 |
not_name_start = compile(f"[^{xml_name_start}]") |
| 434 |
|
| 435 |
|
| 436 |
def get_var_name(src: str) -> str: |
| 437 |
"""Returns a valid MF2 name.""" |
| 438 |
pm = printf.match(src) |
| 439 |
if pm: |
| 440 |
return f"arg{pm[1][0]}" if pm[1] else "arg" |
| 441 |
name = not_name_char.sub("", src) |
| 442 |
if not_name_start.match(name): |
| 443 |
name = name[1:] |
| 444 |
return name or "arg" |