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