ndarule.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright 2023 Modelling, Simulation and Design Lab (MSDL)
  2. # at the University of Antwerp (http://msdl.uantwerpen.be/).
  3. #
  4. # Licensed under the GNU Public License v3 (the "License");
  5. # you may not use this file except in compliance with the
  6. # License. You may obtain a copy of the License at
  7. # https://www.gnu.org/licenses/gpl-3.0.en.html
  8. #
  9. # Unless required by applicable law or agreed to in writing,
  10. # software distributed under the License is distributed on an
  11. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. # either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the
  14. # License.
  15. from pytcore.tcore.composer import Composer
  16. from pytcore.tcore.matcher import Matcher
  17. from pytcore.tcore.iterator import Iterator
  18. from pytcore.tcore.rewriter import Rewriter
  19. from pytcore.tcore.resolver import Resolver
  20. class NDARule(Composer):
  21. '''
  22. Applies the transformation on one match.
  23. '''
  24. def __init__(self, LHS, RHS, rng, sendAndApplyDeltaFunc,ignore_resolver=False, external_matches_only=False,
  25. custom_resolution=lambda packet: False):
  26. '''
  27. Applies the transformation on one match.
  28. @param LHS: The pre-condition pattern (LHS + NACs).
  29. @param RHS: The post-condition pattern (RHS).
  30. @param ignore_resolver: Specifies whether or not a resolver is needed.
  31. @param external_matches_only: Resolve conflicts ignoring the matches found in this ARule.
  32. @param custom_resolution: Override the default resolution function.
  33. '''
  34. super(NDARule, self).__init__()
  35. self.ignore_resolver = ignore_resolver
  36. self.M = Matcher(condition=LHS)
  37. self.I = Iterator(max_iterations=1, rng=rng)
  38. self.W = Rewriter(condition=RHS,sendAndApplyDeltaFunc=sendAndApplyDeltaFunc)
  39. self.R = Resolver(external_matches_only=external_matches_only,
  40. custom_resolution=custom_resolution)
  41. def packet_in(self, packet):
  42. self.exception = None
  43. self.is_success = False
  44. # Match
  45. packet = self.M.packet_in(packet)
  46. if not self.M.is_success:
  47. self.exception = self.M.exception
  48. return packet
  49. # Choose the only match
  50. packet = self.I.packet_in(packet)
  51. if not self.I.is_success:
  52. self.exception = self.I.exception
  53. return packet
  54. # Rewrite
  55. packet = self.W.packet_in(packet)
  56. if not self.W.is_success:
  57. self.exception = self.W.exception
  58. return packet
  59. # Output success packet
  60. self.is_success = True
  61. return packet