resolver.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 rule_primitive import RulePrimitive
  5. from messages import TransformationException
  6. class Resolver(RulePrimitive):
  7. '''
  8. Detects & resolves any conflict between matches and rewritings.
  9. '''
  10. def __init__(self, external_matches_only=False, custom_resolution=lambda packet: False):
  11. '''
  12. Detects & resolves any conflict between matches.
  13. @param external_matches_only: Whether to only check for matches outside the current scope of the resolver.
  14. By default, this is False.
  15. @param custom_resolution: Function that defines how to resolve any conflict
  16. By default, this returns False.
  17. '''
  18. super(Resolver, self).__init__()
  19. self.external_matches_only = external_matches_only
  20. self.custom_resolution = custom_resolution
  21. def packet_in(self, packet):
  22. '''
  23. Attempts to merge the packets into a single one, only if all threads had succeeded.
  24. '''
  25. self.exception = None
  26. self.is_success = False
  27. for cond in packet.match_sets:
  28. # Ignore the current match set when checking for conflicts with external matches only
  29. if self.external_matches_only and cond == packet.current:
  30. continue
  31. for match in packet.match_sets[cond].matches:
  32. if match.is_dirty(packet):
  33. # First try the custom resolution function
  34. if not self._custom_resolution(packet, match):
  35. # Then try the default resolution function
  36. if not self._default_resolution(packet, match):
  37. self.is_success = False
  38. # TODO: This should be an InconsistentUseException
  39. self.exception = TransformationException()
  40. self.exception.packet = packet
  41. self.exception.transformation_unit = self
  42. return packet
  43. # No conflicts are to be reported
  44. self.is_success = True
  45. return packet
  46. def _custom_resolution(self, packet, match):
  47. '''
  48. Applies the user-defined resolution function
  49. '''
  50. return self.custom_resolution(packet)
  51. def _default_resolution(self, packet, match):
  52. '''
  53. Attempts to resolve conservatively any conflicts
  54. '''
  55. return False