forked from bmw-software-engineering/trlc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
1756 lines (1519 loc) · 66.5 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
#!/usr/bin/env python3
#
# TRLC - Treat Requirements Like Code
# Copyright (C) 2022-2023 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
#
# This file is part of the TRLC Python Reference Implementation.
#
# TRLC is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# TRLC is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with TRLC. If not, see <https://www.gnu.org/licenses/>.
import re
from trlc.nested import Nested_Lexer
from trlc.lexer import Token_Base, Token, Lexer_Base, TRLC_Lexer
from trlc.errors import Message_Handler, TRLC_Error
from trlc import ast
class Markup_Token(Token_Base):
KIND = {
"CHARACTER" : "character",
"REFLIST_BEGIN" : "[[",
"REFLIST_END" : "]]",
"REFLIST_COMMA" : ",",
"REFLIST_DOT" : ".",
"REFLIST_IDENTIFIER" : "identifier",
}
def __init__(self, location, kind, value):
super().__init__(location, kind, value)
assert isinstance(value, str)
class Markup_Lexer(Nested_Lexer):
def __init__(self, mh, literal):
super().__init__(mh, literal)
self.in_reflist = False
def file_location(self):
return self.origin_location
def token(self):
if self.in_reflist:
self.skip_whitespace()
else:
self.advance()
if self.cc is None:
return None
start_pos = self.lexpos
start_line = self.line_no
start_col = self.col_no
if self.cc == "[" and self.nc == "[":
kind = "REFLIST_BEGIN"
self.advance()
if self.in_reflist:
self.mh.lex_error(self.source_location(start_line,
start_col,
start_pos,
start_pos + 1),
"cannot nest reference lists")
else:
self.in_reflist = True
elif self.cc == "]" and self.nc == "]":
kind = "REFLIST_END"
self.advance()
if self.in_reflist:
self.in_reflist = False
else:
self.mh.lex_error(self.source_location(start_line,
start_col,
start_pos,
start_pos + 1),
"opening [[ for this ]] found")
elif not self.in_reflist:
kind = "CHARACTER"
elif self.cc == ",":
kind = "REFLIST_COMMA"
elif self.cc == ".":
kind = "REFLIST_DOT"
elif self.is_alpha(self.cc):
kind = "REFLIST_IDENTIFIER"
while self.nc and (self.is_alnum(self.nc) or
self.nc == "_"):
self.advance()
else:
self.mh.lex_error(self.source_location(start_line,
start_col,
start_pos,
start_pos),
"unexpected character '%s'" % self.cc)
loc = self.source_location(start_line,
start_col,
start_pos,
self.lexpos)
return Markup_Token(loc,
kind,
self.content[start_pos:self.lexpos + 1])
class Parser_Base:
def __init__(self, mh, lexer, eoc_name, token_map, keywords):
assert isinstance(mh, Message_Handler)
assert isinstance(lexer, Lexer_Base)
assert isinstance(eoc_name, str)
assert isinstance(token_map, dict)
assert isinstance(keywords, frozenset)
self.mh = mh
self.lexer = lexer
self.eoc_name = eoc_name
self.language_tokens = token_map
self.language_keywords = keywords
self.ct = None
self.nt = None
self.advance()
def advance(self):
# lobster-trace: LRM.Comments
self.ct = self.nt
while True:
self.nt = self.lexer.token()
if self.nt is None or self.nt.kind != "COMMENT":
break
def skip_until_newline(self):
if self.ct is None:
return
current_line = self.ct.location.line_no
while self.nt and self.nt.location.line_no == current_line:
self.advance()
def peek(self, kind):
assert kind in self.language_tokens, \
"%s is not a valid token" % kind
return self.nt is not None and self.nt.kind == kind
def peek_eof(self):
return self.nt is None
def peek_kw(self, value):
assert value in self.language_keywords, \
"%s is not a valid keyword" % value
return self.peek("KEYWORD") and self.nt.value == value
def match(self, kind):
assert kind in self.language_tokens, \
"%s is not a valid token" % kind
if self.nt is None:
if self.ct is None:
self.mh.error(self.lexer.file_location(),
"expected %s, encountered %s instead" %
(self.language_tokens[kind], self.eoc_name))
else:
self.mh.error(self.ct.location,
"expected %s, encountered %s instead" %
(self.language_tokens[kind], self.eoc_name))
elif self.nt.kind != kind:
self.mh.error(self.nt.location,
"expected %s, encountered %s instead" %
(self.language_tokens[kind],
self.language_tokens[self.nt.kind]))
self.advance()
def match_eof(self):
if self.nt is not None:
self.mh.error(self.nt.location,
"expected %s, encountered %s instead" %
(self.eoc_name,
self.language_tokens[self.nt.kind]))
def match_kw(self, value):
assert value in self.language_keywords, \
"%s is not a valid keyword" % value
if self.nt is None:
if self.ct is None:
self.mh.error(self.lexer.file_location(),
"expected keyword %s, encountered %s instead" %
(value, self.eoc_name))
else:
self.mh.error(self.ct.location,
"expected keyword %s, encountered %s instead" %
(value, self.eoc_name))
elif self.nt.kind != "KEYWORD":
self.mh.error(self.nt.location,
"expected keyword %s, encountered %s instead" %
(value,
self.language_tokens[self.nt.kind]))
elif self.nt.value != value:
self.mh.error(self.nt.location,
"expected keyword %s,"
" encountered keyword %s instead" %
(value, self.nt.value))
self.advance()
class Markup_Parser(Parser_Base):
def __init__(self, parent, literal):
assert isinstance(parent, Parser)
super().__init__(parent.mh, Markup_Lexer(parent.mh, literal),
eoc_name = "end-of-string",
token_map = Markup_Token.KIND,
keywords = frozenset())
self.parent = parent
self.references = literal.references
def parse_all_references(self):
while self.nt:
if self.peek("CHARACTER"):
self.advance()
else:
self.parse_ref_list()
self.match_eof()
return self.references
def parse_ref_list(self):
self.match("REFLIST_BEGIN")
self.parse_qualified_name()
while self.peek("REFLIST_COMMA"):
self.match("REFLIST_COMMA")
self.parse_qualified_name()
self.match("REFLIST_END")
def parse_qualified_name(self):
# lobster-trace: LRM.Qualified_Name
# lobster-trace: LRM.Valid_Qualifier
# lobster-trace: LRM.Valid_Name
self.match("REFLIST_IDENTIFIER")
if self.peek("REFLIST_DOT"):
package = self.parent.stab.lookup_direct(
mh = self.mh,
name = self.ct.value,
error_location = self.ct.location,
required_subclass = ast.Package)
if not self.parent.cu.is_visible(package):
self.mh.error(self.ct.location,
"package must be imported before use")
self.match("REFLIST_DOT")
self.match("REFLIST_IDENTIFIER")
else:
package = self.parent.cu.package
ref = ast.Record_Reference(location = self.ct.location,
name = self.ct.value,
typ = None,
package = package)
self.references.append(ref)
class Parser(Parser_Base):
COMPARISON_OPERATOR = ("==", "!=", "<", "<=", ">", ">=")
ADDING_OPERATOR = ("+", "-")
MULTIPLYING_OPERATOR = ("*", "/", "%")
def __init__(self,
mh,
stab,
file_name,
lint_mode,
error_recovery,
primary_file=True,
lexer=None):
assert isinstance(mh, Message_Handler)
assert isinstance(stab, ast.Symbol_Table)
assert isinstance(file_name, str)
assert isinstance(lint_mode, bool)
assert isinstance(error_recovery, bool)
assert isinstance(primary_file, bool)
assert isinstance(lexer, TRLC_Lexer) or lexer is None
if lexer:
super().__init__(mh, lexer,
eoc_name = "end-of-file",
token_map = Token.KIND,
keywords = TRLC_Lexer.KEYWORDS)
else:
super().__init__(mh, TRLC_Lexer(mh, file_name),
eoc_name = "end-of-file",
token_map = Token.KIND,
keywords = TRLC_Lexer.KEYWORDS)
self.lint_mode = lint_mode
self.error_recovery = error_recovery
self.stab = stab
self.cu = ast.Compilation_Unit(file_name)
self.primary = primary_file
self.secondary = False
# Controls if the file is actually fully parsed: primary means
# it was selected on the command-line and secondary means it
# was selected by dependency analysis.
self.builtin_bool = stab.table["Boolean"]
self.builtin_int = stab.table["Integer"]
self.builtin_decimal = stab.table["Decimal"]
self.builtin_str = stab.table["String"]
self.builtin_mstr = stab.table["Markup_String"]
self.section = []
self.default_scope = ast.Scope()
self.default_scope.push(self.stab)
def parse_described_name(self):
# lobster-trace: LRM.Described_Names
# lobster-trace: LRM.Described_Name_Description
self.match("IDENTIFIER")
name = self.ct
if self.peek("STRING"):
self.match("STRING")
return name, self.ct.value
else:
return name, None
def parse_qualified_name(self,
scope,
required_subclass=None,
match_ident=True):
# lobster-trace: LRM.Qualified_Name
# lobster-trace: LRM.Valid_Qualifier
# lobster-trace: LRM.Valid_Name
assert isinstance(scope, ast.Scope)
assert required_subclass is None or isinstance(required_subclass, type)
assert isinstance(match_ident, bool)
if match_ident:
self.match("IDENTIFIER")
sym = scope.lookup(self.mh, self.ct)
if isinstance(sym, ast.Package):
if not self.cu.is_visible(sym):
self.mh.error(self.ct.location,
"package must be imported before use")
self.match("DOT")
self.match("IDENTIFIER")
return sym.symbols.lookup(self.mh, self.ct, required_subclass)
else:
# Easiest way to generate the correct error message
return scope.lookup(self.mh, self.ct, required_subclass)
def parse_type_declaration(self):
# lobster-trace: LRM.Type_Declarations
if self.peek_kw("enum"):
n_item = self.parse_enum_declaration()
elif self.peek_kw("tuple"):
n_item = self.parse_tuple_declaration()
else:
n_item = self.parse_record_declaration()
assert isinstance(n_item, ast.Concrete_Type)
return n_item
def parse_enum_declaration(self):
# lobster-trace: LRM.Enumeration_Declaration
self.match_kw("enum")
name, description = self.parse_described_name()
enum = ast.Enumeration_Type(name = name.value,
description = description,
location = name.location,
package = self.cu.package)
self.cu.package.symbols.register(self.mh, enum)
self.match("C_BRA")
empty = True
while not self.peek("C_KET"):
name, description = self.parse_described_name()
lit = ast.Enumeration_Literal_Spec(name = name.value,
description = description,
location = name.location,
enum = enum)
empty = False
enum.literals.register(self.mh, lit)
self.match("C_KET")
if empty:
# lobster-trace: LRM.No_Empty_Enumerations
self.mh.error(enum.location,
"empty enumerations are not permitted")
return enum
def parse_tuple_field(self,
n_tuple,
optional_allowed,
optional_reason,
optional_required):
assert isinstance(n_tuple, ast.Tuple_Type)
assert isinstance(optional_allowed, bool)
assert isinstance(optional_reason, str)
assert isinstance(optional_required, bool)
assert optional_allowed or not optional_required
field_name, field_description = self.parse_described_name()
if optional_required or self.peek_kw("optional"):
self.match_kw("optional")
if optional_allowed:
field_is_optional = True
else:
self.mh.error(self.ct.location, optional_reason)
else:
field_is_optional = False
# lobster-trace: LRM.Tuple_Field_Types
field_type = self.parse_qualified_name(self.default_scope,
ast.Type)
return ast.Composite_Component(
name = field_name.value,
description = field_description,
location = field_name.location,
member_of = n_tuple,
n_typ = field_type,
optional = field_is_optional)
def parse_tuple_declaration(self):
# lobster-trace: LRM.Tuple_Declaration
self.match_kw("tuple")
name, description = self.parse_described_name()
n_tuple = ast.Tuple_Type(name = name.value,
description = description,
location = name.location,
package = self.cu.package)
self.match("C_BRA")
n_field = self.parse_tuple_field(
n_tuple,
optional_allowed = False,
optional_reason = "first field may not be optional",
optional_required = False)
n_tuple.components.register(self.mh, n_field)
has_separators = False
optional_required = False
separator_allowed = True
while self.peek_kw("separator") or self.peek("IDENTIFIER"):
if has_separators or self.peek_kw("separator"):
has_separators = True
self.match_kw("separator")
if not separator_allowed:
# lobster-trace: LRM.Tuple_Separators_All_Or_None
self.mh.error(self.ct.location,
"either all fields must be separated,"
" or none")
if self.peek("IDENTIFIER") or \
self.peek("AT") or \
self.peek("COLON") or \
self.peek("SEMICOLON"):
self.advance()
n_tuple.add_separator(ast.Separator(self.ct))
else:
separator_allowed = False
# lobster-trace: LRM.Tuple_Optional_Requires_Separators
n_field = self.parse_tuple_field(
n_tuple,
optional_allowed = has_separators,
optional_reason = ("optional only permitted in tuples"
" with separators"),
optional_required = optional_required)
n_tuple.components.register(self.mh, n_field)
# lobster-trace: LRM.Tuple_Optional_Fields
optional_required |= n_field.optional
self.match("C_KET")
# Final check to ban tuples with separators containing other
# tuples.
if has_separators:
# lobster-trace: LRM.Restricted_Tuple_Nesting
for n_field in n_tuple.components.values():
if isinstance(n_field.n_typ, ast.Tuple_Type) and \
n_field.n_typ.has_separators():
self.mh.error(
n_field.location,
"tuple type %s, which contains separators,"
" may not contain another tuple with separators"
% n_tuple.name)
# Late registration to avoid recursion in tuples
# lobster-trace: LRM.Tuple_Field_Types
self.cu.package.symbols.register(self.mh, n_tuple)
return n_tuple
def parse_record_component(self, n_record):
assert isinstance(n_record, ast.Record_Type)
c_name, c_descr = self.parse_described_name()
if self.peek_kw("optional"):
self.match_kw("optional")
c_optional = True
else:
c_optional = False
c_typ = self.parse_qualified_name(self.default_scope,
ast.Type)
if self.peek("S_BRA"):
self.match("S_BRA")
self.match("INTEGER")
a_lo = self.ct.value
loc_lo = self.ct.location
self.match("RANGE")
a_loc = self.ct.location
if self.peek("INTEGER"):
self.match("INTEGER")
a_hi = self.ct.value
elif self.peek("OPERATOR") and self.nt.value == "*":
self.match("OPERATOR")
a_hi = None
else:
self.mh.error(self.nt.location,
"expected INTEGER or * for upper bound")
loc_hi = self.ct.location
self.match("S_KET")
c_typ = ast.Array_Type(location = a_loc,
element_type = c_typ,
lower_bound = a_lo,
upper_bound = a_hi,
loc_lower = loc_lo,
loc_upper = loc_hi)
return ast.Composite_Component(name = c_name.value,
description = c_descr,
location = c_name.location,
member_of = n_record,
n_typ = c_typ,
optional = c_optional)
def parse_record_declaration(self):
if self.peek_kw("abstract"):
self.match_kw("abstract")
is_abstract = True
is_final = False
elif self.peek_kw("final"):
self.match_kw("final")
is_abstract = False
is_final = True
else:
is_abstract = False
is_final = False
self.match_kw("type")
name, description = self.parse_described_name()
if self.peek_kw("extends"):
self.match_kw("extends")
root_record = self.parse_qualified_name(self.default_scope,
ast.Record_Type)
else:
root_record = None
if self.lint_mode and \
root_record and root_record.is_final and \
not is_final:
self.mh.check(name.location,
"consider clarifying that this record is final",
"clarify_final",
("Parent record %s is final, making this record\n"
"also final. Marking it explicitly as final\n"
"clarifies this to casual readers." %
root_record.fully_qualified_name()))
record = ast.Record_Type(name = name.value,
description = description,
location = name.location,
package = self.cu.package,
n_parent = root_record,
is_abstract = is_abstract)
self.cu.package.symbols.register(self.mh, record)
self.match("C_BRA")
while not self.peek("C_KET"):
if self.peek_kw("freeze"):
self.match_kw("freeze")
self.match("IDENTIFIER")
n_comp = record.components.lookup(self.mh,
self.ct,
ast.Composite_Component)
if record.is_frozen(n_comp):
n_value = record.get_freezing_expression(n_comp)
self.mh.error(
self.ct.location,
"duplicate freezing of %s, previously frozen at %s" %
(n_comp.name,
self.mh.cross_file_reference(n_value.location)))
self.match("ASSIGN")
n_value = self.parse_value(n_comp.n_typ)
record.frozen[n_comp.name] = n_value
else:
n_comp = self.parse_record_component(record)
if record.is_final:
self.mh.error(n_comp.location,
"cannot declare new components in"
" final record type")
else:
record.components.register(self.mh, n_comp)
self.match("C_KET")
# Finally mark record final if applicable
if is_final:
record.is_final = True
return record
def parse_expression(self, scope):
# lobster-trace: LRM.Expression
assert isinstance(scope, ast.Scope)
n_lhs = self.parse_relation(scope)
if self.peek_kw("and"):
while self.peek_kw("and"):
self.match_kw("and")
t_op = self.ct
n_rhs = self.parse_relation(scope)
n_lhs = ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = self.builtin_bool,
operator = ast.Binary_Operator.LOGICAL_AND,
n_lhs = n_lhs,
n_rhs = n_rhs)
elif self.peek_kw("or"):
while self.peek_kw("or"):
self.match_kw("or")
t_op = self.ct
n_rhs = self.parse_relation(scope)
n_lhs = ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = self.builtin_bool,
operator = ast.Binary_Operator.LOGICAL_OR,
n_lhs = n_lhs,
n_rhs = n_rhs)
elif self.peek_kw("xor"):
self.match_kw("xor")
t_op = self.ct
n_rhs = self.parse_relation(scope)
n_lhs = ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = self.builtin_bool,
operator = ast.Binary_Operator.LOGICAL_XOR,
n_lhs = n_lhs,
n_rhs = n_rhs)
elif self.peek_kw("implies"):
self.match_kw("implies")
t_op = self.ct
n_rhs = self.parse_relation(scope)
n_lhs = ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = self.builtin_bool,
operator = ast.Binary_Operator.LOGICAL_IMPLIES,
n_lhs = n_lhs,
n_rhs = n_rhs)
return n_lhs
def parse_relation(self, scope):
# lobster-trace: LRM.Relation
# lobster-trace: LRM.Operators
assert isinstance(scope, ast.Scope)
relop_mapping = {"==" : ast.Binary_Operator.COMP_EQ,
"!=" : ast.Binary_Operator.COMP_NEQ,
"<" : ast.Binary_Operator.COMP_LT,
"<=" : ast.Binary_Operator.COMP_LEQ,
">" : ast.Binary_Operator.COMP_GT,
">=" : ast.Binary_Operator.COMP_GEQ}
assert set(relop_mapping) == set(Parser.COMPARISON_OPERATOR)
n_lhs = self.parse_simple_expression(scope)
if self.peek("OPERATOR") and \
self.nt.value in Parser.COMPARISON_OPERATOR:
self.match("OPERATOR")
t_op = self.ct
n_rhs = self.parse_simple_expression(scope)
return ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = self.builtin_bool,
operator = relop_mapping[t_op.value],
n_lhs = n_lhs,
n_rhs = n_rhs)
elif self.peek_kw("not") or self.peek_kw("in"):
if self.peek_kw("not"):
self.match_kw("not")
t_not = self.ct
else:
t_not = None
self.match_kw("in")
t_in = self.ct
n_a = self.parse_simple_expression(scope)
if self.peek("RANGE"):
self.match("RANGE")
n_b = self.parse_simple_expression(scope)
rv = ast.Range_Test(
mh = self.mh,
location = t_in.location,
typ = self.builtin_bool,
n_lhs = n_lhs,
n_lower = n_a,
n_upper = n_b)
elif isinstance(n_a.typ, ast.Builtin_String):
rv = ast.Binary_Expression(
mh = self.mh,
location = t_in.location,
typ = self.builtin_bool,
operator = ast.Binary_Operator.STRING_CONTAINS,
n_lhs = n_lhs,
n_rhs = n_a)
elif isinstance(n_a.typ, ast.Array_Type):
rv = ast.Binary_Expression(
mh = self.mh,
location = t_in.location,
typ = self.builtin_bool,
operator = ast.Binary_Operator.ARRAY_CONTAINS,
n_lhs = n_lhs,
n_rhs = n_a)
else:
self.mh.error(
n_a.location,
"membership test only defined for Strings and Arrays,"
" not for %s" % n_a.typ.name)
if t_not is not None:
rv = ast.Unary_Expression(
mh = self.mh,
location = t_not.location,
typ = self.builtin_bool,
operator = ast.Unary_Operator.LOGICAL_NOT,
n_operand = rv)
return rv
else:
return n_lhs
def parse_simple_expression(self, scope):
# lobster-trace: LRM.Simple_Expression
# lobster-trace: LRM.Operators
# lobster-trace: LRM.Unary_Minus_Parsing
assert isinstance(scope, ast.Scope)
un_add_map = {"+" : ast.Unary_Operator.PLUS,
"-" : ast.Unary_Operator.MINUS}
bin_add_map = {"+" : ast.Binary_Operator.PLUS,
"-" : ast.Binary_Operator.MINUS}
assert set(un_add_map) == set(Parser.ADDING_OPERATOR)
assert set(bin_add_map) == set(Parser.ADDING_OPERATOR)
if self.peek("OPERATOR") and \
self.nt.value in Parser.ADDING_OPERATOR:
self.match("OPERATOR")
t_unary = self.ct
has_explicit_brackets = self.peek("BRA")
else:
t_unary = None
n_lhs = self.parse_term(scope)
if t_unary:
if self.lint_mode and \
isinstance(n_lhs, ast.Binary_Expression) and \
not has_explicit_brackets:
self.mh.check(t_unary.location,
"expression means -(%s), place explicit "
"brackets to clarify intent" %
n_lhs.to_string(),
"unary_minus_precedence")
n_lhs = ast.Unary_Expression(
mh = self.mh,
location = t_unary.location,
typ = n_lhs.typ,
operator = un_add_map[t_unary.value],
n_operand = n_lhs)
if isinstance(n_lhs.typ, ast.Builtin_String):
rtyp = self.builtin_str
else:
rtyp = n_lhs.typ
while self.peek("OPERATOR") and \
self.nt.value in Parser.ADDING_OPERATOR:
self.match("OPERATOR")
t_op = self.ct
n_rhs = self.parse_term(scope)
n_lhs = ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = rtyp,
operator = bin_add_map[t_op.value],
n_lhs = n_lhs,
n_rhs = n_rhs)
return n_lhs
def parse_term(self, scope):
# lobster-trace: LRM.Term
# lobster-trace: LRM.Operators
assert isinstance(scope, ast.Scope)
mul_map = {"*" : ast.Binary_Operator.TIMES,
"/" : ast.Binary_Operator.DIVIDE,
"%" : ast.Binary_Operator.REMAINDER}
assert set(mul_map) == set(Parser.MULTIPLYING_OPERATOR)
n_lhs = self.parse_factor(scope)
while self.peek("OPERATOR") and \
self.nt.value in Parser.MULTIPLYING_OPERATOR:
self.match("OPERATOR")
t_op = self.ct
n_rhs = self.parse_factor(scope)
n_lhs = ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = n_lhs.typ,
operator = mul_map[t_op.value],
n_lhs = n_lhs,
n_rhs = n_rhs)
return n_lhs
def parse_factor(self, scope):
# lobster-trace: LRM.Factor
assert isinstance(scope, ast.Scope)
if self.peek_kw("not"):
self.match_kw("not")
t_op = self.ct
n_operand = self.parse_primary(scope)
return ast.Unary_Expression(
mh = self.mh,
location = t_op.location,
typ = self.builtin_bool,
operator = ast.Unary_Operator.LOGICAL_NOT,
n_operand = n_operand)
elif self.peek_kw("abs"):
self.match_kw("abs")
t_op = self.ct
n_operand = self.parse_primary(scope)
return ast.Unary_Expression(
mh = self.mh,
location = t_op.location,
typ = n_operand.typ,
operator = ast.Unary_Operator.ABSOLUTE_VALUE,
n_operand = n_operand)
else:
n_lhs = self.parse_primary(scope)
if self.peek("OPERATOR") and self.nt.value == "**":
self.match("OPERATOR")
t_op = self.ct
n_rhs = self.parse_primary(scope)
rhs_value = n_rhs.evaluate(self.mh, None)
n_lhs = ast.Binary_Expression(
mh = self.mh,
location = t_op.location,
typ = n_lhs.typ,
operator = ast.Binary_Operator.POWER,
n_lhs = n_lhs,
n_rhs = n_rhs)
if rhs_value.value < 0:
self.mh.error(n_rhs.location,
"exponent must not be negative")
return n_lhs
def parse_primary(self, scope):
# lobster-trace: LRM.Primary
assert isinstance(scope, ast.Scope)
if self.peek("INTEGER"):
# lobster-trace: LRM.Integer_Values
self.match("INTEGER")
return ast.Integer_Literal(self.ct, self.builtin_int)
elif self.peek("DECIMAL"):
# lobster-trace: LRM.Decimal_Values
self.match("DECIMAL")
return ast.Decimal_Literal(self.ct, self.builtin_decimal)
elif self.peek("STRING"):
# lobster-trace: LRM.String_Values
self.match("STRING")
return ast.String_Literal(self.ct, self.builtin_str)
elif self.peek_kw("true") or self.peek_kw("false"):
# lobster-trace: LRM.Boolean_Values
self.match("KEYWORD")
return ast.Boolean_Literal(self.ct, self.builtin_bool)
elif self.peek_kw("null"):
self.match_kw("null")
return ast.Null_Literal(self.ct)
elif self.peek("BRA"):
self.match("BRA")
if self.peek_kw("forall") or self.peek_kw("exists"):
rv = self.parse_quantified_expression(scope)
elif self.peek_kw("if"):
rv = self.parse_conditional_expression(scope)
else:
rv = self.parse_expression(scope)
self.match("KET")
return rv
else:
return self.parse_name(scope)
def parse_quantified_expression(self, scope):
assert isinstance(scope, ast.Scope)
if self.peek_kw("forall"):
self.match_kw("forall")
universal = True
else:
self.match_kw("exists")
universal = False
loc = self.ct.location
self.match("IDENTIFIER")
t_qv = self.ct
if scope.contains(t_qv.value):
pdef = scope.lookup(self.mh, t_qv)
self.mh.error(t_qv.location,
"shadows %s %s from %s" %
(pdef.__class__.__name__,
pdef.name,
self.mh.cross_file_reference(pdef.location)))
self.match_kw("in")
self.match("IDENTIFIER")
field = scope.lookup(self.mh, self.ct, ast.Composite_Component)
n_source = ast.Name_Reference(self.ct.location,
field)
if not isinstance(field.n_typ, ast.Array_Type):
self.mh.error(self.ct.location,
"you can only quantify over arrays")
n_var = ast.Quantified_Variable(t_qv.value,
t_qv.location,
field.n_typ.element_type)
self.match("ARROW")
new_table = ast.Symbol_Table()
new_table.register(self.mh, n_var)
scope.push(new_table)
n_expr = self.parse_expression(scope)
scope.pop()
return ast.Quantified_Expression(mh = self.mh,
location = loc,
typ = self.builtin_bool,
universal = universal,
n_variable = n_var,
n_source = n_source,
n_expr = n_expr)
def parse_conditional_expression(self, scope):
# lobster-trace: LRM.Conditional_Expression
# lobster-trace: LRM.Restricted_Null
assert isinstance(scope, ast.Scope)
self.match_kw("if")
t_if = self.ct
if_cond = self.parse_expression(scope)