arule.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. '''This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. See COPYING.lesser and README.md in the root of this project for full details'''
  4. from tcore.composer import Composer
  5. from tcore.matcher import Matcher
  6. from tcore.iterator import Iterator
  7. from tcore.rewriter import Rewriter
  8. from tcore.resolver import Resolver
  9. class ARule(Composer):
  10. '''
  11. Applies the transformation on one match.
  12. '''
  13. def __init__(self, LHS, RHS,sendAndApplyDeltaFunc):
  14. '''
  15. Applies the transformation on one match.
  16. @param LHS: The pre-condition pattern (LHS + NACs).
  17. @param RHS: The post-condition pattern (RHS).
  18. '''
  19. super(ARule, self).__init__()
  20. self.M = Matcher(condition=LHS, max=1)
  21. self.I = Iterator(max_iterations=1)
  22. self.W = Rewriter(condition=RHS,sendAndApplyDeltaFunc=sendAndApplyDeltaFunc)
  23. def packet_in(self, packet):
  24. self.exception = None
  25. self.is_success = False
  26. # Match
  27. packet = self.M.packet_in(packet)
  28. if not self.M.is_success:
  29. self.exception = self.M.exception
  30. self.M.packet_in(packet)
  31. return packet
  32. # Choose the only match
  33. packet = self.I.packet_in(packet)
  34. if not self.I.is_success:
  35. self.exception = self.I.exception
  36. return packet
  37. # Rewrite
  38. packet = self.W.packet_in(packet)
  39. if not self.W.is_success:
  40. self.exception = self.W.exception
  41. return packet
  42. # Output success packet
  43. self.is_success = True
  44. return packet
  45. class ARule_r(ARule):
  46. '''
  47. Applies the transformation on one match.
  48. '''
  49. def __init__(self, LHS, RHS, external_matches_only=False, custom_resolution=lambda packet: False):
  50. '''
  51. Applies the transformation on one match.
  52. @param LHS: The pre-condition pattern (LHS + NACs).
  53. @param RHS: The post-condition pattern (RHS).
  54. @param external_matches_only: Resolve conflicts ignoring the matches found in this ARule.
  55. @param custom_resolution: Override the default resolution function.
  56. '''
  57. super(ARule_r, self).__init__(LHS, RHS)
  58. self.R = Resolver(external_matches_only=external_matches_only,
  59. custom_resolution=custom_resolution)
  60. def packet_in(self, packet):
  61. packet = super(ARule_r, self).packet_in(packet)
  62. # is_success is True
  63. if self.exception is None:
  64. # Resolve any conflicts if necessary
  65. packet = self.R.packet_in(packet)
  66. if not self.R.is_success:
  67. self.exception = self.R.exception
  68. return packet
  69. # Output success packet
  70. else:
  71. self.is_success = False
  72. return packet