1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.mal_lang.langspec;
18
19 import static java.util.Objects.requireNonNull;
20
21 import jakarta.json.Json;
22 import jakarta.json.JsonObject;
23
24
25
26
27
28
29 public enum Multiplicity {
30
31
32
33
34
35 ZERO_OR_ONE(0, 1),
36
37
38
39
40
41
42 ZERO_OR_MORE(0, Integer.MAX_VALUE),
43
44
45
46
47
48
49 ONE(1, 1),
50
51
52
53
54
55
56 ONE_OR_MORE(1, Integer.MAX_VALUE);
57
58 private final int min;
59 private final int max;
60
61 Multiplicity(int min, int max) {
62 this.min = min;
63 this.max = max;
64 }
65
66
67
68
69
70
71
72 public int getMin() {
73 return this.min;
74 }
75
76
77
78
79
80
81
82 public int getMax() {
83 return this.max;
84 }
85
86 JsonObject toJson() {
87 var jsonMultiplicity = Json.createObjectBuilder().add("min", this.min);
88 if (this.max == Integer.MAX_VALUE) {
89 jsonMultiplicity.addNull("max");
90 } else {
91 jsonMultiplicity.add("max", this.max);
92 }
93 return jsonMultiplicity.build();
94 }
95
96
97
98
99
100
101
102
103
104 public static Multiplicity fromJson(JsonObject jsonMultiplicity) {
105 requireNonNull(jsonMultiplicity);
106 int min = jsonMultiplicity.getInt("min");
107 int max = jsonMultiplicity.isNull("max") ? Integer.MAX_VALUE : jsonMultiplicity.getInt("max");
108 if (min == 0 && max == 1) {
109 return ZERO_OR_ONE;
110 }
111 if (min == 0 && max == Integer.MAX_VALUE) {
112 return ZERO_OR_MORE;
113 }
114 if (min == 1 && max == 1) {
115 return ONE;
116 }
117 if (min == 1 && max == Integer.MAX_VALUE) {
118 return ONE_OR_MORE;
119 }
120 throw new RuntimeException(
121 String.format("Invalid multiplicity {min = %d, max = %d}", min, max));
122 }
123 }