BUG-5222: Optimize use of declared substatements
[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.function.Predicate;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.common.QNameModule;
19 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
20 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
21 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
22 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
27 import org.opendaylight.yangtools.yang.model.repo.api.IfFeaturePredicates;
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 Predicate<QName> isFeatureSupported = stmtContext.getFromNamespace(SupportedFeaturesNamespace.class,
230                 SupportedFeatures.SUPPORTED_FEATURES);
231         if (IfFeaturePredicates.ALL_FEATURES.equals(isFeatureSupported)) {
232             stmtContext.setSupportedByFeatures(true);
233             return true;
234         }
235
236         final boolean result = checkFeatureSupport(stmtContext, isFeatureSupported);
237         stmtContext.setSupportedByFeatures(result);
238         return result;
239     }
240
241     private static boolean checkFeatureSupport(final StmtContext.Mutable<?, ?, ?> stmtContext,
242             final Predicate<QName> isFeatureSupported) {
243         boolean isSupported = false;
244         boolean containsIfFeature = false;
245         for (final StatementContextBase<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
246             if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
247                 containsIfFeature = true;
248                 if (isFeatureSupported.test((QName) stmt.getStatementArgument())) {
249                     isSupported = true;
250                 } else {
251                     isSupported = false;
252                     break;
253                 }
254             }
255         }
256
257         return !containsIfFeature || isSupported;
258     }
259
260     /**
261      * Checks whether statement context is a presence container or not.
262      *
263      * @param stmtCtx
264      *            statement context
265      * @return true if it is a presence container
266      */
267     public static boolean isPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
268         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
269     }
270
271     /**
272      * Checks whether statement context is a non-presence container or not.
273      *
274      * @param stmtCtx
275      *            statement context
276      * @return true if it is a non-presence container
277      */
278     public static boolean isNonPresenceContainer(final StatementContextBase<?, ?, ?> stmtCtx) {
279         return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
280     }
281
282     private static boolean containsPresenceSubStmt(final StatementContextBase<?, ?, ?> stmtCtx) {
283         return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
284     }
285
286     /**
287      * Checks whether statement context is a mandatory node according to RFC6020
288      * or not.
289      *
290      * @param stmtCtx
291      *            statement context
292      * @return true if it is a mandatory node according to RFC6020
293      */
294     public static boolean isMandatoryNode(final StatementContextBase<?, ?, ?> stmtCtx) {
295         return isMandatoryListOrLeafList(stmtCtx) || isMandatoryLeafChoiceOrAnyXML(stmtCtx);
296     }
297
298     private static boolean isMandatoryLeafChoiceOrAnyXML(final StatementContextBase<?, ?, ?> stmtCtx) {
299         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
300             return false;
301         }
302         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
303         case LEAF:
304         case CHOICE:
305         case ANYXML:
306             return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
307         default:
308             return false;
309         }
310     }
311
312     private static boolean isMandatoryListOrLeafList(final StatementContextBase<?, ?, ?> stmtCtx) {
313         if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
314             return false;
315         }
316         switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
317         case LIST:
318         case LEAF_LIST:
319             final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
320             return minElements != null && minElements > 0;
321         default:
322             return false;
323         }
324     }
325
326     /**
327      * Checks whether at least one ancestor of a StatementContext matches one
328      * from collection of statement definitions.
329      *
330      * @param ctx
331      *            StatementContext to be checked
332      * @param ancestorTypes
333      *            collection of statement definitions
334      *
335      * @return true if at least one ancestor of a StatementContext matches one
336      *         from collection of statement definitions, otherwise false.
337      */
338     public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
339             final Collection<StatementDefinition> ancestorTypes) {
340         Preconditions.checkNotNull(ctx);
341         Preconditions.checkNotNull(ancestorTypes);
342         StmtContext<?, ?, ?> current = ctx.getParentContext();
343         while (current != null) {
344             if (ancestorTypes.contains(current.getPublicDefinition())) {
345                 return true;
346             }
347             current = current.getParentContext();
348         }
349         return false;
350     }
351
352     /**
353      * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
354      *
355      * @param ctx StmtContext to be checked
356      * @param ancestorType type of ancestor to search for
357      * @param ancestorChildType type of child to search for in the specified ancestor type
358      *
359      * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
360      */
361     public static <AT, DT extends DeclaredStatement<AT>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
362             final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
363         Preconditions.checkNotNull(ctx);
364         Preconditions.checkNotNull(ancestorType);
365         Preconditions.checkNotNull(ancestorChildType);
366         StmtContext<?, ?, ?> current = ctx.getParentContext();
367         while (!(current instanceof RootStatementContext)) {
368             if (ancestorType.equals(current.getPublicDefinition())) {
369                 @SuppressWarnings("unchecked")
370                 final Class<DT> ancestorChildTypeClass = (Class<DT>) ancestorChildType.getDeclaredRepresentationClass();
371                 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
372                     return false;
373                 }
374             }
375             current = current.getParentContext();
376         }
377
378         return true;
379     }
380
381     /**
382      * Checks whether the parent of StmtContext is of specified type
383      *
384      * @param ctx
385      *            StmtContext to be checked
386      * @param parentType
387      *            type of parent to check
388      *
389      * @return true if the parent of StmtContext is of specified type, otherwise
390      *         false
391      */
392     public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
393         Preconditions.checkNotNull(ctx);
394         Preconditions.checkNotNull(parentType);
395         final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
396         return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
397     }
398 }