Bug 8126 - Some augments are not being processed
[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 leaf, choice, anyxml,
308      * list or leaf-list according to RFC6020 or not.
309      *
310      * @param stmtCtx
311      *            statement context
312      * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
313      *         according to RFC6020.
314      */
315     public static boolean isMandatoryNode(final StatementContextBase<?, ?, ?> stmtCtx) {
316         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
317             return false;
318         }
319         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
320         case LEAF:
321         case CHOICE:
322         case ANYXML:
323             return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
324         case LIST:
325         case LEAF_LIST:
326             final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
327             return minElements != null && minElements > 0;
328         default:
329             return false;
330         }
331     }
332
333     /**
334      * Checks whether a statement context is a statement of supplied statement
335      * definition and whether it is not mandatory leaf, choice, anyxml, list or
336      * leaf-list according to RFC6020.
337      *
338      * @param stmtCtx
339      *            statement context
340      * @param stmtDef
341      *            statement definition
342      * @return true if supplied statement context is a statement of supplied
343      *         statement definition and if it is not mandatory leaf, choice,
344      *         anyxml, list or leaf-list according to RFC6020
345      */
346     public static boolean isNotMandatoryNodeOfType(final StatementContextBase<?, ?, ?> stmtCtx,
347             final StatementDefinition stmtDef) {
348         return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
349     }
350
351     /**
352      * Checks whether at least one ancestor of a StatementContext matches one
353      * from collection of statement definitions.
354      *
355      * @param ctx
356      *            StatementContext to be checked
357      * @param ancestorTypes
358      *            collection of statement definitions
359      *
360      * @return true if at least one ancestor of a StatementContext matches one
361      *         from collection of statement definitions, otherwise false.
362      */
363     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
364             final Collection<StatementDefinition> ancestorTypes) {
365         Preconditions.checkNotNull(ctx);
366         Preconditions.checkNotNull(ancestorTypes);
367         StmtContext<?, ?, ?> current = ctx.getParentContext();
368         while (current != null) {
369             if (ancestorTypes.contains(current.getPublicDefinition())) {
370                 return true;
371             }
372             current = current.getParentContext();
373         }
374         return false;
375     }
376
377     /**
378      * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
379      *
380      * @param ctx StmtContext to be checked
381      * @param ancestorType type of ancestor to search for
382      * @param ancestorChildType type of child to search for in the specified ancestor type
383      *
384      * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
385      */
386     public static <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
387             final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
388         Preconditions.checkNotNull(ctx);
389         Preconditions.checkNotNull(ancestorType);
390         Preconditions.checkNotNull(ancestorChildType);
391         StmtContext<?, ?, ?> current = ctx.getParentContext();
392         while (!(current instanceof RootStatementContext)) {
393             if (ancestorType.equals(current.getPublicDefinition())) {
394                 @SuppressWarnings("unchecked")
395                 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
396                 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
397                     return false;
398                 }
399             }
400             current = current.getParentContext();
401         }
402
403         return true;
404     }
405
406     /**
407      * Checks whether the parent of StmtContext is of specified type
408      *
409      * @param ctx
410      *            StmtContext to be checked
411      * @param parentType
412      *            type of parent to check
413      *
414      * @return true if the parent of StmtContext is of specified type, otherwise
415      *         false
416      */
417     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
418         Preconditions.checkNotNull(ctx);
419         Preconditions.checkNotNull(parentType);
420         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
421         return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
422     }
423
424     /**
425      * Validates the specified statement context with regards to if-feature and when statement on list keys.
426      * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
427      * statement defined in a keyed list (a uses statement may add leaves into the list).
428      *
429      * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
430      *
431      * @param ctx statement context to be validated
432      */
433     public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
434         Preconditions.checkNotNull(ctx);
435
436         if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
437             return;
438         }
439
440         final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
441         final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
442                 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
443
444         if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
445             if (isListKey(ctx, keyStmtCtx)) {
446                 disallowIfFeatureAndWhenOnListKeys(ctx);
447             }
448         } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
449             StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
450                 if (isListKey(leafStmtCtx, keyStmtCtx)) {
451                     disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
452                 }
453             });
454         }
455     }
456
457     private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
458         return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
459                 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
460                 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
461     }
462
463     private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
464             final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
465         for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
466             if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
467                 return true;
468             }
469         }
470
471         return false;
472     }
473
474     private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
475         Iterables.concat(leafStmtCtx.declaredSubstatements(), leafStmtCtx.effectiveSubstatements()).forEach(
476                 leafSubstmtCtx -> {
477             final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
478             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
479                     || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
480                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
481                     statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
482         });
483     }
484 }