2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.spi.meta;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Splitter;
12 import com.google.common.base.Strings;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Iterables;
15 import java.util.Collection;
16 import java.util.Date;
17 import java.util.Optional;
19 import java.util.function.Predicate;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
25 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
26 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
27 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
28 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
37 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
39 import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement;
40 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
42 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
43 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
44 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
45 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
46 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
47 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 public final class StmtContextUtils {
50 public static final Splitter LIST_KEY_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
52 private StmtContextUtils() {
53 throw new UnsupportedOperationException("Utility class");
56 @SuppressWarnings("unchecked")
57 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
58 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
59 for (final StmtContext<?, ?, ?> ctx : contexts) {
60 if (producesDeclared(ctx, declaredType)) {
61 return (A) ctx.getStatementArgument();
67 @SuppressWarnings("unchecked")
68 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
69 final Class<D> declaredType) {
70 return producesDeclared(ctx, declaredType) ? (A) ctx.getStatementArgument() : null;
73 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
74 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
75 final A firstAttribute = firstAttributeOf(ctx.effectiveSubstatements(), declaredType);
76 return firstAttribute != null ? firstAttribute : firstAttributeOf(ctx.declaredSubstatements(), declaredType);
79 @SuppressWarnings("unchecked")
80 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
81 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
82 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
83 if (producesDeclared(subStmtContext, declaredType)) {
84 return (StmtContext<A, ?, ?>) subStmtContext;
90 @SuppressWarnings("unchecked")
91 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
92 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
93 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
94 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
95 if (producesDeclared(subStmtContext, declaredType)) {
96 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
99 return listBuilder.build();
102 @SuppressWarnings("unchecked")
103 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
104 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
105 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
106 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
107 if (producesDeclared(subStmtContext, type)) {
108 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
111 return listBuilder.build();
114 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
115 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
116 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
117 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
118 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
119 return listBuilder.build();
122 @SuppressWarnings("unchecked")
123 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
124 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
125 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
126 if (producesDeclared(subStmtContext, declaredType)) {
127 return (StmtContext<A, ?, ?>) subStmtContext;
134 * Searches for the first substatement of the specified type in the specified statement context.
135 * First, it tries to find the substatement in the effective substatements of the statement context.
136 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
137 * the method returns null.
139 * @param stmtContext statement context to search in
140 * @param declaredType substatement type to search for
141 * @param <A> statement argument type
142 * @param <D> declared statement type
143 * @return statement context that was searched for or null if was not found
145 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
146 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
147 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
148 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
153 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
154 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
155 if (startIndex >= types.length) {
159 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
160 if (producesDeclared(subStmtContext, types[startIndex])) {
161 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
162 ++startIndex, types);
168 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
169 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType, int sublevel) {
170 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
171 if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
172 return subStmtContext;
175 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
176 declaredType, --sublevel);
177 if (result != null) {
186 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
187 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
188 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
189 if (producesDeclared(subStmtContext, declaredType)) {
190 return subStmtContext;
193 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
194 if (result != null) {
202 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
203 final Class<? extends DeclaredStatement<?>> type) {
204 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
207 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
208 StmtContext<?, ?, ?> current = stmtCtx;
209 while (current.getParentContext().getParentContext() != null) {
210 current = current.getParentContext();
211 if (isUnknownStatement(current)) {
220 * Returns true if supplied statement context represents unknown statement,
221 * otherwise returns false.
224 * statement context to be checked
225 * @return true if supplied statement context represents unknown statement,
227 * @throws NullPointerException
228 * if supplied statement context is null
230 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
231 return UnknownStatement.class
232 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
236 * Returns true if supplied statement context represents unrecognized
237 * statement, otherwise returns false.
240 * statement context to be checked
241 * @return true if supplied statement context represents unrecognized
242 * statement, otherwise false
243 * @throws NullPointerException
244 * if supplied statement context is null
246 public static boolean isUnrecognizedStatement(final StmtContext<?, ?, ?> stmtCtx) {
247 return UnrecognizedStatement.class
248 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
251 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
252 final Set<QName> supportedFeatures) {
253 boolean isSupported = false;
254 boolean containsIfFeature = false;
255 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
256 if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
257 containsIfFeature = true;
258 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
267 return !containsIfFeature || isSupported;
271 * Checks whether statement context is a presence container or not.
275 * @return true if it is a presence container
277 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
278 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
282 * Checks whether statement context is a non-presence container or not.
286 * @return true if it is a non-presence container
288 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
289 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
292 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
293 return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
297 * Checks whether statement context is a mandatory leaf, choice, anyxml,
298 * list or leaf-list according to RFC6020 or not.
302 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
303 * according to RFC6020.
305 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
306 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
309 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
313 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
316 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
317 return minElements != null && minElements > 0;
324 * Checks whether a statement context is a statement of supplied statement
325 * definition and whether it is not mandatory leaf, choice, anyxml, list or
326 * leaf-list according to RFC6020.
331 * statement definition
332 * @return true if supplied statement context is a statement of supplied
333 * statement definition and if it is not mandatory leaf, choice,
334 * anyxml, list or leaf-list according to RFC6020
336 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
337 final StatementDefinition stmtDef) {
338 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
342 * Checks whether at least one ancestor of a StatementContext matches one
343 * from collection of statement definitions.
346 * StatementContext to be checked
347 * @param ancestorTypes
348 * collection of statement definitions
350 * @return true if at least one ancestor of a StatementContext matches one
351 * from collection of statement definitions, otherwise false.
353 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
354 final Collection<StatementDefinition> ancestorTypes) {
355 Preconditions.checkNotNull(ctx);
356 Preconditions.checkNotNull(ancestorTypes);
357 StmtContext<?, ?, ?> current = ctx.getParentContext();
358 while (current != null) {
359 if (ancestorTypes.contains(current.getPublicDefinition())) {
362 current = current.getParentContext();
368 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
370 * @param ctx StmtContext to be checked
371 * @param ancestorType type of ancestor to search for
372 * @param ancestorChildType type of child to search for in the specified ancestor type
374 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
376 public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
377 final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
378 Preconditions.checkNotNull(ctx);
379 Preconditions.checkNotNull(ancestorType);
380 Preconditions.checkNotNull(ancestorChildType);
382 StmtContext<?, ?, ?> current = ctx.getParentContext();
383 StmtContext<?, ?, ?> parent = current.getParentContext();
384 while (parent != null) {
385 if (ancestorType.equals(current.getPublicDefinition())) {
386 @SuppressWarnings("unchecked")
387 final Class<D> ancestorChildTypeClass = (Class<D>) ancestorChildType.getDeclaredRepresentationClass();
388 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
394 parent = current.getParentContext();
401 * Checks whether the parent of StmtContext is of specified type
404 * StmtContext to be checked
406 * type of parent to check
408 * @return true if the parent of StmtContext is of specified type, otherwise
411 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
412 Preconditions.checkNotNull(ctx);
413 Preconditions.checkNotNull(parentType);
414 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
415 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
419 * Validates the specified statement context with regards to if-feature and when statement on list keys.
420 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
421 * statement defined in a keyed list (a uses statement may add leaves into the list).
423 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
425 * @param ctx statement context to be validated
427 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
428 Preconditions.checkNotNull(ctx);
430 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
434 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
435 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
436 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
438 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
439 if (isListKey(ctx, keyStmtCtx)) {
440 disallowIfFeatureAndWhenOnListKeys(ctx);
442 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
443 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
444 if (isListKey(leafStmtCtx, keyStmtCtx)) {
445 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
451 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
452 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
453 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
454 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
457 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
458 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
459 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
460 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
468 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
469 Iterables.concat(leafStmtCtx.declaredSubstatements(), leafStmtCtx.effectiveSubstatements()).forEach(
471 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
472 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
473 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
474 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
475 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
479 public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
480 if (Strings.isNullOrEmpty(value)) {
481 return ctx.getPublicDefinition().getStatementName();
485 QNameModule qNameModule = null;
486 String localName = null;
488 final String[] namesParts = value.split(":");
489 switch (namesParts.length) {
491 localName = namesParts[0];
492 qNameModule = StmtContextUtils.getRootModuleQName(ctx);
495 prefix = namesParts[0];
496 localName = namesParts[1];
497 qNameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
498 // in case of unknown statement argument, we're not going to parse it
499 if (qNameModule == null && isUnknownStatement(ctx)) {
501 qNameModule = StmtContextUtils.getRootModuleQName(ctx);
503 if (qNameModule == null
504 && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
505 ctx = ctx.getOriginalCtx().orElse(null);
506 qNameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
511 qNameModule = InferenceException.throwIfNull(qNameModule, ctx.getStatementSourceReference(),
512 "Cannot resolve QNameModule for '%s'", value);
514 final QNameModule resultQNameModule;
515 if (qNameModule.getRevision() == null) {
516 resultQNameModule = QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV)
519 resultQNameModule = qNameModule;
522 return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(resultQNameModule, localName));
525 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
530 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
531 final QNameModule qNameModule;
533 if (producesDeclared(rootCtx, ModuleStatement.class)) {
534 qNameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
535 } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
536 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
537 BelongsToStatement.class);
538 qNameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
543 Preconditions.checkArgument(qNameModule != null, "Failed to look up root QNameModule for %s", ctx);
544 if (qNameModule.getRevision() != null) {
548 return QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV).intern();
551 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
552 final ModuleIdentifier modId = ctx.getRoot().getFromNamespace(ImpPrefixToModuleIdentifier.class, prefix);
553 final QNameModule qNameModule = ctx.getFromNamespace(ModuleIdentifierToModuleQName.class, modId);
555 if (qNameModule == null && producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
556 final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
557 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
562 public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
563 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
564 if (qNameModule != null) {
565 // creates SourceIdentifier for a module
566 return RevisionSourceIdentifier.create((String) root.getStatementArgument(),
567 qNameModule.getFormattedRevision());
570 // creates SourceIdentifier for a submodule
571 final Date revision = Optional.ofNullable(getLatestRevision(root.declaredSubstatements()))
572 .orElse(SimpleDateFormatUtil.DEFAULT_DATE_REV);
573 final String formattedRevision = SimpleDateFormatUtil.getRevisionFormat().format(revision);
574 return RevisionSourceIdentifier.create((String) root.getStatementArgument(), formattedRevision);
577 public static Date getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
578 Date revision = null;
579 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
580 if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(RevisionStatement
582 if (revision == null && subStmt.getStatementArgument() != null) {
583 revision = (Date) subStmt.getStatementArgument();
584 } else if (subStmt.getStatementArgument() != null && ((Date) subStmt.getStatementArgument()).compareTo
586 revision = (Date) subStmt.getStatementArgument();