| 1 |
"""Fluent AST helpers. |
| 2 |
|
| 3 |
The functions defined in this module offer a shorthand for defining common AST |
| 4 |
nodes. |
| 5 |
|
| 6 |
They take a string argument and immediately return a corresponding AST node. |
| 7 |
(As opposed to Transforms which are AST nodes on their own and only return the |
| 8 |
migrated AST nodes when they are evaluated by a MigrationContext.) """ |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
from typing import List |
| 12 |
|
| 13 |
from fluent.syntax import FluentParser, ast as FTL |
| 14 |
from fluent.syntax.visitor import Transformer |
| 15 |
from .transforms import Transform, CONCAT, COPY, COPY_PATTERN |
| 16 |
from .errors import NotSupportedError, InvalidTransformError |
| 17 |
|
| 18 |
|
| 19 |
def VARIABLE_REFERENCE(name): |
| 20 |
"""Create an ExternalArgument expression.""" |
| 21 |
|
| 22 |
return FTL.VariableReference(id=FTL.Identifier(name)) |
| 23 |
|
| 24 |
|
| 25 |
def MESSAGE_REFERENCE(name): |
| 26 |
"""Create a MessageReference expression. |
| 27 |
|
| 28 |
If the passed name contains a `.`, we're generating |
| 29 |
a message reference with an attribute. |
| 30 |
""" |
| 31 |
if "." in name: |
| 32 |
name, attribute = name.split(".") |
| 33 |
attribute = FTL.Identifier(attribute) |
| 34 |
else: |
| 35 |
attribute = None |
| 36 |
|
| 37 |
return FTL.MessageReference( |
| 38 |
id=FTL.Identifier(name), |
| 39 |
attribute=attribute, |
| 40 |
) |
| 41 |
|
| 42 |
|
| 43 |
def TERM_REFERENCE(name): |
| 44 |
"""Create a TermReference expression.""" |
| 45 |
|
| 46 |
return FTL.TermReference(id=FTL.Identifier(name)) |
| 47 |
|
| 48 |
|
| 49 |
class IntoTranforms(Transformer): |
| 50 |
IMPLICIT_TRANSFORMS = ("CONCAT",) |
| 51 |
FORBIDDEN_TRANSFORMS = ("PLURALS", "REPLACE", "REPLACE_IN_TEXT") |
| 52 |
|
| 53 |
def __init__(self, substitutions): |
| 54 |
self.substitutions = substitutions |
| 55 |
|
| 56 |
def visit_Junk(self, node): |
| 57 |
anno = node.annotations[0] |
| 58 |
raise InvalidTransformError( |
| 59 |
"Transform contains parse error: {}, at {}".format( |
| 60 |
anno.message, anno.span.start |
| 61 |
) |
| 62 |
) |
| 63 |
|
| 64 |
def visit_FunctionReference(self, node): |
| 65 |
name = node.id.name |
| 66 |
if name in self.IMPLICIT_TRANSFORMS: |
| 67 |
raise NotSupportedError( |
| 68 |
"{} may not be used with transforms_from(). It runs " |
| 69 |
"implicitly on all Patterns anyways.".format(name) |
| 70 |
) |
| 71 |
if name in self.FORBIDDEN_TRANSFORMS: |
| 72 |
raise NotSupportedError( |
| 73 |
"{} may not be used with transforms_from(). It requires " |
| 74 |
"additional logic in Python code.".format(name) |
| 75 |
) |
| 76 |
if name in ("COPY", "COPY_PATTERN"): |
| 77 |
args = (self.into_argument(arg) for arg in node.arguments.positional) |
| 78 |
kwargs = { |
| 79 |
arg.name.name: self.into_argument(arg.value) |
| 80 |
for arg in node.arguments.named |
| 81 |
} |
| 82 |
if name == "COPY": |
| 83 |
return COPY(*args, **kwargs) |
| 84 |
return COPY_PATTERN(*args, **kwargs) |
| 85 |
return self.generic_visit(node) |
| 86 |
|
| 87 |
def visit_Placeable(self, node): |
| 88 |
"""If the expression is a Transform, replace this Placeable |
| 89 |
with the Transform it's holding. |
| 90 |
Transforms evaluate to Patterns, which are flattened as |
| 91 |
elements of Patterns in Transform.pattern_of, but only |
| 92 |
one level deep. |
| 93 |
""" |
| 94 |
node = self.generic_visit(node) |
| 95 |
if isinstance(node.expression, Transform): |
| 96 |
return node.expression |
| 97 |
return node |
| 98 |
|
| 99 |
def visit_Pattern(self, node): |
| 100 |
"""Replace the Pattern with CONCAT which is more accepting of its |
| 101 |
elements. CONCAT takes PatternElements, Expressions and other |
| 102 |
Patterns (e.g. returned from evaluating transforms). |
| 103 |
""" |
| 104 |
node = self.generic_visit(node) |
| 105 |
return CONCAT(*node.elements) |
| 106 |
|
| 107 |
def into_argument(self, node): |
| 108 |
"""Convert AST node into an argument to migration transforms.""" |
| 109 |
if isinstance(node, FTL.StringLiteral): |
| 110 |
# Special cases for booleans which don't exist in Fluent. |
| 111 |
if node.value == "True": |
| 112 |
return True |
| 113 |
if node.value == "False": |
| 114 |
return False |
| 115 |
return node.value |
| 116 |
if isinstance(node, FTL.MessageReference): |
| 117 |
try: |
| 118 |
return self.substitutions[node.id.name] |
| 119 |
except KeyError: |
| 120 |
raise InvalidTransformError( |
| 121 |
"Unknown substitution in COPY: {}".format(node.id.name) |
| 122 |
) |
| 123 |
else: |
| 124 |
raise InvalidTransformError( |
| 125 |
"Invalid argument passed to COPY: {}".format(type(node).__name__) |
| 126 |
) |
| 127 |
|
| 128 |
|
| 129 |
def transforms_from(ftl, **substitutions) -> List[FTL.Message | FTL.Term]: |
| 130 |
"""Parse FTL code into a list of Message nodes with Transforms. |
| 131 |
|
| 132 |
The FTL may use a fabricated COPY function inside of placeables which |
| 133 |
will be converted into actual COPY migration transform. |
| 134 |
|
| 135 |
new-key = Hardcoded text { COPY("filepath.dtd", "string.key") } |
| 136 |
|
| 137 |
For convenience, COPY may also refer to transforms_from's keyword |
| 138 |
arguments via the MessageReference syntax: |
| 139 |
|
| 140 |
transforms_from(\""" |
| 141 |
new-key = Hardcoded text { COPY(file_dtd, "string.key") } |
| 142 |
\""", file_dtd="very/long/path/to/a/file.dtd") |
| 143 |
|
| 144 |
""" |
| 145 |
|
| 146 |
parser = FluentParser(with_spans=False) |
| 147 |
resource = parser.parse(ftl) |
| 148 |
return IntoTranforms(substitutions).visit(resource).body |