Coverage for trlc/ast.py: 91%
1394 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) 2024-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/>.
22from abc import ABCMeta, abstractmethod
23import re
25from copy import copy
26from difflib import get_close_matches
27from enum import Enum, auto
28from collections import OrderedDict
29from fractions import Fraction
31from trlc.errors import TRLC_Error, Kind, Location, Message_Handler
32from trlc.lexer import Token
33from trlc import math
35#
36# This module defines the AST and related object for the TRLC
37# reference implementation. There are four sections:
38#
39# - Valuations deal with concrete values for record objects
40# - AST expressions deal with the syntax tree
41# - AST entities deal with concrete objects that have been declared
42# - Symbol_Table and scope deals with name resolution
43#
46##############################################################################
47# Valuations
48##############################################################################
51class Value:
52 # lobster-trace: LRM.Boolean_Values
53 # lobster-trace: LRM.Integer_Values
54 # lobster-trace: LRM.Decimal_Values
55 # lobster-trace: LRM.String_Values
56 # lobster-trace: LRM.Markup_String_Values
57 """Polymorphic value for evaluating expressions.
59 Any record references will be fully resolved.
61 :attribute location: source location this value comes from
62 :type: Location
64 :attribute value: the value or None (for null values)
65 :type: str, int, bool, fractions.Fraction, list[Value], \
66 Record_Reference, Enumeration_Literal_Spec
68 :attribute typ: type of the value (or None for null values)
69 :type: Type
70 """
72 def __init__(self, location, value, typ):
73 assert isinstance(location, Location)
74 assert value is None or isinstance(
75 value,
76 (
77 str,
78 int,
79 bool,
80 list, # for arrays
81 dict, # for tuples
82 Fraction,
83 Record_Reference,
84 Enumeration_Literal_Spec,
85 ),
86 )
87 assert typ is None or isinstance(typ, Type)
88 assert (typ is None) == (value is None)
90 self.location = location
91 self.value = value
92 self.typ = typ
94 def __eq__(self, other):
95 return self.typ == other.typ and self.value == other.value
97 def __repr__(self): # pragma: no cover
98 return "Value(%s)" % self.value
100 def resolve_references(self, mh):
101 assert isinstance(mh, Message_Handler)
103 if isinstance(self.value, Record_Reference):
104 self.value.resolve(mh)
107##############################################################################
108# AST Nodes
109##############################################################################
112class Node(metaclass=ABCMeta):
113 """Base class for all AST items.
115 :attribute location: source location
116 :type: Location
117 """
119 def __init__(self, location):
120 # lobster-exclude: Constructor only declares variables
121 assert isinstance(location, Location)
122 self.location = location
124 def set_ast_link(self, tok):
125 assert isinstance(tok, Token)
126 tok.ast_link = self
128 def write_indent(self, indent, message): # pragma: no cover
129 # lobster-exclude: Debugging feature
130 assert isinstance(indent, int)
131 assert indent >= 0
132 assert isinstance(message, str)
133 print(" " * (3 * indent) + message)
135 @abstractmethod
136 def dump(self, indent=0): # pragma: no cover
137 """Visualise the parse tree.
139 This can be called for any :class:`Node` or
140 :class:`Symbol_Table`, and can be very helpful for debugging
141 or understanding the parse tree. The dump method will produce
142 output like this::
144 Symbol_Table
145 Builtin_Boolean
146 Builtin_Integer
147 Builtin_Decimal
148 Builtin_String
149 Builtin_Markup_String
150 Package bar
151 Symbol_Table
152 Record_Type MyType
153 Composite_Component name
154 Optional: False
155 Type: String
156 Checks
157 Error 'description is too short'
158 Anchor: description
159 Binary Binary_Operator.COMP_GT Expression
160 Type: Boolean
161 Unary Unary_Operator.STRING_LENGTH Expression
162 Type: Integer
163 Name Reference to description
164 Integer Literal 10
165 Package instances
166 Symbol_Table
167 Record_Object SomeThing
168 Type: MyType
169 Field description: "Potato"
170 Builtin_Function endswith
171 Builtin_Function len
172 Builtin_Function matches
173 Builtin_Function startswith
174 Builtin_Function oneof
176 """
177 assert isinstance(indent, int) and indent >= 0
178 assert False, f"dump not implemented for {self.__class__.__name__}"
179 # lobster-exclude: Debugging feature
182class Check_Block(Node):
183 """Node representing check blocks
185 Semantically this has no meaning, but it's nice to have some kind
186 of similar representation to how it's in the file.
188 :attribute n_typ: composite type for which the checks apply
189 :type: Composite_Type
191 :attribute checks: list of checks
192 :type: list[Check]
194 """
196 def __init__(self, location, n_typ):
197 # lobster-trace: LRM.Check_Block
198 super().__init__(location)
199 assert isinstance(n_typ, Composite_Type)
200 self.n_typ = n_typ
201 self.checks = []
203 def add_check(self, n_check):
204 # lobster-trace: LRM.Check_Evaluation_Order
205 assert isinstance(n_check, Check)
206 self.checks.append(n_check)
208 def dump(self, indent=0): # pragma: no cover
209 # lobster-exclude: Debugging feature
210 self.write_indent(indent, "Check_Block")
211 self.write_indent(indent + 1, f"Type: {self.n_typ.name}")
212 for n_check in self.checks:
213 n_check.dump(indent + 1)
216class Compilation_Unit(Node):
217 """Special node to represent the concrete file structure
219 :attribute package: the main package this file declares or contributes to
220 :type: Package
222 :attribute imports: packages explicitly imported by this file
223 :type: set[Package]
225 :attribute wildcard_roots: roots of wildcard imports (``import foo.*``)
226 :type: set[Package]
228 :attribute raw_imports: unresolved imports as (name, location, \
229 is_wildcard, tokens)
230 :type: list[tuple[str, Location, bool, list[Token]]]
232 :attribute referenced_imports: imports actually used in this file
233 :type: set[Package]
235 :attribute items: list of
236 :type: list[Node]
238 """
240 def __init__(self, file_name):
241 # lobster-exclude: Constructor only declares variables
242 super().__init__(Location(file_name))
243 self.package = None
244 # Both default to empty sets (rather than None) so is_visible()
245 # behaves consistently even if called before resolve_imports()
246 # has run (e.g. only self-visibility is granted at that point).
247 self.imports = set()
248 self.wildcard_roots = set()
249 # list of (name : str, location : Location, is_wildcard : bool,
250 # tokens : list[Token])
251 self.raw_imports = []
252 self.referenced_imports = set()
253 self.items = []
255 def dump(self, indent=0): # pragma: no cover
256 # lobster-exclude: Debugging feature
257 self.write_indent(indent, f"Compilation_Unit ({self.location.file_name})")
258 for name, _location, is_wildcard, _tokens in self.raw_imports:
259 suffix = ".*" if is_wildcard else ""
260 self.write_indent(indent + 1, f"Import: {name}{suffix}")
261 for n_item in self.items:
262 n_item.dump(indent + 1)
264 def set_package(self, pkg):
265 # lobster-trace: LRM.Current_Package
266 assert isinstance(pkg, Package)
267 self.package = pkg
269 def add_import(self, mh, name, location, is_wildcard=False, tokens=None):
270 # lobster-trace: LRM.Import_Visibility
271 # lobster-trace: LRM.Self_Imports
272 # lobster-trace: LRM.Wildcard_Import
273 # lobster-trace: LRM.Wildcard_Self_Cover
274 assert isinstance(mh, Message_Handler)
275 assert isinstance(name, str)
276 assert isinstance(location, Location)
277 assert isinstance(is_wildcard, bool)
278 assert tokens is None or isinstance(tokens, list)
279 if tokens is None: 279 ↛ 280line 279 didn't jump to line 280 because the condition on line 279 was never true
280 tokens = []
282 # An explicit self-import is an error. A wildcard whose root
283 # covers the current package is permitted: the current package
284 # stays implicitly visible (Wildcard_Self_Cover).
285 if name == self.package.name and not is_wildcard:
286 mh.error(
287 location,
288 "package %s cannot import itself" % self.package.name,
289 explanation="a package always has access to its own "
290 "types and objects; remove this import statement",
291 )
293 # Skip duplicates (same name and same wildcard flavour)
294 for prev_name, _prev_location, prev_wildcard, _prev_tokens in self.raw_imports:
295 if prev_name == name and prev_wildcard == is_wildcard:
296 mh.warning(
297 location,
298 "duplicate import of package %s%s"
299 % (name, ".*" if is_wildcard else ""),
300 explanation="remove this redundant import "
301 "statement, the package is already imported",
302 )
303 return
305 self.raw_imports.append((name, location, is_wildcard, tokens))
307 def resolve_imports(self, mh, stab):
308 # lobster-trace: LRM.Import_Visibility
309 # lobster-trace: LRM.Wildcard_Import
310 assert isinstance(mh, Message_Handler)
311 assert isinstance(stab, Symbol_Table)
312 self.imports = set()
313 self.wildcard_roots = set()
314 for name, location, is_wildcard, tokens in self.raw_imports:
315 # We can ignore errors here, because that just means we
316 # generate more error later.
317 try:
318 a_import = stab.lookup_direct(mh, name, location, Package)
319 except TRLC_Error:
320 continue
321 # Link the import clause's tokens to the resolved package,
322 # so tooling (e.g. go-to-definition) can navigate to it.
323 for token in tokens:
324 a_import.set_ast_link(token)
325 if is_wildcard:
326 self.wildcard_roots.add(a_import)
327 else:
328 self.imports.add(a_import)
330 def covered_by_wildcard(self, pkg):
331 # lobster-trace: LRM.Wildcard_Import
332 # A package is covered by a wildcard root if it is the root
333 # itself or any descendant of it.
334 assert isinstance(pkg, Package)
335 for root in self.wildcard_roots:
336 if pkg == root or pkg.name.startswith(root.name + "."): 336 ↛ 335line 336 didn't jump to line 335 because the condition on line 336 was always true
337 return root
338 return None
340 def mark_import_used(self, pkg):
341 """Record that a package was actually referenced in this file.
343 Called during qualified-name resolution so the lint pass can
344 detect unused imports. If the package is visible through a
345 wildcard import, the wildcard root is marked used as well. A
346 reference to the current package itself never counts as using a
347 wildcard import, even if the wildcard's root covers the current
348 package (see LRM.Wildcard_Self_Cover): the current package is
349 always implicitly visible, not "imported" by the wildcard.
351 :param pkg: the package that was used
352 :type pkg: Package
353 """
354 assert isinstance(pkg, Package)
355 self.referenced_imports.add(pkg)
356 if pkg is self.package:
357 return
358 root = self.covered_by_wildcard(pkg)
359 if root is not None:
360 self.referenced_imports.add(root)
362 def is_visible(self, n_pkg):
363 # lobster-trace: LRM.Import_Visibility
364 # lobster-trace: LRM.Wildcard_Import
365 # lobster-trace: LRM.Nested_Visibility
366 assert isinstance(n_pkg, Package)
367 if n_pkg == self.package or n_pkg in self.imports:
368 return True
369 return self.covered_by_wildcard(n_pkg) is not None
371 def add_item(self, node):
372 # lobster-trace: LRM.RSL_File
373 # lobster-trace: LRM.TRLC_File
374 assert isinstance(node, (Concrete_Type, Check_Block, Record_Object)), (
375 "trying to add %s to a compilation unit" % node.__class__.__name__
376 )
377 self.items.append(node)
380class Check(Node):
381 """User defined check
383 This represent a single user-defined check inside a check block::
385 checks T {
386 a /= null implies a > 5, warning "potato", a
387 ^^^^^^^^^^^^^^^^^^^^^^^1 ^2 ^3 ^4
389 :attribute n_type: The tuple/record type this check applies to
390 :type: Composite_Type
392 :attribute n_expr: The boolean expression for the check (see 1)
393 :type: Expression
395 :attribute n_anchor: The (optional) record component where the message \
396 should be issued (or None) (see 4)
397 :type: Composite_Component
399 :attribute severity: warning, error, or fatal (see 2; also if this is \
400 not specified the default is 'error')
401 :type: str
403 :attribute message: the user-supplied message (see 3)
404 :type: str
405 """
407 def __init__(self, n_type, n_expr, n_anchor, severity, t_message, extrainfo):
408 # lobster-trace: LRM.Check_Block
409 assert isinstance(n_type, Composite_Type)
410 assert isinstance(n_expr, Expression)
411 assert isinstance(n_anchor, Composite_Component) or n_anchor is None
412 assert severity in ("warning", "error", "fatal")
413 assert isinstance(t_message, Token)
414 assert t_message.kind == "STRING"
415 assert isinstance(extrainfo, str) or extrainfo is None
416 super().__init__(t_message.location)
418 self.n_type = n_type
419 self.n_expr = n_expr
420 self.n_anchor = n_anchor
421 self.severity = severity
422 # lobster-trace: LRM.No_Newlines_In_Message
423 # This is the error recovery strategy if we find newlines in
424 # the short error messages: we just remove them. The error
425 # raised is non-fatal.
426 self.message = t_message.value.replace("\n", " ")
427 self.extrainfo = extrainfo
428 self._uses_field_access = None
430 @property
431 def uses_field_access(self):
432 """Cached test: does this check's expression follow a record/union
433 reference?
435 Returns True if any sub-expression of the check expression is a
436 :class:`Field_Access_Expression` whose prefix has a
437 :class:`Record_Type` or :class:`Union_Type` type. Used by
438 the VCG to split checks into Phase A ("at declaration") and
439 Phase B ("after references").
441 :return: whether this check dereferences a record/union reference
442 :rtype: bool
444 """
445 if self._uses_field_access is None:
446 self._uses_field_access = self.n_expr.uses_field_access()
447 return self._uses_field_access
449 def dump(self, indent=0): # pragma: no cover
450 # lobster-exclude: Debugging feature
451 if self.severity == "warning":
452 self.write_indent(indent, f"Warning '{self.message}'")
453 elif self.severity == "error":
454 self.write_indent(indent, f"Error '{self.message}'")
455 else:
456 self.write_indent(indent, f"Fatal error '{self.message}'")
457 if self.n_anchor:
458 self.write_indent(indent + 1, f"Anchor: {self.n_anchor.name}")
459 self.n_expr.dump(indent + 1)
461 def get_real_location(self, composite_object):
462 # lobster-exclude: LRM.Anchoring
463 assert isinstance(composite_object, (Record_Object, Tuple_Aggregate))
464 if isinstance(composite_object, Record_Object):
465 fields = composite_object.field
466 else:
467 fields = composite_object.value
469 if self.n_anchor is None or fields[self.n_anchor.name] is None:
470 return composite_object.location
471 else:
472 return fields[self.n_anchor.name].location
474 def perform(self, mh, composite_object, gstab):
475 # lobster-trace: LRM.Check_Messages
476 # lobster-trace: LRM.Check_Severity
477 assert isinstance(mh, Message_Handler)
478 assert isinstance(composite_object, (Record_Object, Tuple_Aggregate))
479 assert isinstance(gstab, Symbol_Table)
481 if isinstance(composite_object, Record_Object):
482 result = self.n_expr.evaluate(mh, copy(composite_object.field), gstab)
483 else:
484 result = self.n_expr.evaluate(mh, copy(composite_object.value), gstab)
485 if result.value is None:
486 loc = self.get_real_location(composite_object)
487 mh.error(
488 loc,
489 "check %s (%s) evaluates to null"
490 % (self.n_expr.to_string(), mh.cross_file_reference(self.location)),
491 )
493 assert isinstance(result.value, bool)
495 if not result.value:
496 loc = self.get_real_location(composite_object)
497 if self.severity == "warning":
498 mh.warning(
499 location=loc,
500 message=self.message,
501 explanation=self.extrainfo,
502 user=True,
503 )
504 else:
505 mh.error(
506 location=loc,
507 message=self.message,
508 explanation=self.extrainfo,
509 fatal=self.severity == "fatal",
510 user=True,
511 )
512 return False
514 return True
517##############################################################################
518# AST Nodes (Expressions)
519##############################################################################
522class Unary_Operator(Enum):
523 # lobster-exclude: Utility enumeration for unary operators
524 MINUS = auto()
525 PLUS = auto()
526 LOGICAL_NOT = auto()
527 ABSOLUTE_VALUE = auto()
529 STRING_LENGTH = auto()
530 ARRAY_LENGTH = auto()
532 CONVERSION_TO_INT = auto()
533 CONVERSION_TO_DECIMAL = auto()
536class Binary_Operator(Enum):
537 # lobster-exclude: Utility enumeration for binary operators
538 LOGICAL_AND = auto() # Short-circuit
539 LOGICAL_OR = auto() # Short-circuit
540 LOGICAL_XOR = auto()
541 LOGICAL_IMPLIES = auto() # Short-circuit
543 COMP_EQ = auto()
544 COMP_NEQ = auto()
545 COMP_LT = auto()
546 COMP_LEQ = auto()
547 COMP_GT = auto()
548 COMP_GEQ = auto()
550 STRING_CONTAINS = auto()
551 STRING_STARTSWITH = auto()
552 STRING_ENDSWITH = auto()
553 STRING_REGEX = auto()
555 ARRAY_CONTAINS = auto()
557 PLUS = auto()
558 MINUS = auto()
559 TIMES = auto()
560 DIVIDE = auto()
561 REMAINDER = auto()
563 POWER = auto()
565 INDEX = auto()
568class Expression(Node, metaclass=ABCMeta):
569 """Abstract base class for all expressions.
571 :attribute typ: The type of this expression (or None for null values)
572 :type: Type
573 """
575 def __init__(self, location, typ):
576 # lobster-exclude: Constructor only declares variables
577 super().__init__(location)
578 assert typ is None or isinstance(typ, Type)
579 self.typ = typ
581 def evaluate(self, mh, context, gstab): # pragma: no cover
582 """Evaluate the expression in the given context
584 The context can be None, in which case the expression is
585 evaluated in a static context. Otherwise it must be a
586 dictionary that maps names (such as record fields or
587 quantified variables) to expressions.
589 The global symbol table must be None (for static context
590 evaluations), otherwise it must contain the global symbol
591 table to resolve record references.
593 :param mh: the message handler to use
594 :type mh: Message_Handler
595 :param context: name mapping or None (for a static context)
596 :type context: dict[str, Expression]
597 :raise TRLC_Error: if the expression cannot be evaluated
598 :return: result of the evaluation
599 :rtype: Value
601 """
602 assert isinstance(mh, Message_Handler)
603 assert context is None or isinstance(context, dict)
604 assert gstab is None or isinstance(gstab, Symbol_Table)
605 assert False, "evaluate not implemented for %s" % self.__class__.__name__
607 @abstractmethod
608 def to_string(self): # pragma: no cover
609 assert False, "to_string not implemented for %s" % self.__class__.__name__
611 def ensure_type(self, mh, typ):
612 # lobster-trace: LRM.Restricted_Null
613 # lobster-trace: LRM.Null_Is_Invalid
615 assert isinstance(typ, (type, Type))
616 if self.typ is None:
617 mh.error(self.location, "null is not permitted here")
618 elif isinstance(typ, type) and not isinstance(self.typ, typ):
619 mh.error(
620 self.location,
621 "expected expression of type %s, got %s instead"
622 % (typ.__name__, self.typ.__class__.__name__),
623 )
624 elif isinstance(typ, Type) and self.typ != typ:
625 mh.error(
626 self.location,
627 "expected expression of type %s, got %s instead"
628 % (typ.name, self.typ.name),
629 )
631 def resolve_references(self, mh):
632 assert isinstance(mh, Message_Handler)
634 @abstractmethod
635 def can_be_null(self):
636 """Test if the expression could return null
638 Checks the expression if it could generate a null value
639 *without* raising an error. For example `x` could generate a
640 null value if `x` is a record component that is
641 optional. However `x + 1` could not, since an error would
642 occur earlier.
644 :return: possibility of encountering null
645 :rtype: bool
647 """
648 assert False, "can_be_null not implemented for %s" % self.__class__.__name__
650 def uses_field_access(self):
651 """Test if this expression contains a field access on a record or
652 union reference.
654 Returns True if any sub-expression is a
655 :class:`Field_Access_Expression` whose prefix has a
656 :class:`Record_Type` or :class:`Union_Type` type. This is
657 used by the VCG to split checks into "at declaration"
658 (Phase A) and "after references" (Phase B).
660 :return: whether this expression follows a record/union reference
661 :rtype: bool
663 """
664 return False
667class Implicit_Null(Expression):
668 """Synthesised null values
670 When a record object or tuple aggregate is declared and an
671 optional component or field is not specified, we synthesise an
672 implicit null expression for this.
674 For example given this TRLC type::
676 type T {
677 x optional Integer
678 }
680 And this declaration::
682 T Potato {}
684 Then the field mapping for Potato will be::
686 {x: Implicit_Null}
688 Each field will get its own implicit null. Further note that this
689 implicit null is distinct from the explicit :class:`Null_Literal`
690 that can appear in check expressions.
692 """
694 def __init__(self, composite_object, composite_component):
695 # lobster-trace: LRM.Unspecified_Optional_Components
696 assert isinstance(composite_object, (Record_Object, Tuple_Aggregate))
697 assert isinstance(composite_component, Composite_Component)
698 super().__init__(composite_object.location, None)
700 def to_string(self):
701 return "null"
703 def evaluate(self, mh, context, gstab):
704 # lobster-trace: LRM.Unspecified_Optional_Components
705 assert isinstance(mh, Message_Handler)
706 assert context is None or isinstance(context, dict)
707 assert gstab is None or isinstance(gstab, Symbol_Table)
708 return Value(self.location, None, None)
710 def to_python_object(self):
711 return None
713 def dump(self, indent=0): # pragma: no cover
714 # lobster-exclude: Debugging feature
715 self.write_indent(indent, "Implicit_Null")
717 def can_be_null(self):
718 return True
721class Literal(Expression, metaclass=ABCMeta):
722 """Abstract base for all Literals
724 Does not offer any additional features, but it's a nice way to
725 group together all literal types. This is useful if you want to
726 check if you are dealing with a literal::
728 isinstance(my_expression, Literal)
730 """
732 @abstractmethod
733 def to_python_object(self):
734 assert False
737class Null_Literal(Literal):
738 # lobster-trace: LRM.Primary
739 """The null literal
741 This can appear in check expressions::
743 a /= null implies a > 5
744 ^^^^
746 Please note that this is distinct from the :class:`Implicit_Null`
747 values that appear in record objects.
749 """
751 def __init__(self, token):
752 assert isinstance(token, Token)
753 assert token.kind == "KEYWORD"
754 assert token.value == "null"
755 super().__init__(token.location, None)
757 def dump(self, indent=0): # pragma: no cover
758 self.write_indent(indent, "Null Literal")
760 def to_string(self):
761 return "null"
763 def evaluate(self, mh, context, gstab):
764 assert isinstance(mh, Message_Handler)
765 assert context is None or isinstance(context, dict)
766 assert gstab is None or isinstance(gstab, Symbol_Table)
767 return Value(self.location, None, None)
769 def to_python_object(self):
770 return None
772 def can_be_null(self):
773 return True
776class Integer_Literal(Literal):
777 # lobster-trace: LRM.Integer_Values
778 # lobster-trace: LRM.Primary
779 """Integer literals
781 Note that these are always positive. A negative integer is
782 actually a unary negation expression, operating on a positive
783 integer literal::
785 x == -5
787 This would create the following tree::
789 OP_EQUALITY
790 NAME_REFERENCE x
791 UNARY_EXPRESSION -
792 INTEGER_LITERAL 5
794 :attribute value: the non-negative integer value
795 :type: int
796 """
798 def __init__(self, token, typ):
799 assert isinstance(token, Token)
800 assert token.kind == "INTEGER"
801 assert isinstance(typ, Builtin_Integer)
802 super().__init__(token.location, typ)
804 self.value = token.value
806 def dump(self, indent=0): # pragma: no cover
807 self.write_indent(indent, f"Integer Literal {self.value}")
809 def to_string(self):
810 return str(self.value)
812 def evaluate(self, mh, context, gstab):
813 assert isinstance(mh, Message_Handler)
814 assert context is None or isinstance(context, dict)
815 assert gstab is None or isinstance(gstab, Symbol_Table)
816 return Value(self.location, self.value, self.typ)
818 def to_python_object(self):
819 return self.value
821 def can_be_null(self):
822 return False
825class Decimal_Literal(Literal):
826 # lobster-trace: LRM.Decimal_Values
827 # lobster-trace: LRM.Primary
828 """Decimal literals
830 Note that these are always positive. A negative decimal is
831 actually a unary negation expression, operating on a positive
832 decimal literal::
834 x == -5.0
836 This would create the following tree::
838 OP_EQUALITY
839 NAME_REFERENCE x
840 UNARY_EXPRESSION -
841 DECIMAL_LITERAL 5.0
843 :attribute value: the non-negative decimal value
844 :type: fractions.Fraction
845 """
847 def __init__(self, token, typ):
848 assert isinstance(token, Token)
849 assert token.kind == "DECIMAL"
850 assert isinstance(typ, Builtin_Decimal)
851 super().__init__(token.location, typ)
853 self.value = token.value
855 def dump(self, indent=0): # pragma: no cover
856 self.write_indent(indent, f"Decimal Literal {self.value}")
858 def to_string(self):
859 return str(self.value)
861 def evaluate(self, mh, context, gstab):
862 assert isinstance(mh, Message_Handler)
863 assert context is None or isinstance(context, dict)
864 assert gstab is None or isinstance(gstab, Symbol_Table)
865 return Value(self.location, self.value, self.typ)
867 def to_python_object(self):
868 return float(self.value)
870 def can_be_null(self):
871 return False
874class String_Literal(Literal):
875 # lobster-trace: LRM.String_Values
876 # lobster-trace: LRM.Markup_String_Values
877 # lobster-trace: LRM.Primary
878 """String literals
880 Note the value of the string does not include the quotation marks,
881 and any escape sequences are fully resolved. For example::
883 "foo\\"bar"
885 Will have a value of ``foo"bar``.
887 :attribute value: string content
888 :type: str
890 :attribute references: resolved references of a markup string
891 :type: list[Record_Reference]
893 """
895 def __init__(self, token, typ):
896 assert isinstance(token, Token)
897 assert token.kind == "STRING"
898 assert isinstance(typ, Builtin_String)
899 super().__init__(token.location, typ)
901 self.value = token.value
902 self.has_references = isinstance(typ, Builtin_Markup_String)
903 self.references = []
905 def dump(self, indent=0): # pragma: no cover
906 self.write_indent(indent, f"String Literal {repr(self.value)}")
907 if self.has_references:
908 self.write_indent(indent + 1, "Markup References")
909 for ref in self.references:
910 ref.dump(indent + 2)
912 def to_string(self):
913 return self.value
915 def evaluate(self, mh, context, gstab):
916 assert isinstance(mh, Message_Handler)
917 assert context is None or isinstance(context, dict)
918 assert gstab is None or isinstance(gstab, Symbol_Table)
919 return Value(self.location, self.value, self.typ)
921 def to_python_object(self):
922 return self.value
924 def resolve_references(self, mh):
925 assert isinstance(mh, Message_Handler)
926 for ref in self.references:
927 ref.resolve_references(mh)
929 def can_be_null(self):
930 return False
933class Boolean_Literal(Literal):
934 # lobster-trace: LRM.Boolean_Values
935 # lobster-trace: LRM.Primary
936 """Boolean values
938 :attribute value: the boolean value
939 :type: bool
940 """
942 def __init__(self, token, typ):
943 assert isinstance(token, Token)
944 assert token.kind == "KEYWORD"
945 assert token.value in ("false", "true")
946 assert isinstance(typ, Builtin_Boolean)
947 super().__init__(token.location, typ)
949 self.value = token.value == "true"
951 def dump(self, indent=0): # pragma: no cover
952 self.write_indent(indent, f"Boolean Literal {self.value}")
954 def to_string(self):
955 return str(self.value)
957 def evaluate(self, mh, context, gstab):
958 assert isinstance(mh, Message_Handler)
959 assert context is None or isinstance(context, dict)
960 assert gstab is None or isinstance(gstab, Symbol_Table)
961 return Value(self.location, self.value, self.typ)
963 def to_python_object(self):
964 return self.value
966 def can_be_null(self):
967 return False
970class Enumeration_Literal(Literal):
971 """Enumeration values
973 Note that this is distinct from
974 :class:`Enumeration_Literal_Spec`. An enumeration literal is a
975 specific mention of an enumeration member in an expression::
977 foo != my_enum.POTATO
978 ^^^^^^^^^^^^^^
980 To get to the string value of the enumeration literal
981 (i.e. ``POTATO`` here) you can get the name of the literal spec
982 itself: ``enum_lit.value.name``; and to get the name of the
983 enumeration (i.e. ``my_enum`` here) you can use
984 ``enum_lit.value.n_typ.name``.
986 :attribute value: enumeration value
987 :type: Enumeration_Literal_Spec
989 """
991 def __init__(self, location, literal):
992 # lobster-exclude: Constructor only declares variables
993 assert isinstance(literal, Enumeration_Literal_Spec)
994 super().__init__(location, literal.n_typ)
996 self.value = literal
998 def dump(self, indent=0): # pragma: no cover
999 # lobster-exclude: Debugging feature
1000 self.write_indent(
1001 indent, f"Enumeration Literal {self.typ.name}.{self.value.name}"
1002 )
1004 def to_string(self):
1005 return self.typ.name + "." + self.value.name
1007 def evaluate(self, mh, context, gstab):
1008 assert isinstance(mh, Message_Handler)
1009 assert context is None or isinstance(context, dict)
1010 assert gstab is None or isinstance(gstab, Symbol_Table)
1011 return Value(self.location, self.value, self.typ)
1013 def to_python_object(self):
1014 return self.value.name
1016 def can_be_null(self):
1017 return False
1020class Array_Aggregate(Expression):
1021 """Instances of array types
1023 This is created when assigning to array components::
1025 potatoes = ["picasso", "yukon gold", "sweet"]
1026 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1028 The type of expression that can be found in an array is somewhat
1029 limited:
1031 * :class:`Literal`
1032 * :class:`Array_Aggregate`
1033 * :class:`Record_Reference`
1035 :attribute value: contents of the array
1036 :type: list[Expression]
1038 """
1040 def __init__(self, location, typ):
1041 # lobster-trace: LRM.Record_Object_Declaration
1043 super().__init__(location, typ)
1044 self.value = []
1046 def dump(self, indent=0): # pragma: no cover
1047 # lobster-exclude: Debugging feature
1048 self.write_indent(indent, "Array_Aggregate")
1049 for n_value in self.value:
1050 n_value.dump(indent + 1)
1052 def append(self, value):
1053 assert isinstance(
1054 value,
1055 (
1056 Literal,
1057 Unary_Expression,
1058 Array_Aggregate,
1059 Tuple_Aggregate,
1060 Record_Reference,
1061 ),
1062 )
1063 self.value.append(value)
1065 def to_string(self):
1066 return "[" + ", ".join(x.to_string() for x in self.value) + "]"
1068 def evaluate(self, mh, context, gstab):
1069 assert isinstance(mh, Message_Handler)
1070 assert context is None or isinstance(context, dict)
1071 assert gstab is None or isinstance(gstab, Symbol_Table)
1072 return Value(
1073 self.location,
1074 list(element.evaluate(mh, context, gstab) for element in self.value),
1075 self.typ,
1076 )
1078 def resolve_references(self, mh):
1079 assert isinstance(mh, Message_Handler)
1081 for val in self.value:
1082 val.resolve_references(mh)
1084 def to_python_object(self):
1085 return [x.to_python_object() for x in self.value]
1087 def can_be_null(self):
1088 return False
1090 def uses_field_access(self):
1091 return any(expr.uses_field_access() for expr in self.value)
1094class Tuple_Aggregate(Expression):
1095 """Instances of a tuple
1097 This is created when assigning to a tuple components. There are
1098 two forms, the ordinary form::
1100 coordinate = (12.3, 40.0)
1101 ^^^^^^^^^^^^
1103 And the separator form::
1105 item = 12345@42
1106 ^^^^^^^^
1108 In terms of AST there is no difference, as the separator is only
1109 syntactic sugar.
1111 :attribute value: contents of the tuple
1112 :type: dict[str, Expression]
1114 """
1116 def __init__(self, location, typ):
1117 # lobster-trace: LRM.Unspecified_Optional_Components
1118 # lobster-trace: LRM.Record_Object_Declaration
1120 super().__init__(location, typ)
1121 self.value = {
1122 n_field.name: Implicit_Null(self, n_field)
1123 for n_field in self.typ.components.values()
1124 }
1126 def assign(self, field, value):
1127 assert isinstance(field, str)
1128 assert isinstance(
1129 value, (Literal, Unary_Expression, Tuple_Aggregate, Record_Reference)
1130 ), "value is %s" % value.__class__.__name__
1131 assert field in self.typ.components
1133 self.value[field] = value
1135 def dump(self, indent=0): # pragma: no cover
1136 # lobster-exclude: Debugging feature
1137 self.write_indent(indent, "Tuple_Aggregate")
1138 self.write_indent(indent + 1, f"Type: {self.typ.name}")
1139 for n_item in self.typ.iter_sequence():
1140 if isinstance(n_item, Composite_Component):
1141 self.value[n_item.name].dump(indent + 1)
1143 def to_string(self):
1144 first = True
1145 if self.typ.has_separators():
1146 rv = ""
1147 else:
1148 rv = "("
1149 for n_item in self.typ.iter_sequence():
1150 if isinstance(n_item, Separator):
1151 rv += " %s " % n_item.token.value
1152 elif first:
1153 first = False
1154 else:
1155 rv += ", "
1157 if isinstance(n_item, Composite_Component):
1158 rv += self.value[n_item.name].to_string()
1159 if self.typ.has_separators():
1160 rv = ""
1161 else:
1162 rv = ")"
1163 return rv
1165 def evaluate(self, mh, context, gstab):
1166 assert isinstance(mh, Message_Handler)
1167 assert context is None or isinstance(context, dict)
1168 assert gstab is None or isinstance(gstab, Symbol_Table)
1169 return Value(
1170 self.location,
1171 {
1172 name: element.evaluate(mh, context, gstab)
1173 for name, element in self.value.items()
1174 },
1175 self.typ,
1176 )
1178 def resolve_references(self, mh):
1179 assert isinstance(mh, Message_Handler)
1181 for val in self.value.values():
1182 val.resolve_references(mh)
1184 def to_python_object(self):
1185 return {name: value.to_python_object() for name, value in self.value.items()}
1187 def can_be_null(self):
1188 return False
1190 def uses_field_access(self):
1191 return any(expr.uses_field_access() for expr in self.value.values())
1194class Record_Reference(Expression):
1195 """Reference to another record object
1197 This can appear in record object declarations::
1199 Requirement Kitten {
1200 depends_on = Other_Package.Cat
1201 ^1 ^2
1202 }
1204 Note that this is distinct from :class:`Record_Object`. It is just
1205 the name; to get to the object referred to by this you can consult
1206 the target attribute.
1208 The reason we have this indirection is that not all names can be
1209 immediately resolved on parsing in the TRLC language.
1211 Note that while the containing package (see 1) is optional in the
1212 source language, the containing package will always be filled in
1213 in this AST node.
1215 :attribute name: The name of the record (see 2)
1216 :type: str
1218 :attribute target: The concrete record object referred to by (2)
1219 :type: Record_Object
1221 :attribute package: The package (see 1) supposed to contain (2)
1222 :type: Package
1224 """
1226 def __init__(self, location, name, typ, package):
1227 # lobster-exclude: Constructor only declares variables
1228 assert isinstance(location, Location)
1229 assert isinstance(name, str)
1230 assert isinstance(typ, (Record_Type, Union_Type)) or typ is None
1231 assert isinstance(package, Package)
1232 super().__init__(location, typ)
1234 self.name = name
1235 self.target = None
1236 self.package = package
1238 def dump(self, indent=0): # pragma: no cover
1239 # lobster-exclude: Debugging feature
1240 self.write_indent(indent, f"Record Reference {self.name}")
1241 self.write_indent(indent + 1, f"Resolved: {self.target is not None}")
1243 def to_string(self):
1244 return self.name
1246 def evaluate(self, mh, context, gstab):
1247 assert isinstance(mh, Message_Handler)
1248 assert context is None or isinstance(context, dict)
1249 assert gstab is None or isinstance(gstab, Symbol_Table)
1250 return Value(self.location, copy(self.target.field), self.typ)
1252 def resolve_references(self, mh):
1253 # lobster-trace: LRM.References_To_Extensions
1254 # lobster-trace: LRM.Union_Type_Minimum_Members
1255 assert isinstance(mh, Message_Handler)
1257 self.target = self.package.symbols.lookup_direct(
1258 mh=mh,
1259 name=self.name,
1260 error_location=self.location,
1261 required_subclass=Record_Object,
1262 )
1263 if self.typ is None:
1264 self.typ = self.target.n_typ
1265 elif isinstance(self.typ, Union_Type):
1266 if not self.typ.is_compatible(self.target.n_typ):
1267 mh.error(
1268 self.location,
1269 "expected reference of type %s,"
1270 " but %s is of type %s"
1271 % (self.typ.name, self.target.name, self.target.n_typ.name),
1272 )
1273 elif not self.target.n_typ.is_subclass_of(self.typ):
1274 mh.error(
1275 self.location,
1276 "expected reference of type %s, but %s is of type %s"
1277 % (self.typ.name, self.target.name, self.target.n_typ.name),
1278 )
1280 def to_python_object(self):
1281 return self.target.fully_qualified_name()
1283 def can_be_null(self):
1284 return False
1287class Name_Reference(Expression):
1288 # lobster-trace: LRM.Qualified_Name
1289 # lobster-trace: LRM.Static_Regular_Expression
1291 """Reference to a name
1293 Name reference to either a :class:`Composite_Component` or a
1294 :class:`Quantified_Variable`. The actual value of course depends
1295 on the context. See :py:meth:`Expression.evaluate()`.
1297 For example::
1299 (forall x in potato => x > 1)
1300 ^1 ^2
1302 Both indicated parts are a :class:`Name_Reference`, the first one
1303 refers to a :class:`Composite_Component`, and the second refers to a
1304 :class:`Quantified_Variable`.
1306 :attribute entity: the entity named here
1307 :type: Composite_Component, Quantified_Variable
1308 """
1310 def __init__(self, location, entity):
1311 assert isinstance(entity, (Composite_Component, Quantified_Variable))
1312 super().__init__(location, entity.n_typ)
1313 self.entity = entity
1315 def dump(self, indent=0): # pragma: no cover
1316 self.write_indent(indent, f"Name Reference to {self.entity.name}")
1318 def to_string(self):
1319 return self.entity.name
1321 def evaluate(self, mh, context, gstab):
1322 assert isinstance(mh, Message_Handler)
1323 assert context is None or isinstance(context, dict)
1324 assert gstab is None or isinstance(gstab, Symbol_Table)
1326 if context is None:
1327 mh.error(self.location, "cannot be used in a static context")
1329 assert self.entity.name in context
1330 return context[self.entity.name].evaluate(mh, context, gstab)
1332 def can_be_null(self):
1333 # The only way we could generate null here (without raising
1334 # error earlier) is when we refer to a component that is
1335 # optional.
1336 if isinstance(self.entity, Composite_Component):
1337 return self.entity.optional
1338 else:
1339 return False
1342class Unary_Expression(Expression):
1343 """Expression with only one operand
1345 This captures the following operations:
1347 * Unary_Operator.PLUS (e.g. ``+5``)
1348 * Unary_Operator.MINUS (e.g. ``-5``)
1349 * Unary_Operator.ABSOLUTE_VALUE (e.g. ``abs 42``)
1350 * Unary_Operator.LOGICAL_NOT (e.g. ``not True``)
1351 * Unary_Operator.STRING_LENGTH (e.g. ``len("foobar")``)
1352 * Unary_Operator.ARRAY_LENGTH (e.g. ``len(component_name)``)
1353 * Unary_Operator.CONVERSION_TO_INT (e.g. ``Integer(5.3)``)
1354 * Unary_Operator.CONVERSION_TO_DECIMAL (e.g. ``Decimal(5)``)
1356 Note that several builtin functions are mapped to unary operators.
1358 :attribute operator: the operation
1359 :type: Unary_Operator
1361 :attribute n_operand: the expression we operate on
1362 :type: Expression
1364 """
1366 def __init__(self, mh, location, typ, operator, n_operand):
1367 # lobster-trace: LRM.Simple_Expression
1368 # lobster-trace: LRM.Relation
1369 # lobster-trace: LRM.Factor
1370 # lobster-trace: LRM.Signature_Len
1371 # lobster-trace: LRM.Signature_Type_Conversion
1373 super().__init__(location, typ)
1374 assert isinstance(mh, Message_Handler)
1375 assert isinstance(operator, Unary_Operator)
1376 assert isinstance(n_operand, Expression)
1377 self.operator = operator
1378 self.n_operand = n_operand
1380 if operator in (
1381 Unary_Operator.MINUS,
1382 Unary_Operator.PLUS,
1383 Unary_Operator.ABSOLUTE_VALUE,
1384 ):
1385 self.n_operand.ensure_type(mh, Builtin_Numeric_Type)
1386 elif operator == Unary_Operator.LOGICAL_NOT:
1387 self.n_operand.ensure_type(mh, Builtin_Boolean)
1388 elif operator == Unary_Operator.STRING_LENGTH:
1389 self.n_operand.ensure_type(mh, Builtin_String)
1390 elif operator == Unary_Operator.ARRAY_LENGTH:
1391 self.n_operand.ensure_type(mh, Array_Type)
1392 elif operator == Unary_Operator.CONVERSION_TO_INT:
1393 self.n_operand.ensure_type(mh, Builtin_Numeric_Type)
1394 elif operator == Unary_Operator.CONVERSION_TO_DECIMAL:
1395 self.n_operand.ensure_type(mh, Builtin_Numeric_Type)
1396 else:
1397 mh.ice_loc(self.location, "unexpected unary operation %s" % operator)
1399 def to_string(self):
1400 prefix_operators = {
1401 Unary_Operator.MINUS: "-",
1402 Unary_Operator.PLUS: "+",
1403 Unary_Operator.ABSOLUTE_VALUE: "abs ",
1404 Unary_Operator.LOGICAL_NOT: "not ",
1405 }
1406 function_calls = {
1407 Unary_Operator.STRING_LENGTH: "len",
1408 Unary_Operator.ARRAY_LENGTH: "len",
1409 Unary_Operator.CONVERSION_TO_INT: "Integer",
1410 Unary_Operator.CONVERSION_TO_DECIMAL: "Decimal",
1411 }
1413 if self.operator in prefix_operators:
1414 return prefix_operators[self.operator] + self.n_operand.to_string()
1416 elif self.operator in function_calls:
1417 return "%s(%s)" % (
1418 function_calls[self.operator],
1419 self.n_operand.to_string(),
1420 )
1422 else:
1423 assert False
1425 def dump(self, indent=0): # pragma: no cover
1426 # lobster-exclude: Debugging feature
1427 self.write_indent(indent, f"Unary {self.operator} Expression")
1428 self.write_indent(indent + 1, f"Type: {self.typ.name}")
1429 self.n_operand.dump(indent + 1)
1431 def evaluate(self, mh, context, gstab):
1432 # lobster-trace: LRM.Null_Is_Invalid
1433 # lobster-trace: LRM.Signature_Len
1434 # lobster-trace: LRM.Signature_Type_Conversion
1435 # lobster-trace: LRM.Len_Semantics
1436 # lobster-trace: LRM.Integer_Conversion_Semantics
1437 # lobster-trace: LRM.Decimal_Conversion_Semantics
1439 assert isinstance(mh, Message_Handler)
1440 assert context is None or isinstance(context, dict)
1441 assert gstab is None or isinstance(gstab, Symbol_Table)
1443 v_operand = self.n_operand.evaluate(mh, context, gstab)
1444 if v_operand.value is None: 1444 ↛ 1445line 1444 didn't jump to line 1445 because the condition on line 1444 was never true
1445 mh.error(
1446 v_operand.location,
1447 "input to unary expression %s (%s) must not be null"
1448 % (self.to_string(), mh.cross_file_reference(self.location)),
1449 )
1451 if self.operator == Unary_Operator.MINUS:
1452 return Value(location=self.location, value=-v_operand.value, typ=self.typ)
1453 elif self.operator == Unary_Operator.PLUS:
1454 return Value(location=self.location, value=+v_operand.value, typ=self.typ)
1455 elif self.operator == Unary_Operator.LOGICAL_NOT:
1456 return Value(
1457 location=self.location, value=not v_operand.value, typ=self.typ
1458 )
1459 elif self.operator == Unary_Operator.ABSOLUTE_VALUE:
1460 return Value(
1461 location=self.location, value=abs(v_operand.value), typ=self.typ
1462 )
1463 elif self.operator in (
1464 Unary_Operator.STRING_LENGTH,
1465 Unary_Operator.ARRAY_LENGTH,
1466 ):
1467 return Value(
1468 location=self.location, value=len(v_operand.value), typ=self.typ
1469 )
1470 elif self.operator == Unary_Operator.CONVERSION_TO_INT:
1471 if isinstance(v_operand.value, Fraction): 1471 ↛ 1478line 1471 didn't jump to line 1478 because the condition on line 1471 was always true
1472 return Value(
1473 location=self.location,
1474 value=math.round_nearest_away(v_operand.value),
1475 typ=self.typ,
1476 )
1477 else:
1478 return Value(
1479 location=self.location, value=v_operand.value, typ=self.typ
1480 )
1481 elif self.operator == Unary_Operator.CONVERSION_TO_DECIMAL:
1482 return Value(
1483 location=self.location, value=Fraction(v_operand.value), typ=self.typ
1484 )
1485 else:
1486 mh.ice_loc(self.location, "unexpected unary operation %s" % self.operator)
1488 def to_python_object(self):
1489 assert self.operator in (Unary_Operator.MINUS, Unary_Operator.PLUS)
1490 val = self.n_operand.to_python_object()
1491 if self.operator == Unary_Operator.MINUS:
1492 return -val
1493 else:
1494 return val
1496 def can_be_null(self):
1497 return False
1499 def uses_field_access(self):
1500 return self.n_operand.uses_field_access()
1503class Binary_Expression(Expression):
1504 """Expression with two operands
1506 This captures the following operations:
1508 * Binary_Operator.LOGICAL_AND (e.g. ``a and b``)
1509 * Binary_Operator.LOGICAL_OR (e.g. ``a or b``)
1510 * Binary_Operator.LOGICAL_XOR (e.g. ``a xor b``)
1511 * Binary_Operator.LOGICAL_IMPLIES (e.g. ``a implies b``)
1512 * Binary_Operator.COMP_EQ (e.g. ``a == null``)
1513 * Binary_Operator.COMP_NEQ (e.g. ``a != null``)
1514 * Binary_Operator.COMP_LT (e.g. ``1 < 2``)
1515 * Binary_Operator.COMP_LEQ (e.g. ``1 <= 2``)
1516 * Binary_Operator.COMP_GT (e.g. ``a > b``)
1517 * Binary_Operator.COMP_GEQ (e.g. ``a >= b``)
1518 * Binary_Operator.STRING_CONTAINS (e.g. ``"foo" in "foobar"``)
1519 * Binary_Operator.STRING_STARTSWITH (e.g. ``startswith("foo", "f")``)
1520 * Binary_Operator.STRING_ENDSWITH (e.g. ``endswith("foo", "o")``)
1521 * Binary_Operator.STRING_REGEX (e.g. ``matches("foo", ".o.``)
1522 * Binary_Operator.ARRAY_CONTAINS (e.g. ``42 in arr``)
1523 * Binary_Operator.PLUS (e.g. ``42 + b`` or ``"foo" + bar``)
1524 * Binary_Operator.MINUS (e.g. ``a - 1``)
1525 * Binary_Operator.TIMES (e.g. ``2 * x``)
1526 * Binary_Operator.DIVIDE (e.g. ``x / 2``)
1527 * Binary_Operator.REMAINDER (e.g. ``x % 2``)
1528 * Binary_Operator.POWER (e.g. ``x ** 2``)
1529 * Binary_Operator.INDEX (e.g. ``foo[2]``)
1531 Note that several builtin functions are mapped to unary operators.
1533 Note also that the plus operation is supported for integers,
1534 rationals and strings.
1536 :attribute operator: the operation
1537 :type: Binary_Operator
1539 :attribute n_lhs: the first operand
1540 :type: Expression
1542 :attribute n_rhs: the second operand
1543 :type: Expression
1545 """
1547 def __init__(self, mh, location, typ, operator, n_lhs, n_rhs):
1548 # lobster-trace: LRM.Expression
1549 # lobster-trace: LRM.Relation
1550 # lobster-trace: LRM.Simple_Expression
1551 # lobster-trace: LRM.Term
1552 # lobster-trace: LRM.Factor
1553 # lobster-trace: LRM.Signature_String_End_Functions
1554 # lobster-trace: LRM.Signature_Matches
1556 super().__init__(location, typ)
1557 assert isinstance(mh, Message_Handler)
1558 assert isinstance(operator, Binary_Operator)
1559 assert isinstance(n_lhs, Expression)
1560 assert isinstance(n_rhs, Expression)
1561 self.operator = operator
1562 self.n_lhs = n_lhs
1563 self.n_rhs = n_rhs
1565 if operator in (
1566 Binary_Operator.LOGICAL_AND,
1567 Binary_Operator.LOGICAL_OR,
1568 Binary_Operator.LOGICAL_XOR,
1569 Binary_Operator.LOGICAL_IMPLIES,
1570 ):
1571 self.n_lhs.ensure_type(mh, Builtin_Boolean)
1572 self.n_rhs.ensure_type(mh, Builtin_Boolean)
1574 elif operator in (Binary_Operator.COMP_EQ, Binary_Operator.COMP_NEQ):
1575 # lobster-trace: LRM.Union_Type_Equality
1576 # lobster-trace: LRM.Union_Type_Equality_Domain
1577 if (self.n_lhs.typ is None) or (self.n_rhs.typ is None):
1578 # We can compary anything to null (including itself)
1579 pass
1580 elif isinstance(self.n_lhs.typ, Union_Type) or isinstance(
1581 self.n_rhs.typ, Union_Type
1582 ):
1583 # For union types, we allow comparison if both
1584 # sides are record-like (Record_Type or Union_Type)
1585 for n_side in (self.n_lhs, self.n_rhs):
1586 if isinstance(n_side.typ, Union_Type):
1587 n_side.typ.ensure_record_members()
1588 lhs_is_record = isinstance(self.n_lhs.typ, (Record_Type, Union_Type))
1589 rhs_is_record = isinstance(self.n_rhs.typ, (Record_Type, Union_Type))
1590 if not (lhs_is_record and rhs_is_record): 1590 ↛ 1591line 1590 didn't jump to line 1591 because the condition on line 1590 was never true
1591 mh.error(
1592 self.location,
1593 "type mismatch: %s and %s do not match"
1594 % (self.n_lhs.typ.name, self.n_rhs.typ.name),
1595 )
1596 else:
1597 # Check that there is at least one pair of member
1598 # types (one from each side) where one is a subtype
1599 # of the other. This implements Equality_Domain for
1600 # union types: an unrelated record type is rejected.
1601 lhs_members = (
1602 self.n_lhs.typ.record_members()
1603 if isinstance(self.n_lhs.typ, Union_Type)
1604 else [self.n_lhs.typ]
1605 )
1606 rhs_members = (
1607 self.n_rhs.typ.record_members()
1608 if isinstance(self.n_rhs.typ, Union_Type)
1609 else [self.n_rhs.typ]
1610 )
1611 if not any(
1612 lm.is_subclass_of(rm) or rm.is_subclass_of(lm)
1613 for lm in lhs_members
1614 for rm in rhs_members
1615 ):
1616 mh.error(
1617 self.location,
1618 "type mismatch: %s and %s do not match"
1619 % (self.n_lhs.typ.name, self.n_rhs.typ.name),
1620 )
1621 elif self.n_lhs.typ != self.n_rhs.typ:
1622 # Otherwise we can compare anything, as long as the
1623 # types match
1624 mh.error(
1625 self.location,
1626 "type mismatch: %s and %s do not match"
1627 % (self.n_lhs.typ.name, self.n_rhs.typ.name),
1628 )
1630 elif operator in (
1631 Binary_Operator.COMP_LT,
1632 Binary_Operator.COMP_LEQ,
1633 Binary_Operator.COMP_GT,
1634 Binary_Operator.COMP_GEQ,
1635 ):
1636 self.n_lhs.ensure_type(mh, Builtin_Numeric_Type)
1637 self.n_rhs.ensure_type(mh, self.n_lhs.typ)
1639 elif operator in (
1640 Binary_Operator.STRING_CONTAINS,
1641 Binary_Operator.STRING_STARTSWITH,
1642 Binary_Operator.STRING_ENDSWITH,
1643 Binary_Operator.STRING_REGEX,
1644 ):
1645 self.n_lhs.ensure_type(mh, Builtin_String)
1646 self.n_rhs.ensure_type(mh, Builtin_String)
1648 elif operator == Binary_Operator.ARRAY_CONTAINS:
1649 self.n_rhs.ensure_type(mh, Array_Type)
1650 self.n_lhs.ensure_type(mh, self.n_rhs.typ.element_type.__class__)
1652 elif operator == Binary_Operator.PLUS:
1653 if isinstance(self.n_lhs.typ, Builtin_Numeric_Type):
1654 self.n_rhs.ensure_type(mh, self.n_lhs.typ)
1655 else:
1656 self.n_lhs.ensure_type(mh, Builtin_String)
1657 self.n_rhs.ensure_type(mh, Builtin_String)
1659 elif operator in (
1660 Binary_Operator.MINUS,
1661 Binary_Operator.TIMES,
1662 Binary_Operator.DIVIDE,
1663 ):
1664 self.n_lhs.ensure_type(mh, Builtin_Numeric_Type)
1665 self.n_rhs.ensure_type(mh, self.n_lhs.typ)
1667 elif operator == Binary_Operator.POWER:
1668 self.n_lhs.ensure_type(mh, Builtin_Numeric_Type)
1669 self.n_rhs.ensure_type(mh, Builtin_Integer)
1671 elif operator == Binary_Operator.REMAINDER:
1672 self.n_lhs.ensure_type(mh, Builtin_Integer)
1673 self.n_rhs.ensure_type(mh, Builtin_Integer)
1675 elif operator == Binary_Operator.INDEX:
1676 self.n_lhs.ensure_type(mh, Array_Type)
1677 self.n_rhs.ensure_type(mh, Builtin_Integer)
1679 else:
1680 mh.ice_loc(self.location, "unexpected binary operation %s" % operator)
1682 def dump(self, indent=0): # pragma: no cover
1683 # lobster-exclude: Debugging feature
1684 self.write_indent(indent, f"Binary {self.operator} Expression")
1685 self.write_indent(indent + 1, f"Type: {self.typ.name}")
1686 self.n_lhs.dump(indent + 1)
1687 self.n_rhs.dump(indent + 1)
1689 def to_string(self):
1690 infix_operators = {
1691 Binary_Operator.LOGICAL_AND: "and",
1692 Binary_Operator.LOGICAL_OR: "or",
1693 Binary_Operator.LOGICAL_XOR: "xor",
1694 Binary_Operator.LOGICAL_IMPLIES: "implies",
1695 Binary_Operator.COMP_EQ: "==",
1696 Binary_Operator.COMP_NEQ: "!=",
1697 Binary_Operator.COMP_LT: "<",
1698 Binary_Operator.COMP_LEQ: "<=",
1699 Binary_Operator.COMP_GT: ">",
1700 Binary_Operator.COMP_GEQ: ">=",
1701 Binary_Operator.STRING_CONTAINS: "in",
1702 Binary_Operator.ARRAY_CONTAINS: "in",
1703 Binary_Operator.PLUS: "+",
1704 Binary_Operator.MINUS: "-",
1705 Binary_Operator.TIMES: "*",
1706 Binary_Operator.DIVIDE: "/",
1707 Binary_Operator.REMAINDER: "%",
1708 Binary_Operator.POWER: "**",
1709 }
1710 string_functions = {
1711 Binary_Operator.STRING_STARTSWITH: "startswith",
1712 Binary_Operator.STRING_ENDSWITH: "endswith",
1713 Binary_Operator.STRING_REGEX: "matches",
1714 }
1716 if self.operator in infix_operators:
1717 return "%s %s %s" % (
1718 self.n_lhs.to_string(),
1719 infix_operators[self.operator],
1720 self.n_rhs.to_string(),
1721 )
1723 elif self.operator in string_functions:
1724 return "%s(%s, %s)" % (
1725 string_functions[self.operator],
1726 self.n_lhs.to_string(),
1727 self.n_rhs.to_string(),
1728 )
1730 elif self.operator == Binary_Operator.INDEX:
1731 return "%s[%s]" % (self.n_lhs.to_string(), self.n_rhs.to_string())
1733 else:
1734 assert False
1736 def evaluate(self, mh, context, gstab):
1737 # lobster-trace: LRM.Null_Equivalence
1738 # lobster-trace: LRM.Null_Is_Invalid
1739 # lobster-trace: LRM.Signature_String_End_Functions
1740 # lobster-trace: LRM.Signature_Matches
1741 # lobster-trace: LRM.Startswith_Semantics
1742 # lobster-trace: LRM.Endswith_Semantics
1743 # lobster-trace: LRM.Matches_Semantics
1745 assert isinstance(mh, Message_Handler)
1746 assert context is None or isinstance(context, dict)
1747 assert gstab is None or isinstance(gstab, Symbol_Table)
1749 v_lhs = self.n_lhs.evaluate(mh, context, gstab)
1750 if v_lhs.value is None and self.operator not in (
1751 Binary_Operator.COMP_EQ,
1752 Binary_Operator.COMP_NEQ,
1753 ):
1754 mh.error(
1755 v_lhs.location,
1756 "lhs of check %s (%s) must not be null"
1757 % (self.to_string(), mh.cross_file_reference(self.location)),
1758 )
1760 # Check for the short-circuit operators first
1761 if self.operator == Binary_Operator.LOGICAL_AND:
1762 assert isinstance(v_lhs.value, bool)
1763 if v_lhs.value:
1764 return self.n_rhs.evaluate(mh, context, gstab)
1765 else:
1766 return v_lhs
1768 elif self.operator == Binary_Operator.LOGICAL_OR:
1769 assert isinstance(v_lhs.value, bool)
1770 if v_lhs.value:
1771 return v_lhs
1772 else:
1773 return self.n_rhs.evaluate(mh, context, gstab)
1775 elif self.operator == Binary_Operator.LOGICAL_IMPLIES:
1776 assert isinstance(v_lhs.value, bool)
1777 if v_lhs.value:
1778 return self.n_rhs.evaluate(mh, context, gstab)
1779 else:
1780 return Value(location=self.location, value=True, typ=self.typ)
1782 # Otherwise, evaluate RHS and do the operation
1783 v_rhs = self.n_rhs.evaluate(mh, context, gstab)
1784 if v_rhs.value is None and self.operator not in (
1785 Binary_Operator.COMP_EQ,
1786 Binary_Operator.COMP_NEQ,
1787 ):
1788 mh.error(
1789 v_rhs.location,
1790 "rhs of check %s (%s) must not be null"
1791 % (self.to_string(), mh.cross_file_reference(self.location)),
1792 )
1794 if self.operator == Binary_Operator.LOGICAL_XOR:
1795 assert isinstance(v_lhs.value, bool)
1796 assert isinstance(v_rhs.value, bool)
1797 return Value(
1798 location=self.location, value=v_lhs.value ^ v_rhs.value, typ=self.typ
1799 )
1801 elif self.operator == Binary_Operator.COMP_EQ:
1802 return Value(
1803 location=self.location, value=v_lhs.value == v_rhs.value, typ=self.typ
1804 )
1806 elif self.operator == Binary_Operator.COMP_NEQ:
1807 return Value(
1808 location=self.location, value=v_lhs.value != v_rhs.value, typ=self.typ
1809 )
1811 elif self.operator in (
1812 Binary_Operator.COMP_LT,
1813 Binary_Operator.COMP_LEQ,
1814 Binary_Operator.COMP_GT,
1815 Binary_Operator.COMP_GEQ,
1816 ):
1817 return Value(
1818 location=self.location,
1819 value={
1820 Binary_Operator.COMP_LT: lambda lhs, rhs: lhs < rhs,
1821 Binary_Operator.COMP_LEQ: lambda lhs, rhs: lhs <= rhs,
1822 Binary_Operator.COMP_GT: lambda lhs, rhs: lhs > rhs,
1823 Binary_Operator.COMP_GEQ: lambda lhs, rhs: lhs >= rhs,
1824 }[self.operator](v_lhs.value, v_rhs.value),
1825 typ=self.typ,
1826 )
1828 elif self.operator == Binary_Operator.STRING_CONTAINS:
1829 assert isinstance(v_lhs.value, str)
1830 assert isinstance(v_rhs.value, str)
1832 return Value(
1833 location=self.location, value=v_lhs.value in v_rhs.value, typ=self.typ
1834 )
1836 elif self.operator == Binary_Operator.STRING_STARTSWITH:
1837 assert isinstance(v_lhs.value, str)
1838 assert isinstance(v_rhs.value, str)
1839 return Value(
1840 location=self.location,
1841 value=v_lhs.value.startswith(v_rhs.value),
1842 typ=self.typ,
1843 )
1845 elif self.operator == Binary_Operator.STRING_ENDSWITH:
1846 assert isinstance(v_lhs.value, str)
1847 assert isinstance(v_rhs.value, str)
1848 return Value(
1849 location=self.location,
1850 value=v_lhs.value.endswith(v_rhs.value),
1851 typ=self.typ,
1852 )
1854 elif self.operator == Binary_Operator.STRING_REGEX:
1855 assert isinstance(v_lhs.value, str)
1856 assert isinstance(v_rhs.value, str)
1857 return Value(
1858 location=self.location,
1859 value=re.match(v_rhs.value, v_lhs.value) is not None,
1860 typ=self.typ,
1861 )
1863 elif self.operator == Binary_Operator.ARRAY_CONTAINS:
1864 assert isinstance(v_rhs.value, list)
1866 return Value(
1867 location=self.location, value=v_lhs in v_rhs.value, typ=self.typ
1868 )
1870 elif self.operator == Binary_Operator.PLUS:
1871 assert isinstance(v_lhs.value, (int, str, Fraction))
1872 assert isinstance(v_rhs.value, (int, str, Fraction))
1873 return Value(
1874 location=self.location, value=v_lhs.value + v_rhs.value, typ=self.typ
1875 )
1877 elif self.operator == Binary_Operator.MINUS:
1878 assert isinstance(v_lhs.value, (int, Fraction))
1879 assert isinstance(v_rhs.value, (int, Fraction))
1880 return Value(
1881 location=self.location, value=v_lhs.value - v_rhs.value, typ=self.typ
1882 )
1884 elif self.operator == Binary_Operator.TIMES:
1885 assert isinstance(v_lhs.value, (int, Fraction))
1886 assert isinstance(v_rhs.value, (int, Fraction))
1887 return Value(
1888 location=self.location, value=v_lhs.value * v_rhs.value, typ=self.typ
1889 )
1891 elif self.operator == Binary_Operator.DIVIDE:
1892 assert isinstance(v_lhs.value, (int, Fraction))
1893 assert isinstance(v_rhs.value, (int, Fraction))
1895 if v_rhs.value == 0: 1895 ↛ 1896line 1895 didn't jump to line 1896 because the condition on line 1895 was never true
1896 mh.error(
1897 v_rhs.location,
1898 "division by zero in %s (%s)"
1899 % (self.to_string(), mh.cross_file_reference(self.location)),
1900 )
1902 if isinstance(v_lhs.value, int):
1903 return Value(
1904 location=self.location,
1905 value=v_lhs.value // v_rhs.value,
1906 typ=self.typ,
1907 )
1908 else:
1909 return Value(
1910 location=self.location,
1911 value=v_lhs.value / v_rhs.value,
1912 typ=self.typ,
1913 )
1915 elif self.operator == Binary_Operator.REMAINDER:
1916 assert isinstance(v_lhs.value, int)
1917 assert isinstance(v_rhs.value, int)
1919 if v_rhs.value == 0: 1919 ↛ 1920line 1919 didn't jump to line 1920 because the condition on line 1919 was never true
1920 mh.error(
1921 v_rhs.location,
1922 "division by zero in %s (%s)"
1923 % (self.to_string(), mh.cross_file_reference(self.location)),
1924 )
1926 return Value(
1927 location=self.location,
1928 value=math.remainder(v_lhs.value, v_rhs.value),
1929 typ=self.typ,
1930 )
1932 elif self.operator == Binary_Operator.POWER:
1933 assert isinstance(v_lhs.value, (int, Fraction))
1934 assert isinstance(v_rhs.value, int)
1935 return Value(
1936 location=self.location, value=v_lhs.value**v_rhs.value, typ=self.typ
1937 )
1939 elif self.operator == Binary_Operator.INDEX:
1940 assert isinstance(v_lhs.value, list)
1941 assert isinstance(v_rhs.value, int)
1943 if v_rhs.value < 0: 1943 ↛ 1944line 1943 didn't jump to line 1944 because the condition on line 1943 was never true
1944 mh.error(
1945 v_rhs.location,
1946 "index cannot be less than zero in %s (%s)"
1947 % (self.to_string(), mh.cross_file_reference(self.location)),
1948 )
1949 elif ( 1949 ↛ 1953line 1949 didn't jump to line 1953 because the condition on line 1949 was never true
1950 v_lhs.typ.upper_bound is not None
1951 and v_rhs.value > v_lhs.typ.upper_bound
1952 ):
1953 mh.error(
1954 v_rhs.location,
1955 "index cannot be more than %u in %s (%s)"
1956 % (
1957 v_lhs.typ.upper_bound,
1958 self.to_string(),
1959 mh.cross_file_reference(self.location),
1960 ),
1961 )
1962 elif v_rhs.value > len(v_lhs.value): 1962 ↛ 1963line 1962 didn't jump to line 1963 because the condition on line 1962 was never true
1963 mh.error(
1964 v_lhs.location,
1965 "array is not big enough in %s (%s)"
1966 % (self.to_string(), mh.cross_file_reference(self.location)),
1967 )
1969 return Value(
1970 location=self.location,
1971 value=v_lhs.value[v_rhs.value].value,
1972 typ=self.typ,
1973 )
1975 else:
1976 mh.ice_loc(self.location, "unexpected binary operator %s" % self.operator)
1978 def can_be_null(self):
1979 return False
1981 def uses_field_access(self):
1982 return self.n_lhs.uses_field_access() or self.n_rhs.uses_field_access()
1985class Field_Access_Expression(Expression):
1986 """Tuple, Record, or Union field access
1988 For example in::
1990 foo.bar
1991 ^1 ^2
1993 :attribute n_prefix: expression with tuple, record, or union type (see 1)
1994 :type: Expression
1996 :attribute n_field: a field to dereference (see 2)
1997 :type: Composite_Component
1999 :attribute is_union_access: True if the prefix is a union type
2000 :type: bool
2002 :attribute is_universal: True if field exists in all union members.
2003 Only meaningful when is_union_access is True.
2004 :type: bool
2006 """
2008 def __init__(
2009 self, mh, location, n_prefix, n_field, is_union_access=False, is_universal=True
2010 ):
2011 # lobster-trace: LRM.Union_Type_Field_Access
2012 assert isinstance(mh, Message_Handler)
2013 assert isinstance(n_prefix, Expression)
2014 assert isinstance(n_field, Composite_Component)
2015 assert isinstance(is_union_access, bool)
2016 assert isinstance(is_universal, bool)
2017 super().__init__(location, n_field.n_typ)
2018 self.n_prefix = n_prefix
2019 self.n_field = n_field
2020 self.is_union_access = is_union_access
2021 self.is_universal = is_universal
2023 if not is_union_access:
2024 self.n_prefix.ensure_type(mh, self.n_field.member_of)
2026 def dump(self, indent=0): # pragma: no cover
2027 # lobster-exclude: Debugging feature
2028 self.write_indent(indent, f"Field_Access ({self.n_field.name})")
2029 self.n_prefix.dump(indent + 1)
2031 def to_string(self):
2032 return self.n_prefix.to_string() + "." + self.n_field.name
2034 def evaluate(self, mh, context, gstab):
2035 assert isinstance(mh, Message_Handler)
2036 assert context is None or isinstance(context, dict)
2037 assert gstab is None or isinstance(gstab, Symbol_Table)
2039 v_prefix = self.n_prefix.evaluate(mh, context, gstab).value
2040 if v_prefix is None:
2041 # lobster-trace: LRM.Dereference
2042 mh.error(self.n_prefix.location, "null dereference")
2044 # lobster-trace: LRM.Union_Type_Partial_Field_Access
2045 # lobster-trace: LRM.Union_Type_Partial_Field_Null
2046 if self.n_field.name not in v_prefix:
2047 return Value(self.location, None, None)
2049 v_field = v_prefix[self.n_field.name]
2050 if isinstance(v_field, Expression):
2051 # lobster-trace: LRM.Dereference
2052 return v_field.evaluate(mh, context, gstab)
2053 else:
2054 return v_field
2056 def can_be_null(self):
2057 # A union field access on a partial field (not present in all
2058 # member types) evaluates to null at runtime, so we must
2059 # report True in that case.
2060 return self.is_union_access and not self.is_universal
2062 def uses_field_access(self):
2063 # lobster-trace: LRM.Dereference
2064 if isinstance(self.n_prefix.typ, (Record_Type, Union_Type)):
2065 return True
2066 return self.n_prefix.uses_field_access()
2069class Range_Test(Expression):
2070 """Range membership test
2072 For example in::
2074 x in 1 .. field+1
2075 ^lhs ^lower ^^^^^^^upper
2077 Note that none of these are guaranteed to be literals or names;
2078 you can have arbitrarily complex expressions here.
2080 :attribute n_lhs: the expression to test
2081 :type: Expression
2083 :attribute n_lower: the lower bound
2084 :type: Expression
2086 :attribute n_upper: the upper bound
2087 :type: Expression
2089 """
2091 def __init__(self, mh, location, typ, n_lhs, n_lower, n_upper):
2092 # lobster-trace: LRM.Relation
2093 super().__init__(location, typ)
2094 assert isinstance(mh, Message_Handler)
2095 assert isinstance(n_lhs, Expression)
2096 assert isinstance(n_lower, Expression)
2097 assert isinstance(n_upper, Expression)
2098 self.n_lhs = n_lhs
2099 self.n_lower = n_lower
2100 self.n_upper = n_upper
2102 self.n_lhs.ensure_type(mh, Builtin_Numeric_Type)
2103 self.n_lower.ensure_type(mh, self.n_lhs.typ)
2104 self.n_upper.ensure_type(mh, self.n_lhs.typ)
2106 def to_string(self):
2107 return "%s in %s .. %s" % (
2108 self.n_lhs.to_string(),
2109 self.n_lower.to_string(),
2110 self.n_upper.to_string(),
2111 )
2113 def dump(self, indent=0): # pragma: no cover
2114 # lobster-exclude: Debugging feature
2115 self.write_indent(indent, "Range Test")
2116 self.write_indent(indent + 1, f"Type: {self.typ}")
2117 self.n_lhs.dump(indent + 1)
2118 self.n_lower.dump(indent + 1)
2119 self.n_upper.dump(indent + 1)
2121 def evaluate(self, mh, context, gstab):
2122 # lobster-trace: LRM.Null_Is_Invalid
2123 assert isinstance(mh, Message_Handler)
2124 assert context is None or isinstance(context, dict)
2125 assert gstab is None or isinstance(gstab, Symbol_Table)
2127 v_lhs = self.n_lhs.evaluate(mh, context, gstab)
2128 if v_lhs.value is None: 2128 ↛ 2129line 2128 didn't jump to line 2129 because the condition on line 2128 was never true
2129 mh.error(
2130 v_lhs.location,
2131 "lhs of range check %s (%s) see must not be null"
2132 % (self.to_string(), mh.cross_file_reference(self.location)),
2133 )
2135 v_lower = self.n_lower.evaluate(mh, context, gstab)
2136 if v_lower.value is None: 2136 ↛ 2137line 2136 didn't jump to line 2137 because the condition on line 2136 was never true
2137 mh.error(
2138 v_lower.location,
2139 "lower bound of range check %s (%s) must not be null"
2140 % (self.to_string(), mh.cross_file_reference(self.location)),
2141 )
2143 v_upper = self.n_upper.evaluate(mh, context, gstab)
2144 if v_upper.value is None: 2144 ↛ 2145line 2144 didn't jump to line 2145 because the condition on line 2144 was never true
2145 mh.error(
2146 v_upper.location,
2147 "upper bound of range check %s (%s) must not be null"
2148 % (self.to_string(), mh.cross_file_reference(self.location)),
2149 )
2151 return Value(
2152 location=self.location,
2153 value=v_lower.value <= v_lhs.value <= v_upper.value,
2154 typ=self.typ,
2155 )
2157 def can_be_null(self):
2158 return False
2160 def uses_field_access(self):
2161 return (
2162 self.n_lhs.uses_field_access()
2163 or self.n_lower.uses_field_access()
2164 or self.n_upper.uses_field_access()
2165 )
2168class OneOf_Expression(Expression):
2169 """OneOf expression
2171 For example in::
2173 oneof(a, b, c)
2174 ^^^^^^^ choices
2176 :attribute choices: a list of boolean expressions to test
2177 :type: list[Expression]
2178 """
2180 def __init__(self, mh, location, typ, choices):
2181 # lobster-trace: LRM.Signature_OneOf
2182 super().__init__(location, typ)
2183 assert isinstance(typ, Builtin_Boolean)
2184 assert isinstance(mh, Message_Handler)
2185 assert isinstance(choices, list)
2186 assert all(isinstance(item, Expression) for item in choices)
2187 self.choices = choices
2189 for n_choice in choices:
2190 n_choice.ensure_type(mh, Builtin_Boolean)
2192 def to_string(self):
2193 return "oneof(%s)" % ", ".join(
2194 n_choice.to_string() for n_choice in self.choices
2195 )
2197 def dump(self, indent=0): # pragma: no cover
2198 # lobster-exclude: Debugging feature
2199 self.write_indent(indent, "OneOf Test")
2200 self.write_indent(indent + 1, f"Type: {self.typ}")
2201 for n_choice in self.choices:
2202 n_choice.dump(indent + 1)
2204 def evaluate(self, mh, context, gstab):
2205 # lobster-trace: LRM.OneOf_Semantics
2206 assert isinstance(mh, Message_Handler)
2207 assert context is None or isinstance(context, dict)
2208 assert gstab is None or isinstance(gstab, Symbol_Table)
2210 v_choices = [
2211 n_choice.evaluate(mh, context, gstab).value for n_choice in self.choices
2212 ]
2214 return Value(
2215 location=self.location, value=v_choices.count(True) == 1, typ=self.typ
2216 )
2218 def can_be_null(self):
2219 return False
2221 def uses_field_access(self):
2222 return any(n_choice.uses_field_access() for n_choice in self.choices)
2225class Action(Node):
2226 """An if or elseif part inside a conditional expression
2228 Each :class:`Conditional_Expression` is made up of a sequence of
2229 Actions. For example here is a single expression with two
2230 Actions::
2232 (if x == 0 then "zero" elsif x == 1 then "one" else "lots")
2233 ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
2235 Note that the else part is not an action, it is an attribute of
2236 the :class:`Conditional_Expression` itself.
2238 :attribute kind: Either if or elseif
2239 :type: str
2241 :attribute n_cond: The boolean condition expression
2242 :type: Expression
2244 :attribute n_expr: The value if the condition evaluates to true
2245 :type: Expression
2247 """
2249 def __init__(self, mh, t_kind, n_condition, n_expression):
2250 # lobster-trace: LRM.Conditional_Expression
2251 assert isinstance(mh, Message_Handler)
2252 assert isinstance(t_kind, Token)
2253 assert t_kind.kind == "KEYWORD"
2254 assert t_kind.value in ("if", "elsif")
2255 assert isinstance(n_condition, Expression)
2256 assert isinstance(n_expression, Expression)
2257 super().__init__(t_kind.location)
2258 self.kind = t_kind.value
2259 self.n_cond = n_condition
2260 self.n_expr = n_expression
2261 # lobster-trace: LRM.Conditional_Expression_Types
2262 self.n_cond.ensure_type(mh, Builtin_Boolean)
2264 def dump(self, indent=0): # pragma: no cover
2265 # lobster-exclude: Debugging feature
2266 self.write_indent(indent, f"{self.kind.capitalize()} Action")
2267 self.write_indent(indent + 1, "Condition")
2268 self.n_cond.dump(indent + 2)
2269 self.write_indent(indent + 1, "Value")
2270 self.n_expr.dump(indent + 2)
2272 def to_string(self):
2273 return "%s %s then %s" % (
2274 self.kind,
2275 self.n_cond.to_string(),
2276 self.n_expr.to_string(),
2277 )
2280class Conditional_Expression(Expression):
2281 """A conditional expression
2283 Each :class:`Conditional_Expression` is made up of a sequence of
2284 one or more :class:`Action`. For example here is a single
2285 expression with two Actions::
2287 (if x == 0 then "zero" elsif x == 1 then "one" else "lots")
2288 ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
2290 The else expression is part of the conditional expression itself.
2292 A conditional expression will have at least one action (the if
2293 action), and all other actions will be elsif actions. The else
2294 expression is not optional and will always be present. The types
2295 of all actions and the else expression will match.
2297 :attribute actions: a list of Actions
2298 :type: list[Action]
2300 :attribute else_expr: the else expression
2301 :type: Expression
2303 """
2305 def __init__(self, location, if_action):
2306 # lobster-trace: LRM.Conditional_Expression
2307 assert isinstance(if_action, Action)
2308 assert if_action.kind == "if"
2309 super().__init__(location, if_action.n_expr.typ)
2310 self.actions = [if_action]
2311 self.else_expr = None
2313 def add_elsif(self, mh, n_action):
2314 # lobster-trace: LRM.Conditional_Expression
2315 # lobster-trace; LRM.Conditional_Expression_Types
2316 assert isinstance(mh, Message_Handler)
2317 assert isinstance(n_action, Action)
2318 assert n_action.kind == "elsif"
2320 n_action.n_expr.ensure_type(mh, self.typ)
2321 self.actions.append(n_action)
2323 def set_else_part(self, mh, n_expr):
2324 # lobster-trace: LRM.Conditional_Expression
2325 # lobster-trace; LRM.Conditional_Expression_Types
2326 assert isinstance(mh, Message_Handler)
2327 assert isinstance(n_expr, Expression)
2329 n_expr.ensure_type(mh, self.typ)
2330 self.else_expr = n_expr
2332 def dump(self, indent=0): # pragma: no cover
2333 # lobster-exclude: Debugging feature
2334 self.write_indent(indent, "Conditional expression")
2335 for action in self.actions:
2336 action.dump(indent + 1)
2337 self.write_indent(indent + 1, "Else")
2338 self.else_expr.dump(indent + 2)
2340 def to_string(self):
2341 rv = "(" + " ".join(action.to_string() for action in self.actions)
2342 rv += " else %s" % self.else_expr.to_string()
2343 rv += ")"
2344 return rv
2346 def evaluate(self, mh, context, gstab):
2347 # lobster-trace: LRM.Conditional_Expression_Else
2348 # lobster-trace: LRM.Conditional_Expression_Evaluation
2349 # lobster-trace: LRM.Null_Is_Invalid
2350 assert isinstance(mh, Message_Handler)
2351 assert context is None or isinstance(context, dict)
2352 assert gstab is None or isinstance(gstab, Symbol_Table)
2354 for action in self.actions:
2355 v_cond = action.n_cond.evaluate(mh, context, gstab)
2356 if v_cond.value is None: 2356 ↛ 2357line 2356 didn't jump to line 2357 because the condition on line 2356 was never true
2357 mh.error(
2358 v_cond.location,
2359 "condition of %s (%s) must not be null"
2360 % (action.to_string(), mh.cross_file_reference(self.location)),
2361 )
2362 if v_cond.value:
2363 return action.n_expr.evaluate(mh, context, gstab)
2365 return self.else_expr.evaluate(mh, context, gstab)
2367 def can_be_null(self):
2368 if self.else_expr and self.else_expr.can_be_null():
2369 return True
2371 return any(action.n_expr.can_be_null() for action in self.actions)
2373 def uses_field_access(self):
2374 return any(
2375 action.n_cond.uses_field_access() or action.n_expr.uses_field_access()
2376 for action in self.actions
2377 ) or (self.else_expr is not None and self.else_expr.uses_field_access())
2380class Quantified_Expression(Expression):
2381 """A quantified expression
2383 For example::
2385 (forall x in array_component => x > 0)
2386 ^4 ^1 ^2 ^^^^^3
2388 A quantified expression introduces and binds a
2389 :class:`Quantified_Variable` (see 1) from a specified source (see
2390 2). When the body (see 3) is evaluated, the name of 1 is bound to
2391 each component of the source in turn.
2393 :attribute n_var: The quantified variable (see 1)
2394 :type: Quantified_Variable
2396 :attribute n_source: The array to iterate over (see 2)
2397 :type: Name_Reference
2399 :attribute n_expr: The body of the quantifier (see 3)
2400 :type: Expression
2402 :attribute universal: True means forall, false means exists (see 4)
2403 :type: Boolean
2405 """
2407 def __init__(self, mh, location, typ, universal, n_variable, n_source, n_expr):
2408 # lobster-trace: LRM.Quantified_Expression
2409 # lobster-trace: LRM.Quantification_Type
2410 super().__init__(location, typ)
2411 assert isinstance(typ, Builtin_Boolean)
2412 assert isinstance(universal, bool)
2413 assert isinstance(n_variable, Quantified_Variable)
2414 assert isinstance(n_expr, Expression)
2415 assert isinstance(n_source, Name_Reference)
2416 self.universal = universal
2417 self.n_var = n_variable
2418 self.n_expr = n_expr
2419 self.n_source = n_source
2420 self.n_expr.ensure_type(mh, Builtin_Boolean)
2422 def dump(self, indent=0): # pragma: no cover
2423 # lobster-exclude: Debugging feature
2424 if self.universal:
2425 self.write_indent(indent, "Universal quantified expression")
2426 else:
2427 self.write_indent(indent, "Existential quantified expression")
2428 self.n_var.dump(indent + 1)
2429 self.n_expr.dump(indent + 1)
2431 def to_string(self):
2432 return "(%s %s in %s => %s)" % (
2433 "forall" if self.universal else "exists",
2434 self.n_var.name,
2435 self.n_source.to_string(),
2436 self.n_expr.to_string(),
2437 )
2439 def evaluate(self, mh, context, gstab):
2440 # lobster-trace: LRM.Null_Is_Invalid
2441 # lobster-trace: LRM.Universal_Quantification_Semantics
2442 # lobster-trace: LRM.Existential_Quantification_Semantics
2443 assert isinstance(mh, Message_Handler)
2444 assert context is None or isinstance(context, dict)
2445 assert gstab is None or isinstance(gstab, Symbol_Table)
2447 if context is None: 2447 ↛ 2448line 2447 didn't jump to line 2448 because the condition on line 2447 was never true
2448 new_ctx = {}
2449 else:
2450 new_ctx = copy(context)
2452 # This is going to be a bit tricky. We essentially eliminate
2453 # the quantifier and substitute; for the sake of making better
2454 # error messages.
2455 assert isinstance(self.n_source.entity, Composite_Component)
2456 array_values = context[self.n_source.entity.name]
2457 if isinstance(array_values, Implicit_Null):
2458 mh.error(
2459 array_values.location,
2460 "%s in quantified expression %s (%s) "
2461 "must not be null"
2462 % (
2463 self.n_source.to_string(),
2464 self.to_string(),
2465 mh.cross_file_reference(self.location),
2466 ),
2467 )
2468 else:
2469 assert isinstance(array_values, Array_Aggregate)
2471 rv = self.universal
2472 loc = self.location
2473 for binding in array_values.value:
2474 new_ctx[self.n_var.name] = binding
2475 result = self.n_expr.evaluate(mh, new_ctx, gstab)
2476 assert isinstance(result.value, bool)
2477 if self.universal and not result.value:
2478 rv = False
2479 loc = binding.location
2480 break
2481 elif not self.universal and result.value:
2482 rv = True
2483 loc = binding.location
2484 break
2486 return Value(location=loc, value=rv, typ=self.typ)
2488 def can_be_null(self):
2489 return False
2491 def uses_field_access(self):
2492 return self.n_source.uses_field_access() or self.n_expr.uses_field_access()
2495##############################################################################
2496# AST Nodes (Entities)
2497##############################################################################
2500class Entity(Node, metaclass=ABCMeta):
2501 """Base class for all entities.
2503 An entity is a concrete object (with a name) for which we need to
2504 allocate memory. Examples of entities are types and record
2505 objects.
2507 :attribute name: unqualified name of the entity
2508 :type: str
2510 """
2512 def __init__(self, name, location):
2513 # lobster-trace: LRM.Described_Name_Equality
2514 super().__init__(location)
2515 assert isinstance(name, str)
2516 self.name = name
2519class Typed_Entity(Entity, metaclass=ABCMeta):
2520 """Base class for entities with a type.
2522 A typed entity is a concrete object (with a name and TRLC type)
2523 for which we need to allocate memory. Examples of typed entities
2524 are record objects and components.
2526 :attribute n_typ: type of the entity
2527 :type: Type
2529 """
2531 def __init__(self, name, location, n_typ):
2532 # lobster-exclude: Constructor only declares variables
2533 super().__init__(name, location)
2534 assert isinstance(n_typ, Type)
2535 self.n_typ = n_typ
2538class Quantified_Variable(Typed_Entity):
2539 """Variable used in quantified expression.
2541 A quantified expression declares and binds a variable, for which
2542 we need a named entity. For example in::
2544 (forall x in array => x > 1)
2545 ^
2547 We represent this first x as a :class:`Quantified_Variable`, the
2548 second x will be an ordinary :class:`Name_Reference`.
2550 :attribute typ: type of the variable (i.e. element type of the array)
2551 :type: Type
2553 """
2555 def dump(self, indent=0): # pragma: no cover
2556 # lobster-exclude: Debugging feature
2557 self.write_indent(indent, f"Quantified Variable {self.name}")
2558 self.n_typ.dump(indent + 1)
2561class Type(Entity, metaclass=ABCMeta):
2562 """Abstract base class for all types."""
2564 def perform_type_checks(self, mh, value, gstab):
2565 assert isinstance(mh, Message_Handler)
2566 assert isinstance(value, Expression)
2567 assert isinstance(gstab, Symbol_Table)
2568 return True
2570 def get_example_value(self):
2571 # lobster-exclude: utility method
2572 assert False
2575class Concrete_Type(Type, metaclass=ABCMeta):
2576 # lobster-trace: LRM.Type_Declarations
2577 """Abstract base class for all non-anonymous types.
2579 :attribute n_package: package where this type was declared
2580 :type: Package
2581 """
2583 def __init__(self, name, location, n_package):
2584 super().__init__(name, location)
2585 assert isinstance(n_package, Package)
2586 self.n_package = n_package
2587 self._is_forward_decl = False
2588 self._forward_decl_context = None
2589 self._forward_union_use = None
2591 def mark_forward_decl(self):
2592 """Mark this definition as a temporary forward declaration."""
2593 self._is_forward_decl = True
2595 def clear_forward_decl(self):
2596 """Clear the temporary forward-declaration marker."""
2597 self._is_forward_decl = False
2599 def is_forward_decl(self):
2600 """Return whether this type is still only a forward declaration."""
2601 return self._is_forward_decl
2603 def set_forward_decl_context(self, context):
2604 """Set parser bookkeeping for the forward-declaration origin."""
2605 self._forward_decl_context = context
2607 def get_forward_decl_context(self):
2608 """Return parser bookkeeping for the forward-declaration origin."""
2609 return getattr(self, "_forward_decl_context", None)
2611 def set_forward_union_use(self, location):
2612 """Remember where this forward declaration was used as a union member.
2614 Only the first use is kept.
2615 """
2616 if self._forward_union_use is None: 2616 ↛ exitline 2616 didn't return from function 'set_forward_union_use' because the condition on line 2616 was always true
2617 self._forward_union_use = location
2619 def get_forward_union_use(self):
2620 """Return the location of the first union-member use, if any."""
2621 return getattr(self, "_forward_union_use", None)
2623 def fully_qualified_name(self):
2624 """Return the FQN for this type (i.e. PACKAGE.NAME)
2626 :returns: the type's full name
2627 :rtype: str
2628 """
2629 return self.n_package.name + "." + self.name
2631 def __hash__(self):
2632 return hash((self.n_package.name, self.name))
2634 def __repr__(self):
2635 return "%s<%s>" % (self.__class__.__name__, self.fully_qualified_name())
2638class Builtin_Type(Type, metaclass=ABCMeta):
2639 # lobster-trace: LRM.Builtin_Types
2640 """Abstract base class for all builtin types."""
2642 LOCATION = Location(file_name="<builtin>")
2644 def __init__(self, name):
2645 super().__init__(name, Builtin_Type.LOCATION)
2647 def dump(self, indent=0): # pragma: no cover
2648 self.write_indent(indent, self.__class__.__name__)
2651class Builtin_Numeric_Type(Builtin_Type, metaclass=ABCMeta):
2652 # lobster-trace: LRM.Builtin_Types
2653 """Abstract base class for all builtin numeric types."""
2655 def dump(self, indent=0): # pragma: no cover
2656 self.write_indent(indent, self.__class__.__name__)
2659class Builtin_Function(Entity):
2660 # lobster-trace: LRM.Builtin_Functions
2661 """Builtin functions.
2663 These are auto-generated by the :class:`~trlc.trlc.Source_Manager`.
2665 :attribute arity: number of parameters
2666 :type: int
2668 :attribute arity_at_least: when true, arity indicates a lower bound
2669 :type: bool
2671 """
2673 LOCATION = Location(file_name="<builtin>")
2675 def __init__(self, name, arity, arity_at_least=False):
2676 super().__init__(name, Builtin_Function.LOCATION)
2677 assert isinstance(arity, int)
2678 assert isinstance(arity_at_least, bool)
2679 assert arity >= 0
2680 self.arity = arity
2681 self.arity_at_least = arity_at_least
2683 def dump(self, indent=0): # pragma: no cover
2684 self.write_indent(indent, self.__class__.__name__ + " " + self.name)
2687class Array_Type(Type):
2688 """Anonymous array type.
2690 These are declared implicitly for each record component that has
2691 an array specifier::
2693 foo Integer [5 .. *]
2694 ^
2696 :attribute lower_bound: minimum number of elements
2697 :type: int
2699 :attribute loc_lower: text location of the lower bound indicator
2700 :type: Location
2702 :attribute upper_bound: maximum number of elements (or None)
2703 :type: int
2705 :attribute loc_upper: text location of the upper bound indicator
2706 :type: Location
2708 :attribute element_type: type of the array elements
2709 :type: Type
2711 """
2713 def __init__(
2714 self, location, element_type, loc_lower, lower_bound, loc_upper, upper_bound
2715 ):
2716 # lobster-exclude: Constructor only declares variables
2717 assert isinstance(element_type, Type) or element_type is None
2718 assert isinstance(lower_bound, int)
2719 assert lower_bound >= 0
2720 assert upper_bound is None or isinstance(upper_bound, int)
2721 assert upper_bound is None or upper_bound >= 0
2722 assert isinstance(loc_lower, Location)
2723 assert isinstance(loc_upper, Location)
2725 if element_type is None: 2725 ↛ 2726line 2725 didn't jump to line 2726 because the condition on line 2725 was never true
2726 name = "universal array"
2727 elif upper_bound is None:
2728 if lower_bound == 0:
2729 name = "array of %s" % element_type.name
2730 else:
2731 name = "array of at least %u %s" % (lower_bound, element_type.name)
2732 elif lower_bound == upper_bound:
2733 name = "array of %u %s" % (lower_bound, element_type.name)
2734 else:
2735 name = "array of %u to %u %s" % (
2736 lower_bound,
2737 upper_bound,
2738 element_type.name,
2739 )
2740 super().__init__(name, location)
2741 self.lower_bound = lower_bound
2742 self.loc_lower = loc_lower
2743 self.upper_bound = upper_bound
2744 self.loc_upper = loc_upper
2745 self.element_type = element_type
2747 def dump(self, indent=0): # pragma: no cover
2748 # lobster-exclude: Debugging feature
2749 self.write_indent(indent, "Array_Type")
2750 self.write_indent(indent + 1, f"Lower bound: {self.lower_bound}")
2751 if self.upper_bound is None:
2752 self.write_indent(indent + 1, "Upper bound: *")
2753 else:
2754 self.write_indent(indent + 1, f"Upper bound: {self.upper_bound}")
2755 self.write_indent(indent + 1, f"Element type: {self.element_type.name}")
2757 def perform_type_checks(self, mh, value, gstab):
2758 assert isinstance(mh, Message_Handler)
2759 assert isinstance(gstab, Symbol_Table)
2761 if isinstance(value, Array_Aggregate):
2762 return all(
2763 self.element_type.perform_type_checks(mh, v, gstab) for v in value.value
2764 )
2765 else:
2766 assert isinstance(value, Implicit_Null)
2767 return True
2769 def get_example_value(self):
2770 # lobster-exclude: utility method
2771 return "[%s]" % self.element_type.get_example_value()
2774class Union_Type(Type):
2775 # lobster-trace: LRM.union_type
2776 # lobster-trace: LRM.Union_Type_Minimum_Members
2777 # lobster-trace: LRM.Union_Type_Record_Types_Only
2778 """Anonymous union type for record references.
2780 These are declared implicitly when a record component specifies
2781 multiple allowed record types using bracket syntax::
2783 parent [Systemrequirement, Codebeamerrequirement]
2784 ^
2786 :attribute types: the allowed record types
2787 :type: list[Record_Type]
2789 """
2791 def __init__(self, location, types):
2792 assert isinstance(types, list)
2793 assert len(types) >= 1
2794 assert all(isinstance(t, Record_Type) for t in types)
2795 name = "[%s]" % ", ".join(t.name for t in types)
2796 super().__init__(name, location)
2797 self.types = types
2798 self._field_map = None
2800 def record_members(self):
2801 """Return the members that are actually record types.
2803 A forward-declared record placeholder may later turn out to be
2804 some other kind of type (e.g. an enumeration). That is reported
2805 as an error by the linter, but until then such members must
2806 not be treated as records.
2808 :rtype: list[Record_Type]
2809 """
2810 return [t for t in self.types if isinstance(t, Record_Type)]
2812 def ensure_record_members(self):
2813 """Abort the current construct if a member is not a record type.
2815 Such a member is a forward-declared stub that turned out to be
2816 an enumeration or tuple. The parser already printed an error
2817 when that happened, so this raises without printing again.
2819 :raises TRLC_Error: if any member is not a record type
2820 """
2821 for t in self.types:
2822 if not isinstance(t, Record_Type):
2823 raise TRLC_Error(
2824 self.location,
2825 Kind.SYS_ERROR,
2826 f"{t.__class__.__name__} {t.name} is not a Record_Type",
2827 )
2829 def get_field_map(self):
2830 # lobster-trace: LRM.Union_Type_Field_Access
2831 """Compute accessible fields across all union members.
2833 Returns a dict mapping field name to a dict with keys:
2835 * ``component``: a representative Composite_Component
2836 * ``n_typ``: the field type (None if conflicting)
2837 * ``count``: how many member types have this field
2838 * ``total``: total number of member types
2839 * ``optional_in_any``: True if optional in at least one member
2841 :rtype: dict[str, dict]
2842 """
2843 if self._field_map is not None:
2844 return self._field_map
2846 members = self.record_members()
2847 field_map = {}
2848 for record_type in members:
2849 seen_in_type = set()
2850 for comp in record_type.all_components():
2851 if comp.name in seen_in_type: 2851 ↛ 2852line 2851 didn't jump to line 2852 because the condition on line 2851 was never true
2852 continue
2853 seen_in_type.add(comp.name)
2854 if comp.name not in field_map:
2855 field_map[comp.name] = {
2856 "component": comp,
2857 "n_typ": comp.n_typ,
2858 "count": 1,
2859 "total": len(members),
2860 "optional_in_any": comp.optional,
2861 }
2862 else:
2863 info = field_map[comp.name]
2864 info["count"] += 1
2865 # Type identity (is) is correct here:
2866 # non-union type objects are structural
2867 # singletons in the symbol table, so
2868 # identity comparison is both correct and
2869 # cheap.
2870 if info["n_typ"] is not comp.n_typ:
2871 info["n_typ"] = None # type conflict
2872 if comp.optional: 2872 ↛ 2873line 2872 didn't jump to line 2873 because the condition on line 2872 was never true
2873 info["optional_in_any"] = True
2875 self._field_map = field_map
2876 return self._field_map
2878 def dump(self, indent=0): # pragma: no cover
2879 # lobster-exclude: Debugging feature
2880 self.write_indent(indent, "Union_Type")
2881 for t in self.types:
2882 self.write_indent(indent + 1, t.name)
2884 def perform_type_checks(self, mh, value, gstab):
2885 # Union types have no checks of their own; type validation
2886 # happens in Record_Reference.resolve_references() via
2887 # is_compatible(). Returning True unconditionally is
2888 # intentional.
2889 assert isinstance(mh, Message_Handler)
2890 assert isinstance(value, Expression)
2891 assert isinstance(gstab, Symbol_Table)
2892 return True
2894 def is_compatible(self, record_type):
2895 """Test if the given record type is accepted by this union.
2897 :param record_type: type to check
2898 :type record_type: Record_Type
2900 :returns: true if the type is or extends one of the union members
2901 :rtype: bool
2902 """
2903 if not isinstance(record_type, Record_Type): 2903 ↛ 2904line 2903 didn't jump to line 2904 because the condition on line 2903 was never true
2904 return False
2905 return any(record_type.is_subclass_of(t) for t in self.record_members())
2907 def get_example_value(self):
2908 # lobster-exclude: utility method
2909 if not self.types:
2910 return "record_instance"
2911 return "%s_instance" % self.types[0].name
2914class Builtin_Integer(Builtin_Numeric_Type):
2915 # lobster-trace: LRM.Builtin_Types
2916 # lobster-trace: LRM.Integer_Values
2917 """Builtin integer type."""
2919 def __init__(self):
2920 super().__init__("Integer")
2922 def get_example_value(self):
2923 # lobster-exclude: utility method
2924 return "100"
2927class Builtin_Decimal(Builtin_Numeric_Type):
2928 # lobster-trace: LRM.Builtin_Types
2929 # lobster-trace: LRM.Decimal_Values
2930 """Builtin decimal type."""
2932 def __init__(self):
2933 super().__init__("Decimal")
2935 def get_example_value(self):
2936 # lobster-exclude: utility method
2937 return "3.14"
2940class Builtin_Boolean(Builtin_Type):
2941 # lobster-trace: LRM.Builtin_Types
2942 # lobster-trace: LRM.Boolean_Values
2943 """Builtin boolean type."""
2945 def __init__(self):
2946 super().__init__("Boolean")
2948 def get_example_value(self):
2949 # lobster-exclude: utility method
2950 return "true"
2953class Builtin_String(Builtin_Type):
2954 # lobster-trace: LRM.Builtin_Types
2955 # lobster-trace: LRM.String_Values
2956 """Builtin string type."""
2958 def __init__(self):
2959 super().__init__("String")
2961 def get_example_value(self):
2962 # lobster-exclude: utility method
2963 return '"potato"'
2966class Builtin_Markup_String(Builtin_String):
2967 # lobster-trace: LRM.Builtin_Types
2968 # lobster-trace: LRM.Markup_String_Values
2969 """Builtin string type that allows checked references to TRLC
2970 objects.
2971 """
2973 def __init__(self):
2974 super().__init__()
2975 self.name = "Markup_String"
2977 def get_example_value(self):
2978 # lobster-exclude: utility method
2979 return '"also see [[potato]]"'
2982class Package(Entity):
2983 """Packages.
2985 A package is declared when it is first encountered (in either a
2986 rsl or trlc file). A package contains all symbols declared in it,
2987 both types and record objects. A package is not associated with
2988 just a single file, it can be spread over multiple files.
2990 :attribute declared_late: indicates if this package is declared in a \
2991 trlc file
2992 :type: bool
2994 :attribute symbols: symbol table of the package
2995 :type: Symbol_Table
2997 :attribute sub_packages: direct child packages of this package
2998 :type: Symbol_Table
3000 :attribute parent: the parent package, or None for top-level packages
3001 :type: Package
3003 """
3005 def __init__(self, name, location, builtin_stab, declared_late):
3006 # lobster-exclude: Constructor only declares variables
3007 super().__init__(name, location)
3008 assert isinstance(builtin_stab, Symbol_Table)
3009 assert isinstance(declared_late, bool)
3010 self.symbols = Symbol_Table()
3011 self.symbols.make_visible(builtin_stab)
3012 self.declared_late = declared_late
3013 self.sub_packages = Symbol_Table()
3014 self.parent = None
3016 def dump(self, indent=0): # pragma: no cover
3017 # lobster-exclude: Debugging feature
3018 self.write_indent(indent, f"Package {self.name}")
3019 self.write_indent(indent + 1, f"Declared_Late: {self.declared_late}")
3020 self.symbols.dump(indent + 1, omit_heading=True)
3022 def __repr__(self):
3023 return "%s<%s>" % (self.__class__.__name__, self.name)
3026class Composite_Type(Concrete_Type, metaclass=ABCMeta):
3027 """Abstract base for record and tuple types, as they share some
3028 functionality.
3030 :attribute components: type components (including inherited if applicable)
3031 :type: Symbol_Table[Composite_Component]
3033 :attribute description: user-supplied description of the type or None
3034 :type: str
3036 :attribute checks: user-defined checks for this type (excluding \
3037 inherited checks)
3038 :type: list[Check]
3040 """
3042 def __init__(self, name, description, location, package, inherited_symbols=None):
3043 # lobster-trace: LRM.Described_Name_Description
3044 super().__init__(name, location, package)
3045 assert isinstance(description, str) or description is None
3046 assert isinstance(inherited_symbols, Symbol_Table) or inherited_symbols is None
3048 self.components = Symbol_Table(inherited_symbols)
3049 self.description = description
3050 self.checks = []
3052 def add_check(self, n_check):
3053 # lobster-trace: LRM.Check_Evaluation_Order
3054 assert isinstance(n_check, Check)
3055 self.checks.append(n_check)
3057 def iter_checks(self):
3058 # lobster-trace: LRM.Check_Evaluation_Order
3059 yield from self.checks
3061 def all_components(self):
3062 # lobster-exclude: Convenience function
3063 """Convenience function to get a list of all components.
3065 :rtype: list[Composite_Component]
3066 """
3067 return list(self.components.table.values())
3070class Composite_Component(Typed_Entity):
3071 """Component in a record or tuple.
3073 When declaring a composite type, for each component an entity is
3074 declared::
3076 type|tuple T {
3077 foo "blah" optional Boolean
3078 ^1 ^2 ^3 ^4
3080 :attribute description: optional text (see 2) for this component, or None
3081 :type: str
3083 :attribute member_of: a link back to the containing record or tuple; \
3084 for inherited fields this refers back to the original base record type
3085 :type: Composite_Type
3087 :attribute optional: indicates if the component can be null or not (see 3)
3088 :type: bool
3090 """
3092 def __init__(self, name, description, location, member_of, n_typ, optional):
3093 # lobster-trace: LRM.Described_Name_Description
3094 super().__init__(name, location, n_typ)
3095 assert isinstance(description, str) or description is None
3096 assert isinstance(member_of, Composite_Type)
3097 assert isinstance(optional, bool)
3098 self.description = description
3099 self.member_of = member_of
3100 self.optional = optional
3102 def dump(self, indent=0): # pragma: no cover
3103 # lobster-exclude: Debugging feature
3104 self.write_indent(indent, f"Composite_Component {self.name}")
3105 if self.description:
3106 self.write_indent(indent + 1, f"Description: {self.description}")
3107 self.write_indent(indent + 1, f"Optional: {self.optional}")
3108 self.write_indent(indent + 1, f"Type: {self.n_typ.name}")
3110 def __repr__(self):
3111 return "%s<%s>" % (
3112 self.__class__.__name__,
3113 self.member_of.fully_qualified_name() + "." + self.name,
3114 )
3117class Record_Type(Composite_Type):
3118 """A user-defined record type.
3120 In this example::
3122 type T "optional description of T" extends Root_T {
3123 ^1 ^2 ^3
3125 Note that (1) is part of the :class:`Entity` base, and (2) is part
3126 of the :class:`Composite_Type` base.
3128 :attribute parent: root type or None, indicated by (3) above
3129 :type: Record_Type
3131 :attribute frozen: mapping of frozen components
3132 :type: dict[str, Expression]
3134 :attribute is_final: type is final (i.e. no new components may be declared)
3135 :type: bool
3137 :attribute is_abstract: type is abstract
3138 :type: bool
3140 """
3142 def __init__(self, name, description, location, package, n_parent, is_abstract):
3143 # lobster-exclude: Constructor only declares variables
3144 assert isinstance(n_parent, Record_Type) or n_parent is None
3145 assert isinstance(is_abstract, bool)
3146 super().__init__(
3147 name,
3148 description,
3149 location,
3150 package,
3151 n_parent.components if n_parent else None,
3152 )
3153 self.parent = n_parent
3154 self.frozen = {}
3155 self.is_final = n_parent.is_final if n_parent else False
3156 self.is_abstract = is_abstract
3158 def iter_checks(self):
3159 # lobster-trace: LRM.Check_Evaluation_Order
3160 # lobster-trace: LRM.Check_Evaluation_Order_For_Extensions
3161 if self.parent:
3162 yield from self.parent.iter_checks()
3163 yield from self.checks
3165 def dump(self, indent=0): # pragma: no cover
3166 # lobster-exclude: Debugging feature
3167 self.write_indent(indent, f"Record_Type {self.name}")
3168 if self.description:
3169 self.write_indent(indent + 1, f"Description: {self.description}")
3170 if self.parent:
3171 self.write_indent(indent + 1, f"Parent: {self.parent.name}")
3172 self.components.dump(indent + 1, omit_heading=True)
3173 if self.checks:
3174 self.write_indent(indent + 1, "Checks")
3175 for n_check in self.checks:
3176 n_check.dump(indent + 2)
3177 else:
3178 self.write_indent(indent + 1, "Checks: None")
3180 def all_components(self):
3181 """Convenience function to get a list of all components.
3183 :rtype: list[Composite_Component]
3184 """
3185 if self.parent:
3186 return self.parent.all_components() + list(self.components.table.values())
3187 else:
3188 return list(self.components.table.values())
3190 def is_subclass_of(self, record_type):
3191 """Checks if this record type is or inherits from the given type
3193 :param record_type: check if are or extend this type
3194 :type record_type: Record_Type
3196 :returns: true if we are or extend the given type
3197 :rtype: Boolean
3198 """
3199 assert isinstance(record_type, Record_Type)
3201 ptr = self
3202 while ptr:
3203 if ptr is record_type:
3204 return True
3205 else:
3206 ptr = ptr.parent
3207 return False
3209 def is_frozen(self, n_component):
3210 """Test if the given component is frozen.
3212 :param n_component: a composite component of this record type \
3213 (or any of its parents)
3214 :type n_component: Composite_Component
3216 :rtype: bool
3217 """
3218 assert isinstance(n_component, Composite_Component)
3219 if n_component.name in self.frozen:
3220 return True
3221 elif self.parent:
3222 return self.parent.is_frozen(n_component)
3223 else:
3224 return False
3226 def get_freezing_expression(self, n_component):
3227 """Retrieve the frozen value for a frozen component
3229 It is an internal compiler error to call this method with a
3230 component that his not frozen.
3232 :param n_component: a frozen component of this record type \
3233 (or any of its parents)
3234 :type n_component: Composite_Component
3236 :rtype: Expression
3238 """
3239 assert isinstance(n_component, Composite_Component)
3240 if n_component.name in self.frozen: 3240 ↛ 3242line 3240 didn't jump to line 3242 because the condition on line 3240 was always true
3241 return self.frozen[n_component.name]
3242 elif self.parent:
3243 return self.parent.get_freezing_expression(n_component)
3244 else:
3245 assert False
3247 def get_example_value(self):
3248 # lobster-exclude: utility method
3249 return "%s_instance" % self.name
3252class Tuple_Type(Composite_Type):
3253 """A user-defined tuple type.
3255 In this example::
3257 tuple T "optional description of T" {
3258 ^1 ^2
3260 Note that (1) is part of the :class:`Entity` base, and (2) is part
3261 of the :class:`Composite_Type` base.
3263 :attribute separators: list of syntactic separators.
3264 :type: list[Separator]
3266 Note the list of separators will either be empty, or there will be
3267 precisely one less separator than components.
3269 """
3271 def __init__(self, name, description, location, package):
3272 # lobster-trace: LRM.Tuple_Declaration
3273 super().__init__(name, description, location, package)
3274 self.separators = []
3276 def add_separator(self, n_separator):
3277 # lobster-exclude: utility method
3278 assert isinstance(n_separator, Separator)
3279 assert len(self.separators) + 1 == len(self.components.table)
3280 self.separators.append(n_separator)
3282 def iter_separators(self):
3283 """Iterate over all separators"""
3284 # lobster-exclude: utility method
3285 yield from self.separators
3287 def iter_sequence(self):
3288 """Iterate over all components and separators in syntactic order"""
3289 # lobster-exclude: utility method
3290 if self.separators:
3291 for i, n_component in enumerate(self.components.table.values()):
3292 yield n_component
3293 if i < len(self.separators):
3294 yield self.separators[i]
3295 else:
3296 yield from self.components.table.values()
3298 def has_separators(self):
3299 """Returns true if a tuple type requires separators"""
3300 # lobster-exclude: utility method
3301 return bool(self.separators)
3303 def dump(self, indent=0): # pragma: no cover
3304 # lobster-exclude: Debugging feature
3305 self.write_indent(indent, f"Tuple_Type {self.name}")
3306 if self.description:
3307 self.write_indent(indent + 1, f"Description: {self.description}")
3308 self.write_indent(indent + 1, "Fields")
3309 for n_item in self.iter_sequence():
3310 n_item.dump(indent + 2)
3311 if self.checks:
3312 self.write_indent(indent + 1, "Checks")
3313 for n_check in self.checks:
3314 n_check.dump(indent + 2)
3315 else:
3316 self.write_indent(indent + 1, "Checks: None")
3318 def perform_type_checks(self, mh, value, gstab):
3319 # lobster-trace: LRM.Check_Evaluation_Order
3320 assert isinstance(mh, Message_Handler)
3321 assert isinstance(gstab, Symbol_Table)
3323 if isinstance(value, Tuple_Aggregate): 3323 ↛ 3330line 3323 didn't jump to line 3330 because the condition on line 3323 was always true
3324 ok = True
3325 for check in self.iter_checks():
3326 if not check.perform(mh, value, gstab):
3327 ok = False
3328 return ok
3329 else:
3330 assert isinstance(value, Implicit_Null)
3331 return True
3333 def get_example_value(self):
3334 # lobster-exclude: utility method
3335 parts = []
3336 for n_item in self.iter_sequence():
3337 if isinstance(n_item, Composite_Component):
3338 parts.append(n_item.n_typ.get_example_value())
3339 else:
3340 parts.append(n_item.to_string())
3341 if self.has_separators():
3342 return " ".join(parts)
3343 else:
3344 return "(%s)" % ", ".join(parts)
3347class Separator(Node):
3348 # lobster-trace: LRM.Tuple_Declaration
3349 """User-defined syntactic separator
3351 For example::
3353 separator x
3354 ^1
3356 :attribute token: token used to separate fields of the tuple
3357 :type: Token
3358 """
3360 def __init__(self, token):
3361 super().__init__(token.location)
3362 assert isinstance(token, Token) and token.kind in (
3363 "IDENTIFIER",
3364 "AT",
3365 "COLON",
3366 "SEMICOLON",
3367 )
3368 self.token = token
3370 def to_string(self):
3371 return {"AT": "@", "COLON": ":", "SEMICOLON": ";"}.get(
3372 self.token.kind, self.token.value
3373 )
3375 def dump(self, indent=0): # pragma: no cover
3376 self.write_indent(indent, f"Separator {self.token.value}")
3379class Enumeration_Type(Concrete_Type):
3380 """User-defined enumeration types.
3382 For example::
3384 enum T "potato" {
3385 ^1 ^2
3387 :attribute description: user supplied optional description, or None
3388 :type: str
3390 :attribute literals: the literals in this enumeration
3391 :type: Symbol_Table[Enumeration_Literal_Spec]
3393 """
3395 def __init__(self, name, description, location, package):
3396 # lobster-trace: LRM.Described_Name_Description
3397 super().__init__(name, location, package)
3398 assert isinstance(description, str) or description is None
3399 self.literals = Symbol_Table()
3400 self.description = description
3402 def dump(self, indent=0): # pragma: no cover
3403 # lobster-exclude: Debugging feature
3404 self.write_indent(indent, f"Enumeration_Type {self.name}")
3405 if self.description:
3406 self.write_indent(indent + 1, f"Description: {self.description}")
3407 self.literals.dump(indent + 1, omit_heading=True)
3409 def get_example_value(self):
3410 # lobster-exclude: utility method
3411 options = list(self.literals.values())
3412 if options:
3413 choice = len(options) // 2
3414 return self.name + "." + choice.name
3415 else:
3416 return "ERROR"
3419class Enumeration_Literal_Spec(Typed_Entity):
3420 """Declared literal in an enumeration declaration.
3422 Note that for literals mentioned later in record object
3423 declarations, we use :class:`Enumeration_Literal`. Literal specs
3424 are used here::
3426 enum ASIL {
3427 QM "not safety related"
3428 ^1 ^2
3430 :attribute description: the optional user-supplied description, or None
3431 :type: str
3433 """
3435 def __init__(self, name, description, location, enum):
3436 # lobster-trace: LRM.Described_Name_Description
3437 super().__init__(name, location, enum)
3438 assert isinstance(description, str) or description is None
3439 assert isinstance(enum, Enumeration_Type)
3440 self.description = description
3442 def dump(self, indent=0): # pragma: no cover
3443 # lobster-exclude: Debugging feature
3444 self.write_indent(indent, f"Enumeration_Literal_Spec {self.name}")
3445 if self.description:
3446 self.write_indent(indent + 1, f"Description: {self.description}")
3449class Record_Object(Typed_Entity):
3450 """A declared instance of a record type.
3452 This is going to be the bulk of all entities created by TRLC::
3454 section "Potato" {
3455 ^5
3456 Requirement PotatoReq {
3457 ^1 ^2
3458 component1 = 42
3459 ^3 ^4
3461 Note that the name (see 2) and type (see 1) of the object is
3462 provided by the name attribute of the :class:`Typed_Entity` base
3463 class.
3465 :attribute field: the specific values for all components (see 3 and 4)
3466 :type: dict[str, Expression]
3468 :attribute section: None or the section this record is contained in (see 5)
3469 :type: Section
3471 :attribute n_package: The package in which this record is declared in
3472 :type: Section
3474 The actual type of expressions in the field attribute are limited
3475 to:
3477 * :class:`Literal`
3478 * :class:`Unary_Expression`
3479 * :class:`Array_Aggregate`
3480 * :class:`Tuple_Aggregate`
3481 * :class:`Record_Reference`
3482 * :class:`Implicit_Null`
3484 """
3486 def __init__(self, name, location, n_typ, section, n_package):
3487 # lobster-trace: LRM.Section_Declaration
3488 # lobster-trace: LRM.Unspecified_Optional_Components
3489 # lobster-trace: LRM.Record_Object_Declaration
3491 assert isinstance(n_typ, Record_Type)
3492 assert isinstance(section, list) or section is None
3493 assert isinstance(n_package, Package)
3494 super().__init__(name, location, n_typ)
3495 self.field = {
3496 comp.name: Implicit_Null(self, comp) for comp in self.n_typ.all_components()
3497 }
3498 self.section = section
3499 self.n_package = n_package
3501 def fully_qualified_name(self):
3502 """Return the FQN for this type (i.e. PACKAGE.NAME)
3504 :returns: the object's full name
3505 :rtype: str
3506 """
3507 return self.n_package.name + "." + self.name
3509 def to_python_dict(self):
3510 """Return an evaluated and simplified object for Python.
3512 For example it might provide::
3514 {"foo" : [1, 2, 3],
3515 "bar" : None,
3516 "baz" : "value"}
3518 This is a function especially designed for the Python API. The
3519 name of the object itself is not in this returned dictionary.
3521 """
3522 return {name: value.to_python_object() for name, value in self.field.items()}
3524 def is_component_implicit_null(self, component) -> bool:
3525 return not isinstance(self.field[component.name], Implicit_Null)
3527 def assign(self, component, value):
3528 assert isinstance(component, Composite_Component)
3529 assert isinstance(
3530 value,
3531 (
3532 Literal,
3533 Array_Aggregate,
3534 Tuple_Aggregate,
3535 Record_Reference,
3536 Implicit_Null,
3537 Unary_Expression,
3538 ),
3539 ), "value is %s" % value.__class__.__name__
3540 if self.is_component_implicit_null(component): 3540 ↛ 3541line 3540 didn't jump to line 3541 because the condition on line 3540 was never true
3541 raise KeyError(
3542 f"Component {component.name} already \
3543 assigned to {self.n_typ.name} {self.name}!"
3544 )
3545 self.field[component.name] = value
3547 def dump(self, indent=0): # pragma: no cover
3548 # lobster-exclude: Debugging feature
3549 self.write_indent(indent, f"Record_Object {self.name}")
3550 self.write_indent(indent + 1, f"Type: {self.n_typ.name}")
3551 for key, value in self.field.items():
3552 self.write_indent(indent + 1, f"Field {key}")
3553 value.dump(indent + 2)
3554 if self.section:
3555 self.section[-1].dump(indent + 1)
3557 def resolve_references(self, mh):
3558 assert isinstance(mh, Message_Handler)
3559 for val in self.field.values():
3560 val.resolve_references(mh)
3562 def perform_checks(self, mh, gstab):
3563 # lobster-trace: LRM.Check_Evaluation_Order
3564 # lobster-trace: LRM.Evaluation_Of_Checks
3565 assert isinstance(mh, Message_Handler)
3566 assert isinstance(gstab, Symbol_Table)
3568 ok = True
3570 # First evaluate all tuple checks
3571 for n_comp in self.n_typ.all_components():
3572 if not n_comp.n_typ.perform_type_checks(mh, self.field[n_comp.name], gstab):
3573 ok = False
3575 # TODO: Is there a bug here (a check relies on a tuple check)?
3577 # Then evaluate all record checks
3578 for check in self.n_typ.iter_checks():
3579 # Prints messages, if applicable. Raises exception on
3580 # fatal checks, which causes this to abort.
3581 if not check.perform(mh, self, gstab):
3582 ok = False
3584 return ok
3586 def __repr__(self):
3587 return "%s<%s>" % (
3588 self.__class__.__name__,
3589 self.n_package.name + "." + self.n_typ.name + "." + self.name,
3590 )
3593class Section(Entity):
3594 # lobster-trace: LRM.Section_Declaration
3595 """A section for readability
3597 This represents a section construct in TRLC files to group record
3598 objects together::
3600 section "Foo" {
3601 ^^^^^ parent section
3602 section "Bar" {
3603 ^^^^^ section
3605 :attribute parent: the parent section or None
3606 :type: Section
3608 """
3610 def __init__(self, name, location, parent):
3611 super().__init__(name, location)
3612 assert isinstance(parent, Section) or parent is None
3613 self.parent = parent
3615 def dump(self, indent=0): # pragma: no cover
3616 self.write_indent(indent, f"Section {self.name}")
3617 if self.parent is None:
3618 self.write_indent(indent + 1, "Parent: None")
3619 else:
3620 self.write_indent(indent + 1, f"Parent: {self.parent.name}")
3623##############################################################################
3624# Symbol Table & Scopes
3625##############################################################################
3628class Symbol_Table:
3629 """Symbol table mapping names to entities"""
3631 def __init__(self, parent=None):
3632 # lobster-exclude: Constructor only declares variables
3633 assert isinstance(parent, Symbol_Table) or parent is None
3634 self.parent = parent
3635 self.imported = []
3636 self.table = OrderedDict()
3637 self.trlc_files = []
3638 self.section_names = []
3640 @staticmethod
3641 def simplified_name(name):
3642 # lobster-trace: LRM.Sufficiently_Distinct
3643 assert isinstance(name, str)
3644 return name.lower().replace("_", "")
3646 def all_names(self):
3647 # lobster-exclude: API for users
3648 """All names in the symbol table
3650 :rtype: set[str]
3651 """
3652 rv = set(item.name for item in self.table.values())
3653 if self.parent:
3654 rv |= self.parent.all_names()
3655 return rv
3657 def iter_record_objects_by_section(self):
3658 """API for users
3660 Retriving information about the section hierarchy for record objects
3661 Inputs: folder with trlc files where trlc files have sections,
3662 sub sections and record objects
3663 Output: Information about sections and level of sections,
3664 record objects and levels of record object
3665 """
3666 for record_object in self.iter_record_objects():
3667 location = record_object.location.file_name
3668 if location not in self.trlc_files: 3668 ↛ 3671line 3668 didn't jump to line 3671 because the condition on line 3668 was always true
3669 self.trlc_files.append(location)
3670 yield location
3671 if record_object.section:
3672 object_level = len(record_object.section) - 1
3673 for level, section in enumerate(record_object.section):
3674 if section not in self.section_names: 3674 ↛ 3673line 3674 didn't jump to line 3673 because the condition on line 3674 was always true
3675 self.section_names.append(section)
3676 yield section.name, level
3677 yield record_object, object_level
3678 else:
3679 object_level = 0
3680 yield record_object, object_level
3682 def iter_record_objects(self):
3683 # lobster-exclude: API for users
3684 """Iterate over all record objects
3686 :rtype: iterable[Record_Object]
3687 """
3688 for item in self.table.values():
3689 if isinstance(item, Package):
3690 yield from item.symbols.iter_record_objects()
3692 elif isinstance(item, Record_Object):
3693 yield item
3695 def values(self, subtype=None):
3696 # lobster-exclude: API for users
3697 assert subtype is None or isinstance(subtype, type)
3698 if self.parent:
3699 yield from self.parent.values(subtype)
3700 for name in sorted(self.table):
3701 if subtype is None or isinstance(self.table[name], subtype):
3702 yield self.table[name]
3704 def make_visible(self, stab):
3705 assert isinstance(stab, Symbol_Table)
3706 self.imported.append(stab)
3708 def register(self, mh, entity):
3709 # lobster-trace: LRM.Duplicate_Types
3710 # lobster-trace: LRM.Unique_Enumeration_Literals
3711 # lobster-trace: LRM.Tuple_Unique_Field_Names
3712 # lobster-trace: LRM.Sufficiently_Distinct
3713 # lobster-trace: LRM.Unique_Object_Names
3715 assert isinstance(mh, Message_Handler)
3716 assert isinstance(entity, Entity)
3718 simple_name = self.simplified_name(entity.name)
3720 if self.contains_raw(simple_name):
3721 pdef = self.lookup_direct(mh, entity.name, entity.location, simplified=True)
3722 if pdef.name == entity.name:
3723 mh.error(
3724 entity.location,
3725 "duplicate definition, previous definition at %s"
3726 % mh.cross_file_reference(pdef.location),
3727 )
3728 else:
3729 mh.error(
3730 entity.location,
3731 "%s is too similar to %s, declared at %s"
3732 % (entity.name, pdef.name, mh.cross_file_reference(pdef.location)),
3733 )
3735 else:
3736 self.table[simple_name] = entity
3738 def register_with_key(self, mh, entity, key_name):
3739 """Register an entity under a different key name (leaf name).
3741 Used to register nested packages in their parent's ``sub_packages``
3742 table keyed by their leaf segment rather than their full name.
3744 :param mh: The message handler to use
3745 :type mh: Message_Handler
3747 :param entity: the entity to register
3748 :type entity: Entity
3750 :param key_name: the name to use as the lookup key
3751 :type key_name: str
3752 """
3753 # lobster-trace: LRM.Sufficiently_Distinct
3754 assert isinstance(mh, Message_Handler)
3755 assert isinstance(entity, Entity)
3756 assert isinstance(key_name, str)
3758 simple_key = self.simplified_name(key_name)
3760 if simple_key in self.table:
3761 existing = self.table[simple_key]
3762 if existing.name == entity.name: 3762 ↛ 3771line 3762 didn't jump to line 3771 because the condition on line 3762 was always true
3763 mh.error(
3764 entity.location,
3765 "duplicate definition, previous definition at %s"
3766 % mh.cross_file_reference(existing.location),
3767 explanation="rename or remove one of the two "
3768 "declarations so each sub-package has a unique name",
3769 )
3770 else:
3771 mh.error(
3772 entity.location,
3773 "%s is too similar to %s, declared at %s"
3774 % (
3775 entity.name,
3776 existing.name,
3777 mh.cross_file_reference(existing.location),
3778 ),
3779 explanation="package names must be sufficiently "
3780 "distinct (case and underscores are ignored); "
3781 "rename one of the two packages",
3782 )
3783 else:
3784 self.table[simple_key] = entity
3786 def lookup_sub_package(self, segment):
3787 """Look up a direct child package by its leaf segment name.
3789 Used for traversing the nested package hierarchy, where the table
3790 key is the simplified leaf segment but the entity name is the full
3791 dotted package name.
3793 :param segment: the leaf name to look for (e.g. ``"bar"`` for \
3794 ``foo.bar``)
3795 :type segment: str
3797 :returns: the child Package, or None if not found
3798 :rtype: Package or None
3799 """
3800 assert isinstance(segment, str)
3801 simple_key = self.simplified_name(segment)
3802 if simple_key in self.table:
3803 entity = self.table[simple_key]
3804 if isinstance(entity, Package): 3804 ↛ 3806line 3804 didn't jump to line 3806 because the condition on line 3804 was always true
3805 return entity
3806 return None
3808 def __contains__(self, name):
3809 # lobster-trace: LRM.Described_Name_Equality
3810 return self.contains(name)
3812 def contains_raw(self, simple_name, precise_name=None):
3813 # lobster-trace: LRM.Described_Name_Equality
3814 # lobster-trace: LRM.Sufficiently_Distinct
3815 #
3816 # Internal function to test if the simplified name is in the
3817 # table.
3818 assert isinstance(simple_name, str)
3819 assert isinstance(precise_name, str) or precise_name is None
3821 if simple_name in self.table:
3822 # No need to continue searching since registering a
3823 # clashing name would have been stopped
3824 return precise_name is None or self.table[simple_name].name == precise_name
3826 elif self.parent:
3827 return self.parent.contains_raw(simple_name, precise_name)
3829 for stab in self.imported:
3830 if stab.contains_raw(simple_name, precise_name):
3831 return True
3833 return False
3835 def contains(self, name):
3836 # lobster-trace: LRM.Described_Name_Equality
3837 """Tests if the given name is in the table
3839 :param name: the name to test
3840 :type name: str
3842 :rtype: bool
3843 """
3844 assert isinstance(name, str)
3845 return self.contains_raw(self.simplified_name(name), name)
3847 def lookup_assuming(self, mh, name, required_subclass=None):
3848 # lobster-trace: LRM.Described_Name_Equality
3849 # lobster-trace: LRM.Sufficiently_Distinct
3850 """Retrieve an object from the table assuming its there
3852 This is intended for the API specifically where you want to
3853 e.g. find some user-defined types you know are there.
3855 :param mh: The message handler to use
3856 :type mh: Message_Handler
3858 :param name: The name to search for
3859 :type name: str
3861 :param required_subclass: If set, creates an error if the object \
3862 is not an instance of the given class
3863 :type required_subclass: type
3865 :raise TRLC_Error: if the object is not of the required subclass
3866 :returns: the specified entity (or None if it does not exist)
3867 :rtype: Entity
3869 """
3870 assert isinstance(mh, Message_Handler)
3871 assert isinstance(name, str)
3872 assert isinstance(required_subclass, type) or required_subclass is None
3874 simple_name = self.simplified_name(name)
3876 ptr = self
3877 for ptr in [self] + self.imported:
3878 while ptr:
3879 if simple_name in ptr.table:
3880 rv = ptr.table[simple_name]
3881 if rv.name != name:
3882 return None
3884 if required_subclass is not None and not isinstance( 3884 ↛ 3887line 3884 didn't jump to line 3887 because the condition on line 3884 was never true
3885 rv, required_subclass
3886 ):
3887 mh.error(
3888 rv.location,
3889 "%s %s is not a %s"
3890 % (rv.__class__.__name__, name, required_subclass.__name__),
3891 )
3892 return rv
3893 else:
3894 ptr = ptr.parent
3896 return None
3898 def lookup_direct(
3899 self, mh, name, error_location, required_subclass=None, simplified=False
3900 ):
3901 # lobster-trace: LRM.Described_Name_Equality
3902 # lobster-trace: LRM.Sufficiently_Distinct
3903 # lobster-trace: LRM.Valid_Base_Names
3904 # lobster-trace: LRM.Valid_Access_Prefixes
3905 # lobster-trace: LRM.Valid_Function_Prefixes
3906 """Retrieve an object from the table
3908 For example::
3910 pkg = stab.lookup_direct(mh,
3911 "potato",
3912 Location("foobar.txt", 42),
3913 Package)
3915 This would search for an object named ``potato``. If it is
3916 found, and it is a package, it is returned. If it is not a
3917 Package, then the following error is issued::
3919 foobar.txt:42: error: Enumeration_Type potato is not a Package
3921 If it is not found at all, then the following error is issued::
3923 foobar.txt:42: error: unknown symbol potato
3925 :param mh: The message handler to use
3926 :type mh: Message_Handler
3928 :param name: The name to search for
3929 :type name: str
3931 :param error_location: Where to create the error if the name is \
3932 not found
3933 :type error_location: Location
3935 :param required_subclass: If set, creates an error if the object \
3936 is not an instance of the given class
3937 :type required_subclass: type
3939 :param simplified: If set, look up the given simplified name instead \
3940 of the actual name
3941 :type simplified: bool
3943 :raise TRLC_Error: if the name is not in the table
3944 :raise TRLC_Error: if the object is not of the required subclass
3945 :returns: the specified entity
3946 :rtype: Entity
3948 """
3949 assert isinstance(mh, Message_Handler)
3950 assert isinstance(name, str)
3951 assert isinstance(error_location, Location)
3952 assert isinstance(required_subclass, type) or required_subclass is None
3953 assert isinstance(simplified, bool)
3955 simple_name = self.simplified_name(name)
3956 ptr = self
3957 options = []
3959 for ptr in [self] + self.imported:
3960 while ptr:
3961 if simple_name in ptr.table:
3962 rv = ptr.table[simple_name]
3963 if not simplified and rv.name != name: 3963 ↛ 3964line 3963 didn't jump to line 3964 because the condition on line 3963 was never true
3964 mh.error(
3965 error_location,
3966 "unknown symbol %s, did you mean %s?" % (name, rv.name),
3967 )
3969 if required_subclass is not None and not isinstance(
3970 rv, required_subclass
3971 ):
3972 mh.error(
3973 error_location,
3974 "%s %s is not a %s"
3975 % (rv.__class__.__name__, name, required_subclass.__name__),
3976 )
3977 return rv
3978 else:
3979 options += list(item.name for item in ptr.table.values())
3980 ptr = ptr.parent
3982 matches = get_close_matches(word=name, possibilities=options, n=1)
3984 if matches:
3985 mh.error(
3986 error_location,
3987 "unknown symbol %s, did you mean %s?" % (name, matches[0]),
3988 )
3989 else:
3990 mh.error(error_location, "unknown symbol %s" % name)
3992 def lookup(self, mh, referencing_token, required_subclass=None):
3993 # lobster-trace: LRM.Described_Name_Equality
3994 assert isinstance(mh, Message_Handler)
3995 assert isinstance(referencing_token, Token)
3996 assert referencing_token.kind in ("IDENTIFIER", "BUILTIN")
3997 assert isinstance(required_subclass, type) or required_subclass is None
3999 return self.lookup_direct(
4000 mh=mh,
4001 name=referencing_token.value,
4002 error_location=referencing_token.location,
4003 required_subclass=required_subclass,
4004 )
4006 def write_indent(self, indent, message): # pragma: no cover
4007 # lobster-exclude: Debugging feature
4008 assert isinstance(indent, int)
4009 assert indent >= 0
4010 assert isinstance(message, str)
4011 print(" " * (3 * indent) + message)
4013 def dump(self, indent=0, omit_heading=False): # pragma: no cover
4014 # lobster-exclude: Debugging feature
4015 if omit_heading:
4016 new_indent = indent
4017 else:
4018 self.write_indent(indent, "Symbol_Table")
4019 new_indent = indent + 1
4020 ptr = self
4021 while ptr:
4022 for name in ptr.table:
4023 ptr.table[name].dump(new_indent)
4024 ptr = ptr.parent
4026 @classmethod
4027 def create_global_table(cls, mh):
4028 # lobster-trace: LRM.Builtin_Types
4029 # lobster-trace: LRM.Builtin_Functions
4030 # lobster-trace: LRM.Builtin_Type_Conversion_Functions
4031 # lobster-trace: LRM.Signature_Len
4032 # lobster-trace: LRM.Signature_String_End_Functions
4033 # lobster-trace: LRM.Signature_Matches
4035 stab = Symbol_Table()
4036 stab.register(mh, Builtin_Integer())
4037 stab.register(mh, Builtin_Decimal())
4038 stab.register(mh, Builtin_Boolean())
4039 stab.register(mh, Builtin_String())
4040 stab.register(mh, Builtin_Markup_String())
4041 stab.register(mh, Builtin_Function("len", 1))
4042 stab.register(mh, Builtin_Function("startswith", 2))
4043 stab.register(mh, Builtin_Function("endswith", 2))
4044 stab.register(mh, Builtin_Function("matches", 2))
4045 stab.register(mh, Builtin_Function("oneof", 1, arity_at_least=True))
4047 return stab
4050class Scope:
4051 def __init__(self):
4052 # lobster-exclude: Constructor only declares variables
4053 self.scope = []
4055 def push(self, stab):
4056 assert isinstance(stab, Symbol_Table)
4057 self.scope.append(stab)
4059 def pop(self):
4060 self.scope.pop()
4062 def contains(self, name):
4063 assert isinstance(name, str)
4065 for stab in reversed(self.scope):
4066 if stab.contains(name):
4067 return True
4068 return False
4070 def lookup(self, mh, referencing_token, required_subclass=None):
4071 assert len(self.scope) >= 1
4072 assert isinstance(mh, Message_Handler)
4073 assert isinstance(referencing_token, Token)
4074 assert referencing_token.kind in ("IDENTIFIER", "BUILTIN")
4075 assert isinstance(required_subclass, type) or required_subclass is None
4077 for stab in reversed(self.scope[1:]):
4078 if stab.contains(referencing_token.value):
4079 return stab.lookup(mh, referencing_token, required_subclass)
4080 return self.scope[0].lookup(mh, referencing_token, required_subclass)
4082 def size(self):
4083 return len(self.scope)