ad1c7e78d2e6b60b2f640c46ca548c6f2844dacf
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / StmtContextUtils.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 package org.opendaylight.yangtools.yang.parser.spi.meta;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Splitter;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.collect.ImmutableSet.Builder;
15 import com.google.common.collect.Iterables;
16 import java.util.Collection;
17 import java.util.Set;
18 import java.util.function.Predicate;
19 import org.opendaylight.yangtools.yang.common.QName;
20 import org.opendaylight.yangtools.yang.common.QNameModule;
21 import org.opendaylight.yangtools.yang.common.YangVersion;
22 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
23 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
24 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
25 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
31 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
32 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
33 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
34 import org.opendaylight.yangtools.yang.parser.stmt.reactor.RootStatementContext;
35 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
36 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
37
38 public final class StmtContextUtils {
39     public static final Splitter LIST_KEY_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
40
41     private StmtContextUtils() {
42         throw new UnsupportedOperationException("Utility class");
43     }
44
45     @SuppressWarnings("unchecked")
46     public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(
47             final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<DT> declaredType) {
48         for (final StmtContext<?, ?, ?> ctx : contexts) {
49             if (producesDeclared(ctx, declaredType)) {
50                 return (AT) ctx.getStatementArgument();
51             }
52         }
53         return null;
54     }
55
56     @SuppressWarnings("unchecked")
57     public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(final StmtContext<?, ?, ?> ctx,
58             final Class<DT> declaredType) {
59         return producesDeclared(ctx, declaredType) ? (AT) ctx.getStatementArgument() : null;
60     }
61
62     public static <AT, DT extends DeclaredStatement<AT>> AT firstSubstatementAttributeOf(
63             final StmtContext<?, ?, ?> ctx, final Class<DT> declaredType) {
64         final AT firstAttribute = firstAttributeOf(ctx.effectiveSubstatements(), declaredType);
65         return firstAttribute != null ? firstAttribute : firstAttributeOf(ctx.declaredSubstatements(), declaredType);
66     }
67
68     @SuppressWarnings("unchecked")
69     public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstDeclaredSubstatement(
70             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
71         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
72             if (producesDeclared(subStmtContext, declaredType)) {
73                 return (StmtContext<AT, ?, ?>) subStmtContext;
74             }
75         }
76         return null;
77     }
78
79     @SuppressWarnings("unchecked")
80     public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllDeclaredSubstatements(
81             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
82         final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
83         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
84             if (producesDeclared(subStmtContext, declaredType)) {
85                 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
86             }
87         }
88         return listBuilder.build();
89     }
90
91     @SuppressWarnings("unchecked")
92     public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllEffectiveSubstatements(
93             final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
94         final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
95         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
96             if (producesDeclared(subStmtContext, type)) {
97                 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
98             }
99         }
100         return listBuilder.build();
101     }
102
103     public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllSubstatements(
104             final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
105         final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
106         listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
107         listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
108         return listBuilder.build();
109     }
110
111     @SuppressWarnings("unchecked")
112     public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstEffectiveSubstatement(
113             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
114         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
115             if (producesDeclared(subStmtContext, declaredType)) {
116                 return (StmtContext<AT, ?, ?>) subStmtContext;
117             }
118         }
119         return null;
120     }
121
122     /**
123      * Searches for the first substatement of the specified type in the specified statement context.
124      * First, it tries to find the substatement in the effective substatements of the statement context.
125      * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
126      * the method returns null.
127      *
128      * @param stmtContext statement context to search in
129      * @param declaredType substatement type to search for
130      * @param <AT> statement argument type
131      * @param <DT> declared statement type
132      * @return statement context that was searched for or null if was not found
133      */
134     public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstSubstatement(
135             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
136         final StmtContext<AT, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
137         return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
138                 declaredType);
139     }
140
141     @SafeVarargs
142     public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
143             int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
144         if (startIndex >= types.length) {
145             return null;
146         }
147
148         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
149             if (producesDeclared(subStmtContext, types[startIndex])) {
150                 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
151                         ++startIndex, types);
152             }
153         }
154         return null;
155     }
156
157     public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
158             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType, int sublevel) {
159         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
160             if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
161                 return subStmtContext;
162             }
163             if (sublevel > 1) {
164                 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
165                         declaredType, --sublevel);
166                 if (result != null) {
167                     return result;
168                 }
169             }
170         }
171
172         return null;
173     }
174
175     public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
176             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
177         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
178             if (producesDeclared(subStmtContext, declaredType)) {
179                 return subStmtContext;
180             }
181
182             final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
183             if (result != null) {
184                 return result;
185             }
186         }
187
188         return null;
189     }
190
191     public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
192             final Class<? extends DeclaredStatement<?>> type) {
193         return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
194     }
195
196     public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
197         StmtContext<?, ?, ?> current = stmtCtx;
198         while (!current.getParentContext().isRootContext()) {
199             current = current.getParentContext();
200             if (producesDeclared(current, UnknownStatementImpl.class)) {
201                 return true;
202             }
203         }
204
205         return false;
206     }
207
208     public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
209         return producesDeclared(stmtCtx, UnknownStatementImpl.class);
210     }
211
212     public static Collection<SchemaNodeIdentifier> replaceModuleQNameForKey(
213             final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?> keyStmtCtx,
214             final QNameModule newQNameModule) {
215
216         final Builder<SchemaNodeIdentifier> builder = ImmutableSet.builder();
217         boolean replaced = false;
218         for (final SchemaNodeIdentifier arg : keyStmtCtx.getStatementArgument()) {
219             final QName qname = arg.getLastComponent();
220             if (!newQNameModule.equals(qname)) {
221                 final QName newQname = keyStmtCtx.getFromNamespace(QNameCacheNamespace.class,
222                         QName.create(newQNameModule, qname.getLocalName()));
223                 builder.add(SchemaNodeIdentifier.create(false, newQname));
224                 replaced = true;
225             } else {
226                 builder.add(arg);
227             }
228         }
229
230         // This makes sure we reuse the collection when a grouping is
231         // instantiated in the same module
232         return replaced ? builder.build() : keyStmtCtx.getStatementArgument();
233     }
234
235     public static boolean areFeaturesSupported(final StmtContext.Mutable<?, ?, ?> stmtContext) {
236         switch (stmtContext.getSupportedByFeatures()) {
237         case SUPPORTED:
238             return true;
239         case NOT_SUPPORTED:
240             return false;
241         default:
242             break;
243         }
244
245         final Set<QName> supportedFeatures = stmtContext.getFromNamespace(SupportedFeaturesNamespace.class,
246                 SupportedFeatures.SUPPORTED_FEATURES);
247         /*
248          * If set of supported features has not been provided, all features are
249          * supported by default.
250          */
251         if (supportedFeatures == null) {
252             stmtContext.setSupportedByFeatures(true);
253             return true;
254         }
255
256         final boolean result = checkFeatureSupport(stmtContext, supportedFeatures);
257         stmtContext.setSupportedByFeatures(result);
258         return result;
259     }
260
261     private static boolean checkFeatureSupport(final StmtContext.Mutable<?, ?, ?> stmtContext,
262             final Set<QName> supportedFeatures) {
263         boolean isSupported = false;
264         boolean containsIfFeature = false;
265         for (final StatementContextBase<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
266             if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
267                 containsIfFeature = true;
268                 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
269                     isSupported = true;
270                 } else {
271                     isSupported = false;
272                     break;
273                 }
274             }
275         }
276
277         return !containsIfFeature || isSupported;
278     }
279
280     /**
281      * Checks whether statement context is a presence container or not.
282      *
283      * @param stmtCtx
284      *            statement context
285      * @return true if it is a presence container
286      */
287     public static boolean isPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
288         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
289     }
290
291     /**
292      * Checks whether statement context is a non-presence container or not.
293      *
294      * @param stmtCtx
295      *            statement context
296      * @return true if it is a non-presence container
297      */
298     public static boolean isNonPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
299         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
300     }
301
302     private static boolean containsPresenceSubStmt(final StatementContextBase<?, ?, ?> stmtCtx) {
303         return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
304     }
305
306     /**
307      * Checks whether statement context is a mandatory node according to RFC6020
308      * or not.
309      *
310      * @param stmtCtx
311      *            statement context
312      * @return true if it is a mandatory node according to RFC6020
313      */
314     public static boolean isMandatoryNode(final StatementContextBase<?, ?, ?> stmtCtx) {
315         return isMandatoryListOrLeafList(stmtCtx) || isMandatoryLeafChoiceOrAnyXML(stmtCtx);
316     }
317
318     private static boolean isMandatoryLeafChoiceOrAnyXML(final StatementContextBase<?, ?, ?> stmtCtx) {
319         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
320             return false;
321         }
322         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
323         case LEAF:
324         case CHOICE:
325         case ANYXML:
326             return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
327         default:
328             return false;
329         }
330     }
331
332     private static boolean isMandatoryListOrLeafList(final StatementContextBase<?, ?, ?> stmtCtx) {
333         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
334             return false;
335         }
336         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
337         case LIST:
338         case LEAF_LIST:
339             final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
340             return minElements != null && minElements > 0;
341         default:
342             return false;
343         }
344     }
345
346     /**
347      * Checks whether at least one ancestor of a StatementContext matches one
348      * from collection of statement definitions.
349      *
350      * @param ctx
351      *            StatementContext to be checked
352      * @param ancestorTypes
353      *            collection of statement definitions
354      *
355      * @return true if at least one ancestor of a StatementContext matches one
356      *         from collection of statement definitions, otherwise false.
357      */
358     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
359             final Collection<StatementDefinition> ancestorTypes) {
360         Preconditions.checkNotNull(ctx);
361         Preconditions.checkNotNull(ancestorTypes);
362         StmtContext<?, ?, ?> current = ctx.getParentContext();
363         while (current != null) {
364             if (ancestorTypes.contains(current.getPublicDefinition())) {
365                 return true;
366             }
367             current = current.getParentContext();
368         }
369         return false;
370     }
371
372     /**
373      * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
374      *
375      * @param ctx StmtContext to be checked
376      * @param ancestorType type of ancestor to search for
377      * @param ancestorChildType type of child to search for in the specified ancestor type
378      *
379      * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
380      */
381     public static <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
382             final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
383         Preconditions.checkNotNull(ctx);
384         Preconditions.checkNotNull(ancestorType);
385         Preconditions.checkNotNull(ancestorChildType);
386         StmtContext<?, ?, ?> current = ctx.getParentContext();
387         while (!(current instanceof RootStatementContext)) {
388             if (ancestorType.equals(current.getPublicDefinition())) {
389                 @SuppressWarnings("unchecked")
390                 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
391                 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
392                     return false;
393                 }
394             }
395             current = current.getParentContext();
396         }
397
398         return true;
399     }
400
401     /**
402      * Checks whether the parent of StmtContext is of specified type
403      *
404      * @param ctx
405      *            StmtContext to be checked
406      * @param parentType
407      *            type of parent to check
408      *
409      * @return true if the parent of StmtContext is of specified type, otherwise
410      *         false
411      */
412     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
413         Preconditions.checkNotNull(ctx);
414         Preconditions.checkNotNull(parentType);
415         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
416         return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
417     }
418
419     /**
420      * Validates the specified statement context with regards to if-feature and when statement on list keys.
421      * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
422      * statement defined in a keyed list (a uses statement may add leaves into the list).
423      *
424      * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
425      *
426      * @param ctx statement context to be validated
427      */
428     public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
429         Preconditions.checkNotNull(ctx);
430
431         if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
432             return;
433         }
434
435         final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
436         final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
437                 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
438
439         if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
440             if (isListKey(ctx, keyStmtCtx)) {
441                 disallowIfFeatureAndWhenOnListKeys(ctx);
442             }
443         } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
444             StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
445                 if (isListKey(leafStmtCtx, keyStmtCtx)) {
446                     disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
447                 }
448             });
449         }
450     }
451
452     private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
453         return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
454                 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
455                 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
456     }
457
458     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
459             final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
460         for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
461             if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
462                 return true;
463             }
464         }
465
466         return false;
467     }
468
469     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
470         Iterables.concat(leafStmtCtx.declaredSubstatements(), leafStmtCtx.effectiveSubstatements()).forEach(
471                 leafSubstmtCtx -> {
472             final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
473             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
474                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
475                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
476                     statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
477         });
478     }
479 }