Repository navigation
Expand file tree
/
Copy pathcompiler.py
More file actions
1932 lines (1542 loc) · 58.6 KB
/
Copy pathcompiler.py
File metadata and controls
1932 lines (1542 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import ast
import builtins
import collections
import functools
import itertools
import logging
import pickle
import re
import sys
import textwrap
import threading
from chameleon.astutil import Builtin
from chameleon.astutil import Comment
from chameleon.astutil import NameLookupRewriteVisitor
from chameleon.astutil import Node
from chameleon.astutil import Static
from chameleon.astutil import Symbol
from chameleon.astutil import TokenRef
from chameleon.astutil import load
from chameleon.astutil import param
from chameleon.astutil import store
from chameleon.astutil import subscript
from chameleon.codegen import TemplateCodeGenerator
from chameleon.codegen import template
from chameleon.exc import ExpressionError
from chameleon.exc import TranslationError
from chameleon.i18n import simple_translate
from chameleon.nodes import And
from chameleon.nodes import Assignment
from chameleon.nodes import Context
from chameleon.nodes import Equals
from chameleon.nodes import Is
from chameleon.nodes import IsNot
from chameleon.nodes import Logical
from chameleon.nodes import Module
from chameleon.nodes import Substitution
from chameleon.nodes import Text
from chameleon.nodes import Value
from chameleon.parser import groupdict
from chameleon.tal import NAME
from chameleon.tal import ErrorInfo
from chameleon.tokenize import Token
from chameleon.utils import ListDictProxy
from chameleon.utils import char2entity
from chameleon.utils import decode_htmlentities
from chameleon.utils import join
from chameleon.utils import safe_native
log = logging.getLogger('chameleon.compiler')
# Disallowing the use of the following symbols to avoid misunderstandings.
COMPILER_INTERNALS_OR_DISALLOWED = {
"econtext",
"rcontext",
}
RE_MANGLE = re.compile(r'[^\w_]')
RE_NAME = re.compile('^%s$' % NAME)
def identifier(prefix: str, suffix: str | None = None) -> str:
return "__{}_{}".format(prefix, mangle(suffix or id(prefix)))
def mangle(string: int | str) -> str:
return RE_MANGLE.sub('_', str(string)).replace('\n', '').replace('-', '_')
def load_econtext(name):
return template("getname(KEY)", KEY=ast.Constant(name), mode="eval")
def store_econtext(name: object) -> ast.Subscript:
name = str(name)
return subscript(name, load("econtext"), ast.Store())
def store_rcontext(name: object) -> ast.Subscript:
name = str(name)
return subscript(name, load("rcontext"), ast.Store())
def eval_token(token):
try:
line, column = token.location
except AttributeError:
line, column = 0, 0
string = safe_native(token)
return template(
"(string, line, col)",
string=ast.Constant(string),
line=ast.Constant(line),
col=ast.Constant(column),
mode="eval"
)
def indent(s: str | None) -> str:
return textwrap.indent(s, " ") if s else ""
emit_node_if_non_trivial = template(is_func=True, func_args=('node',),
source=r"""
if node is not None:
__append(node)
""")
emit_bool = template(is_func=True,
func_args=('target', 's', 'default_marker', 'default'),
func_defaults=(None, None), source=r"""
if target is default_marker:
target = default
elif target:
target = s
else:
target = None""")
emit_convert = template(is_func=True,
func_args=('target', 'encoded', 'str', 'type',
'default_marker', 'default'),
func_defaults=(bytes, str, type, None),
source=r"""
if target is None:
pass
elif target is default_marker:
target = default
else:
__tt = type(target)
if __tt is encoded:
target = decode(target)
elif __tt is not str:
if __tt is int or __tt is float:
target = str(target)
else:
__markup = getattr(target, "__html__", None)
if __markup is None:
__converted = translate(
target,
domain=__i18n_domain,
context=__i18n_context,
target_language=target_language
)
target = str(target) \
if target is __converted \
else __converted
else:
target = __markup()""")
emit_func_convert = template(
is_func=True, func_args=(
'func', 'encoded', 'str', 'type'), func_defaults=(
bytes, str, type), source=r"""
def func(target):
if target is None:
return
__tt = type(target)
if __tt is encoded:
target = decode(target)
elif __tt is not str:
if __tt is int or __tt is float:
target = str(target)
else:
__markup = getattr(target, "__html__", None)
if __markup is None:
__converted = translate(
target,
domain=__i18n_domain,
context=__i18n_context,
target_language=target_language
)
target = str(target) \
if target is __converted \
else __converted
else:
target = __markup()
return target"""
)
emit_translate = template(is_func=True,
func_args=('target', 'msgid',
'default'),
func_defaults=(None,),
source=r"""
target = translate(
msgid,
default=default,
domain=__i18n_domain,
context=__i18n_context,
target_language=target_language
)""")
emit_func_convert_and_escape = template(
is_func=True,
func_args=('func', 'str', 'type', 'encoded'),
func_defaults=(str, type, bytes,),
source=r"""
def func(target, quote, quote_entity, default, default_marker):
if target is None:
return
if target is default_marker:
return default
__tt = type(target)
if __tt is encoded:
target = decode(target)
elif __tt is not str:
if __tt is int or __tt is float:
return str(target)
__markup = getattr(target, "__html__", None)
if __markup is None:
__converted = translate(
target,
domain=__i18n_domain,
context=__i18n_context,
target_language=target_language
)
target = str(target) if target is __converted \
else __converted
else:
return __markup()
if target is not None:
try:
escape = __re_needs_escape(target) is not None
except TypeError:
pass
else:
if escape:
# Character escape
if '&' in target:
target = target.replace('&', '&')
if '<' in target:
target = target.replace('<', '<')
if '>' in target:
target = target.replace('>', '>')
if quote is not None and quote in target:
target = target.replace(quote, quote_entity)
return target""")
class EmitText(Node):
"""Append text to output."""
_fields = "s",
class TranslationContext(Node):
"""Set a local output context.
This is used for the translation machinery.
"""
_fields = "body", "append", "stream"
body = None
append = None
stream = None
class Interpolator:
braces_required_regex = re.compile(
r'\$({(?P<expression>.*)})', re.DOTALL
)
braces_optional_regex = re.compile(
r'\$({(?P<expression>.*)}|(?P<variable>[A-Za-z][A-Za-z0-9_]*))',
re.DOTALL,
)
def __init__(
self,
expression,
braces_required,
translate: bool = False,
decode_htmlentities: bool = False,
) -> None:
self.expression = expression
self.regex = (
self.braces_required_regex
if braces_required
else self.braces_optional_regex
)
self.translate = translate
self.decode_htmlentities = decode_htmlentities
def __call__(self, name, engine):
"""The strategy is to find possible expression strings and
call the ``validate`` function of the parser to validate.
For every possible starting point, the longest possible
expression is tried first, then the second longest and so
forth.
Example 1:
${'expressions use the ${<expression>} format'}
The entire expression is attempted first and it is also the
only one that validates.
Example 2:
${'Hello'} ${'world!'}
Validation of the longest possible expression (the entire
string) will fail, while the second round of attempts,
``${'Hello'}`` and ``${'world!'}`` respectively, validate.
"""
body = []
nodes = []
text = self.expression
expr_map = {}
translate = self.translate
while text:
matched = text
m = self.regex.search(matched)
if m is None:
text = text.replace('$$', '$')
nodes.append(ast.Constant(text))
break
part = text[:m.start()]
text = text[m.start():]
if part:
i = 0
length = len(part)
while i < length and part[-i - 1] == '$':
i += 1
skip = i & 1
part = part.replace('$$', '$')
node = ast.Constant(part)
nodes.append(node)
if skip:
text = text[1:]
continue
if not body:
target = name
else:
target = store("%s_%d" % (name.id, text.pos))
while True:
d = groupdict(m, matched)
string = d["expression"] or d.get("variable") or ""
if self.decode_htmlentities:
string = decode_htmlentities(string)
if string:
try:
compiler = engine.parse(string)
body += compiler.assign_text(target)
except ExpressionError:
matched = matched[m.start():m.end() - 1]
m = self.regex.search(matched)
if m is None:
raise
continue
else:
s = m.group()
assign = ast.Assign(
targets=[target], value=ast.Constant(s))
body += [assign]
break
# If one or more expressions are not simple names, we
# disable translation.
if RE_NAME.match(string) is None:
translate = False
# if this is the first expression, use the provided
# assignment name; otherwise, generate one (here based
# on the string position)
node = load(target.id)
nodes.append(node)
expr_map[node] = safe_native(string)
text = text[len(m.group()):]
if len(nodes) == 1:
target = nodes[0]
if (
translate
and isinstance(target, ast.Constant)
and isinstance(target.value, str)
):
target = template(
"translate(msgid, domain=__i18n_domain, context=__i18n_context, target_language=target_language)", # noqa: E501 line too long
msgid=target,
mode="eval",
)
else:
if translate:
formatting_string = ""
keys = []
values = []
for node in nodes:
if (
isinstance(node, ast.Constant)
and isinstance(node.value, str)
):
formatting_string += node.value
else:
string = expr_map[node]
formatting_string += "${%s}" % string
keys.append(ast.Constant(string))
values.append(node)
target = template(
"translate(msgid, mapping=mapping, domain=__i18n_domain, context=__i18n_context, target_language=target_language)", # noqa: E501 line too long
msgid=ast.Constant(
formatting_string),
mapping=ast.Dict(
keys=keys,
values=values),
mode="eval")
else:
nodes = [
node
if (
isinstance(node, ast.Constant)
and isinstance(node.value, str)
) else
template(
"NODE if NODE is not None else ''",
NODE=node, mode="eval"
)
for node in nodes
]
target = ast.BinOp(
left=ast.Constant("%s" * len(nodes)),
op=ast.Mod(),
right=ast.Tuple(elts=nodes, ctx=ast.Load()))
body += [ast.Assign(targets=[name], value=target)]
return body
class ExpressionEngine:
"""Expression engine.
This test demonstrates how to configure and invoke the engine.
>>> from chameleon import tales
>>> parser = tales.ExpressionParser({
... 'python': tales.PythonExpr,
... 'not': tales.NotExpr,
... 'exists': tales.ExistsExpr,
... 'string': tales.StringExpr,
... }, 'python')
>>> engine = ExpressionEngine(parser)
An expression evaluation function:
>>> eval = lambda expression: tales.test(
... tales.IdentityExpr(expression), engine)
We have provided 'python' as the default expression type. This
means that when no prefix is given, the expression is evaluated as
a Python expression:
>>> eval('not False')
True
Note that the ``type`` prefixes bind left. If ``not`` and
``exits`` are two expression type prefixes, consider the
following::
>>> eval('not: exists: int(None)')
True
The pipe operator binds right. In the following example, but
arguments are evaluated against ``not: exists: ``.
>>> eval('not: exists: help')
False
"""
supported_char_escape_set = {'&', '<', '>'}
def __init__(
self,
parser,
char_escape=(),
default=None,
default_marker=None,
literal_false: bool = True,
) -> None:
self._parser = parser
self._char_escape = char_escape
self._default = default
self._default_marker = default_marker
self._literal_false = literal_false
def __call__(self, string, target):
# BBB: This method is deprecated. Instead, a call should first
# be made to ``parse`` and then one of the assignment methods
# ("value" or "text").
compiler = self.parse(string)
return compiler(string, target)
def parse(self, string, handle_errors: bool = True, char_escape=None):
expression = self._parser(string)
compiler = self.get_compiler(
expression, string, handle_errors, char_escape
)
return ExpressionCompiler(compiler, self)
def get_compiler(self, expression, string, handle_errors, char_escape):
if char_escape is None:
char_escape = self._char_escape
def compiler(target, engine, result_type=None, *args):
stmts = expression(target, engine)
if result_type is not None:
method = getattr(self, '_convert_%s' % result_type)
steps = method(target, char_escape, *args)
if not self._literal_false:
steps = [
ast.If(
ast.UnaryOp(
op=ast.Not(),
operand=target
),
[ast.Assign(
targets=[store(target.id)],
value=load('None')
)],
steps
)
]
stmts.extend(steps)
if handle_errors and isinstance(string, Token):
stmts.insert(0, TokenRef(string.strip()))
return stmts
return compiler
def _convert_bool(self, target, char_escape, s):
"""Converts value given by ``target`` to a string ``s`` if the
target is a true value, otherwise ``None``.
"""
return emit_bool(
target, ast.Constant(s),
default=self._default,
default_marker=self._default_marker
)
def _convert_structure(self, target, char_escape):
"""Converts value given by ``target`` to structure output."""
return emit_convert(
target,
default=self._default,
default_marker=self._default_marker,
)
def _convert_text(self, target, char_escape):
"""Converts value given by ``target`` to text."""
if not char_escape:
return self._convert_structure(target, char_escape)
# This is a cop-out - we really only support a very select
# set of escape characters
other = set(char_escape) - self.supported_char_escape_set
if other:
for supported in '"', '\'', '':
if supported in char_escape:
quote = supported
break
else:
raise RuntimeError(
"Unsupported escape set: %s." % repr(char_escape)
)
else:
quote = '\0'
entity = char2entity(quote or '\0')
return template(
"TARGET = __quote(TARGET, QUOTE, Q_ENTITY, DEFAULT, MARKER)",
TARGET=target,
QUOTE=ast.Constant(quote),
Q_ENTITY=ast.Constant(entity),
DEFAULT=self._default,
MARKER=self._default_marker,
)
class ExpressionCompiler:
def __init__(self, compiler, engine) -> None:
self.compiler = compiler
self.engine = engine
def assign_bool(self, target, s):
return self.compiler(target, self.engine, "bool", s)
def assign_text(self, target):
return self.compiler(target, self.engine, "text")
def assign_value(self, target):
return self.compiler(target, self.engine)
class ExpressionEvaluator:
"""Evaluates dynamic expression.
This is not particularly efficient, but supported for legacy
applications.
>>> from chameleon import tales
>>> parser = tales.ExpressionParser({'python': tales.PythonExpr}, 'python')
>>> engine = functools.partial(ExpressionEngine, parser)
>>> evaluator = ExpressionEvaluator(engine, {
... 'foo': 'bar',
... })
We'll use the following convenience function to test the expression
evaluator.
>>> from chameleon.utils import Scope
>>> def evaluate(d, *args):
... return evaluator(Scope(d), *args)
The evaluation function is passed the local and remote context,
the expression type and finally the expression.
>>> evaluate({'boo': 'baz'}, {}, 'python', 'foo + boo')
'barbaz'
The cache is now primed:
>>> evaluate({'boo': 'baz'}, {}, 'python', 'foo + boo')
'barbaz'
Note that the call method supports currying of the expression
argument:
>>> python = evaluate({'boo': 'baz'}, {}, 'python')
>>> python('foo + boo')
'barbaz'
"""
__slots__ = "_engine", "_cache", "_names", "_builtins"
def __init__(self, engine, builtins):
self._engine = engine
self._names = tuple(builtins)
self._builtins = tuple(builtins.values())
self._cache = {}
def __call__(self, econtext, rcontext, expression_type, string=None):
if string is None:
return functools.partial(
self.__call__, econtext, rcontext, expression_type
)
expression = "{}:{}".format(expression_type, string)
try:
evaluate = self._cache[expression]
except KeyError:
assignment = Assignment(["_result"], expression, True)
module = Module("evaluate", Context(assignment))
compiler = Compiler(
self._engine, module, "<string>", string,
('econtext', 'rcontext') + self._names
)
env = {}
exec(compiler.code, env)
evaluate = self._cache[expression] = env["evaluate"]
evaluate(econtext, rcontext, *self._builtins)
return econtext['_result']
class NameTransform:
"""
>>> nt = NameTransform(
... set(('foo', 'bar', )), {'boo': 'boz'},
... ('econtext', ),
... )
>>> def test(name):
... rewritten = nt(load(name))
... module = ast.Module([ast.fix_missing_locations(rewritten)], [])
... codegen = TemplateCodeGenerator(module)
... return codegen.code
Any odd name:
>>> test('frobnitz')
"getname('frobnitz')"
A 'builtin' name will first be looked up via ``get`` allowing fall
back to the global builtin value:
>>> test('foo')
"get('foo', foo)"
Internal names (with two leading underscores) are left alone:
>>> test('__internal')
'__internal'
Compiler internals or disallowed names:
>>> test('econtext')
'econtext'
Aliased names:
>>> test('boo')
'boz'
"""
def __init__(self, builtins, aliases, internals) -> None:
self.builtins = builtins
self.aliases = aliases
self.internals = internals
def __call__(self, node):
name = node.id
# Don't rewrite names that begin with an underscore; they are
# internal and can be assumed to be locally defined. This
# policy really should be part of the template program, not
# defined here in the compiler.
if name.startswith('__') or name in self.internals:
return node
# Some expressions allow setting variables which we transform to
# storing them as template context.
if isinstance(node.ctx, ast.Store):
return store_econtext(name)
aliased = self.aliases.get(name)
if aliased is not None:
return load(aliased)
# If the name is a Python global, first try acquiring it from
# the dynamic context, then fall back to the global.
if name in self.builtins:
return template(
"get(key, name)",
mode="eval",
key=ast.Constant(name),
name=Builtin(name),
)
# Otherwise, simply acquire it from the dynamic context.
return load_econtext(name)
class ExpressionTransform:
"""Internal wrapper to transform expression nodes into assignment
statements.
The node input may use the provided expression engine, but other
expression node types are supported such as ``Builtin`` which
simply resolves a built-in name.
Used internally be the compiler.
"""
loads_symbol = Symbol(pickle.loads)
def __init__(
self, engine_factory, cache, visitor, strict: bool = True
) -> None:
self.engine_factory = engine_factory
self.cache = cache
self.strict = strict
self.visitor = visitor
def __call__(self, expression, target):
if isinstance(target, str):
target = store(target)
try:
stmts = self._translate(expression, target)
except ExpressionError as exc:
if self.strict:
raise
p = pickle.dumps(exc, -1)
stmts = template(
"__exc = loads(p)", loads=self.loads_symbol, p=ast.Constant(p)
)
stmts += [
TokenRef(exc.token),
ast.Raise(exc=load("__exc"))
]
# Apply visitor to each statement
stmts = [self.visitor(stmt) for stmt in stmts]
return stmts
def _translate(self, expression, target):
if isinstance(target, str):
target = store(target)
cached = self.cache.get(expression)
if cached is not None:
stmts = [ast.Assign(targets=[target], value=cached)]
elif isinstance(expression, ast.expr):
stmts = [ast.Assign(targets=[target], value=expression)]
else:
# The engine interface supports simple strings, which
# default to expression nodes
if isinstance(expression, str):
expression = Value(expression, True)
kind = type(expression).__name__
visitor = getattr(self, "visit_%s" % kind)
stmts = visitor(expression, target)
# Add comment
target_id = getattr(target, "id", target)
comment = Comment(" {!r} -> {}".format(expression, target_id))
stmts.insert(0, comment)
return stmts
def visit_Value(self, node, target):
engine = self.engine_factory(
default=node.default,
default_marker=node.default_marker
)
compiler = engine.parse(node.value)
return compiler.assign_value(target)
def visit_Copy(self, node, target):
return self._translate(node.expression, target)
def visit_Substitution(self, node, target):
engine = self.engine_factory(
default=node.default,
default_marker=node.default_marker,
literal_false=node.literal_false,
)
compiler = engine.parse(node.value, char_escape=node.char_escape)
return compiler.assign_text(target)
def visit_Negate(self, node, target):
return self._translate(node.value, target) + \
template("TARGET = not TARGET", TARGET=target)
def visit_BinOp(self, node, target):
expression = self._translate(node.left, "__expression")
value = self._translate(node.right, "__value")
op = {
Is: "is",
IsNot: "is not",
Equals: "==",
}[node.op]
return expression + value + \
template("TARGET = __expression %s __value" % op, TARGET=target)
def visit_Boolean(self, node, target):
engine = self.engine_factory(
default=node.default,
default_marker=node.default_marker,
)
compiler = engine.parse(node.value)
return compiler.assign_bool(target, node.s)
def visit_Interpolation(self, node, target):
expr = node.value
if isinstance(expr, Substitution):
engine = self.engine_factory(
char_escape=expr.char_escape,
default=expr.default,
default_marker=expr.default_marker,
literal_false=expr.literal_false,
)
elif isinstance(expr, Value):
engine = self.engine_factory(
default=expr.default,
default_marker=expr.default_marker
)
else:
raise RuntimeError("Bad value: %r." % node.value)
interpolator = Interpolator(
expr.value, node.braces_required,
translate=node.translation,
decode_htmlentities=True
)
compiler = engine.get_compiler(interpolator, expr.value, True, ())
return compiler(target, engine, "text")
def visit_Replace(self, node, target):
stmts = self._translate(node.value, target)
return stmts + template(
"if TARGET: TARGET = S",
TARGET=target,
S=ast.Constant(node.s)
)
def visit_Translate(self, node, target):
if node.msgid is not None:
msgid = ast.Constant(node.msgid)
else:
msgid = target
return self._translate(node.node, target) + \
emit_translate(target, msgid, default=target)
def visit_Static(self, node, target):
return [ast.Assign(targets=[target], value=node)]
def visit_Builtin(self, node, target):
return [ast.Assign(targets=[target], value=node)]
def visit_Symbol(self, node, target):
return template("TARGET = SYMBOL", TARGET=target, SYMBOL=node)
class Compiler:
"""Generic compiler class.
Iterates through nodes and yields Python statements which form a
template program.
"""
defaults = {
'translate': Symbol(simple_translate),
'decode': Builtin("str"),
'on_error_handler': Builtin("str"),
}
lock = threading.Lock()
global_builtins = set(builtins.__dict__)
def __init__(
self,
engine_factory,
node,
filename,
source,
builtins={},
strict=True,
stream_factory=list,
):
self._scopes = [set()]
self._expression_cache = {}
self._translations = []
self._builtins = builtins
self._aliases = [{}]