8a10a96cce2e23e5a5e7368dce9d02873e62fd95
[yangtools.git] / yang / yang-parser-spi / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / SubstatementValidator.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.yangtools.yang.parser.spi.meta;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.Maps;
14 import java.util.HashMap;
15 import java.util.Map;
16 import java.util.Map.Entry;
17 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
18 import org.opendaylight.yangtools.yang.parser.spi.ExtensionNamespace;
19 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
20
21 public final class SubstatementValidator {
22     private final Map<StatementDefinition, Cardinality> cardinalityMap;
23     private final Map<StatementDefinition, Cardinality> mandatoryStatements;
24     private final StatementDefinition currentStatement;
25
26     private SubstatementValidator(final Builder builder) {
27         this.cardinalityMap = builder.cardinalityMap.build();
28         this.currentStatement = builder.currentStatement;
29         this.mandatoryStatements = ImmutableMap.copyOf(Maps.filterValues(cardinalityMap, c -> c.getMin() > 0));
30     }
31
32     public static Builder builder(final StatementDefinition currentStatement) {
33         return new Builder(currentStatement);
34     }
35
36     public static final class Builder {
37         private static final Cardinality ONE_MAX = new Cardinality(1, Integer.MAX_VALUE);
38         private static final Cardinality ONE_ONE = new Cardinality(1, 1);
39         private static final Cardinality ZERO_MAX = new Cardinality(0, Integer.MAX_VALUE);
40         private static final Cardinality ZERO_ONE = new Cardinality(0, 1);
41
42         private final ImmutableMap.Builder<StatementDefinition, Cardinality> cardinalityMap = ImmutableMap.builder();
43         private final StatementDefinition currentStatement;
44
45         Builder(final StatementDefinition currentStatement) {
46             this.currentStatement = currentStatement;
47         }
48
49         private Builder add(final StatementDefinition def, final Cardinality card) {
50             cardinalityMap.put(def, card);
51             return this;
52         }
53
54         public Builder add(final StatementDefinition def, final int min, final int max) {
55             if (max == Integer.MAX_VALUE) {
56                 return addAtLeast(def, min);
57             } else if (min == 0) {
58                 return addAtMost(def, max);
59             } else {
60                 return add(def, new Cardinality(min, max));
61             }
62         }
63
64         // Equivalent to min .. Integer.MAX_VALUE
65         public Builder addAtLeast(final StatementDefinition def, final int min) {
66             switch (min) {
67                 case 0:
68                     return addAny(def);
69                 case 1:
70                     return addMultiple(def);
71                 default:
72                     return add(def, new Cardinality(min, Integer.MAX_VALUE));
73             }
74         }
75
76         // Equivalent to 0 .. max
77         public Builder addAtMost(final StatementDefinition def, final int max) {
78             return max == Integer.MAX_VALUE ? addAny(def) : add(def, new Cardinality(0, max));
79         }
80
81         // Equivalent to 0 .. Integer.MAX_VALUE
82         public Builder addAny(final StatementDefinition def) {
83             return add(def, ZERO_MAX);
84         }
85
86         // Equivalent to 1 .. 1
87         public Builder addMandatory(final StatementDefinition def) {
88             return add(def, ONE_ONE);
89         }
90
91         // Equivalent to 1 .. MAX
92         public Builder addMultiple(final StatementDefinition def) {
93             return add(def, ONE_MAX);
94         }
95
96         // Equivalent to 0 .. 1
97         public Builder addOptional(final StatementDefinition def) {
98             return add(def, ZERO_ONE);
99         }
100
101         public SubstatementValidator build() {
102             return new SubstatementValidator(this);
103         }
104     }
105
106     public void validate(final StmtContext<?, ?, ?> ctx) throws InvalidSubstatementException,
107             MissingSubstatementException {
108
109         final Map<StatementDefinition, Counter> stmtCounts = new HashMap<>();
110         for (StmtContext<?, ?, ?> stmtCtx : ctx.allSubstatements()) {
111             stmtCounts.computeIfAbsent(stmtCtx.getPublicDefinition(), key -> new Counter()).increment();
112         }
113
114         // Mark all mandatory statements as not present. We are using a Map instead of a Set, as it provides us with
115         // explicit value in case of failure (which is not important) and a more efficient instantiation performance
116         // (which is important).
117         final Map<StatementDefinition, Cardinality> missingMandatory = new HashMap<>(mandatoryStatements);
118
119         // Iterate over all statements
120         for (Entry<StatementDefinition, Counter> entry : stmtCounts.entrySet()) {
121             final StatementDefinition key = entry.getKey();
122             final Cardinality cardinality = cardinalityMap.get(key);
123             final int value = entry.getValue().getValue();
124
125             if (cardinality == null) {
126                 if (ctx.getFromNamespace(ExtensionNamespace.class, key.getStatementName()) == null) {
127                     throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
128                         "%s is not valid for %s. Error in module %s (%s)", key, currentStatement,
129                         ctx.getRoot().getStatementArgument(),
130                         ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
131                 }
132
133                 continue;
134             }
135
136             if (cardinality.getMin() > 0) {
137                 if (cardinality.getMin() > value) {
138                     throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
139                         "Minimal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
140                         cardinality.getMin(), value, ctx.getRoot().getStatementArgument(),
141                         ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
142                 }
143
144                 // Encountered a mandatory statement, hence we are not missing it
145                 missingMandatory.remove(key);
146             }
147             if (cardinality.getMax() < value) {
148                 throw new InvalidSubstatementException(ctx.getStatementSourceReference(),
149                     "Maximal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
150                     cardinality.getMax(), value, ctx.getRoot().getStatementArgument(),
151                     ctx.getFromNamespace(ModuleCtxToModuleQName.class, ctx.getRoot()));
152             }
153         }
154
155         // Check if there are any mandatory statements we have missed
156         if (!missingMandatory.isEmpty()) {
157             final Entry<StatementDefinition, Cardinality> e = missingMandatory.entrySet().iterator().next();
158             final StmtContext<?, ?, ?> root = ctx.getRoot();
159
160             throw new MissingSubstatementException(ctx.getStatementSourceReference(),
161                 "%s is missing %s. Minimal count is %s. Error in module %s (%s)", currentStatement, e.getKey(),
162                 e.getValue().getMin(), root.getStatementArgument(), ctx.getFromNamespace(ModuleCtxToModuleQName.class,
163                     root));
164         }
165     }
166
167     private static final class Cardinality {
168         private final int min;
169         private final int max;
170
171         private Cardinality(final int min, final int max) {
172             Preconditions.checkArgument(min >= 0, "Min %s cannot be less than 0!");
173             Preconditions.checkArgument(min <= max, "Min %s can not be greater than max %s!", min, max);
174             this.min = min;
175             this.max = max;
176         }
177
178         private int getMax() {
179             return max;
180         }
181
182         private int getMin() {
183             return min;
184         }
185     }
186
187     private static final class Counter {
188         private int value;
189
190         void increment() {
191             value++;
192         }
193
194         int getValue() {
195             return value;
196         }
197     }
198 }