-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyamlet.py
1624 lines (1408 loc) · 73.4 KB
/
yamlet.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2024 Josh Ventura <joshv10>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import ast
import io
import keyword
import pathlib
import re
import ruamel.yaml
import sys
import token
import tokenize
import typing
VERSION = '0.1.1'
ConstructorError = ruamel.yaml.constructor.ConstructorError
class YamletBaseException(Exception): pass
class YamletOptions:
Error = ['error']
CACHE_VALUES = 1
CACHE_NOTHING = 2
CACHE_DEBUG = 3
def __init__(self, *, import_resolver=None,
missing_name_value=Error, warn_on_missing=True,
functions=None, globals=None, module_vars=None,
constructors=None, caching=CACHE_VALUES, exception_prefix=None,
_yamlet_debug_opts=None):
self.import_resolver = import_resolver or str
self.missing_name_value = missing_name_value
self.warn_on_missing = warn_on_missing
self.functions = functions or {}
self.globals = globals or {}
self.module_vars = module_vars or {}
self.constructors = constructors or {}
self.caching = caching
self.exception_prefix = exception_prefix
self.debugging = _yamlet_debug_opts or _DebugOpts()
class ConstructStyle:
# Your type will be constructed with the loader and node.
# This is identical to how Ruamel/PyYAML constructors work.
RAW = 'RAW'
# Your type will be constructed with the processed YAML value.
# This may be a string, list, GclDict, etc.
SCALAR = 'SCALAR'
# The value will be treated as a string format operation (`!fmt`),
# and your type will be constructed from its result.
FMT = 'FMT'
# The value will be treated as a Yamlet expression (`!expr`),
# and your type will be constructed from the result.
EXPR = 'EXPR'
class ImportInfo:
'''Can be returned from YamletOptions.import_resolver instead of a string.
Provides more information about the module to be loaded, allowing further
configuration customization on the fly.
'''
def __init__(self, path, module_vars={}):
self.path, self.module_vars = path, module_vars
class Loader(ruamel.yaml.YAML):
def __init__(self, opts=None):
super().__init__()
opts = opts or YamletOptions()
self.yamlet_options = opts
self.loaded_modules = {}
# Set custom dict type for base operations
self.constructor.yaml_base_dict_type = GclDict
self.representer.add_representer(GclDict, self.representer.represent_dict)
def UndefinedConstructor(self, node):
raise ConstructorError(
None, None, f'No constructor bound for tag `{node.tag}`',
node.start_mark)
def GclImport(loader, node):
filename = loader.construct_scalar(node)
res = ModuleToLoad(filename, YamlPoint(node.start_mark, node.end_mark))
res._gcl_loader_ = lambda fn: self.LoadCachedFile(fn)
return res
def ConstructScalar(tp):
def Constructor(loader, node):
return tp(loader.construct_scalar(node),
YamlPoint(node.start_mark, node.end_mark))
return Constructor
def ConstructConstant(tag, val):
def Constructor(loader, node):
n = loader.construct_scalar(node)
if n != '': raise ConstructorError(None, None,
f'Yamlet `!{tag}` got unexpected node type: {repr(node)}',
node.start_mark)
return val
return Constructor
yc = self.constructor
yc.add_constructor(None, UndefinedConstructor) # Raise on undefined tags
yc.add_constructor(ruamel.yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
self.ConstructGclDict)
yc.add_constructor("!import", GclImport)
yc.add_constructor("!composite", self.DeferGclComposite)
yc.add_constructor("!fmt", ConstructScalar(StringToSubstitute))
yc.add_constructor("!expr", ConstructScalar(ExpressionToEvaluate))
yc.add_constructor("!lambda", ConstructScalar(GclLambda))
yc.add_constructor("!local", ConstructScalar(GclLocalKey))
yc.add_constructor("!template", self.ConstructGclTemplate)
yc.add_constructor("!if", ConstructScalar(YamletIfStatement))
yc.add_constructor("!elif", ConstructScalar(YamletElifStatement))
yc.add_constructor("!else", Loader._ConstructElse)
yc.add_constructor("!null", ConstructConstant('null', null))
yc.add_constructor("!external", ConstructConstant('external', external))
for tag, ctor in self.yamlet_options.constructors.items():
if callable(ctor): self.add_constructor(tag, ctor)
else:
assert isinstance(ctor, dict), ('Yamlet constructors should be callable'
' or give arguments to `add_constructor`; '
f'got `{type(ctor).__name__}` for `{tag}`')
self.add_constructor(tag, **ctor)
def add_constructor(self, tag, ctor,
style=ConstructStyle.RAW, tag_compositing=True):
yc = self.constructor
if style == ConstructStyle.RAW:
def RawUserConstructor(loader, node):
try: return ctor(loader, node)
except Exception as e:
raise ConstructorError(None, None,
f'Yamlet user constructor `!{tag}` encountered an error; '
'is your type constructable from `(ruamel.Loader, ruamel.Node)`?',
node.start_mark) from e
yc.add_constructor(tag, RawUserConstructor)
return self
def ConstructDefer(deferred, tp):
def Constructor(loader, node):
return deferred(tp, loader.construct_scalar(node),
YamlPoint(node.start_mark, node.end_mark))
return Constructor
def ConstructScalar(tp):
def Constructor(loader, node): return tp(loader.construct_scalar(node))
return Constructor
match style:
case ConstructStyle.SCALAR:
yc.add_constructor(tag, ConstructScalar(ctor))
case ConstructStyle.FMT:
yc.add_constructor(tag, ConstructDefer(StringToSubAndWrap, ctor))
case ConstructStyle.EXPR:
yc.add_constructor(tag, ConstructDefer(ExprToEvalAndWrap, ctor))
case _:
raise ValueError(f'Unknown construction style `{style}`')
if tag_compositing:
yc.add_constructor(tag + ':raw', ConstructScalar(ctor))
yc.add_constructor(tag + ':fmt', ConstructDefer(StringToSubAndWrap, ctor))
yc.add_constructor(tag + ':expr', ConstructDefer(ExprToEvalAndWrap, ctor))
return self
def LoadCachedFile(self, fn):
fn = fn.resolve()
if fn in self.loaded_modules:
res = self.loaded_modules[fn]
if res is None:
raise RecursionError(f'Processing config `{fn}` results in recursion. '
'This isn\'t supposed to happen, as import loads '
'are deferred until name lookup.')
return res
self.loaded_modules[fn] = None
with open(fn) as file:
try: res = self._ProcessYamlGcl(file)
except Exception as e:
self.loaded_modules.pop(fn)
raise
self.loaded_modules[fn] = res
return res
def ConstructGclDict(self, loader, node):
try:
return ProcessYamlPairs(
loader.construct_pairs(node), gcl_opts=self.yamlet_options,
yaml_point=YamlPoint(start=node.start_mark, end=node.end_mark),
is_template=False)
except Exception as e:
if isinstance(e, ConstructorError): raise
raise ConstructorError(None, None,
f'Yamlet error while processing dictionary: {str(e)}',
node.start_mark) from e
def ConstructGclTemplate(self, loader, node):
try:
return ProcessYamlPairs(
loader.construct_pairs(node), gcl_opts=self.yamlet_options,
yaml_point=YamlPoint(start=node.start_mark, end=node.end_mark),
is_template=True)
except Exception as e:
if isinstance(e, ConstructorError): raise
raise ConstructorError(None, None,
f'Yamlet error while processing dictionary: {str(e)}',
node.start_mark) from e
def DeferGclComposite(self, loader, node):
marks = YamlPoint(node.start_mark, node.end_mark)
if isinstance(node, ruamel.yaml.ScalarNode):
return TupleListToComposite(loader.construct_scalar(node).split(), marks)
if isinstance(node, ruamel.yaml.SequenceNode):
return TupleListToComposite(loader.construct_sequence(node), marks)
raise ConstructorError(None, None,
f'Yamlet `!composite` got unexpected node type: {repr(node)}',
node.start_mark)
def _ConstructElse(loader, node):
marks = YamlPoint(node.start_mark, node.end_mark)
if isinstance(node, ruamel.yaml.ScalarNode):
s = loader.construct_scalar(node)
if s: raise ruamel.yaml.constructor.ConstructorError(
None, None,
f'A Yamlet `!else` should not have a value attached, '
f'but contained {s}', node.start_mark)
return YamletElseStatement('', marks)
raise ruamel.yaml.constructor.ConstructorError(
f'Yamlet `!else` got unexpected node type: {repr(node)}')
def _ProcessYamlGcl(self, ygcl):
tup = super().load(_WrapStream(ygcl))
ectx = None
while isinstance(tup, DeferredValue):
if not ectx:
ectx = _EvalContext(None, self.yamlet_options, tup._yaml_point_,
'Evaluating preprocessors in Yamlet document.')
tup = tup._gcl_resolve_(ectx)
return tup
def load_file(self, filename):
with open(filename) as fn: return self.load(fn)
def load(self, yaml_gcl): return self._ProcessYamlGcl(yaml_gcl)
class _DebugOpts:
'''This class contains debugging options that aren't really meant for users.
If you're reading this, though, you might find this class useful... 😛
'''
PREPROCESS_MINIMAL = 0 # Whether to use PreprocessingTuple if there are
PREPROCESS_EVERYTHING = 1 # active preprocessors, or always.
TRACE_PRETTY = 0 # Whether to include the entire dump of exception traces,
TRACE_VERBOSE = 1 # or just the trace in the Yamlet input + user code.
def __init__(self, preprocessing=None, traces=None):
def default(x, y): return y if x is None else x
self.preprocessing = default(preprocessing, _DebugOpts.PREPROCESS_MINIMAL)
self.traces = default(traces, _DebugOpts.TRACE_VERBOSE)
def load(data): return Loader().load(data)
def load_file(data): return Loader().load_file(data)
'''▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▓██▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██▓▒░
░▒▓██ Some basic built-ins and interfaces. ██▓▒░
░▒▓██▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄██▓▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒'''
def _NoneType(name):
class Nothing:
def __bool__(self): return False
def __nonzero__(self): return False
def __str__(self): return name
def __repr__(self): return name
return Nothing
def _BuiltinNones():
class external(_NoneType('external')): pass
class null(_NoneType('null')): pass
class undefined(_NoneType('undefined')): pass
class empty(_NoneType('empty')): pass
return external(), null(), undefined(), empty()
external, null, _undefined, _empty = _BuiltinNones()
class Cloneable:
'''Clonable objects can be duplicated (via deep-copy) at any time.
Any cloned object can be mutated freely without contaminating the parent.
This is critical for proper templating implementation.
All object references within a clone (such as parent pointers) should also be
updated to point within the new cloned ecosystem.
'''
def yamlet_clone(self, new_scope, ectx):
raise NotImplementedError(
'A class which extends `yamlet.Cloneable` should implement '
f'`yamlet_clone()`; `{type(self).__name__}` does not.')
class Compositable(Cloneable):
'''Compositable objects are objects which can be merged together (composited).
They must also be cloneable, so that merging them does not destroy the
original template.
'''
def yamlet_merge(self, other, ectx):
ectx.Raise(NotImplementedError, 'A class which implements '
'`yamlet.Compositable` should implement `yamlet_merge()`; '
f'`{type(self).__name__}` does not.')
'''▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▓██▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██▓▒░
░▒▓██ GclDict: Grand Central Dispatch for deferred values from files. ██▓▒░
░▒▓██▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄██▓▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒'''
class GclDict(dict, Compositable):
def __init__(self, *args, gcl_locals,
gcl_parent, gcl_super, gcl_opts, yaml_point, preprocessors,
gcl_is_template):
super().__init__(*args)
self._gcl_parent_ = gcl_parent
self._gcl_super_ = gcl_super
self._gcl_opts_ = gcl_opts
assert isinstance(gcl_locals, dict)
assert isinstance(preprocessors, dict)
self._gcl_locals_ = gcl_locals
self._gcl_preprocessors_ = preprocessors
self._gcl_is_template_ = gcl_is_template
self._gcl_provenances_ = {}
self._yaml_point_ = yaml_point
def _resolvekv(self, k, v, ectx=None):
bt_msg = f'Lookup of `{k}` in this scope'
if ectx: ectx = ectx.BranchForNameResolution(bt_msg, k, self)
while isinstance(v, DeferredValue):
uncaught_recursion = None
ectx = ectx or (
_EvalContext(self, self._gcl_opts_, self._yaml_point_, name=bt_msg))
v = v._gcl_resolve_(ectx)
# XXX: This is a nice optimization but breaks accessing templates before
# their derived types. We need to let the caching done in DeferredValue
# handle it for that case.
# self.__setitem__(k, r)
return v
def __getitem__(self, key):
try:
return self._resolvekv(key, super().__getitem__(key))
except ExceptionWithYamletTrace as e: exception_during_access = e
e = exception_during_access
exception_during_access = e.rewind()
if self._gcl_opts_.debugging.traces:
raise exception_during_access from e
else:
raise exception_during_access
def __contains__(self, key):
return super().get(key, null) is not null
def items(self):
return ((k, self._resolvekv(k, v)) for k, v in super().items())
def values(self):
return (v for _, v in self.items())
def explain_value(self, k):
if k not in super().keys(): return f'`{k}` is not defined in this object.'
obj = super().__getitem__(k)
if isinstance(obj, DeferredValue):
if not obj._gcl_provenance_:
return f'`{k}` has not been evaluated; defined {_TuplePointStr(obj)}'
return obj._gcl_provenance_.ExplainUp(_prep = f'`{k}` was computed from')
inherited = self._gcl_provenances_.get(k)
if inherited:
return f'`{k}` was inherited from another tuple {_TuplePointStr(inherited)}'
return f'`{k}` was declared directly in this tuple {_TuplePointStr(self)}'
def yamlet_merge(self, other, ectx):
ectx.Assert(isinstance(other, Compositable),
'Expected Compositable to merge.', ex_class=TypeError)
ectx.Assert(isinstance(other, GclDict) or
isinstance(other, PreprocessingTuple),
'Expected dict-like type to composite.', ex_class=TypeError)
for k, v in other._gcl_noresolve_items_():
if isinstance(v, Compositable):
v1 = self._gcl_locals_.get(k, _undefined)
if v1 is _undefined: v1 = super().setdefault(k, _undefined)
if v1 is not _undefined:
if not isinstance(v1, Compositable):
ectx.Raise(TypeError, f'Cannot composite `{type(v1)}` object `{k}` '
'with dictionary value in extending tuple.')
v1.yamlet_merge(v, ectx)
v = v1
else:
v = v.yamlet_clone(self, ectx)
self._gcl_kv_assign_(k, v)
assert v._gcl_parent_ is self
elif isinstance(v, Cloneable):
self._gcl_kv_assign_(k, v.yamlet_clone(self, ectx))
# NOTE: These other values will not have provenance info attached from a
# merge or clone operation, as the assignments above do.
elif v or (v not in (null, external, _undefined)):
self._gcl_provenances_[k] = other._gcl_provenances_.get(k, other)
self._gcl_kv_assign_(k, v)
elif v is null:
self._gcl_provenances_[k] = other._gcl_provenances_.get(k, other)
super().pop(k, None)
elif v is _undefined:
ectx.Raise(AssertionError,
'An undefined value was propagated into a Yamlet tuple.')
for k, v in other._gcl_preprocessors_.items():
if k not in self._gcl_preprocessors_:
self._gcl_preprocessors_[k] = v.yamlet_clone(self, ectx)
self._gcl_preprocess_(ectx)
def _gcl_kv_assign_(self, k, v):
if k in self._gcl_locals_: self._gcl_locals_[k] = v
else: super().__setitem__(k, v)
def _gcl_preprocess_(self, ectx):
ectx = ectx.Branch('Yamlet Preprocessing', ectx._trace_point, self,
constrain_scope=True)
for _, v in self._gcl_preprocessors_.items():
v._gcl_preprocess_(ectx)
erased = set()
for k, v in self._gcl_noresolve_items_():
if isinstance(v, DeferredValue) and v._gcl_is_undefined_(ectx):
erased.add(k)
for k in erased: super().pop(k)
def yamlet_clone(self, new_scope, ectx):
cloned_preprocessors = {k: v.yamlet_clone(new_scope, ectx)
for k, v in self._gcl_preprocessors_.items()}
res = GclDict(gcl_parent=new_scope, gcl_super=self, gcl_locals={},
gcl_opts=self._gcl_opts_, preprocessors=cloned_preprocessors,
gcl_is_template=False, yaml_point=ectx.GetPoint())
for k, v in self._gcl_noresolve_items_():
if isinstance(v, Cloneable): v = v.yamlet_clone(res, ectx)
res.__setitem__(k, v)
for k, v in self._gcl_locals_.items():
if isinstance(v, Cloneable): v = v.yamlet_clone(res, ectx)
res._gcl_locals_[k] = v
return res
def evaluate_fully(self, ectx=None):
ectx = (
ectx.Branch('Fully evaluating nested tuple', self._yaml_point_, self)
if ectx else _EvalContext(self, self._gcl_opts_, self._yaml_point_,
name='Fully evaluating Yamlet tuple'))
def ev(v):
while isinstance(v, DeferredValue): v = v._gcl_resolve_(ectx)
if isinstance(v, GclDict): v = v.evaluate_fully(ectx)
return v
def excl(k, v):
return isinstance(v, (GclDict, PreprocessingTuple)) and v._gcl_is_template_
return {k: ev(v) for k, v in self._gcl_noresolve_items_() if not excl(k, v)}
def _gcl_update_parent_(self, parent): self._gcl_parent_ = parent
def _gcl_noresolve_values_(self): return super().values()
def _gcl_noresolve_items_(self): return super().items()
def _gcl_noresolve_get_(self, k): return super().__getitem__(k)
def _gcl_traceable_get_(self, key, ectx):
return self._resolvekv(key, super().__getitem__(key), ectx)
'''▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▓██████████████████████████████████████████████████████████████████████████▓▒░
░▒▓██▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██▓▒░
░▒▓██ Context tracking: Information about (and used during) evaluation. ██▓▒░
░▒▓██▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄██▓▒░
░▒▓██████████████████████████████████████████████████████████████████████████▓▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒'''
def exceptions(bc):
'''Looks like a namespace in stack traces but is really a function.'''
class YamletException(bc, YamletBaseException):
def __init__(self, message, details):
super().__init__(message)
self.details = details
self.traced_message = message
def __str__(self): return self.traced_message
return YamletException
class ExceptionWithYamletTrace(YamletBaseException):
def __init__(self, ex_class, message):
super().__init__(message)
self.ex_class = ex_class
self.traced_message = message
def rewind(self):
return exceptions(self.ex_class)(self.traced_message, self)
class YamlPoint:
def __init__(self, start, end):
self.start = start
self.end = end
def filename(self):
name = self.start.name
if len(name) > 256 or len(name.splitlines()) > 1:
return name[:256].splitlines()[0] + '...'
return name
def as_args(self):
s, e = self.start, self.end
res = f'file={self.filename()},line={s.line},col={s.column}'
if e.line > s.line or (e.line == s.line and e.column > s.column):
if e.line != s.line: res += f',endLine={e.line}'
res += f',endColumn={e.column}'
return res
def print_warning(self, msg):
print(f'::warning {self.as_args()}::{msg}', file=sys.stderr)
class _EvalContext:
def __init__(self, scope, opts, yaml_point, name, parent=None, deferred=None,
constrain_scope=False):
self.scope = scope
self.opts = opts
self._trace_point = _EvalContext._TracePoint(yaml_point, name)
self._evaluating = id(deferred)
self._parent = parent
self._children = None
self._name_deps = None
self._constrain_scope = constrain_scope
def _PrettyError(tace_item):
if tace_item.name: return f'{tace_item.name}\n{tace_item.start}'
return str(tace_item.start)
class _ScopeVisit:
def __init__(self, ectx, scope):
self.ectx, self.scope, self.oscope = ectx, scope, ectx.scope
def __enter__(self): self.ectx.scope = self.scope
def __exit__(self, exc_type, exc_val, exc_tb): self.ectx.scope = self.oscope
class _TracePoint(YamlPoint):
def __init__(self, yaml_point, name):
super().__init__(yaml_point.start, yaml_point.end)
self.name = name
def FormatError(yaml_point, msg): return f'{yaml_point.start}\n{msg}'
def GetPoint(self): return self._trace_point
def ModuleFilename(self): return self.GetPoint().filename()
def Error(self, msg): return _EvalContext.FormatError(self.GetPoint(), msg)
def NewGclDict(self, *args, gcl_parent=None, gcl_super=None, **kwargs):
return GclDict(*args, **kwargs,
gcl_parent=gcl_parent or self.scope,
gcl_super=gcl_super,
gcl_opts=self.opts,
gcl_locals={},
preprocessors={},
gcl_is_template=False,
yaml_point=self._trace_point)
def Branch(self, name, yaml_point, scope, constrain_scope=False):
return self._TrackChild(
_EvalContext(scope, self.opts, yaml_point, name, parent=self,
constrain_scope=constrain_scope))
def BranchForNameResolution(self, lookup_description, lookup_key, scope):
return self._TrackNameDep(lookup_key,
_EvalContext(scope, self.opts, scope._yaml_point_, lookup_description,
parent=self))
def BranchForDeferredEval(self, deferred_object, description):
tp = _EvalContext._TracePoint(deferred_object._yaml_point_, description)
if id(deferred_object) in self._EnumEvaluating():
self.Raise(RecursionError, 'Dependency cycle in tuple values.')
return self._TrackChild(
_EvalContext(self.scope, self.opts, deferred_object._yaml_point_,
description, parent=self, deferred=deferred_object))
def UpScope(self):
pscope = self.scope
up = self._parent
assert up is not self
while up:
if up._constrain_scope: return None
if up.scope is not pscope: return up if up.scope is not None else None
assert up is not up._parent
up = up._parent
return None
def _TrackChild(self, child):
if self._children: self._children.append(child)
else: self._children = [child]
return child
def _TrackNameDep(self, name, child):
if self._name_deps:
# XXX: It would be nice to assert that `name` isn't already in the dict,
# however, basic lambda expressions such as the test `lambda x: x + x`
# refer to the same variable twice in one scope, and I don't think it's
# helpful for our traceback to explain that it is adding two numbers...
self._name_deps[name] = child
else: self._name_deps = {name: child}
return child
def ExplainUp(self, indent=4, _prep=None):
ind = ' ' * indent
if not _prep: _prep = 'From'
me = self._trace_point.name
me = me[0].lower() + me[1:]
me = f'{_prep} {me} {str(self._trace_point.start).strip()}'
me = f'\n'.join(me.splitlines())
froms = (ind + f'\n{ind}'.join(
[f' - {child.ExplainUp(indent).strip()}'
for child in (self._children or [])])).rstrip()
withs = (ind + f'\n{ind}'.join(
[f' - {child.ExplainUp(indent, _prep="With").strip()}'
for child in (self._name_deps or {}).values()])).rstrip()
if froms or withs: me += '\n'
if froms and withs: froms += '\n'
return f'{me}{froms}{withs}'
def Scope(self, scope):
return _EvalContext._ScopeVisit(self, scope)
def Assert(self, expr, msg, ex_class=AssertionError):
if not expr: self.Raise(ex_class, msg)
def Raise(self, ex_class, message_sentence, e=None):
if message_sentence == message_sentence.rstrip():
message_sentence += ' ' if message_sentence.endswith((*'.!?',)) else '\n'
if self.opts.exception_prefix:
message_sentence = f'{self.opts.exception_prefix}{message_sentence}'
raise ExceptionWithYamletTrace(ex_class,
f'{ex_class.__name__} occurred while evaluating a Yamlet expression:\n'
+ '\n'.join(_EvalContext._PrettyError(t) for t in self.FullTrace())
+ f'\n{message_sentence}See above trace for more details.') from e
def _EnumEvaluating(self):
p = self
while p:
if p._evaluating: yield p._evaluating
p = p._parent
def FullTrace(self):
p = self
trace = []
while p:
trace.append(p._trace_point)
p = p._parent
return trace[::-1]
'''▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▓██████████████████████████████████████████████████████████████████████████▓▒░
░▒▓██▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██▓▒░
░▒▓██ Deferred Value: Unit for template value application. ██▓▒░
░▒▓██▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄██▓▒░
░▒▓██████████████████████████████████████████████████████████████████████████▓▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒'''
class DeferredValue(Cloneable):
def __init__(self, data, yaml_point):
self._gcl_construct_ = data
self._gcl_cache_ = _empty
self._yaml_point_ = yaml_point
self._gcl_provenance_ = None
def __eq__(self, other):
return (isinstance(other, DeferredValue) and
other._gcl_construct_ == self._gcl_construct_)
def _gcl_update_parent_(self, parent): pass
def _gcl_resolve_(self, ectx):
if self._gcl_cache_ is _empty:
self._gcl_provenance_ = ectx.BranchForDeferredEval(
self, self._gcl_explanation_())
res = self._gcl_evaluate_(self._gcl_construct_, self._gcl_provenance_)
if ectx.opts.caching == YamletOptions.CACHE_NOTHING: return res
if ectx.opts.caching == YamletOptions.CACHE_DEBUG:
if getattr(self, '_gcl_cache_debug_', _empty) is not _empty:
assert res == self._gcl_cache_debug_, ('Internal error: Cache bug! '
f'Cached value `{self._gcl_cache_debug_}` is not `{res}`!\n'
f'There is an error in how `{type(self).__name__}` '
f'values are being passed around.\nRepr: {self!r}')
self._gcl_cache_debug_ = res
return res
self._gcl_cache_ = res
return self._gcl_cache_
def yamlet_clone(self, new_scope, ectx):
return type(self)(self._gcl_construct_, self._yaml_point_)
def _gcl_is_undefined_(self, ectx): return False
def __str__(self):
return (f'<Unevaluated: {self._gcl_construct_}>' if not self._gcl_cache_
else str(self._gcl_cache_))
def __repr__(self):
return (f'{type(self).__name__}({self._gcl_construct_!r}, '
f'cache={self._gcl_cache_!r})')
class ModuleToLoad(DeferredValue):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
def _gcl_explanation_(self):
return f'Resolving import `{self._gcl_construct_}`'
def _gcl_evaluate_(self, value, ectx):
fn = _ResolveStringValue(value, ectx)
import_info = ectx.opts.import_resolver(fn)
module_vars = None
if isinstance(import_info, ImportInfo):
final_path = import_info.path
module_vars = import_info.module_vars
else: final_path = import_info
fn = pathlib.Path(final_path)
if not fn.exists():
if str(value) == str(fn):
ectx.Raise(FileNotFoundError, f'Could not import Yamlet file: {value}')
ectx.Raise(FileNotFoundError,
f'Could not import Yamlet file: `{fn}`\n'
f'As evaluated from this expression: `{value}`.\n')
fn = fn.resolve()
if module_vars: ectx.opts.module_vars[str(fn)] = module_vars
loaded = self._gcl_loader_(fn)
return loaded
class StringToSubstitute(DeferredValue):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
def _gcl_explanation_(self):
return f'Evaluating string `{self._gcl_construct_}`'
def _gcl_evaluate_(self, value, ectx):
return _ResolveStringValue(value, ectx)
class ExpressionToEvaluate(DeferredValue):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
def _gcl_explanation_(self):
return f'Evaluating expression `{self._gcl_construct_.strip()}`'
def _gcl_evaluate_(self, value, ectx):
try: return _GclExprEval(value, ectx)
except Exception as e:
if isinstance(e, YamletBaseException): raise
ectx.Raise(type(e), f'Error in Yamlet expression: {e}.\n', e)
class DeferredValueWrapper(DeferredValue):
def __init__(self, klass, *args, **kwargs):
super().__init__(*args, **kwargs)
self.klass = klass
def _gcl_evaluate_(self, value, ectx):
return self.klass(super()._gcl_evaluate_(value, ectx))
def yamlet_clone(self, new_scope, ectx):
return type(self)(self.klass, self._gcl_construct_, self._yaml_point_)
class StringToSubAndWrap(DeferredValueWrapper, StringToSubstitute): pass
class ExprToEvalAndWrap(DeferredValueWrapper, ExpressionToEvaluate): pass
class TupleListToComposite(DeferredValue):
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
def _gcl_explanation_(self):
return f'Compositing tuple list `{self._gcl_construct_}`'
def _gcl_evaluate_(self, value, ectx):
return _CompositeYamlTupleList(value, ectx)
class IfLadderTableIndex(DeferredValue):
'''Stashes a sequence of if expressions extracted from an if-else ladder,
and evaluates them in order, caching the index of the first truthy expression.
Else is represented as -1; the final index in each IfLadderItem table.
'''
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
def _gcl_explanation_(self):
return f'Pre-evaluating if-else ladder'
def _gcl_evaluate_(self, value, ectx):
for i, cond in enumerate(value.cond_dvals):
if cond._gcl_resolve_(ectx):
return i
return -1
class IfLadderItem(DeferredValue):
'''References an extracted IfLadderTableIndex in its final scope to look up a
value in a table, generated from its values in an if-else ladder.
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _gcl_explanation_(self):
return f'Evaluating item in if-else ladder'
def _gcl_evaluate_(self, value, ectx):
ladder, table = value
ladder = ectx.scope._gcl_preprocessors_.get(ladder)
ectx.Assert(ladder, 'Internal error: The preprocessor '
f'`!if` directive from which this value was assigned was not inherited.'
f'\nGot: {(*ectx.scope._gcl_preprocessors_.keys(),)}\nWant: {ladder}')
index = ladder.index._gcl_resolve_(ectx)
result = table[index]
while isinstance(result, DeferredValue): result = result._gcl_resolve_(ectx)
return result
def yamlet_clone(self, new_scope, ectx):
return IfLadderItem((self._gcl_construct_[0], [
e.yamlet_clone(new_scope, ectx) if isinstance(e, Cloneable) else e
for i, e in enumerate(self._gcl_construct_[1])]), self._yaml_point_)
def _gcl_update_parent_(self, parent):
_UpdateParents(self._gcl_construct_[1], parent)
def _gcl_is_undefined_(self, ectx):
try: result = self._gcl_resolve_(ectx)
except Exception as e: return False # Keep and let user discover the error.
if isinstance(result, DeferredValue): return result._gcl_is_undefined_(ectx)
return result is _undefined
class FlatCompositor(DeferredValue):
def __init__(self, *args, varname, **kwargs):
super().__init__(*args, **kwargs)
self._gcl_varname_ = varname
def _gcl_explanation_(self):
return f'Compositing values given for `{self._gcl_varname_}`'
def _gcl_evaluate_(self, value, ectx):
active_composite = []
for term in value:
while isinstance(term, DeferredValue): term = term._gcl_resolve_(ectx)
if term: active_composite.append(term)
else:
if term is _undefined: continue
if term is external: ectx.Raise(ValueError,
f'External value found while evaluating `{self._gcl_varname_}`.')
active_composite.append(term)
if len(active_composite) == 1: return active_composite[0]
cxable = sum(isinstance(term, Compositable) for term in active_composite)
if cxable != len(active_composite):
if not cxable: return active_composite[-1]
ectx.Raise(ValueError,
f'Mixture of compositable and non-compositable values given for '
f'`{self._gcl_varname_}`. Types to composite: ' +
', '.join(f'{type(t).__name__}' for t in active_composite))
return _CompositeGclTuples(active_composite, ectx)
def _gcl_update_parent_(self, parent):
_UpdateParents(self._gcl_construct_, parent)
def _gcl_is_undefined_(self, ectx):
for term in self._gcl_construct_:
if not isinstance(term, DeferredValue): return False
if not term._gcl_is_undefined_(ectx): return False
return True
def add_compositing_value(self, value): self._gcl_construct_.append(value)
def latest_compositing_value(self): return self._gcl_construct_[-1]
def yamlet_clone(self, new_scope, ectx):
return FlatCompositor(
[v.yamlet_clone(new_scope, ectx) if isinstance(v, Cloneable) else v
for v in self._gcl_construct_], self._yaml_point_,
varname=self._gcl_varname_)
class GclLambda:
'''GclLambda isn't actually a DeferredValue, but they appear similar in YAML.
The glass actually provides an interface to make itself callable, and the
`EvalGclAst` checks for its type directly before raising that an object
is not callable.
'''
def __init__(self, expr, yaml_point):
self.yaml_point = yaml_point
sep = expr.find(':')
if sep < 0: raise ArgumentError(_EvalContext.FormatError(yaml_point,
f'Lambda does not delimit arguments from expression: `{expr}`'))
self.params = [x.strip() for x in expr[:sep].split(',')]
self.expression = expr[sep+1:]
def Callable(self, name, ectx):
params = self.params
def LambdaEvaluator(*args, **kwargs):
mapped_args = list(args)
if len(mapped_args) > len(params):
ectx.Raise(TypeError, f'Too many arguments to lambda; '
f'wanted {len(params)}, got {len(mapped_args)}.')
while len(mapped_args) < len(params):
p = params[len(mapped_args)]
if p in kwargs:
mapped_args.append(kwargs[p])
del kwargs[p]
else:
ectx.Raise(TypeError, f'Missing argument `{p}` to lambda `{name}`')
if kwargs: ectx.Raise(TypeError,
f'Extra keyword arguments `{kwargs.keys()}` to lambda `{name}`')
return _GclExprEval(self.expression, ectx.Branch(
f'lambda `{name}`', self.yaml_point, ectx.NewGclDict(
{params[i]: mapped_args[i] for i in range(len(params))}
)
))
return LambdaEvaluator
class PreprocessingTuple(DeferredValue, Compositable):
def __init__(self, tup, yaml_point=None):
assert(isinstance(tup, GclDict))
super().__init__(tup, yaml_point or tup._yaml_point_)
def _gcl_explanation_(self):
return f'Preprocessing Yamlet tuple'
def _gcl_evaluate_(self, value, ectx):
value._gcl_preprocess_(ectx)
return value
def _gcl_update_parent_(self, parent):
self._gcl_construct_._gcl_update_parent_(parent)
def keys(self): return self._gcl_construct_.keys()
def _gcl_noresolve_items_(self):
return self._gcl_construct_._gcl_noresolve_items_()
def __getattr__(self, attr):
if attr == '_gcl_parent_': return self._gcl_construct_._gcl_parent_
if attr == '_gcl_provenances_': return self._gcl_construct_._gcl_provenances_
if attr == '_gcl_preprocessors_':
return self._gcl_construct_._gcl_preprocessors_
if attr == '_gcl_is_template_': return self._gcl_construct_._gcl_is_template_
raise AttributeError(f'PreprocessingTuple has no attribute `{attr}`')
def __eq__(self, other): return self._gcl_construct_ == other
def yamlet_clone(self, new_scope, ectx):
return PreprocessingTuple(
self._gcl_construct_.yamlet_clone(new_scope, ectx))
def yamlet_merge(self, other, ectx):
self._gcl_construct_.yamlet_merge(other, ectx)
def _UpdateParents(items, parent):
for i in items:
if isinstance(i, (GclDict, DeferredValue)):
i._gcl_update_parent_(parent)
'''▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▓██████████████████████████████████████████████████████████████████████████▓▒░
░▒▓█▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█▓▒░
░▒▓█ Stream manipulation: Preprocess YAML sources to work around bugs. █▓▒░
░▒▓█▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█▓▒░
░▒▓██████████████████████████████████████████████████████████████████████████▓▒░
░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒░
░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒'''
def _FixElseColons(s):
'''This is a miserable hack that is necessary to save headaches for now.
The YAML spec allows colons in tags, so `!else:` is a valid tag and does not
start a mapping, even though `: ` and `:\n` are supposed to always begin a
mapping. This project is getting screwed both ways by that behavior.
To work around it, we just replace any free-standing `!else:` with `!else :`,
which could modify a value in user data if it appears inside a literal-style
block. There's nothing reasonable I can do about that right now.
'''
return re.sub('(\\s*!else):(\\s*#.*|\\s*)$', r'\1 :\2', s, flags=re.MULTILINE)
class ReplaceElseStream(io.IOBase):
def __init__(self, original_stream):
self.original_stream = original_stream
def read(self, size=-1):
data = self.original_stream.read(size)
return data and _FixElseColons(data)
def readline(self, size=-1):