context.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # from dataclasses import *
  2. from typing import *
  3. from sccd.syntax.expression import *
  4. from sccd.util.namespace import *
  5. from sccd.util.duration import *
  6. # @dataclass
  7. class Context:
  8. # max_delta: upper bound on model delta
  9. def __init__(self, fixed_delta: Optional[Duration] = Duration(100, Microsecond)):
  10. self.fixed_delta = fixed_delta
  11. self.events = Namespace()
  12. self.inports = Namespace()
  13. self.outports = Namespace()
  14. self.durations: List[DurationLiteral] = []
  15. # The smallest unit for all durations in the model.
  16. # Calculated after all expressions have been parsed, based on all DurationLiterals.
  17. self.delta: Optional[Duration] = None
  18. # Convert all DurationLiterals to model delta
  19. def _conv(self):
  20. for d in self.durations:
  21. # The following error is impossible: (i think)
  22. # if d.original % self.delta != Duration(0):
  23. # raise Exception("Duration %s cannot be represented by delta %s" % (str(d.original), str(self.delta)))
  24. d.converted = d.original // self.delta
  25. def process_durations(self):
  26. self.delta = gcd(*(d.original for d in self.durations))
  27. # Ensure delta not too big
  28. if self.fixed_delta:
  29. if self.delta < self.fixed_delta:
  30. raise Exception("Model contains duration deltas (smallest = %s) not representable with fixed delta of %s." % (str(self.delta), str(self.fixed_delta)))
  31. else:
  32. self.delta = self.fixed_delta
  33. self._conv()
  34. def assert_ready(self):
  35. if self.delta is None:
  36. raise Exception("Context not ready: durations not yet processed.")