Bug 6868: If-feature argument may be boolean expression
[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 java.util.Collection;
16 import java.util.Set;
17 import java.util.function.Predicate;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.common.QNameModule;
20 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
21 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
22 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
23 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
28 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
29 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
30 import org.opendaylight.yangtools.yang.parser.stmt.reactor.RootStatementContext;
31 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
32 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
33
34 public final class StmtContextUtils {
35     public static final Splitter LIST_KEY_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
36
37     private StmtContextUtils() {
38         throw new UnsupportedOperationException("Utility class");
39     }
40
41     @SuppressWarnings("unchecked")
42     public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(
43             final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<DT> declaredType) {
44         for (final StmtContext<?, ?, ?> ctx : contexts) {
45             if (producesDeclared(ctx, declaredType)) {
46                 return (AT) ctx.getStatementArgument();
47             }
48         }
49         return null;
50     }
51
52     @SuppressWarnings("unchecked")
53     public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(final StmtContext<?, ?, ?> ctx,
54             final Class<DT> declaredType) {
55         return producesDeclared(ctx, declaredType) ? (AT) ctx.getStatementArgument() : null;
56     }
57
58     public static <AT, DT extends DeclaredStatement<AT>> AT firstSubstatementAttributeOf(
59             final StmtContext<?, ?, ?> ctx, final Class<DT> declaredType) {
60         final AT firstAttribute = firstAttributeOf(ctx.effectiveSubstatements(), declaredType);
61         return firstAttribute != null ? firstAttribute : firstAttributeOf(ctx.declaredSubstatements(), declaredType);
62     }
63
64     @SuppressWarnings("unchecked")
65     public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstDeclaredSubstatement(
66             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
67         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
68             if (producesDeclared(subStmtContext, declaredType)) {
69                 return (StmtContext<AT, ?, ?>) subStmtContext;
70             }
71         }
72         return null;
73     }
74
75     @SuppressWarnings("unchecked")
76     public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllDeclaredSubstatements(
77             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
78         final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
79         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
80             if (producesDeclared(subStmtContext, declaredType)) {
81                 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
82             }
83         }
84         return listBuilder.build();
85     }
86
87     @SuppressWarnings("unchecked")
88     public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllEffectiveSubstatements(
89             final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
90         final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
91         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
92             if (producesDeclared(subStmtContext, type)) {
93                 listBuilder.add((StmtContext<AT, DT, ?>) subStmtContext);
94             }
95         }
96         return listBuilder.build();
97     }
98
99     public static <AT, DT extends DeclaredStatement<AT>> Collection<StmtContext<AT, DT, ?>> findAllSubstatements(
100             final StmtContext<?, ?, ?> stmtContext, final Class<DT> type) {
101         final ImmutableList.Builder<StmtContext<AT, DT, ?>> listBuilder = ImmutableList.builder();
102         listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
103         listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
104         return listBuilder.build();
105     }
106
107     @SuppressWarnings("unchecked")
108     public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstEffectiveSubstatement(
109             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
110         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
111             if (producesDeclared(subStmtContext, declaredType)) {
112                 return (StmtContext<AT, ?, ?>) subStmtContext;
113             }
114         }
115         return null;
116     }
117
118     public static <AT, DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstSubstatement(
119             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
120         final StmtContext<AT, ?, ?> declaredSubstatement = findFirstDeclaredSubstatement(stmtContext, declaredType);
121         return declaredSubstatement != null ? declaredSubstatement : findFirstEffectiveSubstatement(stmtContext,
122                 declaredType);
123     }
124
125     @SafeVarargs
126     public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
127             int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
128         if (startIndex >= types.length) {
129             return null;
130         }
131
132         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
133             if (producesDeclared(subStmtContext, types[startIndex])) {
134                 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
135                         ++startIndex, types);
136             }
137         }
138         return null;
139     }
140
141     public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
142             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType, int sublevel) {
143         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
144             if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
145                 return subStmtContext;
146             }
147             if (sublevel > 1) {
148                 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
149                         declaredType, --sublevel);
150                 if (result != null) {
151                     return result;
152                 }
153             }
154         }
155
156         return null;
157     }
158
159     public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
160             final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) {
161         for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
162             if (producesDeclared(subStmtContext, declaredType)) {
163                 return subStmtContext;
164             }
165
166             final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
167             if (result != null) {
168                 return result;
169             }
170         }
171
172         return null;
173     }
174
175     public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
176             final Class<? extends DeclaredStatement<?>> type) {
177         return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
178     }
179
180     public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
181         StmtContext<?, ?, ?> current = stmtCtx;
182         while (!current.getParentContext().isRootContext()) {
183             current = current.getParentContext();
184             if (producesDeclared(current, UnknownStatementImpl.class)) {
185                 return true;
186             }
187         }
188
189         return false;
190     }
191
192     public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
193         return producesDeclared(stmtCtx, UnknownStatementImpl.class);
194     }
195
196     public static Collection<SchemaNodeIdentifier> replaceModuleQNameForKey(
197             final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?> keyStmtCtx,
198             final QNameModule newQNameModule) {
199
200         final Builder<SchemaNodeIdentifier> builder = ImmutableSet.builder();
201         boolean replaced = false;
202         for (final SchemaNodeIdentifier arg : keyStmtCtx.getStatementArgument()) {
203             final QName qname = arg.getLastComponent();
204             if (!newQNameModule.equals(qname)) {
205                 final QName newQname = keyStmtCtx.getFromNamespace(QNameCacheNamespace.class,
206                         QName.create(newQNameModule, qname.getLocalName()));
207                 builder.add(SchemaNodeIdentifier.create(false, newQname));
208                 replaced = true;
209             } else {
210                 builder.add(arg);
211             }
212         }
213
214         // This makes sure we reuse the collection when a grouping is
215         // instantiated in the same module
216         return replaced ? builder.build() : keyStmtCtx.getStatementArgument();
217     }
218
219     public static boolean areFeaturesSupported(final StmtContext.Mutable<?, ?, ?> stmtContext) {
220         switch (stmtContext.getSupportedByFeatures()) {
221         case SUPPORTED:
222             return true;
223         case NOT_SUPPORTED:
224             return false;
225         default:
226             break;
227         }
228
229         final Set<QName> supportedFeatures = stmtContext.getFromNamespace(SupportedFeaturesNamespace.class,
230                 SupportedFeatures.SUPPORTED_FEATURES);
231         /*
232          * If set of supported features has not been provided, all features are
233          * supported by default.
234          */
235         if (supportedFeatures == null) {
236             stmtContext.setSupportedByFeatures(true);
237             return true;
238         }
239
240         final boolean result = checkFeatureSupport(stmtContext, supportedFeatures);
241         stmtContext.setSupportedByFeatures(result);
242         return result;
243     }
244
245     private static boolean checkFeatureSupport(final StmtContext.Mutable<?, ?, ?> stmtContext,
246             final Set<QName> supportedFeatures) {
247         boolean isSupported = false;
248         boolean containsIfFeature = false;
249         for (final StatementContextBase<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
250             if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
251                 containsIfFeature = true;
252                 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
253                     isSupported = true;
254                 } else {
255                     isSupported = false;
256                     break;
257                 }
258             }
259         }
260
261         return !containsIfFeature || isSupported;
262     }
263
264     /**
265      * Checks whether statement context is a presence container or not.
266      *
267      * @param stmtCtx
268      *            statement context
269      * @return true if it is a presence container
270      */
271     public static boolean isPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
272         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
273     }
274
275     /**
276      * Checks whether statement context is a non-presence container or not.
277      *
278      * @param stmtCtx
279      *            statement context
280      * @return true if it is a non-presence container
281      */
282     public static boolean isNonPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
283         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
284     }
285
286     private static boolean containsPresenceSubStmt(final StatementContextBase<?, ?, ?> stmtCtx) {
287         return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
288     }
289
290     /**
291      * Checks whether statement context is a mandatory node according to RFC6020
292      * or not.
293      *
294      * @param stmtCtx
295      *            statement context
296      * @return true if it is a mandatory node according to RFC6020
297      */
298     public static boolean isMandatoryNode(final StatementContextBase<?, ?, ?> stmtCtx) {
299         return isMandatoryListOrLeafList(stmtCtx) || isMandatoryLeafChoiceOrAnyXML(stmtCtx);
300     }
301
302     private static boolean isMandatoryLeafChoiceOrAnyXML(final StatementContextBase<?, ?, ?> stmtCtx) {
303         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
304             return false;
305         }
306         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
307         case LEAF:
308         case CHOICE:
309         case ANYXML:
310             return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
311         default:
312             return false;
313         }
314     }
315
316     private static boolean isMandatoryListOrLeafList(final StatementContextBase<?, ?, ?> stmtCtx) {
317         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
318             return false;
319         }
320         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
321         case LIST:
322         case LEAF_LIST:
323             final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
324             return minElements != null && minElements > 0;
325         default:
326             return false;
327         }
328     }
329
330     /**
331      * Checks whether at least one ancestor of a StatementContext matches one
332      * from collection of statement definitions.
333      *
334      * @param ctx
335      *            StatementContext to be checked
336      * @param ancestorTypes
337      *            collection of statement definitions
338      *
339      * @return true if at least one ancestor of a StatementContext matches one
340      *         from collection of statement definitions, otherwise false.
341      */
342     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
343             final Collection<StatementDefinition> ancestorTypes) {
344         Preconditions.checkNotNull(ctx);
345         Preconditions.checkNotNull(ancestorTypes);
346         StmtContext<?, ?, ?> current = ctx.getParentContext();
347         while (current != null) {
348             if (ancestorTypes.contains(current.getPublicDefinition())) {
349                 return true;
350             }
351             current = current.getParentContext();
352         }
353         return false;
354     }
355
356     /**
357      * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
358      *
359      * @param ctx StmtContext to be checked
360      * @param ancestorType type of ancestor to search for
361      * @param ancestorChildType type of child to search for in the specified ancestor type
362      *
363      * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
364      */
365     public static <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
366             final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
367         Preconditions.checkNotNull(ctx);
368         Preconditions.checkNotNull(ancestorType);
369         Preconditions.checkNotNull(ancestorChildType);
370         StmtContext<?, ?, ?> current = ctx.getParentContext();
371         while (!(current instanceof RootStatementContext)) {
372             if (ancestorType.equals(current.getPublicDefinition())) {
373                 @SuppressWarnings("unchecked")
374                 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
375                 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
376                     return false;
377                 }
378             }
379             current = current.getParentContext();
380         }
381
382         return true;
383     }
384
385     /**
386      * Checks whether the parent of StmtContext is of specified type
387      *
388      * @param ctx
389      *            StmtContext to be checked
390      * @param parentType
391      *            type of parent to check
392      *
393      * @return true if the parent of StmtContext is of specified type, otherwise
394      *         false
395      */
396     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
397         Preconditions.checkNotNull(ctx);
398         Preconditions.checkNotNull(parentType);
399         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
400         return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
401     }
402 }