01_constraints.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # We now make our meta-model more interesting by adding a 'price' attribute to B, and constraints to it.
  2. mm_cs = """
  3. # class named 'A':
  4. A:Class
  5. # class named 'B':
  6. B:Class {
  7. constraint = ```
  8. # Price must be less than 100
  9. get_value(get_slot(this, "price")) < 100
  10. ```;
  11. }
  12. # 'B' has an attribute 'price':
  13. B_price:AttributeLink (B -> Integer) {
  14. name = "price";
  15. optional = False;
  16. }
  17. # An association from 'A' to 'B':
  18. a2b:Association (A -> B) {
  19. # Every 'A' must be associated with at least one 'B'
  20. target_lower_cardinality = 1;
  21. }
  22. totalPriceLessThan500:GlobalConstraint {
  23. constraint = ```
  24. total_price = 0;
  25. for b_name, b_id in get_all_instances("B"):
  26. total_price += get_value(get_slot(b_id, "price"))
  27. total_price < 500
  28. ```;
  29. }
  30. """
  31. ####
  32. # Note: The name 'B_price' follows a fixed format: <class_name>_<attribute_name>.
  33. # This format must be followed!
  34. ####
  35. # We update our model to include a price:
  36. m_cs = """
  37. myA:A
  38. myB:B {
  39. price = 1000;
  40. }
  41. myLnk:a2b (myA -> myB)
  42. """
  43. # And do a conformance check:
  44. from state.devstate import DevState
  45. from bootstrap.scd import bootstrap_scd
  46. from concrete_syntax.textual_od import parser
  47. from framework.conformance import Conformance, render_conformance_check_result
  48. state = DevState()
  49. print("Loading meta-meta-model...")
  50. mmm = bootstrap_scd(state)
  51. print("OK")
  52. print()
  53. print("Parsing meta-model...")
  54. mm = parser.parse_od(
  55. state,
  56. m_text=mm_cs, # the string of text to parse
  57. mm=mmm, # the meta-model of class diagrams (= our meta-meta-model)
  58. )
  59. print("OK")
  60. print()
  61. print("Parsing model...")
  62. m = parser.parse_od(
  63. state,
  64. m_text=m_cs,
  65. mm=mm, # this time, the meta-model is the previous model we parsed
  66. )
  67. print("OK")
  68. print()
  69. print("Is our model a valid instance of our meta model?")
  70. conf = Conformance(state, m, mm)
  71. print(render_conformance_check_result(conf.check_nominal()))
  72. # Can you fix the constraint violation?