lrule.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.util.infinity import INFINITY
  16. from pytcore.tcore.composer import Composer
  17. from pytcore.tcore.matcher import Matcher
  18. from pytcore.tcore.iterator import Iterator
  19. class LRule(Composer):
  20. '''
  21. Applies an inner rule for each match of the LHS.
  22. '''
  23. def __init__(self, LHS, inner_rule, max_iterations=INFINITY):
  24. '''
  25. Applies an inner rule for each match of the LHS.
  26. @param LHS: The pre-condition pattern (LHS + NACs).
  27. @param inner_rule: The rule to apply in the loop.
  28. @param max_iterations: The maximum number of matches of the LHS.
  29. '''
  30. super(LRule, self).__init__()
  31. self.M = Matcher(condition=LHS, max=max_iterations)
  32. self.I = Iterator(max_iterations=max_iterations)
  33. self.inner_rule = inner_rule
  34. def packet_in(self, packet):
  35. self.exception = None
  36. self.is_success = False
  37. # Match
  38. packet = self.M.packet_in(packet)
  39. if not self.M.is_success:
  40. self.exception = self.M.exception
  41. return packet
  42. # Choose the first match
  43. packet = self.I.packet_in(packet)
  44. if not self.I.is_success:
  45. self.exception = self.I.exception
  46. return packet
  47. while True:
  48. # Apply the inner rule
  49. packet = self.inner_rule.packet_in(packet)
  50. if not self.inner_rule.is_success:
  51. if self.inner_rule.exception:
  52. self.exception = self.inner_rule.exception
  53. return packet
  54. # Clean the packet: required since there is no Rewriter in a Query
  55. if len(packet.match_sets[self.I.condition].matches) == 0:
  56. del packet.match_sets[self.I.condition]
  57. # Choose another match
  58. packet = self.I.next_in(packet)
  59. # No more iterations are left
  60. if not self.I.is_success:
  61. if self.I.exception:
  62. self.exception = self.I.exception
  63. else:
  64. # Output success packet
  65. self.is_success = True
  66. return packet