Coverage for trlc/parser.py: 96%
1267 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-30 14:20 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-30 14:20 +0000
1#!/usr/bin/env python3
2#
3# TRLC - Treat Requirements Like Code
4# Copyright (C) 2022-2023 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
5# Copyright (C) 2025 Florian Schanda
6#
7# This file is part of the TRLC Python Reference Implementation.
8#
9# TRLC is free software: you can redistribute it and/or modify it
10# under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# TRLC is distributed in the hope that it will be useful, but WITHOUT
15# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
17# License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with TRLC. If not, see <https://www.gnu.org/licenses/>.
22import re
24from trlc.nested import Nested_Lexer
25from trlc.lexer import Token_Base, Token, Lexer_Base, TRLC_Lexer
26from trlc.errors import Message_Handler, TRLC_Error
27from trlc import ast
30class Markup_Token(Token_Base):
31 # lobster-trace: LRM.Markup_String_Format
33 KIND = {
34 "CHARACTER": "character",
35 "REFLIST_BEGIN": "[[",
36 "REFLIST_END": "]]",
37 "REFLIST_COMMA": ",",
38 "REFLIST_DOT": ".",
39 "REFLIST_IDENTIFIER": "identifier",
40 }
42 def __init__(self, location, kind, value):
43 super().__init__(location, kind, value)
44 assert isinstance(value, str)
47class Markup_Lexer(Nested_Lexer):
48 def __init__(self, mh, literal):
49 super().__init__(mh, literal)
51 self.in_reflist = False
53 def file_location(self):
54 return self.origin_location
56 def token(self):
57 # lobster-trace: LRM.Markup_String_Errors
59 if self.in_reflist:
60 self.skip_whitespace()
61 else:
62 self.advance()
63 if self.cc is None:
64 return None
66 start_pos = self.lexpos
67 start_line = self.line_no
68 start_col = self.col_no
70 if self.cc == "[" and self.nc == "[":
71 kind = "REFLIST_BEGIN"
72 self.advance()
73 if self.in_reflist:
74 self.mh.lex_error(
75 self.source_location(
76 start_line, start_col, start_pos, start_pos + 1
77 ),
78 "cannot nest reference lists",
79 )
80 else:
81 self.in_reflist = True
83 elif self.cc == "]" and self.nc == "]":
84 kind = "REFLIST_END"
85 self.advance()
86 if self.in_reflist:
87 self.in_reflist = False
88 else:
89 self.mh.lex_error(
90 self.source_location(
91 start_line, start_col, start_pos, start_pos + 1
92 ),
93 "opening [[ for this ]] found",
94 )
96 elif not self.in_reflist:
97 kind = "CHARACTER"
99 elif self.cc == ",":
100 kind = "REFLIST_COMMA"
102 elif self.cc == ".":
103 kind = "REFLIST_DOT"
105 elif self.is_alpha(self.cc): 105 ↛ 111line 105 didn't jump to line 111 because the condition on line 105 was always true
106 kind = "REFLIST_IDENTIFIER"
107 while self.nc and (self.is_alnum(self.nc) or self.nc == "_"):
108 self.advance()
110 else:
111 self.mh.lex_error(
112 self.source_location(start_line, start_col, start_pos, start_pos),
113 "unexpected character '%s'" % self.cc,
114 )
116 loc = self.source_location(start_line, start_col, start_pos, self.lexpos)
118 # pylint: disable=possibly-used-before-assignment
119 return Markup_Token(loc, kind, self.content[start_pos : self.lexpos + 1])
122class Parser_Base:
123 def __init__(self, mh, lexer, eoc_name, token_map, keywords):
124 assert isinstance(mh, Message_Handler)
125 assert isinstance(lexer, Lexer_Base)
126 assert isinstance(eoc_name, str)
127 assert isinstance(token_map, dict)
128 assert isinstance(keywords, frozenset)
129 self.mh = mh
130 self.lexer = lexer
132 self.eoc_name = eoc_name
133 self.language_tokens = token_map
134 self.language_keywords = keywords
136 self.ct = None
137 self.nt = None
138 self.advance()
140 def advance(self):
141 # lobster-trace: LRM.Comments
142 self.ct = self.nt
143 while True:
144 self.nt = self.lexer.token()
145 if self.nt is None or self.nt.kind != "COMMENT":
146 break
148 def skip_until_newline(self):
149 if self.ct is None: 149 ↛ 150line 149 didn't jump to line 150 because the condition on line 149 was never true
150 return
151 current_line = self.ct.location.line_no
152 while self.nt and self.nt.location.line_no == current_line:
153 self.advance()
155 def peek(self, kind):
156 assert kind in self.language_tokens, "%s is not a valid token" % kind
157 return self.nt is not None and self.nt.kind == kind
159 def peek_eof(self):
160 return self.nt is None
162 def peek_kw(self, value):
163 assert value in self.language_keywords, "%s is not a valid keyword" % value
164 return self.peek("KEYWORD") and self.nt.value == value
166 def match(self, kind):
167 # lobster-trace: LRM.Matching_Value_Types
169 assert kind in self.language_tokens, "%s is not a valid token" % kind
170 if self.nt is None:
171 if self.ct is None: 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true
172 self.mh.error(
173 self.lexer.file_location(),
174 "expected %s, encountered %s instead"
175 % (self.language_tokens[kind], self.eoc_name),
176 )
177 else:
178 self.mh.error(
179 self.ct.location,
180 "expected %s, encountered %s instead"
181 % (self.language_tokens[kind], self.eoc_name),
182 )
183 elif self.nt.kind != kind:
184 self.mh.error(
185 self.nt.location,
186 "expected %s, encountered %s instead"
187 % (self.language_tokens[kind], self.language_tokens[self.nt.kind]),
188 )
189 self.advance()
191 def match_eof(self):
192 if self.nt is not None: 192 ↛ 193line 192 didn't jump to line 193 because the condition on line 192 was never true
193 self.mh.error(
194 self.nt.location,
195 "expected %s, encountered %s instead"
196 % (self.eoc_name, self.language_tokens[self.nt.kind]),
197 )
199 def match_kw(self, value):
200 assert value in self.language_keywords, "%s is not a valid keyword" % value
201 if self.nt is None:
202 if self.ct is None: 202 ↛ 209line 202 didn't jump to line 209 because the condition on line 202 was always true
203 self.mh.error(
204 self.lexer.file_location(),
205 "expected keyword %s, encountered %s instead"
206 % (value, self.eoc_name),
207 )
208 else:
209 self.mh.error(
210 self.ct.location,
211 "expected keyword %s, encountered %s instead"
212 % (value, self.eoc_name),
213 )
214 elif self.nt.kind != "KEYWORD":
215 self.mh.error(
216 self.nt.location,
217 "expected keyword %s, encountered %s instead"
218 % (value, self.language_tokens[self.nt.kind]),
219 )
220 elif self.nt.value != value:
221 self.mh.error(
222 self.nt.location,
223 "expected keyword %s,"
224 " encountered keyword %s instead" % (value, self.nt.value),
225 )
226 self.advance()
229class Markup_Parser(Parser_Base):
230 def __init__(self, parent, literal):
231 assert isinstance(parent, Parser)
232 super().__init__(
233 parent.mh,
234 Markup_Lexer(parent.mh, literal),
235 eoc_name="end-of-string",
236 token_map=Markup_Token.KIND,
237 keywords=frozenset(),
238 )
239 self.parent = parent
240 self.references = literal.references
242 def parse_all_references(self):
243 while self.nt:
244 if self.peek("CHARACTER"):
245 self.advance()
246 else:
247 self.parse_ref_list()
248 self.match_eof()
249 return self.references
251 def parse_ref_list(self):
252 self.match("REFLIST_BEGIN")
253 self.parse_qualified_name()
254 while self.peek("REFLIST_COMMA"):
255 self.match("REFLIST_COMMA")
256 self.parse_qualified_name()
257 self.match("REFLIST_END")
259 def parse_qualified_name(self):
260 # lobster-trace: LRM.Qualified_Name
261 # lobster-trace: LRM.Valid_Qualifier
262 # lobster-trace: LRM.Valid_Name
263 # lobster-trace: LRM.Markup_String_Resolution
264 # lobster-trace: LRM.Markup_String_Types
266 self.match("REFLIST_IDENTIFIER")
267 if self.peek("REFLIST_DOT"):
268 package = self.parent.stab.lookup_direct(
269 mh=self.mh,
270 name=self.ct.value,
271 error_location=self.ct.location,
272 required_subclass=ast.Package,
273 )
274 if not self.parent.cu.is_visible(package):
275 self.mh.error(self.ct.location, "package must be imported before use")
277 self.match("REFLIST_DOT")
278 self.match("REFLIST_IDENTIFIER")
279 else:
280 package = self.parent.cu.package
282 ref = ast.Record_Reference(
283 location=self.ct.location, name=self.ct.value, typ=None, package=package
284 )
285 self.references.append(ref)
288class Parser(Parser_Base):
289 COMPARISON_OPERATOR = ("==", "!=", "<", "<=", ">", ">=")
290 ADDING_OPERATOR = ("+", "-")
291 MULTIPLYING_OPERATOR = ("*", "/", "%")
293 # Keyword that introduces the package indication; overridden by the
294 # markdown parser, where the H1 heading takes this role.
295 PACKAGE_KEYWORD = "package"
297 def __init__(
298 self,
299 mh,
300 stab,
301 file_name,
302 lint_mode,
303 error_recovery,
304 primary_file=True,
305 lexer=None,
306 ):
307 assert isinstance(mh, Message_Handler)
308 assert isinstance(stab, ast.Symbol_Table)
309 assert isinstance(file_name, str)
310 assert isinstance(lint_mode, bool)
311 assert isinstance(error_recovery, bool)
312 assert isinstance(primary_file, bool)
313 assert isinstance(lexer, TRLC_Lexer) or lexer is None
314 if lexer: 314 ↛ 323line 314 didn't jump to line 323 because the condition on line 314 was always true
315 super().__init__(
316 mh,
317 lexer,
318 eoc_name="end-of-file",
319 token_map=Token.KIND,
320 keywords=TRLC_Lexer.KEYWORDS,
321 )
322 else:
323 super().__init__(
324 mh,
325 TRLC_Lexer(mh, file_name),
326 eoc_name="end-of-file",
327 token_map=Token.KIND,
328 keywords=TRLC_Lexer.KEYWORDS,
329 )
331 self.lint_mode = lint_mode
332 self.error_recovery = error_recovery
334 self.stab = stab
335 self.cu = ast.Compilation_Unit(file_name)
337 self.primary = primary_file
338 self.secondary = False
339 # Controls if the file is actually fully parsed: primary means
340 # it was selected on the command-line and secondary means it
341 # was selected by dependency analysis.
343 self.builtin_bool = stab.lookup_assuming(self.mh, "Boolean")
344 self.builtin_int = stab.lookup_assuming(self.mh, "Integer")
345 self.builtin_decimal = stab.lookup_assuming(self.mh, "Decimal")
346 self.builtin_str = stab.lookup_assuming(self.mh, "String")
347 self.builtin_mstr = stab.lookup_assuming(self.mh, "Markup_String")
349 self.section = []
350 self.default_scope = ast.Scope()
351 self.default_scope.push(self.stab)
352 self.unavailable_tuple_types = set()
354 # "rsl" or "trlc"; set by parse_preamble. Remains None only until
355 # parse_preamble runs; code that reads this (e.g.
356 # check_not_self_descendant) is only reachable from parse_rsl_file /
357 # parse_trlc_file, which the Source_Manager only calls on this same
358 # parser instance after its parse_preamble call has completed
359 # successfully, so it is never observed as None there.
360 self.file_kind = None
362 def parse_described_name(self):
363 # lobster-trace: LRM.Described_Names
364 # lobster-trace: LRM.Described_Name_Description
365 self.match("IDENTIFIER")
366 name = self.ct
368 if self.peek("STRING"):
369 self.match("STRING")
370 t_descr = self.ct
371 return name, t_descr.value, t_descr
372 else:
373 return name, None, None
375 def parse_dotted_name(self):
376 """Parse a dotted package name: ``IDENTIFIER { '.' IDENTIFIER }``.
378 :returns: ``(full_name, first_location, tokens)``
379 :rtype: tuple[str, Location, list[Token]]
380 """
381 # lobster-trace: LRM.Nested_Package_Names
382 self.match("IDENTIFIER")
383 parts = [self.ct.value]
384 first_location = self.ct.location
385 tokens = [self.ct]
387 while self.peek("DOT"):
388 self.match("DOT")
389 tokens.append(self.ct)
390 self.match("IDENTIFIER")
391 parts.append(self.ct.value)
392 tokens.append(self.ct)
394 return ".".join(parts), first_location, tokens
396 def parse_import_name(self):
397 """Parse an import target: a dotted package name with an optional
398 trailing ``.*`` wildcard.
400 Consumes ``IDENTIFIER { '.' IDENTIFIER } [ '.' '*' ]``. The ``*``
401 lexes as an ``OPERATOR`` token with value ``"*"``.
403 :returns: ``(full_name, first_location, tokens, is_wildcard)``
404 :rtype: tuple[str, Location, list[Token], bool]
405 """
406 # lobster-trace: LRM.Wildcard_Import
407 # lobster-trace: LRM.Nested_Package_Names
408 self.match("IDENTIFIER")
409 parts = [self.ct.value]
410 first_location = self.ct.location
411 tokens = [self.ct]
412 is_wildcard = False
414 while self.peek("DOT"):
415 self.match("DOT")
416 t_dot = self.ct
417 if self.peek("OPERATOR") and self.nt.value == "*":
418 self.match("OPERATOR")
419 tokens.append(t_dot)
420 tokens.append(self.ct)
421 is_wildcard = True
422 break
423 tokens.append(t_dot)
424 self.match("IDENTIFIER")
425 parts.append(self.ct.value)
426 tokens.append(self.ct)
428 return ".".join(parts), first_location, tokens, is_wildcard
430 def check_not_self_descendant(self, pkg, t_pkg):
431 # lobster-trace: LRM.Self_Descendant_Reference
432 # An rsl file is always elaborated before the rsl files of its
433 # sub-packages, so their declarations do not exist yet. Without
434 # this check the user would get a confusing "unknown symbol"
435 # error for the member instead.
436 if self.file_kind != "rsl":
437 return
438 if not pkg.name.startswith(self.cu.package.name + "."):
439 return
440 self.mh.error(
441 t_pkg.location,
442 "cannot refer to sub-package %s of the current package" % pkg.name,
443 explanation="package %s is elaborated before its sub-packages, "
444 "so %s cannot be used here; move the declarations you need "
445 "into %s itself, or into a package outside the %s subtree"
446 % (
447 self.cu.package.name,
448 pkg.name,
449 self.cu.package.name,
450 self.cu.package.name,
451 ),
452 )
454 def descend_sub_packages(self, pkg, t_pkg):
455 # lobster-trace: LRM.Qualified_Name
456 # lobster-trace: LRM.Nested_Visibility
457 # Greedily consume `. segment` pairs, descending into sub-packages
458 # for as long as a segment names one. The first segment that is not
459 # a sub-package is the member name; we check that the package it
460 # belongs to is visible and mark the import used. Returns
461 # (leaf_package, t_member). If the dotted name ends on a package the
462 # trailing token (self.ct) is returned as the member, so the caller
463 # produces a sensible "unknown symbol" error.
464 #
465 # t_pkg is the token that named the current pkg; it is used as the
466 # location for the "package must be imported" error so the caret
467 # points at the offending package rather than the member.
468 while self.peek("DOT"): 468 ↛ 491line 468 didn't jump to line 491 because the condition on line 468 was always true
469 self.match("DOT")
470 t_dot = self.ct
471 self.match("IDENTIFIER")
472 t_member = self.ct
473 child = pkg.sub_packages.lookup_sub_package(t_member.value)
474 if child is None:
475 pkg.set_ast_link(t_dot)
476 if not self.cu.is_visible(pkg):
477 self.mh.error(
478 t_pkg.location,
479 "package must be imported before use",
480 explanation="add 'import %s' to the "
481 "preamble of this file" % pkg.name,
482 )
483 self.check_not_self_descendant(pkg, t_pkg)
484 self.cu.mark_import_used(pkg)
485 return pkg, t_member
486 child.set_ast_link(t_dot)
487 child.set_ast_link(t_member)
488 pkg = child
489 t_pkg = t_member
491 if not self.cu.is_visible(pkg):
492 self.mh.error(
493 t_pkg.location,
494 "package must be imported before use",
495 explanation="add 'import %s' to the preamble of this file" % pkg.name,
496 )
497 self.check_not_self_descendant(pkg, t_pkg)
498 self.cu.mark_import_used(pkg)
499 return pkg, self.ct
501 def error_extends_undeclared(self, t_name):
502 # The parser reads declarations in order, so it cannot tell a type
503 # declared later from one that is not declared at all.
504 self.mh.error(
505 t_name.location,
506 f"cannot extend {t_name.value} before it is declared",
507 explanation=(
508 f"{t_name.value} is declared later or not at all; "
509 "declare it before the derived type"
510 ),
511 )
513 def parse_qualified_name(
514 self,
515 scope,
516 required_subclass=None,
517 match_ident=True,
518 allow_forward=False,
519 for_extends=False,
520 ):
521 # lobster-trace: LRM.Qualified_Name
522 # lobster-trace: LRM.Valid_Qualifier
523 # lobster-trace: LRM.Valid_Name
524 assert isinstance(scope, ast.Scope)
525 assert required_subclass is None or isinstance(required_subclass, type)
526 assert isinstance(match_ident, bool)
528 if match_ident:
529 self.match("IDENTIFIER")
530 t_first = self.ct
532 if not scope.contains(self.ct.value):
533 if for_extends and not self.peek("DOT"):
534 self.error_extends_undeclared(self.ct)
535 if (
536 allow_forward
537 and self.file_kind == "rsl"
538 and required_subclass in (ast.Type, ast.Record_Type)
539 and self.ct.value not in self.unavailable_tuple_types
540 and self.cu.package is not None
541 and self.cu.package.symbols is not None
542 ):
543 forward_decl = ast.Record_Type(
544 name=self.ct.value,
545 description=None,
546 location=self.ct.location,
547 package=self.cu.package,
548 n_parent=None,
549 is_abstract=False,
550 )
551 forward_decl.mark_forward_decl()
552 forward_decl.set_forward_decl_context(None)
553 self.cu.package.symbols.register(self.mh, forward_decl)
554 forward_decl.set_ast_link(self.ct)
555 return forward_decl
557 sym = scope.lookup(self.mh, self.ct)
558 sym.set_ast_link(self.ct)
560 if isinstance(sym, ast.Package):
561 pkg, t_member = self.descend_sub_packages(sym, self.ct)
562 # Qualified parent in the current package (e.g. demo.Parent):
563 # the member must already be declared, otherwise report the
564 # same forward-inheritance error as for unqualified names.
565 if (
566 for_extends
567 and t_member is not t_first
568 and pkg is self.cu.package
569 and not pkg.symbols.contains(t_member.value)
570 ):
571 self.error_extends_undeclared(t_member)
572 sym = pkg.symbols.lookup(self.mh, t_member, required_subclass)
573 else:
574 sym = scope.lookup(self.mh, self.ct, required_subclass)
576 if ( 576 ↛ 581line 576 didn't jump to line 581 because the condition on line 576 was never true
577 isinstance(sym, ast.Concrete_Type)
578 and sym.n_package is self.cu.package
579 and sym.name in self.unavailable_tuple_types
580 ):
581 self.mh.error(
582 self.ct.location,
583 f"unknown symbol {self.ct.value}",
584 explanation=f"declare {self.ct.value} before using it here",
585 )
586 if (
587 isinstance(sym, ast.Concrete_Type)
588 and sym.is_forward_decl()
589 and not allow_forward
590 ):
591 if for_extends: 591 ↛ 593line 591 didn't jump to line 593 because the condition on line 591 was always true
592 self.error_extends_undeclared(self.ct)
593 self.mh.error(
594 self.ct.location,
595 f"unknown symbol {self.ct.value}",
596 explanation=f"declare {self.ct.value} before using it here",
597 )
598 return sym
600 def parse_type_declaration(self):
601 # lobster-trace: LRM.Type_Declarations
602 if self.peek_kw("enum"):
603 n_item = self.parse_enum_declaration()
604 elif self.peek_kw("tuple"):
605 n_item = self.parse_tuple_declaration()
606 else:
607 n_item = self.parse_record_declaration()
608 assert isinstance(n_item, ast.Concrete_Type)
609 return n_item
611 def parse_enum_declaration(self):
612 # lobster-trace: LRM.Enumeration_Declaration
613 self.match_kw("enum")
614 t_enum = self.ct
615 name, description, t_description = self.parse_described_name()
617 existing = self.cu.package.symbols.lookup_assuming(
618 self.mh, name.value, ast.Concrete_Type
619 )
620 if existing is not None and existing.is_forward_decl():
621 if existing.get_forward_decl_context() == "tuple_field":
622 self.mh.error(
623 existing.location,
624 f"unknown symbol {name.value}",
625 fatal=False,
626 )
627 enum = existing
628 union_use = existing.get_forward_union_use()
629 enum.__class__ = ast.Enumeration_Type
630 enum.clear_forward_decl()
631 enum.description = description
632 enum.location = name.location
633 if not hasattr(enum, "literals"): 633 ↛ 635line 633 didn't jump to line 635 because the condition on line 633 was always true
634 enum.literals = ast.Symbol_Table()
635 if union_use is not None:
636 # Reported here, rather than only by the linter, so that
637 # --no-lint cannot make an invalid union valid. Fatal, so
638 # later checks never see the enum inside a union.
639 self.mh.error(
640 union_use,
641 f"Enumeration_Type {name.value} is not a Record_Type",
642 explanation=("all members of a union type must be record types"),
643 )
644 else:
645 enum = ast.Enumeration_Type(
646 name=name.value,
647 description=description,
648 location=name.location,
649 package=self.cu.package,
650 )
651 self.cu.package.symbols.register(self.mh, enum)
652 enum.set_ast_link(t_enum)
653 enum.set_ast_link(name)
654 if t_description:
655 enum.set_ast_link(t_description)
657 self.match("C_BRA")
658 enum.set_ast_link(self.ct)
659 empty = True
660 while not self.peek("C_KET"):
661 name, description, t_description = self.parse_described_name()
662 lit = ast.Enumeration_Literal_Spec(
663 name=name.value,
664 description=description,
665 location=name.location,
666 enum=enum,
667 )
668 lit.set_ast_link(name)
669 if t_description:
670 lit.set_ast_link(self.ct)
671 empty = False
672 enum.literals.register(self.mh, lit)
673 self.match("C_KET")
674 enum.set_ast_link(self.ct)
676 if empty:
677 # lobster-trace: LRM.No_Empty_Enumerations
678 self.mh.error(enum.location, "empty enumerations are not permitted")
680 return enum
682 def parse_tuple_field(
683 self, n_tuple, optional_allowed, optional_reason, optional_required
684 ):
685 assert isinstance(n_tuple, ast.Tuple_Type)
686 assert isinstance(optional_allowed, bool)
687 assert isinstance(optional_reason, str)
688 assert isinstance(optional_required, bool)
689 assert optional_allowed or not optional_required
691 field_name, field_description, t_descr = self.parse_described_name()
693 if optional_required or self.peek_kw("optional"):
694 self.match_kw("optional")
695 t_optional = self.ct
696 field_is_optional = True
697 if not optional_allowed:
698 self.mh.error(self.ct.location, optional_reason)
699 else:
700 field_is_optional = False
701 t_optional = None
703 # lobster-trace: LRM.Tuple_Field_Types
704 # S_BRA here means a union type '[T1, T2, ...]', not array bounds.
705 if self.peek("S_BRA"):
706 # lobster-trace: LRM.union_type
707 field_type = self.parse_union_type()
708 else:
709 field_type = self.parse_qualified_name(
710 self.default_scope, ast.Type, allow_forward=True
711 )
712 if isinstance(field_type, ast.Record_Type) and field_type.is_forward_decl():
713 field_type.set_forward_decl_context("tuple_field")
714 comp = ast.Composite_Component(
715 name=field_name.value,
716 description=field_description,
717 location=field_name.location,
718 member_of=n_tuple,
719 n_typ=field_type,
720 optional=field_is_optional,
721 )
722 comp.set_ast_link(field_name)
723 if t_descr:
724 comp.set_ast_link(t_descr)
725 if field_is_optional:
726 comp.set_ast_link(t_optional)
728 return comp
730 def parse_tuple_declaration(self):
731 # lobster-trace: LRM.Tuple_Declaration
732 self.match_kw("tuple")
733 t_tuple = self.ct
734 name, description, t_descr = self.parse_described_name()
735 self.unavailable_tuple_types.add(name.value)
737 existing = self.cu.package.symbols.lookup_assuming(
738 self.mh, name.value, ast.Concrete_Type
739 )
740 if existing is not None and existing.is_forward_decl():
741 used_by_tuple_field = existing.get_forward_decl_context() == "tuple_field"
742 union_use = existing.get_forward_union_use()
743 forward_use_location = existing.location
744 n_tuple = existing
745 n_tuple.__class__ = ast.Tuple_Type
746 n_tuple.clear_forward_decl()
747 n_tuple.description = description
748 n_tuple.location = name.location
749 n_tuple.components = ast.Symbol_Table()
750 n_tuple.separators = []
751 if used_by_tuple_field:
752 # A tuple field may not refer forward to a tuple. This
753 # also rules out cycles between tuples (A -> B -> A),
754 # which would have infinite size. The error must be
755 # fatal: continuing would leave a cyclic type graph
756 # behind for the linter and VCG to trip over. The stub
757 # was converted above so that it is not additionally
758 # reported as never declared.
759 self.mh.error(
760 forward_use_location,
761 f"unknown symbol {name.value}",
762 explanation=(
763 f"tuple {name.value} is declared later in the file; "
764 "declare it before the tuple field that uses it"
765 ),
766 )
767 if union_use is not None:
768 self.mh.error(
769 union_use,
770 f"Tuple_Type {name.value} is not a Record_Type",
771 explanation=("all members of a union type must be record types"),
772 )
773 else:
774 n_tuple = ast.Tuple_Type(
775 name=name.value,
776 description=description,
777 location=name.location,
778 package=self.cu.package,
779 )
781 n_tuple.set_ast_link(t_tuple)
782 n_tuple.set_ast_link(name)
783 if t_descr:
784 n_tuple.set_ast_link(t_descr)
785 self.match("C_BRA")
786 n_tuple.set_ast_link(self.ct)
788 n_field = self.parse_tuple_field(
789 n_tuple,
790 optional_allowed=False,
791 optional_reason="first field may not be optional",
792 optional_required=False,
793 )
794 n_tuple.components.register(self.mh, n_field)
796 has_separators = False
797 optional_required = False
798 separator_allowed = True
800 while self.peek_kw("separator") or self.peek("IDENTIFIER"):
801 if has_separators or self.peek_kw("separator"):
802 has_separators = True
803 self.match_kw("separator")
804 t_sep = self.ct
805 if not separator_allowed:
806 # lobster-trace: LRM.Tuple_Separators_All_Or_None
807 self.mh.error(
808 self.ct.location, "either all fields must be separated, or none"
809 )
810 if ( 810 ↛ 824line 810 didn't jump to line 824 because the condition on line 810 was always true
811 self.peek("IDENTIFIER")
812 or self.peek("AT")
813 or self.peek("COLON")
814 or self.peek("SEMICOLON")
815 ):
816 self.advance()
817 sep = ast.Separator(self.ct)
818 sep.set_ast_link(t_sep)
819 sep.set_ast_link(self.ct)
820 n_tuple.add_separator(sep)
821 else:
822 separator_allowed = False
823 # lobster-trace: LRM.Tuple_Optional_Requires_Separators
824 n_field = self.parse_tuple_field(
825 n_tuple,
826 optional_allowed=has_separators,
827 optional_reason=("optional only permitted in tuples with separators"),
828 optional_required=optional_required,
829 )
830 n_tuple.components.register(self.mh, n_field)
831 # lobster-trace: LRM.Tuple_Optional_Fields
832 optional_required |= n_field.optional
834 self.match("C_KET")
835 n_tuple.set_ast_link(self.ct)
837 # Final check to ban tuples with separators containing other
838 # tuples.
839 if has_separators:
840 # lobster-trace: LRM.Restricted_Tuple_Nesting
841 for n_field in n_tuple.components.values():
842 if (
843 isinstance(n_field.n_typ, ast.Tuple_Type)
844 and n_field.n_typ.has_separators()
845 ):
846 self.mh.error(
847 n_field.location,
848 "tuple type %s, which contains separators,"
849 " may not contain another tuple with separators" % n_tuple.name,
850 )
852 self.unavailable_tuple_types.remove(name.value)
853 if existing is not n_tuple:
854 self.cu.package.symbols.register(self.mh, n_tuple)
856 return n_tuple
858 def parse_union_type(self):
859 """Parse a union type declaration: '[' Type1 ',' Type2 ... ']'
861 The leading S_BRA must be the next token when called.
862 Returns an ast.Union_Type node.
863 """
864 # lobster-trace: LRM.union_type
865 # lobster-trace: LRM.Union_Type_No_Duplicates
866 # lobster-trace: LRM.Union_Type_Record_Types_Only
867 self.match("S_BRA")
868 t_s_bra = self.ct
870 union_type_entries = [] # list of (Record_Type, Location)
871 first_type = self.parse_qualified_name(
872 self.default_scope, ast.Record_Type, allow_forward=True
873 )
874 first_type.set_ast_link(self.ct)
875 if isinstance(first_type, ast.Record_Type) and first_type.is_forward_decl():
876 first_type.set_forward_union_use(self.ct.location)
877 if not isinstance(first_type, ast.Record_Type): 877 ↛ 878line 877 didn't jump to line 878 because the condition on line 877 was never true
878 self.mh.error(
879 self.ct.location,
880 f"{first_type.__class__.__name__} {first_type.name} "
881 "is not a Record_Type",
882 fatal=False,
883 )
884 else:
885 union_type_entries.append((first_type, self.ct.location))
887 while self.peek("COMMA"):
888 self.match("COMMA")
889 next_type = self.parse_qualified_name(
890 self.default_scope, ast.Record_Type, allow_forward=True
891 )
892 next_type.set_ast_link(self.ct)
893 if isinstance(next_type, ast.Record_Type) and next_type.is_forward_decl():
894 next_type.set_forward_union_use(self.ct.location)
895 if not isinstance(next_type, ast.Record_Type): 895 ↛ 896line 895 didn't jump to line 896 because the condition on line 895 was never true
896 self.mh.error(
897 self.ct.location,
898 f"{next_type.__class__.__name__} {next_type.name} "
899 "is not a Record_Type",
900 fatal=False,
901 )
902 else:
903 union_type_entries.append((next_type, self.ct.location))
905 self.match("S_KET")
906 t_s_ket = self.ct
908 seen = {}
909 for t, loc in union_type_entries:
910 fqn = t.fully_qualified_name()
911 if fqn in seen:
912 self.mh.error(loc, "duplicate type %s in union" % t.name, fatal=False)
913 else:
914 seen[fqn] = loc
916 union_types = [t for t, _ in union_type_entries]
917 c_typ = ast.Union_Type(location=t_s_bra.location, types=union_types)
918 c_typ.set_ast_link(t_s_bra)
919 c_typ.set_ast_link(t_s_ket)
920 return c_typ
922 def parse_record_component(self, n_record):
923 assert isinstance(n_record, ast.Record_Type)
925 c_name, c_descr, t_descr = self.parse_described_name()
926 t_optional = None
927 c_optional = False
928 if self.peek_kw("optional"):
929 self.match_kw("optional")
930 t_optional = self.ct
931 c_optional = True
933 # S_BRA here means a union type '[T1, T2, ...]', not array bounds.
934 # Array bounds '[INTEGER..INTEGER]' are checked in the next block.
935 if self.peek("S_BRA"):
936 c_typ = self.parse_union_type()
937 else:
938 c_typ = self.parse_qualified_name(
939 self.default_scope, ast.Type, allow_forward=True
940 )
941 c_typ.set_ast_link(self.ct)
943 if self.peek("S_BRA"):
944 self.match("S_BRA")
945 t_s_bra = self.ct
946 self.match("INTEGER")
947 t_lo = self.ct
948 a_lo = self.ct.value
949 loc_lo = self.ct.location
950 self.match("RANGE")
951 t_range = self.ct
952 a_loc = self.ct.location
953 a_hi = None
954 if self.peek("INTEGER"):
955 self.match("INTEGER")
956 a_hi = self.ct.value
957 elif self.peek("OPERATOR") and self.nt.value == "*": 957 ↛ 960line 957 didn't jump to line 960 because the condition on line 957 was always true
958 self.match("OPERATOR")
959 else:
960 self.mh.error(self.nt.location, "expected INTEGER or * for upper bound")
961 t_hi = self.ct
962 loc_hi = self.ct.location
963 self.match("S_KET")
964 t_s_ket = self.ct
965 c_typ = ast.Array_Type(
966 location=a_loc,
967 element_type=c_typ,
968 lower_bound=a_lo,
969 upper_bound=a_hi,
970 loc_lower=loc_lo,
971 loc_upper=loc_hi,
972 )
973 c_typ.set_ast_link(t_s_bra)
974 c_typ.set_ast_link(t_lo)
975 c_typ.set_ast_link(t_range)
976 c_typ.set_ast_link(t_hi)
977 c_typ.set_ast_link(t_s_ket)
979 c_comp = ast.Composite_Component(
980 name=c_name.value,
981 description=c_descr,
982 location=c_name.location,
983 member_of=n_record,
984 n_typ=c_typ,
985 optional=c_optional,
986 )
987 c_comp.set_ast_link(c_name)
988 if t_descr:
989 c_comp.set_ast_link(t_descr)
990 if c_optional:
991 c_comp.set_ast_link(t_optional)
993 return c_comp
995 def parse_record_declaration(self):
996 t_abstract = None
997 t_final = None
998 is_abstract = False
999 is_final = False
1000 if self.peek_kw("abstract"):
1001 self.match_kw("abstract")
1002 t_abstract = self.ct
1003 is_abstract = True
1004 elif self.peek_kw("final"):
1005 self.match_kw("final")
1006 t_final = self.ct
1007 is_final = True
1009 self.match_kw("type")
1010 t_type = self.ct
1011 name, description, t_description = self.parse_described_name()
1013 if self.peek_kw("extends"):
1014 self.match_kw("extends")
1015 t_extends = self.ct
1016 root_record = self.parse_qualified_name(
1017 self.default_scope, ast.Record_Type, for_extends=True
1018 )
1019 root_record.set_ast_link(t_extends)
1020 root_record.set_ast_link(self.ct)
1021 else:
1022 root_record = None
1024 if self.lint_mode and root_record and root_record.is_final and not is_final:
1025 self.mh.check(
1026 name.location,
1027 "consider clarifying that this record is final",
1028 "clarify_final",
1029 (
1030 "Parent record %s is final, making this record\n"
1031 "also final. Marking it explicitly as final\n"
1032 "clarifies this to casual readers."
1033 % root_record.fully_qualified_name()
1034 ),
1035 )
1037 existing = self.cu.package.symbols.lookup_assuming(
1038 self.mh, name.value, ast.Concrete_Type
1039 )
1040 if existing is not None and existing.is_forward_decl():
1041 record = existing
1042 record.clear_forward_decl()
1043 record.parent = root_record
1044 record.is_abstract = is_abstract
1045 record.description = description
1046 record.location = name.location
1047 record.components = ast.Symbol_Table(
1048 root_record.components if root_record else None
1049 )
1050 record.frozen = {}
1051 record.is_final = root_record.is_final if root_record else False
1052 else:
1053 record = ast.Record_Type(
1054 name=name.value,
1055 description=description,
1056 location=name.location,
1057 package=self.cu.package,
1058 n_parent=root_record,
1059 is_abstract=is_abstract,
1060 )
1061 self.cu.package.symbols.register(self.mh, record)
1063 record.parent = root_record
1064 record.is_abstract = is_abstract
1065 record.description = description
1066 record.location = name.location
1067 if root_record is not None:
1068 record.components = ast.Symbol_Table(root_record.components)
1069 else:
1070 record.components = ast.Symbol_Table()
1071 record.frozen = {}
1072 record.is_final = root_record.is_final if root_record else False
1073 if is_abstract:
1074 record.set_ast_link(t_abstract)
1075 if is_final:
1076 record.set_ast_link(t_final)
1077 record.set_ast_link(t_type)
1078 record.set_ast_link(name)
1079 if t_description:
1080 record.set_ast_link(t_description)
1082 self.match("C_BRA")
1083 record.set_ast_link(self.ct)
1084 while not self.peek("C_KET"):
1085 if self.peek_kw("freeze"):
1086 self.match_kw("freeze")
1087 t_freeze = self.ct
1088 self.match("IDENTIFIER")
1089 n_comp = record.components.lookup(
1090 self.mh, self.ct, ast.Composite_Component
1091 )
1092 if record.is_frozen(n_comp):
1093 n_value = record.get_freezing_expression(n_comp)
1094 self.mh.error(
1095 self.ct.location,
1096 "duplicate freezing of %s, previously frozen at %s"
1097 % (n_comp.name, self.mh.cross_file_reference(n_value.location)),
1098 )
1099 n_comp.set_ast_link(t_freeze)
1100 n_comp.set_ast_link(self.ct)
1101 self.match("ASSIGN")
1102 n_comp.set_ast_link(self.ct)
1103 n_value = self.parse_value(n_comp.n_typ)
1104 n_value.set_ast_link(self.ct)
1106 record.frozen[n_comp.name] = n_value
1108 else:
1109 n_comp = self.parse_record_component(record)
1110 if record.is_final:
1111 self.mh.error(
1112 n_comp.location,
1113 "cannot declare new components in final record type",
1114 )
1115 else:
1116 record.components.register(self.mh, n_comp)
1118 self.match("C_KET")
1119 record.set_ast_link(self.ct)
1121 # Finally mark record final if applicable
1122 if is_final:
1123 record.is_final = True
1125 return record
1127 def parse_expression(self, scope):
1128 # lobster-trace: LRM.Expression
1129 assert isinstance(scope, ast.Scope)
1131 n_lhs = self.parse_relation(scope)
1133 if self.peek_kw("and"):
1134 while self.peek_kw("and"):
1135 self.match_kw("and")
1136 t_op = self.ct
1137 a_op = ast.Binary_Operator.LOGICAL_AND
1138 t_op.ast_link = a_op
1139 n_rhs = self.parse_relation(scope)
1140 n_lhs = ast.Binary_Expression(
1141 mh=self.mh,
1142 location=t_op.location,
1143 typ=self.builtin_bool,
1144 operator=a_op,
1145 n_lhs=n_lhs,
1146 n_rhs=n_rhs,
1147 )
1149 elif self.peek_kw("or"):
1150 while self.peek_kw("or"):
1151 self.match_kw("or")
1152 t_op = self.ct
1153 a_op = ast.Binary_Operator.LOGICAL_OR
1154 t_op.ast_link = a_op
1155 n_rhs = self.parse_relation(scope)
1156 n_lhs = ast.Binary_Expression(
1157 mh=self.mh,
1158 location=t_op.location,
1159 typ=self.builtin_bool,
1160 operator=a_op,
1161 n_lhs=n_lhs,
1162 n_rhs=n_rhs,
1163 )
1165 elif self.peek_kw("xor"):
1166 self.match_kw("xor")
1167 t_op = self.ct
1168 a_op = ast.Binary_Operator.LOGICAL_XOR
1169 t_op.ast_link = a_op
1170 n_rhs = self.parse_relation(scope)
1171 n_lhs = ast.Binary_Expression(
1172 mh=self.mh,
1173 location=t_op.location,
1174 typ=self.builtin_bool,
1175 operator=a_op,
1176 n_lhs=n_lhs,
1177 n_rhs=n_rhs,
1178 )
1180 elif self.peek_kw("implies"):
1181 self.match_kw("implies")
1182 t_op = self.ct
1183 a_op = ast.Binary_Operator.LOGICAL_IMPLIES
1184 t_op.ast_link = a_op
1185 n_rhs = self.parse_relation(scope)
1186 n_lhs = ast.Binary_Expression(
1187 mh=self.mh,
1188 location=t_op.location,
1189 typ=self.builtin_bool,
1190 operator=a_op,
1191 n_lhs=n_lhs,
1192 n_rhs=n_rhs,
1193 )
1195 return n_lhs
1197 def parse_relation(self, scope):
1198 # lobster-trace: LRM.Relation
1199 # lobster-trace: LRM.Operators
1200 assert isinstance(scope, ast.Scope)
1201 relop_mapping = {
1202 "==": ast.Binary_Operator.COMP_EQ,
1203 "!=": ast.Binary_Operator.COMP_NEQ,
1204 "<": ast.Binary_Operator.COMP_LT,
1205 "<=": ast.Binary_Operator.COMP_LEQ,
1206 ">": ast.Binary_Operator.COMP_GT,
1207 ">=": ast.Binary_Operator.COMP_GEQ,
1208 }
1209 assert set(relop_mapping) == set(Parser.COMPARISON_OPERATOR)
1211 n_lhs = self.parse_simple_expression(scope)
1213 if self.peek("OPERATOR") and self.nt.value in Parser.COMPARISON_OPERATOR:
1214 self.match("OPERATOR")
1215 t_op = self.ct
1216 a_op = relop_mapping[t_op.value]
1217 t_op.ast_link = a_op
1218 n_rhs = self.parse_simple_expression(scope)
1219 return ast.Binary_Expression(
1220 mh=self.mh,
1221 location=t_op.location,
1222 typ=self.builtin_bool,
1223 operator=a_op,
1224 n_lhs=n_lhs,
1225 n_rhs=n_rhs,
1226 )
1228 elif self.peek_kw("not") or self.peek_kw("in"):
1229 if self.peek_kw("not"):
1230 self.match_kw("not")
1231 t_not = self.ct
1232 else:
1233 t_not = None
1235 self.match_kw("in")
1236 t_in = self.ct
1238 n_a = self.parse_simple_expression(scope)
1239 t_n_a = self.ct
1240 if self.peek("RANGE"):
1241 self.match("RANGE")
1242 t_range = self.ct
1243 n_b = self.parse_simple_expression(scope)
1244 n_b.set_ast_link(self.ct)
1245 n_a.set_ast_link(t_n_a)
1246 rv = ast.Range_Test(
1247 mh=self.mh,
1248 location=t_in.location,
1249 typ=self.builtin_bool,
1250 n_lhs=n_lhs,
1251 n_lower=n_a,
1252 n_upper=n_b,
1253 )
1254 rv.set_ast_link(t_range)
1255 rv.set_ast_link(t_in)
1257 elif isinstance(n_a.typ, ast.Builtin_String):
1258 rv = ast.Binary_Expression(
1259 mh=self.mh,
1260 location=t_in.location,
1261 typ=self.builtin_bool,
1262 operator=ast.Binary_Operator.STRING_CONTAINS,
1263 n_lhs=n_lhs,
1264 n_rhs=n_a,
1265 )
1266 rv.set_ast_link(t_in)
1268 elif isinstance(n_a.typ, ast.Array_Type): 1268 ↛ 1281line 1268 didn't jump to line 1281 because the condition on line 1268 was always true
1269 a_op = ast.Binary_Operator.ARRAY_CONTAINS
1270 t_in.ast_link = a_op
1271 rv = ast.Binary_Expression(
1272 mh=self.mh,
1273 location=t_in.location,
1274 typ=self.builtin_bool,
1275 operator=a_op,
1276 n_lhs=n_lhs,
1277 n_rhs=n_a,
1278 )
1280 else:
1281 self.mh.error(
1282 n_a.location,
1283 "membership test only defined for Strings and Arrays,"
1284 " not for %s" % n_a.typ.name,
1285 )
1287 if t_not is not None:
1288 a_unary_op = ast.Unary_Operator.LOGICAL_NOT
1289 t_not.ast_link = a_unary_op
1290 rv = ast.Unary_Expression(
1291 mh=self.mh,
1292 location=t_not.location,
1293 typ=self.builtin_bool,
1294 operator=a_unary_op,
1295 n_operand=rv,
1296 )
1298 return rv
1300 else:
1301 return n_lhs
1303 def parse_simple_expression(self, scope):
1304 # lobster-trace: LRM.Simple_Expression
1305 # lobster-trace: LRM.Operators
1306 # lobster-trace: LRM.Unary_Minus_Parsing
1307 assert isinstance(scope, ast.Scope)
1308 un_add_map = {"+": ast.Unary_Operator.PLUS, "-": ast.Unary_Operator.MINUS}
1309 bin_add_map = {"+": ast.Binary_Operator.PLUS, "-": ast.Binary_Operator.MINUS}
1310 assert set(un_add_map) == set(Parser.ADDING_OPERATOR)
1311 assert set(bin_add_map) == set(Parser.ADDING_OPERATOR)
1313 if self.peek("OPERATOR") and self.nt.value in Parser.ADDING_OPERATOR:
1314 self.match("OPERATOR")
1315 t_unary = self.ct
1316 a_unary = un_add_map[t_unary.value]
1317 t_unary.ast_link = a_unary
1318 has_explicit_brackets = self.peek("BRA")
1319 else:
1320 t_unary = None
1322 n_lhs = self.parse_term(scope)
1323 if t_unary:
1324 # pylint: disable=possibly-used-before-assignment
1325 if (
1326 self.lint_mode
1327 and isinstance(n_lhs, ast.Binary_Expression)
1328 and not has_explicit_brackets
1329 ):
1330 self.mh.check(
1331 t_unary.location,
1332 "expression means -(%s), place explicit "
1333 "brackets to clarify intent" % n_lhs.to_string(),
1334 "unary_minus_precedence",
1335 )
1337 n_lhs = ast.Unary_Expression(
1338 mh=self.mh,
1339 location=t_unary.location,
1340 typ=n_lhs.typ,
1341 operator=a_unary,
1342 n_operand=n_lhs,
1343 )
1345 if isinstance(n_lhs.typ, ast.Builtin_String):
1346 rtyp = self.builtin_str
1347 else:
1348 rtyp = n_lhs.typ
1350 while self.peek("OPERATOR") and self.nt.value in Parser.ADDING_OPERATOR:
1351 self.match("OPERATOR")
1352 t_op = self.ct
1353 a_op = bin_add_map[t_op.value]
1354 t_op.ast_link = a_op
1355 n_rhs = self.parse_term(scope)
1356 n_lhs = ast.Binary_Expression(
1357 mh=self.mh,
1358 location=t_op.location,
1359 typ=rtyp,
1360 operator=a_op,
1361 n_lhs=n_lhs,
1362 n_rhs=n_rhs,
1363 )
1365 return n_lhs
1367 def parse_term(self, scope):
1368 # lobster-trace: LRM.Term
1369 # lobster-trace: LRM.Operators
1370 assert isinstance(scope, ast.Scope)
1371 mul_map = {
1372 "*": ast.Binary_Operator.TIMES,
1373 "/": ast.Binary_Operator.DIVIDE,
1374 "%": ast.Binary_Operator.REMAINDER,
1375 }
1376 assert set(mul_map) == set(Parser.MULTIPLYING_OPERATOR)
1378 n_lhs = self.parse_factor(scope)
1379 while self.peek("OPERATOR") and self.nt.value in Parser.MULTIPLYING_OPERATOR:
1380 self.match("OPERATOR")
1381 t_op = self.ct
1382 a_op = mul_map[t_op.value]
1383 t_op.ast_link = a_op
1384 n_rhs = self.parse_factor(scope)
1385 n_lhs = ast.Binary_Expression(
1386 mh=self.mh,
1387 location=t_op.location,
1388 typ=n_lhs.typ,
1389 operator=a_op,
1390 n_lhs=n_lhs,
1391 n_rhs=n_rhs,
1392 )
1394 return n_lhs
1396 def parse_factor(self, scope):
1397 # lobster-trace: LRM.Factor
1398 assert isinstance(scope, ast.Scope)
1400 if self.peek_kw("not"):
1401 self.match_kw("not")
1402 t_op = self.ct
1403 n_operand = self.parse_primary(scope)
1404 a_not = ast.Unary_Operator.LOGICAL_NOT
1405 t_op.ast_link = a_not
1406 return ast.Unary_Expression(
1407 mh=self.mh,
1408 location=t_op.location,
1409 typ=self.builtin_bool,
1410 operator=a_not,
1411 n_operand=n_operand,
1412 )
1414 elif self.peek_kw("abs"):
1415 self.match_kw("abs")
1416 t_op = self.ct
1417 n_operand = self.parse_primary(scope)
1418 a_abs = ast.Unary_Operator.ABSOLUTE_VALUE
1419 t_op.ast_link = a_abs
1420 return ast.Unary_Expression(
1421 mh=self.mh,
1422 location=t_op.location,
1423 typ=n_operand.typ,
1424 operator=a_abs,
1425 n_operand=n_operand,
1426 )
1428 else:
1429 n_lhs = self.parse_primary(scope)
1430 if self.peek("OPERATOR") and self.nt.value == "**":
1431 self.match("OPERATOR")
1432 t_op = self.ct
1433 n_rhs = self.parse_primary(scope)
1434 rhs_value = n_rhs.evaluate(self.mh, None, None)
1435 a_binary = ast.Binary_Operator.POWER
1436 t_op.ast_link = a_binary
1437 n_lhs = ast.Binary_Expression(
1438 mh=self.mh,
1439 location=t_op.location,
1440 typ=n_lhs.typ,
1441 operator=a_binary,
1442 n_lhs=n_lhs,
1443 n_rhs=n_rhs,
1444 )
1445 if rhs_value.value < 0: 1445 ↛ 1446line 1445 didn't jump to line 1446 because the condition on line 1445 was never true
1446 self.mh.error(n_rhs.location, "exponent must not be negative")
1447 return n_lhs
1449 def parse_primary(self, scope):
1450 # lobster-trace: LRM.Primary
1451 assert isinstance(scope, ast.Scope)
1453 if self.peek("INTEGER"):
1454 # lobster-trace: LRM.Integer_Values
1455 self.match("INTEGER")
1456 int_lit = ast.Integer_Literal(self.ct, self.builtin_int)
1457 int_lit.set_ast_link(self.ct)
1458 return int_lit
1460 elif self.peek("DECIMAL"):
1461 # lobster-trace: LRM.Decimal_Values
1462 self.match("DECIMAL")
1463 dec_lit = ast.Decimal_Literal(self.ct, self.builtin_decimal)
1464 dec_lit.set_ast_link(self.ct)
1465 return dec_lit
1467 elif self.peek("STRING"):
1468 # lobster-trace: LRM.String_Values
1469 self.match("STRING")
1470 string_lit = ast.String_Literal(self.ct, self.builtin_str)
1471 string_lit.set_ast_link(self.ct)
1472 return string_lit
1474 elif self.peek_kw("true") or self.peek_kw("false"):
1475 # lobster-trace: LRM.Boolean_Values
1476 self.match("KEYWORD")
1477 bool_lit = ast.Boolean_Literal(self.ct, self.builtin_bool)
1478 bool_lit.set_ast_link(self.ct)
1479 return bool_lit
1481 elif self.peek_kw("null"):
1482 self.match_kw("null")
1483 null_lit = ast.Null_Literal(self.ct)
1484 null_lit.set_ast_link(self.ct)
1485 return null_lit
1487 elif self.peek("BRA"):
1488 self.match("BRA")
1489 t_bra = self.ct
1490 if self.peek_kw("forall") or self.peek_kw("exists"):
1491 rv = self.parse_quantified_expression(scope)
1492 elif self.peek_kw("if"):
1493 rv = self.parse_conditional_expression(scope)
1494 else:
1495 rv = self.parse_expression(scope)
1496 rv.set_ast_link(t_bra)
1497 self.match("KET")
1498 rv.set_ast_link(self.ct)
1499 return rv
1501 else:
1502 return self.parse_name(scope)
1504 def parse_quantified_expression(self, scope):
1505 # lobster-trace: LRM.Quantified_Expression
1506 assert isinstance(scope, ast.Scope)
1508 if self.peek_kw("forall"):
1509 self.match_kw("forall")
1510 t_quantified = self.ct
1511 universal = True
1512 else:
1513 self.match_kw("exists")
1514 t_quantified = self.ct
1515 universal = False
1516 loc = self.ct.location
1517 self.match("IDENTIFIER")
1518 t_qv = self.ct
1519 if scope.contains(t_qv.value):
1520 # lobster-trace: LRM.Quantification_Naming_Scope
1521 pdef = scope.lookup(self.mh, t_qv)
1522 self.mh.error(
1523 t_qv.location,
1524 "shadows %s %s from %s"
1525 % (
1526 pdef.__class__.__name__,
1527 pdef.name,
1528 self.mh.cross_file_reference(pdef.location),
1529 ),
1530 )
1531 self.match_kw("in")
1532 t_in = self.ct
1533 self.match("IDENTIFIER")
1534 field = scope.lookup(self.mh, self.ct, ast.Composite_Component)
1535 n_source = ast.Name_Reference(self.ct.location, field)
1536 n_source.set_ast_link(self.ct)
1537 if not isinstance(field.n_typ, ast.Array_Type):
1538 # lobster-trace: LRM.Quantification_Object
1539 self.mh.error(self.ct.location, "you can only quantify over arrays")
1540 n_var = ast.Quantified_Variable(
1541 t_qv.value, t_qv.location, field.n_typ.element_type
1542 )
1543 n_var.set_ast_link(t_qv)
1544 self.match("ARROW")
1545 t_arrow = self.ct
1547 new_table = ast.Symbol_Table()
1548 new_table.register(self.mh, n_var)
1549 scope.push(new_table)
1550 n_expr = self.parse_expression(scope)
1551 scope.pop()
1553 quantified_expression = ast.Quantified_Expression(
1554 mh=self.mh,
1555 location=loc,
1556 typ=self.builtin_bool,
1557 universal=universal,
1558 n_variable=n_var,
1559 n_source=n_source,
1560 n_expr=n_expr,
1561 )
1563 quantified_expression.set_ast_link(t_quantified)
1564 quantified_expression.set_ast_link(t_in)
1565 quantified_expression.set_ast_link(t_arrow)
1567 return quantified_expression
1569 def parse_conditional_expression(self, scope):
1570 # lobster-trace: LRM.Conditional_Expression
1571 # lobster-trace: LRM.Restricted_Null
1572 assert isinstance(scope, ast.Scope)
1574 self.match_kw("if")
1575 t_if = self.ct
1576 if_cond = self.parse_expression(scope)
1577 self.match_kw("then")
1578 t_then = self.ct
1579 if_expr = self.parse_expression(scope)
1580 if if_expr.typ is None:
1581 self.mh.error(if_expr.location, "null is not permitted here")
1582 if_action = ast.Action(self.mh, t_if, if_cond, if_expr)
1584 rv = ast.Conditional_Expression(location=t_if.location, if_action=if_action)
1585 if_action.set_ast_link(t_if)
1586 if_action.set_ast_link(t_then)
1588 while self.peek_kw("elsif"):
1589 self.match_kw("elsif")
1590 t_elsif = self.ct
1591 elsif_cond = self.parse_expression(scope)
1592 self.match_kw("then")
1593 t_then = self.ct
1594 elsif_expr = self.parse_expression(scope)
1595 elsif_action = ast.Action(self.mh, t_elsif, elsif_cond, elsif_expr)
1596 elsif_action.set_ast_link(t_elsif)
1597 elsif_action.set_ast_link(t_then)
1598 rv.add_elsif(self.mh, elsif_action)
1600 self.match_kw("else")
1601 rv.set_ast_link(self.ct)
1602 else_expr = self.parse_expression(scope)
1603 rv.set_else_part(self.mh, else_expr)
1605 return rv
1607 def parse_builtin(self, scope, n_name, t_name):
1608 # lobster-trace: LRM.Builtin_Functions
1609 # lobster-trace: LRM.Builtin_Type_Conversion_Functions
1610 assert isinstance(scope, ast.Scope)
1611 assert isinstance(n_name, (ast.Builtin_Function, ast.Builtin_Numeric_Type))
1612 assert isinstance(t_name, Token)
1614 # Parse the arguments.
1615 parameters = []
1616 n_name.set_ast_link(self.ct)
1617 self.match("BRA")
1618 n_name.set_ast_link(self.ct)
1619 while not self.peek("KET"): 1619 ↛ 1630line 1619 didn't jump to line 1630 because the condition on line 1619 was always true
1620 exp = self.parse_expression(scope)
1621 if not self.ct.ast_link: 1621 ↛ 1622line 1621 didn't jump to line 1622 because the condition on line 1621 was never true
1622 exp.set_ast_link(self.ct)
1623 parameters.append(exp)
1625 if self.peek("COMMA"):
1626 self.match("COMMA")
1627 n_name.set_ast_link(self.ct)
1628 else:
1629 break
1630 self.match("KET")
1631 n_name.set_ast_link(self.ct)
1633 # Enforce arity
1634 if isinstance(n_name, ast.Builtin_Function):
1635 required_arity = n_name.arity
1636 precise = not n_name.arity_at_least
1637 else:
1638 required_arity = 1
1639 precise = True
1641 if precise:
1642 if required_arity != len(parameters):
1643 self.mh.error(
1644 t_name.location, "function requires %u parameters" % n_name.arity
1645 )
1646 else:
1647 if required_arity > len(parameters): 1647 ↛ 1648line 1647 didn't jump to line 1648 because the condition on line 1647 was never true
1648 self.mh.error(
1649 t_name.location,
1650 "function requires at least %u parameters" % n_name.arity,
1651 )
1653 # Enforce types
1654 if n_name.name == "len":
1655 if isinstance(parameters[0].typ, ast.Builtin_String):
1656 return ast.Unary_Expression(
1657 mh=self.mh,
1658 location=t_name.location,
1659 typ=self.builtin_int,
1660 operator=ast.Unary_Operator.STRING_LENGTH,
1661 n_operand=parameters[0],
1662 )
1663 else:
1664 return ast.Unary_Expression(
1665 mh=self.mh,
1666 location=t_name.location,
1667 typ=self.builtin_int,
1668 operator=ast.Unary_Operator.ARRAY_LENGTH,
1669 n_operand=parameters[0],
1670 )
1672 elif n_name.name in ("startswith", "endswith"):
1673 return ast.Binary_Expression(
1674 mh=self.mh,
1675 location=t_name.location,
1676 typ=self.builtin_bool,
1677 operator=(
1678 ast.Binary_Operator.STRING_STARTSWITH
1679 if "startswith" in n_name.name
1680 else ast.Binary_Operator.STRING_ENDSWITH
1681 ),
1682 n_lhs=parameters[0],
1683 n_rhs=parameters[1],
1684 )
1686 elif n_name.name == "matches":
1687 parameters[1].ensure_type(self.mh, ast.Builtin_String)
1688 try:
1689 # lobster-trace: LRM.Static_Regular_Expression
1690 # scope is None on purpose to enforce static context
1691 value = parameters[1].evaluate(self.mh, None, None)
1692 assert isinstance(value.typ, ast.Builtin_String)
1693 re.compile(value.value)
1694 except re.error as err:
1695 self.mh.error(value.location, str(err))
1696 return ast.Binary_Expression(
1697 mh=self.mh,
1698 location=t_name.location,
1699 typ=self.builtin_bool,
1700 operator=ast.Binary_Operator.STRING_REGEX,
1701 n_lhs=parameters[0],
1702 n_rhs=parameters[1],
1703 )
1705 elif n_name.name == "oneof":
1706 return ast.OneOf_Expression(
1707 mh=self.mh,
1708 location=t_name.location,
1709 typ=self.builtin_bool,
1710 choices=parameters,
1711 )
1713 elif isinstance(n_name, ast.Builtin_Numeric_Type):
1714 parameters[0].ensure_type(self.mh, ast.Builtin_Numeric_Type)
1715 if isinstance(n_name, ast.Builtin_Integer):
1716 return ast.Unary_Expression(
1717 mh=self.mh,
1718 location=t_name.location,
1719 typ=self.builtin_int,
1720 operator=ast.Unary_Operator.CONVERSION_TO_INT,
1721 n_operand=parameters[0],
1722 )
1723 elif isinstance(n_name, ast.Builtin_Decimal):
1724 return ast.Unary_Expression(
1725 mh=self.mh,
1726 location=t_name.location,
1727 typ=self.builtin_decimal,
1728 operator=ast.Unary_Operator.CONVERSION_TO_DECIMAL,
1729 n_operand=parameters[0],
1730 )
1731 else:
1732 self.mh.ice_loc(t_name.location, "unexpected type conversion")
1734 else:
1735 self.mh.ice_loc(t_name.location, "unexpected builtin")
1737 def parse_name(self, scope):
1738 # lobster-trace: LRM.Names
1740 # This is a bit more complex. The grammar is:
1741 #
1742 # qualified_name ::= [ IDENTIFIER_package_name '.' ] IDENTIFIER_name
1743 #
1744 # name ::= qualified_name
1745 # | name '.' IDENTIFIER
1746 # | name '[' expression ']'
1747 # | name '(' parameter_list ')'
1748 #
1749 # parameter_list ::= expression { ',' expression }
1751 assert isinstance(scope, ast.Scope)
1753 # All names start with a (qualified) identifier. We parse that
1754 # first. There is a special complication for functions, as
1755 # builtin functions (e.g. len) can shadow record
1756 # components. However as functions cannot be stored in
1757 # components the true grammar for function calls is always
1758 # IDENTIFIER '('; so we can slightly special case this.
1760 # lobster-trace: LRM.Builtin_Functions
1761 # lobster-trace: LRM.Builtin_Type_Conversion_Functions
1762 self.match("IDENTIFIER")
1763 if self.peek("BRA"):
1764 # If we follow our name with brackets
1765 # immediately, we have a builtin function call.
1766 n_name = self.stab.lookup(self.mh, self.ct)
1767 if not isinstance(n_name, (ast.Builtin_Function, ast.Builtin_Numeric_Type)): 1767 ↛ 1768line 1767 didn't jump to line 1768 because the condition on line 1767 was never true
1768 self.mh.error(
1769 self.ct.location, "not a valid builtin function or numeric type"
1770 )
1771 else:
1772 n_name = self.parse_qualified_name(scope, match_ident=False)
1774 # Enum literals are a bit different, so we deal with them
1775 # first.
1776 if isinstance(n_name, ast.Enumeration_Type):
1777 n_name.set_ast_link(self.ct)
1778 self.match("DOT")
1779 n_name.set_ast_link(self.ct)
1780 self.match("IDENTIFIER")
1781 lit = n_name.literals.lookup(self.mh, self.ct, ast.Enumeration_Literal_Spec)
1782 enum_lit = ast.Enumeration_Literal(location=self.ct.location, literal=lit)
1783 enum_lit.set_ast_link(self.ct)
1784 return enum_lit
1786 # Anything that remains is either a function call or an actual
1787 # name. Let's just enforce this for sanity.
1788 if not isinstance( 1788 ↛ 1797line 1788 didn't jump to line 1797 because the condition on line 1788 was never true
1789 n_name,
1790 (
1791 ast.Builtin_Function,
1792 ast.Builtin_Numeric_Type,
1793 ast.Composite_Component,
1794 ast.Quantified_Variable,
1795 ),
1796 ):
1797 self.mh.error(
1798 self.ct.location,
1799 "%s %s is not a valid name" % (n_name.__class__.__name__, n_name.name),
1800 )
1802 # Right now function calls and type conversions must be
1803 # top-level, so let's get these out of the way as well.
1804 if isinstance(n_name, (ast.Builtin_Function, ast.Builtin_Numeric_Type)):
1805 # lobster-trace: LRM.Builtin_Functions
1806 # lobster-trace: LRM.Builtin_Type_Conversion_Functions
1807 return self.parse_builtin(scope, n_name, self.ct)
1809 assert isinstance(n_name, (ast.Composite_Component, ast.Quantified_Variable))
1811 # We now process the potentially recursive part:
1812 # | name '.' IDENTIFIER
1813 # | name '[' expression ']'
1814 n_name = ast.Name_Reference(location=self.ct.location, entity=n_name)
1815 n_name.set_ast_link(self.ct)
1816 while self.peek("DOT") or self.peek("S_BRA"):
1817 if self.peek("DOT"):
1818 if not isinstance( 1818 ↛ 1822line 1818 didn't jump to line 1822 because the condition on line 1818 was never true
1819 n_name.typ, (ast.Tuple_Type, ast.Record_Type, ast.Union_Type)
1820 ):
1821 # lobster-trace: LRM.Valid_Index_Prefixes
1822 self.mh.error(
1823 n_name.location,
1824 "expression '%s' has type %s, "
1825 "which is not a tuple, record, or union"
1826 % (n_name.to_string(), n_name.typ.name),
1827 )
1829 self.match("DOT")
1830 t_dot = self.ct
1831 self.match("IDENTIFIER")
1832 t_field = self.ct
1834 is_union_access = isinstance(n_name.typ, ast.Union_Type)
1835 is_universal = True
1837 if is_union_access:
1838 # lobster-trace: LRM.Union_Type_Field_Access
1839 # lobster-trace: LRM.Union_Type_Field_Type_Conflict
1840 # lobster-trace: LRM.Union_Type_Field_Access_Validity
1841 field_name = t_field.value
1842 # A forward-declared stub may have turned into a
1843 # non-record type (already reported); abort this
1844 # check instead of inspecting that member.
1845 n_name.typ.ensure_record_members()
1846 field_map = n_name.typ.get_field_map()
1847 if field_name not in field_map:
1848 self.mh.error(
1849 t_field.location,
1850 "field %s does not exist in any member"
1851 " of union type %s" % (field_name, n_name.typ.name),
1852 )
1853 info = field_map[field_name]
1854 if info["n_typ"] is None:
1855 self.mh.error(
1856 t_field.location,
1857 "field %s has conflicting types in"
1858 " members of union type %s" % (field_name, n_name.typ.name),
1859 )
1860 is_universal = info["count"] == info["total"]
1861 # lobster-trace: LRM.Union_Type_Partial_Field_Access
1862 if self.lint_mode and not is_universal:
1863 self.mh.check(
1864 t_field.location,
1865 "field %s exists only in %u of %u"
1866 " members of union type %s;"
1867 " accessing it on other members"
1868 " returns null"
1869 % (
1870 field_name,
1871 info["count"],
1872 info["total"],
1873 n_name.typ.name,
1874 ),
1875 "union_partial_field_access",
1876 )
1877 n_field = info["component"]
1878 else:
1879 n_field = n_name.typ.components.lookup(
1880 self.mh, t_field, ast.Composite_Component
1881 )
1883 n_field.set_ast_link(t_field)
1884 n_name = ast.Field_Access_Expression(
1885 mh=self.mh,
1886 location=t_field.location,
1887 n_prefix=n_name,
1888 n_field=n_field,
1889 is_union_access=is_union_access,
1890 is_universal=is_universal,
1891 )
1892 n_name.set_ast_link(t_dot)
1894 elif self.peek("S_BRA"): 1894 ↛ 1816line 1894 didn't jump to line 1816 because the condition on line 1894 was always true
1895 if not isinstance(n_name.typ, ast.Array_Type):
1896 self.mh.error(
1897 n_name.location,
1898 "expression '%s' has type %s, "
1899 "which is not an array" % (n_name.to_string(), n_name.typ.name),
1900 )
1902 self.match("S_BRA")
1903 t_bracket = self.ct
1904 n_index = self.parse_expression(scope)
1905 self.match("S_KET")
1906 a_binary = ast.Binary_Operator.INDEX
1907 t_bracket.ast_link = a_binary
1908 self.ct.ast_link = a_binary
1910 n_name = ast.Binary_Expression(
1911 mh=self.mh,
1912 location=t_bracket.location,
1913 typ=n_name.typ.element_type,
1914 operator=a_binary,
1915 n_lhs=n_name,
1916 n_rhs=n_index,
1917 )
1919 return n_name
1921 def parse_check_block(self):
1922 # lobster-trace: LRM.Check_Block
1923 t_severity = None
1924 self.match_kw("checks")
1925 t_checks = self.ct
1926 self.match("IDENTIFIER")
1927 # lobster-trace: LRM.Applicable_Types
1928 # lobster-trace: LRM.Applicable_Components
1929 n_ctype = self.cu.package.symbols.lookup(self.mh, self.ct, ast.Composite_Type)
1930 n_check_block = ast.Check_Block(location=self.ct.location, n_typ=n_ctype)
1931 n_check_block.set_ast_link(t_checks)
1932 n_ctype.set_ast_link(self.ct)
1933 scope = ast.Scope()
1934 scope.push(self.stab)
1935 scope.push(self.cu.package.symbols)
1936 scope.push(n_ctype.components)
1937 self.match("C_BRA")
1938 n_check_block.set_ast_link(self.ct)
1939 while not self.peek("C_KET"):
1940 c_expr = self.parse_expression(scope)
1941 if not isinstance(c_expr.typ, ast.Builtin_Boolean): 1941 ↛ 1942line 1941 didn't jump to line 1942 because the condition on line 1941 was never true
1942 self.mh.error(c_expr.location, "check expression must be Boolean")
1944 self.match("COMMA")
1945 t_first_comma = self.ct
1946 if self.peek("KEYWORD"):
1947 self.match("KEYWORD")
1948 t_severity = self.ct
1949 if self.ct.value not in ("warning", "error", "fatal"): 1949 ↛ 1950line 1949 didn't jump to line 1950 because the condition on line 1949 was never true
1950 self.mh.error(self.ct.location, "expected warning|error|fatal")
1951 c_sev = self.ct.value
1952 else:
1953 c_sev = "error"
1955 self.match("STRING")
1956 if "\n" in self.ct.value:
1957 # lobster-trace: LRM.No_Newlines_In_Message
1958 self.mh.error(
1959 self.ct.location,
1960 "error message must not contain a newline",
1961 fatal=False,
1962 )
1963 t_msg = self.ct
1965 has_extrainfo = False
1966 has_anchor = False
1967 if self.peek("COMMA"):
1968 self.match("COMMA")
1969 t_second_comma = self.ct
1970 if self.peek("IDENTIFIER"):
1971 has_anchor = True
1972 elif self.peek("STRING"): 1972 ↛ 1975line 1972 didn't jump to line 1975 because the condition on line 1972 was always true
1973 has_extrainfo = True
1974 else:
1975 self.mh.error(
1976 self.nt.location,
1977 "expected either a details string or"
1978 " identifier to anchor the check message",
1979 )
1981 if has_extrainfo:
1982 self.match("STRING")
1983 t_extrainfo = self.ct
1984 c_extrainfo = self.ct.value
1986 if self.peek("COMMA"): 1986 ↛ 1987line 1986 didn't jump to line 1987 because the condition on line 1986 was never true
1987 self.match("COMMA")
1988 t_third_comma = self.ct
1989 has_anchor = True
1991 else:
1992 c_extrainfo = None
1994 if has_anchor:
1995 self.match("IDENTIFIER")
1996 t_anchor = self.ct
1997 c_anchor = n_ctype.components.lookup(
1998 self.mh, self.ct, ast.Composite_Component
1999 )
2000 else:
2001 c_anchor = None
2003 n_check = ast.Check(
2004 n_type=n_ctype,
2005 n_expr=c_expr,
2006 n_anchor=c_anchor,
2007 severity=c_sev,
2008 t_message=t_msg,
2009 extrainfo=c_extrainfo,
2010 )
2012 # pylint: disable=possibly-used-before-assignment
2013 # pylint: disable=used-before-assignment
2015 n_check.set_ast_link(t_first_comma)
2016 if t_severity:
2017 n_check.set_ast_link(t_severity)
2018 n_check.set_ast_link(t_msg)
2019 if c_extrainfo or c_anchor:
2020 n_check.set_ast_link(t_second_comma)
2021 if c_extrainfo:
2022 n_check.set_ast_link(t_extrainfo)
2023 if c_anchor:
2024 c_anchor.set_ast_link(t_anchor)
2025 if c_anchor and c_extrainfo: 2025 ↛ 2026line 2025 didn't jump to line 2026 because the condition on line 2025 was never true
2026 n_check.set_ast_link(t_third_comma)
2028 n_ctype.add_check(n_check)
2029 n_check_block.add_check(n_check)
2031 assert scope.size() == 3
2033 self.match("C_KET")
2034 n_check_block.set_ast_link(self.ct)
2036 return n_check_block
2038 def parse_section_declaration(self):
2039 # lobster-trace: LRM.Section_Declaration
2040 self.match_kw("section")
2041 t_section = self.ct
2042 self.match("STRING")
2043 sec = ast.Section(
2044 name=self.ct.value,
2045 location=self.ct.location,
2046 parent=self.section[-1] if self.section else None,
2047 )
2048 sec.set_ast_link(self.ct)
2049 sec.set_ast_link(t_section)
2050 self.section.append(sec)
2051 self.match("C_BRA")
2052 sec.set_ast_link(self.ct)
2053 while not self.peek("C_KET"):
2054 self.parse_trlc_entry()
2055 self.match("C_KET")
2056 sec.set_ast_link(self.ct)
2057 self.section.pop()
2059 def parse_boolean(self):
2060 # lobster-trace: LRM.Boolean_Values
2061 self.match("KEYWORD")
2062 if self.ct.value in ("true", "false"): 2062 ↛ 2065line 2062 didn't jump to line 2065 because the condition on line 2062 was always true
2063 return ast.Boolean_Literal(self.ct, self.builtin_bool)
2064 else:
2065 self.mh.error(self.ct.location, "expected boolean literal (true or false)")
2067 def parse_value(self, typ):
2068 # lobster-trace: LRM.Tuple_Syntax_Correct_Form
2069 assert isinstance(typ, ast.Type)
2071 if isinstance(typ, ast.Builtin_Numeric_Type):
2072 # lobster-trace: LRM.Integer_Values
2073 # lobster-trace: LRM.Decimal_Values
2074 if self.peek("OPERATOR") and self.nt.value in Parser.ADDING_OPERATOR:
2075 self.match("OPERATOR")
2076 t_op = self.ct
2077 e_op = (
2078 ast.Unary_Operator.PLUS
2079 if t_op.value == "+"
2080 else ast.Unary_Operator.MINUS
2081 )
2082 t_op.ast_link = e_op
2083 else:
2084 t_op = None
2086 if isinstance(typ, ast.Builtin_Decimal):
2087 self.match("DECIMAL")
2088 rv = ast.Decimal_Literal(self.ct, self.builtin_decimal)
2089 rv.set_ast_link(self.ct)
2090 elif isinstance(typ, ast.Builtin_Integer):
2091 self.match("INTEGER")
2092 rv = ast.Integer_Literal(self.ct, self.builtin_int)
2093 rv.set_ast_link(self.ct)
2094 else:
2095 assert False
2097 if t_op:
2098 rv = ast.Unary_Expression(
2099 mh=self.mh,
2100 location=t_op.location,
2101 typ=rv.typ,
2102 operator=e_op,
2103 n_operand=rv,
2104 )
2106 return rv
2108 elif isinstance(typ, ast.Builtin_Markup_String):
2109 # lobster-trace: LRM.Markup_String_Values
2110 return self.parse_markup_string()
2112 elif isinstance(typ, ast.Builtin_String):
2113 # lobster-trace: LRM.String_Values
2114 self.match("STRING")
2115 rv = ast.String_Literal(self.ct, self.builtin_str)
2116 rv.set_ast_link(self.ct)
2117 return rv
2119 elif isinstance(typ, ast.Builtin_Boolean):
2120 rv = self.parse_boolean()
2121 rv.set_ast_link(self.ct)
2122 return rv
2124 elif isinstance(typ, ast.Array_Type):
2125 self.match("S_BRA")
2126 rv = ast.Array_Aggregate(self.ct.location, typ)
2127 rv.set_ast_link(self.ct)
2128 while not self.peek("S_KET"):
2129 array_elem = self.parse_value(typ.element_type)
2130 rv.append(array_elem)
2131 if self.peek("COMMA"):
2132 self.match("COMMA")
2133 rv.set_ast_link(self.ct)
2134 elif self.peek("S_KET") or self.nt is None: 2134 ↛ 2137line 2134 didn't jump to line 2137 because the condition on line 2134 was always true
2135 break
2136 else:
2137 self.mh.error(
2138 self.ct.location,
2139 "comma separating array elements is missing",
2140 fatal=False,
2141 )
2143 self.match("S_KET")
2144 rv.set_ast_link(self.ct)
2146 if len(rv.value) < typ.lower_bound:
2147 self.mh.error(
2148 self.ct.location,
2149 "this array requires at least %u elements "
2150 "(only %u provided)" % (typ.lower_bound, len(rv.value)),
2151 fatal=False,
2152 )
2153 if typ.upper_bound and len(rv.value) > typ.upper_bound:
2154 self.mh.error(
2155 rv.value[typ.upper_bound].location,
2156 "this array requires at most %u elements "
2157 "(%u provided)" % (typ.upper_bound, len(rv.value)),
2158 fatal=False,
2159 )
2161 return rv
2163 elif isinstance(typ, ast.Enumeration_Type):
2164 enum = self.parse_qualified_name(self.default_scope, ast.Enumeration_Type)
2165 enum.set_ast_link(self.ct)
2166 if enum != typ:
2167 self.mh.error(self.ct.location, "expected %s" % typ.name)
2168 self.match("DOT")
2169 enum.set_ast_link(self.ct)
2170 self.match("IDENTIFIER")
2171 lit = enum.literals.lookup(self.mh, self.ct, ast.Enumeration_Literal_Spec)
2172 return ast.Enumeration_Literal(self.ct.location, lit)
2174 elif isinstance(typ, (ast.Record_Type, ast.Union_Type)):
2175 self.match("IDENTIFIER")
2176 t_name = self.ct
2177 if self.peek("DOT"):
2178 # Parse a (potentially nested) package prefix followed by
2179 # the object name via a greedy sub-package descent.
2180 the_pkg = self.stab.lookup(self.mh, t_name, ast.Package)
2181 the_pkg.set_ast_link(t_name)
2182 the_pkg, t_name = self.descend_sub_packages(the_pkg, t_name)
2183 else:
2184 the_pkg = self.cu.package
2186 rv = ast.Record_Reference(
2187 location=t_name.location, name=t_name.value, typ=typ, package=the_pkg
2188 )
2189 rv.set_ast_link(t_name)
2191 # We can do an early lookup if the target is known
2192 if the_pkg.symbols.contains(t_name.value):
2193 rv.resolve_references(self.mh)
2195 return rv
2197 elif isinstance(typ, ast.Tuple_Type) and typ.has_separators():
2198 # lobster-trace: LRM.Tuple_Separator_Form
2199 rv = ast.Tuple_Aggregate(self.nt.location, typ)
2201 next_is_optional = False
2202 for n_item in typ.iter_sequence():
2203 if isinstance(n_item, ast.Composite_Component):
2204 if next_is_optional and n_item.optional:
2205 break
2206 value = self.parse_value(n_item.n_typ)
2207 rv.assign(n_item.name, value)
2209 elif n_item.token.kind in ("AT", "COLON", "SEMICOLON"):
2210 if self.peek(n_item.token.kind):
2211 self.match(n_item.token.kind)
2212 n_item.set_ast_link(self.ct)
2213 else:
2214 next_is_optional = True
2216 elif n_item.token.kind == "IDENTIFIER":
2217 if self.peek("IDENTIFIER") and self.nt.value == n_item.token.value:
2218 self.match("IDENTIFIER")
2219 n_item.set_ast_link(self.ct)
2220 else:
2221 next_is_optional = True
2223 else:
2224 assert False
2226 return rv
2228 elif isinstance(typ, ast.Tuple_Type) and not typ.has_separators():
2229 # lobster-trace: LRM.Tuple_Generic_Form
2230 self.match("BRA")
2231 rv = ast.Tuple_Aggregate(self.ct.location, typ)
2232 rv.set_ast_link(self.ct)
2234 first = True
2235 for n_field in typ.iter_sequence():
2236 if first:
2237 first = False
2238 else:
2239 self.match("COMMA")
2240 rv.set_ast_link(self.ct)
2241 rv.assign(n_field.name, self.parse_value(n_field.n_typ))
2243 self.match("KET")
2244 rv.set_ast_link(self.ct)
2245 return rv
2247 else:
2248 self.mh.ice_loc(
2249 self.ct.location,
2250 "logic error: unexpected type %s" % typ.__class__.__name__,
2251 )
2253 def parse_markup_string(self):
2254 # lobster-trace: LRM.Markup_String_Values
2255 self.match("STRING")
2256 rv = ast.String_Literal(self.ct, self.builtin_mstr)
2257 mpar = Markup_Parser(self, rv)
2258 mpar.parse_all_references()
2259 return rv
2261 def parse_record_object_declaration(self):
2262 # lobster-trace: LRM.Section_Declaration
2263 # lobster-trace: LRM.Record_Object_Declaration
2264 # lobster-trace: LRM.Valid_Record_Types
2265 # lobster-trace: LRM.Valid_Components
2266 # lobster-trace: LRM.Valid_Enumeration_Literals
2267 # lobster-trace: LRM.Mandatory_Components
2268 # lobster-trace: LRM.Evaluation_Of_Checks
2269 # lobster-trace: LRM.Single_Value_Assignment
2271 r_typ = self.parse_qualified_name(self.default_scope, ast.Record_Type)
2272 r_typ.set_ast_link(self.ct)
2273 # lobster-trace: LRM.Abstract_Types
2274 if r_typ.is_abstract:
2275 self.mh.error(
2276 self.ct.location,
2277 "cannot declare object of abstract record type %s" % r_typ.name,
2278 )
2280 self.match("IDENTIFIER")
2281 obj = ast.Record_Object(
2282 name=self.ct.value,
2283 location=self.ct.location,
2284 n_typ=r_typ,
2285 section=self.section.copy() if self.section else None,
2286 n_package=self.cu.package,
2287 )
2288 self.cu.package.symbols.register(self.mh, obj)
2289 obj.set_ast_link(self.ct)
2291 self.match("C_BRA")
2292 obj.set_ast_link(self.ct)
2293 while not self.peek("C_KET"):
2294 self.match("IDENTIFIER")
2295 comp = r_typ.components.lookup(self.mh, self.ct, ast.Composite_Component)
2296 if obj.is_component_implicit_null(comp):
2297 self.mh.error(
2298 self.ct.location,
2299 "component '%s' already assigned at line %i"
2300 % (comp.name, obj.field[comp.name].location.line_no),
2301 )
2302 comp.set_ast_link(self.ct)
2303 if r_typ.is_frozen(comp):
2304 self.mh.error(
2305 self.ct.location, "cannot overwrite frozen component %s" % comp.name
2306 )
2307 self.match("ASSIGN")
2308 comp.set_ast_link(self.ct)
2309 value = self.parse_value(comp.n_typ)
2310 if not self.ct.ast_link:
2311 value.set_ast_link(self.ct)
2312 obj.assign(comp, value)
2314 # Check that each non-optional component has been specified
2315 for comp in r_typ.all_components():
2316 if isinstance(obj.field[comp.name], ast.Implicit_Null):
2317 if r_typ.is_frozen(comp):
2318 obj.assign(comp, r_typ.get_freezing_expression(comp))
2319 elif not comp.optional:
2320 self.mh.error(
2321 obj.location,
2322 "required component %s (see %s) is not defined"
2323 % (comp.name, self.mh.cross_file_reference(comp.location)),
2324 )
2326 self.match("C_KET")
2327 obj.set_ast_link(self.ct)
2329 return obj
2331 def parse_trlc_entry(self):
2332 # lobster-trace: LRM.TRLC_File
2333 if self.peek_kw("section"):
2334 self.parse_section_declaration()
2335 else:
2336 self.cu.add_item(self.parse_record_object_declaration())
2338 def parse_preamble(self, kind):
2339 assert kind in ("rsl", "trlc")
2340 # lobster-trace: LRM.Layout
2341 # lobster-trace: LRM.Preamble
2343 self.file_kind = kind
2345 # First, parse package indication, declaring the package if
2346 # needed
2347 self.match_kw(self.PACKAGE_KEYWORD)
2348 t_pkg = self.ct
2349 pkg_name, pkg_location, pkg_tokens = self.parse_dotted_name()
2351 if kind == "rsl":
2352 declare_package = True
2353 else:
2354 # lobster-trace: LRM.Late_Package_Declarations
2355 declare_package = not self.stab.contains(pkg_name)
2357 if declare_package:
2358 # lobster-trace: LRM.Package_Declaration
2359 pkg = ast.Package(
2360 name=pkg_name,
2361 location=pkg_location,
2362 builtin_stab=self.stab,
2363 declared_late=kind == "trlc",
2364 )
2365 self.stab.register(self.mh, pkg)
2366 else:
2367 pkg = self.stab.lookup_direct(self.mh, pkg_name, pkg_location, ast.Package)
2369 pkg.set_ast_link(t_pkg)
2370 for t in pkg_tokens:
2371 pkg.set_ast_link(t)
2373 # lobster-trace: LRM.Current_Package
2374 self.cu.set_package(pkg)
2376 self.default_scope.push(self.cu.package.symbols)
2378 # Second, parse import list (but don't resolve names yet)
2379 # lobster-trace: LRM.Import_Visibility
2380 if kind != "check": 2380 ↛ exitline 2380 didn't return from function 'parse_preamble' because the condition on line 2380 was always true
2381 while self.peek_kw("import"):
2382 self.match_kw("import")
2383 t_import_kw = self.ct
2384 imp_name, imp_location, imp_tokens, imp_wildcard = (
2385 self.parse_import_name()
2386 )
2387 pkg.set_ast_link(t_import_kw)
2388 self.cu.add_import(
2389 self.mh, imp_name, imp_location, imp_wildcard, imp_tokens
2390 )
2392 def parse_rsl_file(self):
2393 # lobster-trace: LRM.RSL_File
2394 assert self.cu.package is not None
2396 ok = True
2397 while not self.peek_eof():
2398 try:
2399 if self.peek_kw("checks"):
2400 self.cu.add_item(self.parse_check_block())
2401 else:
2402 self.cu.add_item(self.parse_type_declaration())
2403 except TRLC_Error as err:
2404 if not self.error_recovery or err.kind == "lex error":
2405 raise
2407 ok = False
2409 # Recovery strategy is to scan until we get the next
2410 # relevant keyword
2411 self.skip_until_newline()
2412 while not self.peek_eof():
2413 if (
2414 self.peek_kw("checks")
2415 or self.peek_kw("type")
2416 or self.peek_kw("abstract")
2417 or self.peek_kw("final")
2418 or self.peek_kw("tuple")
2419 or self.peek_kw("enum")
2420 ):
2421 break
2422 self.advance()
2423 self.skip_until_newline()
2425 self.match_eof()
2427 for tok in self.lexer.tokens:
2428 if tok.kind == "COMMENT":
2429 self.cu.package.set_ast_link(tok)
2431 return ok
2433 def parse_trlc_file(self):
2434 # lobster-trace: LRM.TRLC_File
2435 assert self.cu.package is not None
2437 ok = True
2439 while self.peek_kw("section") or self.peek("IDENTIFIER"):
2440 try:
2441 self.parse_trlc_entry()
2442 except TRLC_Error as err:
2443 if not self.error_recovery or err.kind == "lex error":
2444 raise
2446 ok = False
2448 # Recovery strategy is to keep going until we find an
2449 # identifier that is a package or type, or section, or
2450 # EOF
2451 self.skip_until_newline()
2452 while not self.peek_eof():
2453 if self.peek_kw("section"): 2453 ↛ 2454line 2453 didn't jump to line 2454 because the condition on line 2453 was never true
2454 break
2455 elif not self.peek("IDENTIFIER"):
2456 pass
2457 elif self.stab.contains(self.nt.value): 2457 ↛ 2458line 2457 didn't jump to line 2458 because the condition on line 2457 was never true
2458 n_sym = self.stab.lookup_assuming(self.mh, self.nt.value)
2459 if isinstance(n_sym, ast.Package):
2460 break
2461 elif self.cu.package.symbols.contains(self.nt.value):
2462 n_sym = self.cu.package.symbols.lookup_assuming(
2463 self.mh, self.nt.value
2464 )
2465 if isinstance(n_sym, ast.Record_Type):
2466 break
2467 self.advance()
2468 self.skip_until_newline()
2470 self.match_eof()
2472 for tok in self.lexer.tokens:
2473 if tok.kind == "COMMENT":
2474 self.cu.package.set_ast_link(tok)
2476 return ok