-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathparser.py
2113 lines (1843 loc) · 71.9 KB
/
parser.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
# pylint: disable=too-many-lines
from __future__ import annotations
import itertools
import logging
import textwrap
from collections import OrderedDict, defaultdict
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Union
import librflxlang as lang
import rflx.typing_ as rty
from rflx import expression as expr, model
from rflx.common import STDIN, unique
from rflx.error import Location, RecordFluxError, Severity, Subsystem, fail, warn
from rflx.identifier import ID, StrID
from rflx.integration import Integration
from rflx.model import declaration as decl, statement as stmt
from rflx.specification.const import RESERVED_WORDS
from . import style
from .cache import Cache
log = logging.getLogger(__name__)
def node_location(node: lang.RFLXNode, filename: Path, end_location: bool = False) -> Location:
start = node.token_start.sloc_range
end = node.token_end.sloc_range
return Location(
start=(start.start.line, start.start.column)
if not end_location
else (end.end.line, end.end.column),
source=filename,
end=(end.end.line, end.end.column),
)
def type_location(identifier: ID, node: lang.RFLXNode) -> Location:
"""
Create a location object.
The location object covers the area from the start of an identifier to the end of a node.
"""
assert identifier.location is not None
assert identifier.location.source is not None
return Location(
identifier.location.start,
identifier.location.source,
node_location(node, identifier.location.source).end,
)
def diagnostics_to_error(
diagnostics: Sequence[lang.Diagnostic], error: RecordFluxError, filename: Path
) -> bool:
"""Append langkit diagnostics to RecordFlux error. Return True if error occured."""
if len(diagnostics) == 0:
return False
for diag in diagnostics:
loc = diag.sloc_range
error.extend(
[
(
diag.message,
Subsystem.PARSER,
Severity.ERROR,
Location(
start=(loc.start.line, loc.start.column),
source=filename,
end=(loc.end.line, loc.end.column),
),
)
],
)
return True
def create_description(description: lang.Description = None) -> Optional[str]:
if description:
assert isinstance(description.text, str)
return description.text.split('"')[1]
return None
def create_transition(
error: RecordFluxError, transition: lang.Transition, filename: Path
) -> model.Transition:
if transition.kind_name not in ("Transition", "ConditionalTransition"):
raise NotImplementedError(f"Transition kind {transition.kind_name} unsupported")
target = create_id_or_null(error, transition.f_target, filename)
condition: expr.Expr = expr.TRUE
description = create_description(transition.f_description)
if isinstance(transition, lang.ConditionalTransition):
condition = create_bool_expression(error, transition.f_condition, filename)
return model.Transition(target, condition, description, node_location(transition, filename))
def create_reset(error: RecordFluxError, reset: lang.Statement, filename: Path) -> stmt.Statement:
assert isinstance(reset, lang.Reset)
return stmt.Reset(
create_id(error, reset.f_identifier, filename),
{
create_id(error, c.f_identifier, filename): create_expression(
error, c.f_expression, filename
)
for c in reset.f_associations
},
location=node_location(reset, filename),
)
def create_assignment(
error: RecordFluxError, assignment: lang.Statement, filename: Path
) -> stmt.Statement:
assert isinstance(assignment, lang.Assignment)
return stmt.VariableAssignment(
create_id(error, assignment.f_identifier, filename),
create_expression(error, assignment.f_expression, filename),
location=node_location(assignment, filename),
)
def create_message_field_assignment(
error: RecordFluxError, assignment: lang.Statement, filename: Path
) -> stmt.Statement:
assert isinstance(assignment, lang.MessageFieldAssignment)
return stmt.MessageFieldAssignment(
create_id(error, assignment.f_message, filename),
create_id(error, assignment.f_field, filename),
create_expression(error, assignment.f_expression, filename),
location=node_location(assignment, filename),
)
def create_attribute_statement(
error: RecordFluxError, expression: lang.Statement, filename: Path
) -> stmt.Statement:
assert isinstance(expression, lang.AttributeStatement)
attrs = {
"Append": stmt.Append,
"Extend": stmt.Extend,
"Read": stmt.Read,
"Write": stmt.Write,
}
constructor = attrs[expression.f_attr.text]
return constructor(
create_id(error, expression.f_identifier, filename),
create_expression(error, expression.f_expression, filename),
location=node_location(expression, filename),
)
def create_statement(
error: RecordFluxError, statement: lang.Statement, filename: Path
) -> stmt.Statement:
handlers = {
"Reset": create_reset,
"Assignment": create_assignment,
"MessageFieldAssignment": create_message_field_assignment,
"AttributeStatement": create_attribute_statement,
}
return handlers[statement.kind_name](error, statement, filename)
def create_state(
error: RecordFluxError, state: lang.State, package: ID, filename: Path
) -> model.State:
location = node_location(state, filename)
identifier = create_id(error, state.f_identifier, filename)
assert isinstance(state.f_body, lang.StateBody)
if state.f_identifier.text != state.f_body.f_end_identifier.text:
error.extend(
[
(
"inconsistent state identifier: "
f"{state.f_identifier.text} /= {state.f_body.f_end_identifier.text}",
Subsystem.PARSER,
Severity.ERROR,
location,
)
]
)
transitions = []
for t in state.f_body.f_conditional_transitions:
transitions.append(create_transition(error, t, filename))
transitions.append(create_transition(error, state.f_body.f_final_transition, filename))
exception_transition = (
create_transition(error, state.f_body.f_exception_transition, filename)
if state.f_body.f_exception_transition
else None
)
actions = []
for a in state.f_body.f_actions:
actions.append(create_statement(error, a, filename))
declarations = []
for d in state.f_body.f_declarations:
declarations.append(create_declaration(error, d, package, filename))
description = create_description(state.f_description)
return model.State(
identifier=identifier,
transitions=transitions,
exception_transition=exception_transition,
actions=actions,
declarations=declarations,
description=description,
location=node_location(state, filename),
)
def _check_session_identifier(
error: RecordFluxError, session: lang.SessionDecl, filename: Path
) -> None:
if session.f_identifier.text != session.f_end_identifier.text:
error.extend(
[
(
"inconsistent session identifier: "
f"{session.f_identifier.text} /= {session.f_end_identifier.text}",
Subsystem.PARSER,
Severity.ERROR,
node_location(session, filename),
)
]
)
def create_unproven_session(
error: RecordFluxError,
session: lang.SessionDecl,
package: ID,
filename: Path,
types: Sequence[model.Type] = None,
) -> model.UnprovenSession:
_check_session_identifier(error, session, filename)
return model.UnprovenSession(
package * create_id(error, session.f_identifier, filename),
[create_state(error, s, package, filename) for s in session.f_states],
[create_declaration(error, d, package, filename) for d in session.f_declarations],
[create_formal_declaration(error, p, package, filename) for p in session.f_parameters],
types or [],
node_location(session, filename),
)
def create_session(
error: RecordFluxError,
session: lang.SessionDecl,
package: ID,
filename: Path,
types: Sequence[model.Type] = None,
) -> Optional[model.Session]:
try:
return create_unproven_session(error, session, package, filename, types).proven()
except RecordFluxError as e:
error.extend(e)
return None
def create_id(error: RecordFluxError, identifier: lang.AbstractID, filename: Path) -> ID:
if isinstance(identifier, lang.UnqualifiedID):
if identifier.text.lower() in RESERVED_WORDS:
error.extend(
[
(
f'reserved word "{identifier.text}" used as identifier',
Subsystem.PARSER,
Severity.ERROR,
node_location(identifier, filename),
)
]
)
return ID(identifier.text, location=node_location(identifier, filename))
if isinstance(identifier, lang.ID):
name = ID(identifier.f_name.text, location=node_location(identifier.f_name, filename))
if identifier.f_package:
return (
ID(
identifier.f_package.text,
location=node_location(identifier.f_package, filename),
)
* name
)
return name
raise NotImplementedError(f"Invalid ID: {identifier.text} {type(identifier)}")
def create_id_or_null(error: RecordFluxError, identifier: lang.AbstractID, filename: Path) -> ID:
if isinstance(identifier, lang.UnqualifiedID) and identifier.text.lower() == "null":
return ID("null", location=node_location(identifier, filename))
return create_id(error, identifier, filename)
def create_sequence(
error: RecordFluxError,
identifier: ID,
_parameters: lang.Parameters,
sequence: lang.TypeDef,
types: Sequence[model.Type],
_skip_verification: bool,
_workers: int,
_cache: Cache,
filename: Path,
) -> Optional[model.Type]:
assert isinstance(sequence, lang.SequenceTypeDef)
element_identifier = model.internal_type_identifier(
create_id(error, sequence.f_element_type, filename), identifier.parent
)
try:
element_type = next(t for t in types if element_identifier == t.identifier)
except StopIteration:
error.extend(
[
(
f'undefined element type "{element_identifier}"',
Subsystem.PARSER,
Severity.ERROR,
element_identifier.location,
)
]
)
return None
result = model.Sequence(identifier, element_type, type_location(identifier, sequence))
error.extend(result.error)
return result
def create_numeric_literal(
_error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
location = node_location(expression, filename)
num = expression.text.split("#")
if len(num) == 1:
return expr.Number(int(num[0]), location=location)
if len(num) == 3:
base = int(num[0])
return expr.Number(int(num[1], base), base=base, location=location)
raise NotImplementedError(f"Invalid numeric literal: {expression.text}")
OPERATIONS: Mapping[str, type[expr.BinExpr]] = {
"OpIn": expr.In,
"OpNotin": expr.NotIn,
"OpEq": expr.Equal,
"OpNeq": expr.NotEqual,
}
def create_binop(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.BinOp)
loc = node_location(expression, filename)
if expression.f_op.kind_name in OPERATIONS:
return OPERATIONS[expression.f_op.kind_name](
create_expression(error, expression.f_left, filename),
create_expression(error, expression.f_right, filename),
location=loc,
)
if expression.f_op.kind_name in BOOLEAN_OPERATIONS:
return BOOLEAN_OPERATIONS[expression.f_op.kind_name](
create_expression(error, expression.f_left, filename),
create_expression(error, expression.f_right, filename),
location=loc,
)
left = create_math_expression(error, expression.f_left, filename)
right = create_math_expression(error, expression.f_right, filename)
if expression.f_op.kind_name in MATH_OPERATIONS:
return MATH_OPERATIONS[expression.f_op.kind_name](left, right, location=loc)
if expression.f_op.kind_name in MATH_COMPARISONS:
return MATH_COMPARISONS[expression.f_op.kind_name](left, right, location=loc)
raise NotImplementedError(f"Invalid BinOp {expression.f_op.kind_name} => {expression.text}")
MATH_OPERATIONS: Mapping[str, Union[type[expr.BinExpr], type[expr.AssExpr]]] = {
"OpPow": expr.Pow,
"OpAdd": expr.Add,
"OpSub": expr.Sub,
"OpMul": expr.Mul,
"OpDiv": expr.Div,
"OpMod": expr.Mod,
}
def create_math_binop(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.BinOp)
if expression.f_op.kind_name in MATH_OPERATIONS:
return MATH_OPERATIONS[expression.f_op.kind_name](
create_math_expression(error, expression.f_left, filename),
create_math_expression(error, expression.f_right, filename),
location=node_location(expression, filename),
)
if expression.f_op.kind_name in [*OPERATIONS, *MATH_COMPARISONS, *BOOLEAN_OPERATIONS]:
fail(
"boolean expression in math context",
Subsystem.PARSER,
location=node_location(expression, filename),
)
raise NotImplementedError(
f"Invalid math BinOp {expression.f_op.kind_name} => {expression.text}"
)
MATH_COMPARISONS: Mapping[str, type[expr.Relation]] = {
"OpLt": expr.Less,
"OpGt": expr.Greater,
"OpLe": expr.LessEqual,
"OpGe": expr.GreaterEqual,
}
BOOLEAN_OPERATIONS = {
"OpAnd": expr.And,
"OpOr": expr.Or,
}
def create_bool_binop(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.BinOp)
if expression.f_op.kind_name in MATH_COMPARISONS:
return MATH_COMPARISONS[expression.f_op.kind_name](
create_math_expression(error, expression.f_left, filename),
create_math_expression(error, expression.f_right, filename),
location=node_location(expression, filename),
)
if expression.f_op.kind_name in BOOLEAN_OPERATIONS:
return BOOLEAN_OPERATIONS[expression.f_op.kind_name](
create_bool_expression(error, expression.f_left, filename),
create_bool_expression(error, expression.f_right, filename),
location=node_location(expression, filename),
)
if expression.f_op.kind_name in OPERATIONS:
return OPERATIONS[expression.f_op.kind_name](
create_expression(error, expression.f_left, filename),
create_expression(error, expression.f_right, filename),
location=node_location(expression, filename),
)
if expression.f_op.kind_name in MATH_OPERATIONS:
fail(
"math expression in boolean context",
Subsystem.PARSER,
location=node_location(expression, filename),
)
raise NotImplementedError(
f"Invalid bool BinOp {expression.f_op.kind_name} => {expression.text}"
)
def create_paren_bool_expression(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.ParenExpression)
return create_bool_expression(error, expression.f_data, filename)
def create_paren_math_expression(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.ParenExpression)
return create_math_expression(error, expression.f_data, filename)
def create_paren_expression(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.ParenExpression)
return create_expression(error, expression.f_data, filename)
def create_variable(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.Variable)
location = node_location(expression, filename)
if expression.f_identifier.text.lower() in ("true", "false"):
return expr.Literal(
create_id(error, expression.f_identifier, filename),
location=location,
type_=rty.BOOLEAN,
)
return expr.Variable(create_id(error, expression.f_identifier, filename), location=location)
def create_math_attribute(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.Attribute)
inner = create_expression(error, expression.f_expression, filename)
if expression.f_kind.kind_name == "AttrLast":
return expr.Last(inner)
if expression.f_kind.kind_name == "AttrFirst":
return expr.First(inner)
if expression.f_kind.kind_name == "AttrSize":
return expr.Size(inner)
raise NotImplementedError(
f"Invalid math attribute: {expression.f_kind.kind_name} => {expression.text}"
)
def create_attribute(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.Attribute)
inner = create_expression(error, expression.f_expression, filename)
if expression.f_kind.kind_name == "AttrLast":
return expr.Last(inner)
if expression.f_kind.kind_name == "AttrFirst":
return expr.First(inner)
if expression.f_kind.kind_name == "AttrSize":
return expr.Size(inner)
if expression.f_kind.kind_name == "AttrValidChecksum":
return expr.ValidChecksum(inner)
if expression.f_kind.kind_name == "AttrHasData":
return expr.HasData(inner)
if expression.f_kind.kind_name == "AttrHead":
return expr.Head(inner)
if expression.f_kind.kind_name == "AttrOpaque":
return expr.Opaque(inner)
if expression.f_kind.kind_name == "AttrPresent":
return expr.Present(inner)
if expression.f_kind.kind_name == "AttrValid":
return expr.Valid(inner)
raise NotImplementedError(
f"Invalid attribute: {expression.f_kind.kind_name} => {expression.text}"
)
def create_sequence_aggregate(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.SequenceAggregate)
return expr.Aggregate(
*[create_math_expression(error, v, filename) for v in expression.f_values],
location=node_location(expression, filename),
)
def create_string_literal(
_error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
return expr.String(
expression.text.split('"')[1],
location=node_location(expression, filename),
)
def create_call(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.Call)
return expr.Call(
create_id(error, expression.f_identifier, filename),
[create_expression(error, a, filename) for a in expression.f_arguments],
location=node_location(expression, filename),
)
def create_quantified_expression(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.QuantifiedExpression)
param_id = create_id(error, expression.f_parameter_identifier, filename)
iterable = create_expression(error, expression.f_iterable, filename)
predicate = create_expression(error, expression.f_predicate, filename)
location = node_location(expression, filename)
if expression.f_operation.kind_name == "QuantifierAll":
return expr.ForAllIn(param_id, iterable, predicate, location)
if expression.f_operation.kind_name == "QuantifierSome":
return expr.ForSomeIn(param_id, iterable, predicate, location)
raise NotImplementedError(f"Invalid quantified: {expression.f_operation.text}")
def create_binding(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.Binding)
bindings: Mapping[Union[str, ID], expr.Expr] = {
create_id(error, b.f_identifier, filename): create_expression(
error, b.f_expression, filename
)
for b in expression.f_bindings
}
return expr.Binding(
create_expression(error, expression.f_expression, filename),
bindings,
node_location(expression, filename),
)
def create_variable_decl(
error: RecordFluxError, declaration: lang.LocalDecl, package: ID, filename: Path
) -> decl.BasicDeclaration:
assert isinstance(declaration, lang.VariableDecl)
initializer = (
create_expression(error, declaration.f_initializer, filename)
if declaration.f_initializer
else None
)
return decl.VariableDeclaration(
create_id(error, declaration.f_identifier, filename),
model.internal_type_identifier(
create_id(error, declaration.f_type_identifier, filename), package
),
initializer,
location=node_location(declaration, filename),
)
def create_channel_decl(
error: RecordFluxError,
declaration: lang.FormalDecl,
_package: ID,
filename: Path,
) -> decl.FormalDeclaration:
assert isinstance(declaration, lang.FormalChannelDecl)
readable = False
writable = False
grouped = defaultdict(list)
for p in declaration.f_parameters:
grouped[p.kind_name].append(node_location(p, filename))
for name, locations in grouped.items():
check_duplicate_aspect(error, name, locations)
if name == "Readable":
readable = True
elif name == "Writable":
writable = True
else:
raise NotImplementedError(f"channel parameter: {name}")
return decl.ChannelDeclaration(
create_id(error, declaration.f_identifier, filename),
readable=readable,
writable=writable,
location=node_location(declaration, filename),
)
def create_renaming_decl(
error: RecordFluxError, declaration: lang.LocalDecl, package: ID, filename: Path
) -> decl.BasicDeclaration:
assert isinstance(declaration, lang.RenamingDecl)
selected = create_expression(error, declaration.f_expression, filename)
assert isinstance(selected, expr.Selected)
return decl.RenamingDeclaration(
create_id(error, declaration.f_identifier, filename),
model.internal_type_identifier(
create_id(error, declaration.f_type_identifier, filename), package
),
selected,
location=node_location(declaration, filename),
)
def create_function_decl(
error: RecordFluxError,
declaration: lang.FormalDecl,
package: ID,
filename: Path,
) -> decl.FormalDeclaration:
assert isinstance(declaration, lang.FormalFunctionDecl)
arguments = []
if declaration.f_parameters:
for p in declaration.f_parameters.f_parameters:
arguments.append(
decl.Argument(
create_id(error, p.f_identifier, filename),
model.internal_type_identifier(
create_id(error, p.f_type_identifier, filename), package
),
)
)
return decl.FunctionDeclaration(
create_id(error, declaration.f_identifier, filename),
arguments,
model.internal_type_identifier(
create_id(error, declaration.f_return_type_identifier, filename), package
),
location=node_location(declaration, filename),
)
def create_negation(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.Negation)
math_expr = create_math_expression(error, expression.f_data, filename)
assert isinstance(math_expr, expr.Number)
return expr.Number(-math_expr.value, math_expr.base, node_location(expression, filename))
def create_concatenation(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.Concatenation)
left = create_expression(error, expression.f_left, filename)
right = create_expression(error, expression.f_right, filename)
assert isinstance(left, expr.Aggregate)
assert isinstance(right, expr.Aggregate)
return expr.Aggregate(
*(left.elements + right.elements), location=node_location(expression, filename)
)
def create_comprehension(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.Comprehension)
condition = (
create_bool_expression(error, expression.f_condition, filename)
if expression.f_condition
else expr.TRUE
)
return expr.Comprehension(
create_id(error, expression.f_iterator, filename),
create_expression(error, expression.f_sequence, filename),
create_expression(error, expression.f_selector, filename),
condition,
node_location(expression, filename),
)
def create_selected(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.SelectNode)
return expr.Selected(
create_expression(error, expression.f_expression, filename),
create_id(error, expression.f_selector, filename),
location=node_location(expression, filename),
)
def create_case(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.CaseExpression)
def create_choice(
value: Union[lang.AbstractID, lang.Expr], filename: Path
) -> Union[ID, expr.Number]:
if isinstance(value, lang.AbstractID):
return create_id(error, value, filename)
assert isinstance(value, lang.Expr)
result = create_numeric_literal(error, value, filename)
assert isinstance(result, expr.Number)
return result
choices: Sequence[tuple[Sequence[Union[ID, expr.Number]], expr.Expr]] = [
(
[
create_choice(s, filename)
for s in c.f_selectors
if isinstance(s, (lang.AbstractID, lang.Expr))
],
create_expression(error, c.f_expression, filename),
)
for c in expression.f_choices
]
return expr.CaseExpr(
create_expression(error, expression.f_expression, filename),
choices,
location=node_location(expression, filename),
)
def create_conversion(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
assert isinstance(expression, lang.Conversion)
return expr.Conversion(
create_id(error, expression.f_target_identifier, filename),
create_expression(error, expression.f_argument, filename),
location=node_location(expression, filename),
)
def create_message_aggregate(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
assert isinstance(expression, lang.MessageAggregate)
values: Mapping[StrID, expr.Expr] = {}
if isinstance(expression.f_values, lang.NullMessageAggregate):
values = {}
elif isinstance(expression.f_values, lang.MessageAggregateAssociations):
values = {
create_id(error, c.f_identifier, filename): create_expression(
error, c.f_expression, filename
)
for c in expression.f_values.f_associations
}
else:
raise NotImplementedError(f"invalid message field: {type(expression.f_values)}")
return expr.MessageAggregate(
create_id(error, expression.f_identifier, filename),
values,
location=node_location(expression, filename),
)
EXPRESSION_MAP = {
"NumericLiteral": create_numeric_literal,
"ParenExpression": create_paren_expression,
"Variable": create_variable,
"Attribute": create_attribute,
"SequenceAggregate": create_sequence_aggregate,
"StringLiteral": create_string_literal,
"Call": create_call,
"QuantifiedExpression": create_quantified_expression,
"Binding": create_binding,
"Negation": create_negation,
"Concatenation": create_concatenation,
"Comprehension": create_comprehension,
"SelectNode": create_selected,
"Conversion": create_conversion,
"MessageAggregate": create_message_aggregate,
"BinOp": create_binop,
"CaseExpression": create_case,
}
def create_expression(error: RecordFluxError, expression: lang.Expr, filename: Path) -> expr.Expr:
return EXPRESSION_MAP[expression.kind_name](error, expression, filename)
def create_declaration(
error: RecordFluxError, declaration: lang.LocalDecl, package: ID, filename: Path
) -> decl.BasicDeclaration:
handlers = {
"VariableDecl": create_variable_decl,
"RenamingDecl": create_renaming_decl,
}
return handlers[declaration.kind_name](error, declaration, package, filename)
def create_formal_declaration(
error: RecordFluxError, declaration: lang.FormalDecl, package: ID, filename: Path
) -> decl.FormalDeclaration:
handlers = {
"FormalChannelDecl": create_channel_decl,
"FormalFunctionDecl": create_function_decl,
}
return handlers[declaration.kind_name](error, declaration, package, filename)
def create_math_expression(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
handlers = {
"NumericLiteral": create_numeric_literal,
"BinOp": create_math_binop,
"ParenExpression": create_paren_math_expression,
"Variable": create_variable,
"Call": create_call,
"Binding": create_binding,
"Negation": create_negation,
"Attribute": create_math_attribute,
"SelectNode": create_selected,
"SequenceAggregate": create_sequence_aggregate,
}
result = handlers[expression.kind_name](error, expression, filename)
if result.type_ == rty.BOOLEAN:
fail(
"boolean expression in math context",
Subsystem.PARSER,
location=node_location(expression, filename),
)
return result
def create_bool_expression(
error: RecordFluxError, expression: lang.Expr, filename: Path
) -> expr.Expr:
handlers = {
"BinOp": create_bool_binop,
"ParenExpression": create_paren_bool_expression,
"Attribute": create_attribute,
"Call": create_call,
"Variable": create_variable,
"QuantifiedExpression": create_quantified_expression,
"Binding": create_binding,
"SelectNode": create_selected,
"CaseExpression": create_case,
}
if expression.kind_name == "NumericLiteral":
fail(
"math expression in boolean context",
Subsystem.PARSER,
location=node_location(expression, filename),
)
return handlers[expression.kind_name](error, expression, filename)
def create_modular(
error: RecordFluxError,
identifier: ID,
_parameters: lang.Parameters,
modular: lang.TypeDef,
_types: Sequence[model.Type],
_skip_verification: bool,
_workers: int,
_cache: Cache,
filename: Path,
) -> None:
assert isinstance(modular, lang.ModularTypeDef)
modulus = create_math_expression(error, modular.f_mod, filename).simplified()
assert isinstance(modulus, expr.Number)
upper = int(modulus) - 1
error.extend(
[
(
"modular integer types are not supported",
Subsystem.PARSER,
Severity.ERROR,
type_location(identifier, modular),
),
(
f'use "type {identifier.name} is range 0 .. {upper}'
f' with Size => {upper.bit_length()}" instead',
Subsystem.PARSER,
Severity.INFO,
type_location(identifier, modular),
),
]
)
def create_range(
error: RecordFluxError,
identifier: ID,
_parameters: lang.Parameters,
rangetype: lang.TypeDef,
_types: Sequence[model.Type],
_skip_verification: bool,
_workers: int,
_cache: Cache,
filename: Path,
) -> Optional[model.Type]:
assert isinstance(rangetype, lang.RangeTypeDef)
if rangetype.f_size.f_identifier.text != "Size":
error.extend(
[
(
f"invalid aspect {rangetype.f_size.f_identifier.text} "
f"for range type {identifier}",
Subsystem.PARSER,
Severity.ERROR,
node_location(rangetype, filename),
)
]
)
size = create_math_expression(error, rangetype.f_size.f_value, filename)
result = model.Integer(
identifier,
create_math_expression(error, rangetype.f_first, filename),
create_math_expression(error, rangetype.f_last, filename),
size,
type_location(identifier, rangetype),
)
error.extend(result.error)
return result
def create_null_message(
_error: RecordFluxError,
identifier: ID,
_parameters: lang.Parameters,
message: lang.TypeDef,
_types: Sequence[model.Type],
_skip_verification: bool,
_workers: int,
_cache: Cache,
_filename: Path,
) -> Optional[model.Type]:
assert isinstance(message, lang.NullMessageTypeDef)
return model.Message(identifier, [], {}, location=type_location(identifier, message))
def create_message(
error: RecordFluxError,
identifier: ID,
parameters: lang.Parameters,
message: lang.TypeDef,
types: Sequence[model.Type],
skip_verification: bool,
workers: int,
cache: Cache,
filename: Path,
) -> Optional[model.Type]:
# pylint: disable = too-many-arguments, too-many-locals
assert isinstance(message, lang.MessageTypeDef)
fields = message.f_message_fields
field_types, message_arguments = create_message_types(
error, identifier, parameters, fields, types, filename
)
structure = create_message_structure(error, fields, filename)