| 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 Generator |
| 18 |
from itertools import product |
| 19 |
from re import finditer |
| 20 |
from typing import Any, Literal, Tuple, cast, overload |
| 21 |
|
| 22 |
from fluent.syntax import FluentParser |
| 23 |
from fluent.syntax import ast as ftl |
| 24 |
|
| 25 |
from ... import message as msg |
| 26 |
from .. import data as res |
| 27 |
from ..format import Format |
| 28 |
|
| 29 |
|
| 30 |
@overload |
| 31 |
def fluent_parse( |
| 32 |
source: bytes | str | ftl.Resource, |
| 33 |
*, |
| 34 |
as_ftl_patterns: Literal[False] = False, |
| 35 |
with_linepos: bool = True, |
| 36 |
) -> res.Resource[msg.Message, str]: ... |
| 37 |
|
| 38 |
|
| 39 |
@overload |
| 40 |
def fluent_parse( |
| 41 |
source: bytes | str | ftl.Resource, |
| 42 |
*, |
| 43 |
as_ftl_patterns: Literal[True], |
| 44 |
with_linepos: bool = True, |
| 45 |
) -> res.Resource[ftl.Pattern, str]: ... |
| 46 |
|
| 47 |
|
| 48 |
def fluent_parse( |
| 49 |
source: bytes | str | ftl.Resource, |
| 50 |
*, |
| 51 |
as_ftl_patterns: bool = False, |
| 52 |
with_linepos: bool = True, |
| 53 |
) -> res.Resource[msg.Message, Any] | res.Resource[ftl.Pattern, Any]: |
| 54 |
""" |
| 55 |
Parse a .ftl file into a message resource. |
| 56 |
|
| 57 |
Message and term references are represented by `message` function annotations, |
| 58 |
with term identifiers prefixed with a `-`. |
| 59 |
|
| 60 |
By default, messages are parsed as Messages; |
| 61 |
to keep them as Fluent Patterns, use `as_ftl_patterns=True`. |
| 62 |
|
| 63 |
Function names are lower-cased, so e.g. the Fluent `NUMBER` is `number` in the Resource. |
| 64 |
|
| 65 |
The parsed resource will not include any metadata. |
| 66 |
""" |
| 67 |
|
| 68 |
if isinstance(source, ftl.Resource): |
| 69 |
fluent_res = source |
| 70 |
lpm = None # Source is required for line positions |
| 71 |
else: |
| 72 |
source_str = source if isinstance(source, str) else source.decode("utf-8") |
| 73 |
fluent_res = FluentParser(with_spans=with_linepos).parse(source_str) |
| 74 |
lpm = LinePosMapper(source_str) if with_linepos else None |
| 75 |
|
| 76 |
entries: list[res.Entry[Any, Any] | res.Comment] = [] |
| 77 |
section = res.Section((), entries) |
| 78 |
resource = res.Resource(Format.fluent, [section]) |
| 79 |
fluent_body = fluent_res.body |
| 80 |
if fluent_body and isinstance(fluent_body[0], ftl.Comment): |
| 81 |
resource.meta.append(res.Metadata("info", fluent_body[0].content)) |
| 82 |
fluent_body = fluent_body[1:] |
| 83 |
for entry in fluent_body: |
| 84 |
if isinstance(entry, ftl.Message) or isinstance(entry, ftl.Term): |
| 85 |
entries.extend(patterns(entry, as_ftl_patterns, lpm)) |
| 86 |
elif isinstance(entry, ftl.ResourceComment): |
| 87 |
if entry.content: |
| 88 |
resource.comment = ( |
| 89 |
(resource.comment.rstrip() + "\n\n" + entry.content) |
| 90 |
if resource.comment |
| 91 |
else entry.content |
| 92 |
) |
| 93 |
elif isinstance(entry, ftl.GroupComment): |
| 94 |
if entries or section.comment: |
| 95 |
entries = [] |
| 96 |
section = res.Section((), entries, comment=entry.content or "") |
| 97 |
if lpm and entry.span: |
| 98 |
span = entry.span |
| 99 |
section.linepos = lpm.get_linepos( |
| 100 |
span.start, span.start, span.start, span.end |
| 101 |
) |
| 102 |
resource.sections.append(section) |
| 103 |
else: |
| 104 |
section.comment = entry.content or "" |
| 105 |
if lpm and entry.span: |
| 106 |
span = entry.span |
| 107 |
section.linepos = lpm.get_linepos( |
| 108 |
span.start, span.start, span.start, span.end |
| 109 |
) |
| 110 |
elif isinstance(entry, ftl.Comment): |
| 111 |
if entry.content: |
| 112 |
entries.append(res.Comment(entry.content)) |
| 113 |
else: # Junk |
| 114 |
try: |
| 115 |
message = entry.annotations[0].message |
| 116 |
except Exception: |
| 117 |
message = "" |
| 118 |
raise ValueError(message or "Fluent parser error") |
| 119 |
return resource |
| 120 |
|
| 121 |
|
| 122 |
def patterns( |
| 123 |
ftl_entry: ftl.Message | ftl.Term, |
| 124 |
as_ftl_patterns: bool, |
| 125 |
lpm: LinePosMapper | None, |
| 126 |
) -> Generator[res.Entry[msg.Message, Any] | res.Entry[ftl.Pattern, Any], None, None]: |
| 127 |
message = (lambda m: m) if as_ftl_patterns else fluent_parse_message |
| 128 |
id = ftl_entry.id.name |
| 129 |
if isinstance(ftl_entry, ftl.Term): |
| 130 |
id = "-" + id |
| 131 |
comment = ftl_entry.comment.content or "" if ftl_entry.comment else "" |
| 132 |
if ftl_entry.value: |
| 133 |
entry: res.Entry[Any, Any] = res.Entry( |
| 134 |
id=(id,), value=message(ftl_entry.value), comment=comment |
| 135 |
) |
| 136 |
if lpm and ftl_entry.span and ftl_entry.value.span: |
| 137 |
v_span = ftl_entry.value.span |
| 138 |
c_span = ( |
| 139 |
ftl_entry.comment.span |
| 140 |
if comment and ftl_entry.comment and ftl_entry.comment.span |
| 141 |
else ftl_entry.span |
| 142 |
) |
| 143 |
k_span = ftl_entry.id.span or ftl_entry.span |
| 144 |
entry.linepos = lpm.get_linepos( |
| 145 |
c_span.start, k_span.start, v_span.start, v_span.end |
| 146 |
) |
| 147 |
yield entry |
| 148 |
if comment: |
| 149 |
comment = "" |
| 150 |
for attr in ftl_entry.attributes: |
| 151 |
entry = res.Entry( |
| 152 |
id=(id, attr.id.name), value=message(attr.value), comment=comment |
| 153 |
) |
| 154 |
if lpm and attr.span: |
| 155 |
span = attr.span |
| 156 |
c_span = ( |
| 157 |
ftl_entry.comment.span |
| 158 |
if comment and ftl_entry.comment and ftl_entry.comment.span |
| 159 |
else span |
| 160 |
) |
| 161 |
k_span = attr.id.span or span |
| 162 |
v_span = attr.value.span or span |
| 163 |
entry.linepos = lpm.get_linepos( |
| 164 |
c_span.start, k_span.start, v_span.start, span.end |
| 165 |
) |
| 166 |
yield entry |
| 167 |
if comment: |
| 168 |
comment = "" |
| 169 |
|
| 170 |
|
| 171 |
def fluent_parse_message(ftl_pattern: ftl.Pattern) -> msg.Message: |
| 172 |
sel_data = find_selectors(ftl_pattern, []) |
| 173 |
selectors = [sd[0] for sd in sel_data] |
| 174 |
filter: list[Key | None] = [None] * len(selectors) |
| 175 |
msg_variants: dict[tuple[Key, ...], msg.Pattern] |
| 176 |
if selectors: |
| 177 |
key_lists = [list(dict.fromkeys(sd[2])) for sd in sel_data] |
| 178 |
for keys in key_lists: |
| 179 |
keys.sort(key=lambda k: (k[2], not k[1])) |
| 180 |
msg_variants = {key: [] for key in product(*key_lists)} |
| 181 |
else: |
| 182 |
msg_variants = {(): []} |
| 183 |
|
| 184 |
def add_pattern(ftl_pattern: ftl.Pattern) -> None: |
| 185 |
el: ( |
| 186 |
ftl.TextElement |
| 187 |
| ftl.Placeable |
| 188 |
| ftl.InlineExpression |
| 189 |
| ftl.SelectExpression |
| 190 |
) |
| 191 |
for el in ftl_pattern.elements: |
| 192 |
while isinstance(el, ftl.Placeable): |
| 193 |
el = el.expression |
| 194 |
if isinstance(el, ftl.SelectExpression): |
| 195 |
msg_sel = next(sd[0] for sd in sel_data if el.selector in sd[1]) |
| 196 |
idx = selectors.index(msg_sel) |
| 197 |
prev_filt = filter[idx] |
| 198 |
for v in el.variants: |
| 199 |
filter[idx] = variant_key(v) |
| 200 |
add_pattern(v.value) |
| 201 |
filter[idx] = prev_filt |
| 202 |
else: |
| 203 |
for keys, msg_pattern in msg_variants.items(): |
| 204 |
if all( |
| 205 |
(filt is None or key == filt) for key, filt in zip(keys, filter) |
| 206 |
): |
| 207 |
if isinstance(el, ftl.TextElement): |
| 208 |
if msg_pattern and isinstance(msg_pattern[-1], str): |
| 209 |
msg_pattern[-1] += el.value |
| 210 |
else: |
| 211 |
msg_pattern.append(el.value) |
| 212 |
else: |
| 213 |
msg_pattern.append(inline_expression(el)) |
| 214 |
|
| 215 |
add_pattern(ftl_pattern) |
| 216 |
|
| 217 |
if selectors: |
| 218 |
variants = { |
| 219 |
tuple(map(message_key, keys)): msg_pattern |
| 220 |
for keys, msg_pattern in msg_variants.items() |
| 221 |
if msg_pattern |
| 222 |
} |
| 223 |
return msg.SelectMessage(selectors, variants) |
| 224 |
else: |
| 225 |
return msg.PatternMessage(next(iter(msg_variants.values()))) |
| 226 |
|
| 227 |
|
| 228 |
Key = Tuple[str, bool, bool] |
| 229 |
"(name, is_numeric, is_default)" |
| 230 |
|
| 231 |
|
| 232 |
def variant_key(v: ftl.Variant) -> Key: |
| 233 |
name: str |
| 234 |
is_numeric: bool |
| 235 |
if isinstance(v.key, ftl.Identifier): |
| 236 |
name = v.key.name |
| 237 |
is_numeric = False |
| 238 |
else: |
| 239 |
name = v.key.value |
| 240 |
is_numeric = True |
| 241 |
return (name, is_numeric, v.default) |
| 242 |
|
| 243 |
|
| 244 |
def message_key(key: Key) -> str | msg.CatchallKey: |
| 245 |
name, _, is_default = key |
| 246 |
return msg.CatchallKey(name) if is_default else name |
| 247 |
|
| 248 |
|
| 249 |
def find_selectors( |
| 250 |
pattern: ftl.Pattern, |
| 251 |
result: list[tuple[msg.Expression, list[ftl.InlineExpression], list[Key]]], |
| 252 |
) -> list[tuple[msg.Expression, list[ftl.InlineExpression], list[Key]]]: |
| 253 |
for el in pattern.elements: |
| 254 |
if isinstance(el, ftl.Placeable) and isinstance( |
| 255 |
el.expression, ftl.SelectExpression |
| 256 |
): |
| 257 |
ftl_sel = el.expression.selector |
| 258 |
keys = [variant_key(v) for v in el.expression.variants] |
| 259 |
msg_sel = select_expression(ftl_sel, keys) |
| 260 |
prev = next((x for x in result if x[0] == msg_sel), None) |
| 261 |
if prev: |
| 262 |
_, ftl_list, key_list = prev |
| 263 |
ftl_list.append(ftl_sel) |
| 264 |
key_list += keys |
| 265 |
else: |
| 266 |
result.append((msg_sel, [ftl_sel], keys)) |
| 267 |
for v in el.expression.variants: |
| 268 |
find_selectors(v.value, result) |
| 269 |
return result |
| 270 |
|
| 271 |
|
| 272 |
def select_expression(ftl_sel: ftl.InlineExpression, keys: list[Key]) -> msg.Expression: |
| 273 |
plural_categories = ("zero", "one", "two", "few", "many", "other") |
| 274 |
if isinstance(ftl_sel, ftl.VariableReference): |
| 275 |
name = ( |
| 276 |
"number" |
| 277 |
if all( |
| 278 |
is_numeric or name in plural_categories for name, is_numeric, _ in keys |
| 279 |
) |
| 280 |
else "string" |
| 281 |
) |
| 282 |
return msg.Expression( |
| 283 |
msg.VariableRef(ftl_sel.id.name), msg.FunctionAnnotation(name) |
| 284 |
) |
| 285 |
elif isinstance(ftl_sel, ftl.StringLiteral): |
| 286 |
return msg.Expression(literal_value(ftl_sel), msg.FunctionAnnotation("string")) |
| 287 |
else: |
| 288 |
return inline_expression(ftl_sel) |
| 289 |
|
| 290 |
|
| 291 |
def inline_expression(exp: ftl.InlineExpression) -> msg.Expression: |
| 292 |
if isinstance(exp, ftl.NumberLiteral): |
| 293 |
value = exp.value |
| 294 |
return msg.Expression(value, msg.FunctionAnnotation("number")) |
| 295 |
elif isinstance(exp, ftl.StringLiteral): |
| 296 |
value = exp.parse().get("value") or "" |
| 297 |
return msg.Expression(value) |
| 298 |
elif isinstance(exp, ftl.MessageReference): |
| 299 |
name = exp.id.name |
| 300 |
if exp.attribute is not None: |
| 301 |
name += "." + exp.attribute.name |
| 302 |
return msg.Expression(name, msg.FunctionAnnotation("message")) |
| 303 |
elif isinstance(exp, ftl.TermReference): |
| 304 |
name = "-" + exp.id.name |
| 305 |
if exp.attribute is not None: |
| 306 |
name += "." + exp.attribute.name |
| 307 |
ftl_named = exp.arguments.named if exp.arguments else [] |
| 308 |
return msg.Expression( |
| 309 |
name, |
| 310 |
msg.FunctionAnnotation( |
| 311 |
"message", |
| 312 |
{opt.name.name: literal_value(opt.value) for opt in ftl_named}, |
| 313 |
), |
| 314 |
) |
| 315 |
elif isinstance(exp, ftl.VariableReference): |
| 316 |
name = exp.id.name |
| 317 |
return msg.Expression(msg.VariableRef(name)) |
| 318 |
else: # ftl.FunctionReference |
| 319 |
name = exp.id.name.lower() |
| 320 |
if len(exp.arguments.positional) > 1: |
| 321 |
raise ValueError( |
| 322 |
f"Functions with more than one positional argument are not supported: {name}" |
| 323 |
) |
| 324 |
ftl_arg: ftl.Placeable | ftl.InlineExpression | None = next( |
| 325 |
iter(exp.arguments.positional), None |
| 326 |
) |
| 327 |
while isinstance(ftl_arg, ftl.Placeable): |
| 328 |
ftl_arg = cast(ftl.InlineExpression, ftl_arg.expression) |
| 329 |
arg: str | msg.VariableRef | None |
| 330 |
if not ftl_arg: |
| 331 |
arg = None |
| 332 |
elif isinstance(ftl_arg, ftl.NumberLiteral) or isinstance( |
| 333 |
ftl_arg, ftl.StringLiteral |
| 334 |
): |
| 335 |
arg = literal_value(ftl_arg) |
| 336 |
elif isinstance(ftl_arg, ftl.VariableReference): |
| 337 |
arg = msg.VariableRef(ftl_arg.id.name) |
| 338 |
else: |
| 339 |
raise ValueError(f"Unexpected value: {ftl_arg}") |
| 340 |
ftl_named = exp.arguments.named |
| 341 |
return msg.Expression( |
| 342 |
arg, |
| 343 |
msg.FunctionAnnotation( |
| 344 |
name, |
| 345 |
{opt.name.name: literal_value(opt.value) for opt in ftl_named}, |
| 346 |
), |
| 347 |
) |
| 348 |
|
| 349 |
|
| 350 |
def literal_value(arg: ftl.NumberLiteral | ftl.StringLiteral) -> str: |
| 351 |
return ( |
| 352 |
arg.value |
| 353 |
if isinstance(arg, ftl.NumberLiteral) |
| 354 |
else arg.parse().get("value") or "" |
| 355 |
) |
| 356 |
|
| 357 |
|
| 358 |
class LinePosMapper: |
| 359 |
def __init__(self, src: str) -> None: |
| 360 |
self._len = len(src) |
| 361 |
self._newlines = [m.start() for m in finditer("\n", src)] |
| 362 |
|
| 363 |
def _get_line(self, char_idx: int) -> int: |
| 364 |
# Treat the end of the string as a newline. |
| 365 |
if not self._newlines and char_idx >= self._len: |
| 366 |
return 2 |
| 367 |
return next( |
| 368 |
(idx + 1 for idx, nl in enumerate(self._newlines) if nl > char_idx), |
| 369 |
len(self._newlines) + 1, |
| 370 |
) |
| 371 |
|
| 372 |
def get_linepos(self, start: int, key: int, value: int, end: int) -> res.LinePos: |
| 373 |
start_line = self._get_line(start) |
| 374 |
key_line = start_line if key == start else self._get_line(key) |
| 375 |
value_line = key_line if value == key else self._get_line(value) |
| 376 |
end_line = self._get_line(end) |
| 377 |
return res.LinePos(start_line, key_line, value_line, end_line) |