-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathscope.py
2823 lines (2680 loc) · 116 KB
/
scope.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
import math
import os.path
import sys
from inspect import signature
import lark
import re
from lark import Lark
from colorama import Fore, Style
import importlib.util
from variable import Variable
from function import Function
from native_function import NativeFunction
from type import (
NType,
NGenericType,
NAliasType,
NTypeVars,
NModule,
NModuleWrapper,
apply_generics,
apply_generics_to,
resolve_equal_types,
NClass,
)
from enums import EnumType, EnumValue, EnumPattern
from native_function import NativeFunction
from native_types import n_list_type, n_cmd_type, n_maybe_type, none, yes, NMap
from ncmd import Cmd
from type_check_error import TypeCheckError, display_type
from display import display_value
from operation_types import (
binary_operation_types,
unary_operation_types,
comparable_types,
iterable_types,
legacy_iterable_types,
assignment_types,
assignment_expression_types,
)
from file import File
from imported_error import ImportedError
import native_functions
from syntax_error import format_error
from classes import NConstructor
from modules import libraries
unit_test_results = {}
basepath = ""
if getattr(sys, "frozen", False):
basepath = os.path.dirname(sys.executable)
elif __file__:
basepath = os.path.dirname(__file__)
syntaxpath = os.path.join(basepath, "syntax.lark")
def parse_file(file_path, base_path, parent_imports):
import_scope = Scope(
base_path=base_path, file_path=file_path, parent_imports=parent_imports
)
native_functions.add_funcs(import_scope)
with open(syntaxpath, "r") as f:
parse = f.read()
n_parser = Lark(parse, start="start", propagate_positions=True)
with open(file_path, "r", encoding="utf-8") as f:
file = File(f, name=os.path.relpath(file_path, start=base_path))
try:
tree = file.parse(n_parser)
except lark.exceptions.UnexpectedCharacters as e:
print(format_error(e, file))
sys.exit()
except lark.exceptions.UnexpectedEOF as e:
print(format_error(e, file))
sys.exit()
return import_scope, tree, file
async def eval_file(file_path, base_path, parent_imports):
import_scope, tree, _ = parse_file(file_path, base_path, parent_imports)
import_scope.variables = {
**import_scope.variables,
**(await parse_tree(tree, import_scope)).variables,
}
return import_scope
def type_check_file(file_path, base_path, parent_imports):
import_scope, tree, text_file = parse_file(file_path, base_path, parent_imports)
scope = type_check(tree, import_scope)
import_scope.variables = {**import_scope.variables, **scope.variables}
import_scope.public_types = {**import_scope.public_types, **scope.public_types}
import_scope.errors += scope.errors[:]
import_scope.warnings += scope.warnings[:]
return import_scope, text_file
def type_check(tree, import_scope):
scope = import_scope.new_scope(inherit_errors=False)
if tree.data == "start":
for child in tree.children:
scope.type_check_command(child)
else:
scope.errors.append(
TypeCheckError(
tree, "Internal issue: I cannot type check from a non-starting branch."
)
)
return scope
async def parse_tree(tree, import_scope):
if tree.data == "start":
scope = import_scope.new_scope(inherit_errors=False)
for child in tree.children:
await scope.eval_command(child)
return scope
else:
raise SyntaxError("Unable to run parse_tree on non-starting branch")
def get_destructure_pattern(tree):
if isinstance(tree, lark.Tree):
if tree.data == "record_pattern":
entries = []
for pattern in tree.children:
if isinstance(pattern, lark.Token):
entries.append((pattern.value, (pattern.value, pattern)))
else:
key, value = pattern.children
entries.append((key.value, get_destructure_pattern(value)))
return (dict(entries), tree)
elif tree.data == "tuple_pattern":
return (
tuple(get_destructure_pattern(pattern.children[0]) for pattern in tree.children),
tree,
)
elif tree.data == "list_pattern":
patterns = []
for pattern in tree.children:
patterns.append(get_destructure_pattern(pattern))
return (patterns, tree)
elif tree.data == "enum_pattern":
enum_name, *pattern_trees = tree.children
patterns = []
for pattern in pattern_trees:
patterns.append(get_destructure_pattern(pattern))
return (EnumPattern(enum_name.children[0], patterns), tree)
return (None if tree.value == "_" else tree.value, tree)
def pattern_to_name(pattern_and_src):
pattern, _ = pattern_and_src
if isinstance(pattern, str):
return pattern
else:
return "<destructuring pattern>"
def get_arguments(tree):
"""
The arguments syntax briefly had the WS token which had to be removed.
"""
arguments = [tree for tree in tree.children if isinstance(tree, lark.Tree)]
if len(arguments) > 0 and arguments[0].data == "generic_declaration":
return arguments[0].children, arguments[1:]
else:
return [], arguments
escapes = {
"n": "\n",
"r": "\r",
"t": "\t",
"v": "\v",
"0": "\0",
"f": "\f",
"b": "\b",
'"': '"',
"\\": "\\",
}
def unescape_sequence(escape_sequence_match):
if escape_sequence_match[1]:
return escapes[escape_sequence_match[1]]
elif escape_sequence_match[2]:
return chr(int(escape_sequence_match[2], 16))
else:
return escape_sequence_match[3]
def unescape(string):
return re.sub(
r'\\(?:([nrtv0fb"\\])|u\{([0-9a-fA-F]+)\}|\{(.)\})', unescape_sequence, string
)
class Scope:
def __init__(
self,
parent=None,
parent_function=None,
errors=None,
warnings=None,
base_path="",
file_path="",
parent_imports=None,
parent_type="top",
stack_trace=None,
unit_tests=None,
internal_traits=None,
enum_variants=None,
):
self.parent = parent
self.parent_function = parent_function
self.variables = {}
self.types = {}
self.public_types = {}
self.errors = errors if errors is not None else []
self.warnings = warnings if warnings is not None else []
# The path of the directory containing the initial file. Used to
# determine the relative path of a file to the starting file.
self.base_path = base_path
# The path of the file the Scope is associated with.
self.file_path = file_path
# The other files it has been imported from to prevent circular imports
self.parent_imports = parent_imports if parent_imports is not None else []
self.parent_type = parent_type
self.stack_trace = stack_trace if stack_trace is not None else []
self.unit_tests = unit_tests if unit_tests is not None else []
self.internal_traits = internal_traits if internal_traits is not None else {}
self.enum_variants = enum_variants if enum_variants is not None else {}
def new_scope(
self,
parent_function=None,
inherit_errors=True,
parent_type=None,
inherit_stack_trace=True,
inherit_unit_tests=True,
inherit_internal_traits=True,
inherit_enum_variants=True,
):
return Scope(
self,
parent_function=parent_function or self.parent_function,
errors=self.errors if inherit_errors else [],
warnings=self.warnings if inherit_errors else [],
base_path=self.base_path,
file_path=self.file_path,
parent_imports=self.parent_imports,
parent_type=parent_type or self.parent_type,
stack_trace=self.stack_trace if inherit_stack_trace else [],
unit_tests=self.unit_tests if inherit_unit_tests else [],
internal_traits=self.internal_traits if inherit_internal_traits else {},
enum_variants=self.enum_variants if inherit_enum_variants else {},
)
def get_value_internal_traits(self, value):
if isinstance(value, NModuleWrapper):
return self.internal_traits.get("module")
elif isinstance(value, NMap):
return self.internal_traits.get("map")
elif isinstance(value, dict):
return value
elif isinstance(value, list):
return self.internal_traits.get("list")
elif isinstance(value, tuple):
return self.internal_traits.get("tuple")
elif isinstance(value, bool):
return self.internal_traits.get("bool")
elif isinstance(value, int):
return self.internal_traits.get("int")
elif isinstance(value, float):
return self.internal_traits.get("float")
elif isinstance(value, str):
if len(value) == 1:
return {**self.internal_traits.get("str"), **self.internal_traits.get("char")}
return self.internal_traits.get("str")
elif isinstance(value, EnumValue):
for enum in self.enum_variants.keys():
if value.variant in self.enum_variants[enum]:
return self.internal_traits.get(enum)
return None
elif isinstance(value, Cmd):
return self.internal_traits.get("cmd")
return None
def get_type_internal_traits(self, value):
if isinstance(value, NTypeVars):
return self.internal_traits.get(value.name)
elif isinstance(value, str):
return self.internal_traits.get(value)
elif isinstance(value, list):
if isinstance(value[0], lark.Token):
if value[0].type == "LIST":
return self.internal_traits.get("list")
elif isinstance(value, NModule):
return self.internal_traits.get("module")
elif isinstance(value, dict):
return value
return None
def get_variable(self, name, err=True):
variable = self.variables.get(name)
if variable is None:
if self.parent:
return self.parent.get_variable(name, err=err)
elif err:
raise NameError(
"You tried to get a variable/function `%s`, but it isn't defined."
% name
)
else:
return variable
def get_type(self, name, err=True):
scope_type = self.types.get(name)
if scope_type is None:
if self.parent:
return self.parent.get_type(name, err=err)
elif err:
raise NameError(
"You tried to get a type `%s`, but it isn't defined." % name
)
else:
return scope_type
def get_parent_function(self):
if self.parent_function is None:
if self.parent:
return self.parent.get_parent_function()
else:
return None
else:
return self.parent_function
def get_parent_types(self, types):
if self.parent_type not in types:
if self.parent:
return self.parent.get_parent_types(types)
else:
return None
else:
return self.parent_type
def get_module_type(self, module_type, err=True):
*modules, type_name = module_type.children
if len(modules) > 0:
current_module = self.get_variable(modules[0].value, err=err)
if current_module is None:
self.errors.append(
TypeCheckError(
modules[0],
"I can't find `%s` from this scope." % modules[0].value,
)
)
return None
current_module = current_module.type
if not isinstance(current_module, NModule):
self.errors.append(
TypeCheckError(modules[0], "%s is not a module." % modules[0].value)
)
return None
for module in modules[1:]:
current_module = current_module.get(module.value)
if not isinstance(current_module, NModule):
self.errors.append(
TypeCheckError(module, "%s is not a module." % module.value)
)
return None
n_type = current_module.types.get(type_name.value)
if n_type is None:
self.errors.append(
TypeCheckError(
type_name,
"The module doesn't export a type `%s`." % type_name.value,
)
)
return None
else:
n_type = self.get_type(type_name.value, err=err)
if n_type is None:
self.errors.append(
TypeCheckError(
module_type,
"I don't know what type you're referring to by `%s`."
% type_name.value,
)
)
return None
if n_type == "invalid":
return None
else:
return n_type
def parse_type(self, tree_or_token, err=True):
if tree_or_token is None:
return "infer"
if isinstance(tree_or_token, lark.Tree):
if tree_or_token.data == "with_typevars":
module_type, *typevars = tree_or_token.children
typevar_type = self.get_module_type(module_type, err=err)
parsed_typevars = [
self.parse_type(typevar, err=err) for typevar in typevars
]
if typevar_type is None:
return None
elif isinstance(typevar_type, NAliasType) or isinstance(
typevar_type, NTypeVars
):
# Duck typing :sunglasses:
if len(typevars) < len(typevar_type.typevars):
self.errors.append(
TypeCheckError(
tree_or_token,
"%s expects %d type variable(s)."
% (
display_type(typevar_type),
len(typevar_type.typevars),
),
)
)
return None
elif len(typevars) > len(typevar_type.typevars):
self.errors.append(
TypeCheckError(
tree_or_token,
"%s only expects %d type variable(s)."
% (
display_type(typevar_type),
len(typevar_type.typevars),
),
)
)
return None
return (
typevar_type.with_typevars(parsed_typevars)
if None not in parsed_typevars
else None
)
else:
self.errors.append(
TypeCheckError(
tree_or_token,
"%s doesn't take any type variables."
% display_type(typevar_type),
)
)
return None
elif tree_or_token.data == "tupledef":
tuple_type = [
self.parse_type(child, err=err) for child in tree_or_token.children
]
return tuple_type if None not in tuple_type else None
elif tree_or_token.data == "recorddef":
record_type = {
entry.children[0].value: self.parse_type(entry.children[1], err=err)
for entry in tree_or_token.children
}
return record_type if None not in record_type.values() else None
elif tree_or_token.data == "module_type":
n_type = self.get_module_type(tree_or_token, err=err)
if n_type is None:
return None
elif (
isinstance(n_type, NAliasType) or isinstance(n_type, NTypeVars)
) and len(n_type.typevars) > 0:
self.errors.append(
TypeCheckError(
tree_or_token,
"%s expects %d type variables."
% (display_type(n_type), len(n_type.typevars)),
)
)
return None
elif isinstance(n_type, NAliasType):
return n_type.with_typevars()
return n_type
elif tree_or_token.data == "func_type":
func_types = tree_or_token.children
if (
isinstance(func_types[0], lark.Tree)
and func_types[0].data == "generic_declaration"
):
generics, *func_types = func_types
scope = self.new_scope()
for generic in generics.children:
if generic.value in scope.types:
self.errors.append(
TypeCheckError(
generic,
"You already defined a generic type with this name.",
)
)
scope.types[generic.value] = NGenericType(generic.value)
else:
scope = self
func_type = tuple(
scope.parse_type(child, err=err) for child in func_types
)
if None in func_type:
return None
# If the function type returns a function, flatten the entire
# thing
if isinstance(func_type[-1], tuple):
func_type = tuple([*func_type[0:-1], *func_type[-1]])
return func_type
elif err:
raise NameError(
"Type annotation of type %s; I am not ready for this."
% tree_or_token.data
)
else:
self.errors.append(
TypeCheckError(
tree_or_token,
"Internal problem: encountered a type annotation type %s."
% tree_or_token.data,
)
)
return None
elif tree_or_token.type == "UNIT":
return "unit"
elif err:
raise NameError(
"Type annotation token of type %s; I am not ready for this."
% tree_or_token.data
)
else:
self.errors.append(
TypeCheckError(
tree_or_token,
"Internal problem: encountered a type annotation token type %s."
% tree_or_token.data,
)
)
return None
def get_name_type(self, name_type, err=True, get_type=True):
pattern = get_destructure_pattern(name_type.children[0])
if len(name_type.children) == 1:
# No type annotation given, so it's implied
return pattern, "infer"
else:
return (
pattern,
self.parse_type(name_type.children[1], err) if get_type else "whatever",
)
"""
Sets variables from a pattern given a value or a type and returns whether
the entire pattern matched.
This is used by both type-checking (with warn=True) and interpreting
(warn=False). During type-checking, `value_or_type` is the type (notably,
tuples are lists), so it must determine whether it's even reasonable to
destructure the type (for example, it doesn't make sense to destructure a
record as a list), and error accordingly. During interpreting,
`value_or_type` is the actual value, and thanks to the type-checker, the
value should be guaranteed to fit the pattern.
- warn=True - Is the pattern valid?
- warn=False - Does the pattern match?
Note that this sets variables while checking the pattern, so it's possible
that variables are assigned even if the entire pattern doesn't match.
Fortunately, this is only used in cases where the conditional let would
create a new scope (such as in an if statement), so the extra variables can
be discarded if the pattern ends up not matching.
NOTE: This must return True if warn=True. (In other words, don't short
circuit if a pattern fails to match.)
"""
def assign_to_pattern(
self,
pattern_and_src,
value_or_type,
warn=False,
path=None,
public=False,
certain=False,
mutable=False,
):
path_name = path or "the value"
pattern, src = pattern_and_src
if isinstance(pattern, dict):
is_dict = isinstance(value_or_type, dict)
if is_dict:
# Should this be an error? Warning?
unused_keys = [
key for key in value_or_type.keys() if key not in pattern
]
if len(unused_keys) > 0:
self.errors.append(
TypeCheckError(
src,
"%s (%s) has field(s) %s, but you haven't destructured them. (Hint: use `_` to denote unused fields.)"
% (
display_type(value_or_type),
path_name,
", ".join(unused_keys),
),
)
)
else:
if warn:
if value_or_type is not None:
self.errors.append(
TypeCheckError(
src,
"I can't destructure %s as a record because %s is not a record."
% (path_name, display_type(value_or_type)),
)
)
else:
raise TypeError("Destructuring non-record as record.")
for key, (sub_pattern, parse_src) in pattern.items():
value = value_or_type.get(key) if is_dict else None
if is_dict and value is None:
if warn:
self.errors.append(
TypeCheckError(
parse_src,
"I can't get the field %s from %s because %s doesn't have that field."
% (key, path_name, display_type(value_or_type)),
)
)
else:
raise TypeError("Given record doesn't have a key %s." % key)
valid = self.assign_to_pattern(
(sub_pattern, parse_src),
value,
warn,
"%s.%s" % (path or "<record>", key),
public,
certain=certain,
mutable=mutable,
)
if not valid:
return False
elif isinstance(pattern, tuple):
# I believe the interpreter uses actual Python tuples, while the
# type checker uses lists for tuple types. We should fix that for
# the type checker.
is_tuple = (
isinstance(value_or_type, list)
if warn
else isinstance(value_or_type, tuple)
)
if not is_tuple:
if warn:
if value_or_type is not None:
self.errors.append(
TypeCheckError(
src,
"I can't destructure %s as a tuple because %s is not a tuple."
% (path_name, display_type(value_or_type)),
)
)
else:
raise TypeError("Destructuring non-record as record.")
if is_tuple and len(pattern) != len(value_or_type):
if warn:
if len(pattern) > len(value_or_type):
_, parse_src = pattern[len(value_or_type)]
self.errors.append(
TypeCheckError(
parse_src,
"I can't destructure %d items from a %s."
% (len(pattern), display_type(value_or_type)),
)
)
else:
self.errors.append(
TypeCheckError(
src,
"I can't destructure only %d items from a %s. (Hint: use `_` to denote unused members of a destructured tuple.)"
% (len(pattern), display_type(value_or_type)),
)
)
else:
raise TypeError(
"Number of destructured values from tuple doesn't match tuple length."
)
for i, (sub_pattern, parse_src) in enumerate(pattern):
value = (
value_or_type[i] if is_tuple and i < len(value_or_type) else None
)
valid = self.assign_to_pattern(
(sub_pattern, parse_src),
value,
warn,
"%s.%d" % (path or "<tuple>", i),
public,
certain=certain,
mutable=mutable,
)
if not valid:
return False
elif isinstance(pattern, EnumPattern):
if warn:
problem = False
if not isinstance(value_or_type, EnumType):
if value_or_type is not None:
self.errors.append(
TypeCheckError(
src,
"I cannot destructure %s as an enum because it's a %s."
% (path_name, display_type(value_or_type)),
)
)
problem = True
else:
variant_types = value_or_type.get_types(pattern.variant)
if variant_types is None:
self.errors.append(
TypeCheckError(
src,
"%s has no variant %s because it's a %s."
% (
path_name,
pattern.variant,
display_type(value_or_type),
),
)
)
problem = True
elif len(pattern.patterns) < len(variant_types):
self.errors.append(
TypeCheckError(
src,
"Variant %s has %d fields, but you only destructure %d of them."
% (
pattern.variant,
len(variant_types),
len(pattern.patterns),
),
)
)
problem = True
elif len(pattern.patterns) > len(variant_types):
self.errors.append(
TypeCheckError(
pattern.patterns[len(variant_types)][1],
"Variant %s only has %d fields."
% (pattern.variant, len(variant_types)),
)
)
problem = True
else:
if not isinstance(value_or_type, EnumValue):
raise TypeError("Destructuring non-enum as enum.")
elif pattern.variant != value_or_type.variant:
return False
if warn and not problem and certain and len(value_or_type.variants) > 1:
self.errors.append(
TypeCheckError(
src,
"I can't be sure that %s will be a `%s`; for example, it could instead be a `%s`."
% (
path_name,
pattern.variant,
(
value_or_type.variants[1]
if value_or_type.variants[0][0] == pattern.variant
else value_or_type.variants[0]
)[0],
),
)
)
problem = True
for i, (sub_pattern, parse_src) in enumerate(pattern.patterns):
if warn:
value = None if problem else variant_types[i]
else:
value = value_or_type.values[i]
valid = self.assign_to_pattern(
(sub_pattern, parse_src),
value,
warn,
"%s.%s#%d" % (path or "<enum>", pattern.variant, i + 1),
public,
certain=certain,
mutable=mutable,
)
if not valid:
return False
elif isinstance(pattern, list):
if warn:
if (
not isinstance(value_or_type, NTypeVars)
or value_or_type.base_type is not n_list_type
):
if value_or_type is not None:
self.errors.append(
TypeCheckError(
src,
"I cannot destructure %s as a list because it's a %s."
% (path_name, display_type(value_or_type)),
)
)
return True
contained_type = value_or_type.typevars[0]
else:
if not isinstance(value_or_type, list):
raise TypeError("Destructuring non-list as list.")
if warn and certain:
self.errors.append(
TypeCheckError(
src,
"I can't be sure that %s has exactly %d item(s); for example, it could instead %s."
% (
path_name,
len(pattern),
"have two items" if len(pattern) == 0 else "be empty",
),
)
)
if not warn and len(value_or_type) != len(pattern):
return False
for i, (sub_pattern, parse_src) in enumerate(pattern):
valid = self.assign_to_pattern(
(sub_pattern, parse_src),
contained_type if warn else value_or_type[i],
warn,
"%s[%d]" % (path or "<enum variant>", i),
public,
certain=certain,
mutable=mutable,
)
if not valid:
return False
elif pattern is not None:
name = pattern
if warn and name in self.variables:
self.errors.append(
TypeCheckError(src, "You've already defined `%s`." % name)
)
self.variables[name] = Variable(value_or_type, value_or_type, public, mutable)
return True
async def eval_record_entry(self, entry):
if isinstance(entry, lark.Tree):
if entry.data == "spread":
return [entry.children[0]]
return entry.children[0].value, await self.eval_expr(entry.children[1])
else:
return entry.value, self.eval_value(entry)
"""
Deals with spread operators for lists
"""
async def eval_spread_list(self, spread_tree, list_val):
for val in await self.eval_expr(spread_tree.children[0]):
list_val.append(val)
def eval_value(self, value):
if value.type == "HEX":
return int(value.value, 16)
if value.type == "BINARY":
return int(value.value, 2)
if value.type == "OCTAL":
return int(value.value, 8)
if value.type == "NUMBER":
if "." in str(value.value):
return float(value)
return int(value)
elif value.type == "STRING":
return unescape(value[1:-1])
elif value.type == "BOOLEAN":
if value.value == "false":
return False
elif value.value == "true":
return True
else:
raise SyntaxError("Unexpected boolean value %s" % value.value)
elif value.type == "NAME":
return self.get_variable(value.value).value
elif value.type == "UNIT":
return ()
else:
raise SyntaxError(
"Unexpected value type %s value %s" % (value.type, value.value)
)
"""
Evaluate a parsed expression with Trees and Tokens from Lark.
"""
async def eval_expr(self, expr):
if isinstance(expr, lark.Token):
return self.eval_value(expr)
if expr.data == "ifelse_expr":
condition, if_true, if_false = expr.children
scope = self.new_scope()
if condition.data == "conditional_let":
pattern, value = condition.children
if scope.assign_to_pattern(
get_destructure_pattern(pattern), await self.eval_expr(value)
):
return await scope.eval_expr(if_true)
else:
return await scope.eval_expr(if_false)
elif await self.eval_expr(condition):
return await self.eval_expr(if_true)
else:
return await self.eval_expr(if_false)
elif expr.data == "function_def":
if len(expr.children) == 3:
arguments, returntype, codeblock = expr.children
else:
arguments, codeblock = expr.children
returntype = lark.Token("UNIT", "()")
arguments = arguments.children
# Remove generic declarations
if len(arguments) >= 1 and isinstance(arguments[0], lark.Tree) and arguments[0].data == "generic_declaration":
arguments = arguments[1:]
return Function(
self,
[self.get_name_type(arg, get_type=False) for arg in arguments],
returntype,
codeblock,
)
elif expr.data == "function_callback" or expr.data == "function_callback_pipe":
if expr.data == "function_callback":
function, *arguments = expr.children[0].children
else:
mainarg = expr.children[0]
function, *arguments = expr.children[1].children
arguments.append(mainarg)
arg_values = []
for arg in arguments:
if isinstance(arg, lark.Tree) and arg.data == "spread":
arg_values.extend(list(await self.eval_expr(arg.children[0])))
else:
arg_values.append(await self.eval_expr(arg))
if len(arg_values) == 0:
arg_values = [()]
func = await self.eval_expr(function)
with open(self.file_path, "r", encoding="utf-8") as f:
self.stack_trace.append(
(
expr,
File(
f,
name=os.path.relpath(
self.file_path, start=self.base_path
),
),
)
)
out = await func.run(arg_values)
self.stack_trace.pop()
return out
elif expr.data == "or_expression":
left, _, right = expr.children
left = await self.eval_expr(left)
right = await self.eval_expr(right)
if isinstance(left, int):
return left | right
if isinstance(left, bool):
return left or right
if left.variant == "yes":
return left.values[0]
else:
return right
elif expr.data == "and_expression":
left, _, right = expr.children
left = await self.eval_expr(left)
right = await self.eval_expr(right)
if isinstance(left, int):
return left & right
return left and right
elif expr.data == "xor_expression":
left, _, right = expr.children
return await self.eval_expr(left) ^ await self.eval_expr(right)
elif expr.data == "not_expression":
_, value = expr.children
return not await self.eval_expr(value)
elif expr.data == "in_expression":
left, _, right = expr.children
return await self.eval_expr(left) in await self.eval_expr(right)
elif expr.data == "compare_expression":
# compare_expression chains leftwards. It's rather complex because it