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 java.util.Collection;
15 import java.util.Date;
16 import java.util.Optional;
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.SimpleDateFormatUtil;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
24 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
25 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
26 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
27 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
36 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
38 import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement;
39 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
42 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
43 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
44 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
45 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
46 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
48 public final class StmtContextUtils {
49 public static final Splitter LIST_KEY_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
51 private StmtContextUtils() {
52 throw new UnsupportedOperationException("Utility class");
55 @SuppressWarnings("unchecked")
56 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(
57 final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<D> declaredType) {
58 for (final StmtContext<?, ?, ?> ctx : contexts) {
59 if (producesDeclared(ctx, declaredType)) {
60 return (A) ctx.getStatementArgument();
66 @SuppressWarnings("unchecked")
67 public static <A, D extends DeclaredStatement<A>> A firstAttributeOf(final StmtContext<?, ?, ?> ctx,
68 final Class<D> declaredType) {
69 return producesDeclared(ctx, declaredType) ? (A) ctx.getStatementArgument() : null;
72 public static <A, D extends DeclaredStatement<A>> A firstSubstatementAttributeOf(
73 final StmtContext<?, ?, ?> ctx, final Class<D> declaredType) {
74 return firstAttributeOf(ctx.allSubstatements(), declaredType);
77 @SuppressWarnings("unchecked")
78 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstDeclaredSubstatement(
79 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
80 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
81 if (producesDeclared(subStmtContext, declaredType)) {
82 return (StmtContext<A, ?, ?>) subStmtContext;
88 @SuppressWarnings("unchecked")
89 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
90 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
91 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
92 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
93 if (producesDeclared(subStmtContext, declaredType)) {
94 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
97 return listBuilder.build();
100 @SuppressWarnings("unchecked")
101 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
102 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
103 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
104 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
105 if (producesDeclared(subStmtContext, type)) {
106 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
109 return listBuilder.build();
112 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
113 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
114 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
115 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
116 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
117 return listBuilder.build();
120 @SuppressWarnings("unchecked")
121 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
122 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
123 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
124 if (producesDeclared(subStmtContext, declaredType)) {
125 return (StmtContext<A, ?, ?>) subStmtContext;
132 * Searches for the first substatement of the specified type in the specified statement context.
133 * First, it tries to find the substatement in the effective substatements of the statement context.
134 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
135 * the method returns null.
137 * @param stmtContext statement context to search in
138 * @param declaredType substatement type to search for
139 * @param <A> statement argument type
140 * @param <D> declared statement type
141 * @return statement context that was searched for or null if was not found
143 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
144 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
145 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
146 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
151 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
152 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
153 if (startIndex >= types.length) {
157 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
158 if (producesDeclared(subStmtContext, types[startIndex])) {
159 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
160 ++startIndex, types);
166 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel(
167 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType, int sublevel) {
168 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
169 if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) {
170 return subStmtContext;
173 final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel(subStmtContext,
174 declaredType, --sublevel);
175 if (result != null) {
184 public static <D extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement(
185 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
186 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
187 if (producesDeclared(subStmtContext, declaredType)) {
188 return subStmtContext;
191 final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType);
192 if (result != null) {
200 public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx,
201 final Class<? extends DeclaredStatement<?>> type) {
202 return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass());
205 public static boolean isInExtensionBody(final StmtContext<?, ?, ?> stmtCtx) {
206 StmtContext<?, ?, ?> current = stmtCtx;
207 while (current.getParentContext().getParentContext() != null) {
208 current = current.getParentContext();
209 if (isUnknownStatement(current)) {
218 * Returns true if supplied statement context represents unknown statement,
219 * otherwise returns false.
222 * statement context to be checked
223 * @return true if supplied statement context represents unknown statement,
225 * @throws NullPointerException
226 * if supplied statement context is null
228 public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) {
229 return UnknownStatement.class
230 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
234 * Returns true if supplied statement context represents unrecognized
235 * statement, otherwise returns false.
238 * statement context to be checked
239 * @return true if supplied statement context represents unrecognized
240 * statement, otherwise false
241 * @throws NullPointerException
242 * if supplied statement context is null
244 public static boolean isUnrecognizedStatement(final StmtContext<?, ?, ?> stmtCtx) {
245 return UnrecognizedStatement.class
246 .isAssignableFrom(stmtCtx.getPublicDefinition().getDeclaredRepresentationClass());
249 public static boolean checkFeatureSupport(final StmtContext<?, ?, ?> stmtContext,
250 final Set<QName> supportedFeatures) {
251 boolean isSupported = false;
252 boolean containsIfFeature = false;
253 for (final StmtContext<?, ?, ?> stmt : stmtContext.declaredSubstatements()) {
254 if (YangStmtMapping.IF_FEATURE.equals(stmt.getPublicDefinition())) {
255 containsIfFeature = true;
256 if (((Predicate<Set<QName>>) stmt.getStatementArgument()).test(supportedFeatures)) {
265 return !containsIfFeature || isSupported;
269 * Checks whether statement context is a presence container or not.
273 * @return true if it is a presence container
275 public static boolean isPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
276 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && containsPresenceSubStmt(stmtCtx);
280 * Checks whether statement context is a non-presence container or not.
284 * @return true if it is a non-presence container
286 public static boolean isNonPresenceContainer(final StmtContext<?, ?, ?> stmtCtx) {
287 return stmtCtx.getPublicDefinition() == YangStmtMapping.CONTAINER && !containsPresenceSubStmt(stmtCtx);
290 private static boolean containsPresenceSubStmt(final StmtContext<?, ?, ?> stmtCtx) {
291 return findFirstSubstatement(stmtCtx, PresenceStatement.class) != null;
295 * Checks whether statement context is a mandatory leaf, choice, anyxml,
296 * list or leaf-list according to RFC6020 or not.
300 * @return true if it is a mandatory leaf, choice, anyxml, list or leaf-list
301 * according to RFC6020.
303 public static boolean isMandatoryNode(final StmtContext<?, ?, ?> stmtCtx) {
304 if (!(stmtCtx.getPublicDefinition() instanceof YangStmtMapping)) {
307 switch ((YangStmtMapping) stmtCtx.getPublicDefinition()) {
311 return Boolean.TRUE.equals(firstSubstatementAttributeOf(stmtCtx, MandatoryStatement.class));
314 final Integer minElements = firstSubstatementAttributeOf(stmtCtx, MinElementsStatement.class);
315 return minElements != null && minElements > 0;
322 * Checks whether a statement context is a statement of supplied statement
323 * definition and whether it is not mandatory leaf, choice, anyxml, list or
324 * leaf-list according to RFC6020.
329 * statement definition
330 * @return true if supplied statement context is a statement of supplied
331 * statement definition and if it is not mandatory leaf, choice,
332 * anyxml, list or leaf-list according to RFC6020
334 public static boolean isNotMandatoryNodeOfType(final StmtContext<?, ?, ?> stmtCtx,
335 final StatementDefinition stmtDef) {
336 return stmtCtx.getPublicDefinition().equals(stmtDef) && !isMandatoryNode(stmtCtx);
340 * Checks whether at least one ancestor of a StatementContext matches one
341 * from collection of statement definitions.
344 * StatementContext to be checked
345 * @param ancestorTypes
346 * collection of statement definitions
348 * @return true if at least one ancestor of a StatementContext matches one
349 * from collection of statement definitions, otherwise false.
351 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
352 final Collection<StatementDefinition> ancestorTypes) {
353 Preconditions.checkNotNull(ctx);
354 Preconditions.checkNotNull(ancestorTypes);
355 StmtContext<?, ?, ?> current = ctx.getParentContext();
356 while (current != null) {
357 if (ancestorTypes.contains(current.getPublicDefinition())) {
360 current = current.getParentContext();
366 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type
368 * @param ctx StmtContext to be checked
369 * @param ancestorType type of ancestor to search for
370 * @param ancestorChildType type of child to search for in the specified ancestor type
372 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
374 public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(final StmtContext<?, ?, ?> ctx,
375 final StatementDefinition ancestorType, final StatementDefinition ancestorChildType) {
376 Preconditions.checkNotNull(ctx);
377 Preconditions.checkNotNull(ancestorType);
378 Preconditions.checkNotNull(ancestorChildType);
380 StmtContext<?, ?, ?> current = ctx.getParentContext();
381 StmtContext<?, ?, ?> parent = current.getParentContext();
382 while (parent != null) {
383 if (ancestorType.equals(current.getPublicDefinition())) {
384 @SuppressWarnings("unchecked")
385 final Class<D> ancestorChildTypeClass = (Class<D>) ancestorChildType.getDeclaredRepresentationClass();
386 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
392 parent = current.getParentContext();
399 * Checks whether the parent of StmtContext is of specified type
402 * StmtContext to be checked
404 * type of parent to check
406 * @return true if the parent of StmtContext is of specified type, otherwise
409 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
410 Preconditions.checkNotNull(ctx);
411 Preconditions.checkNotNull(parentType);
412 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
413 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
417 * Validates the specified statement context with regards to if-feature and when statement on list keys.
418 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
419 * statement defined in a keyed list (a uses statement may add leaves into the list).
421 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
423 * @param ctx statement context to be validated
425 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
426 Preconditions.checkNotNull(ctx);
428 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
432 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
433 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
434 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
436 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
437 if (isListKey(ctx, keyStmtCtx)) {
438 disallowIfFeatureAndWhenOnListKeys(ctx);
440 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
441 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
442 if (isListKey(leafStmtCtx, keyStmtCtx)) {
443 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
449 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
450 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
451 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
452 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
455 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
456 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
457 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
458 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
466 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
467 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
468 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
469 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
470 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
471 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
472 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
476 public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
477 if (Strings.isNullOrEmpty(value)) {
478 return ctx.getPublicDefinition().getStatementName();
482 QNameModule qNameModule = null;
483 String localName = null;
485 final String[] namesParts = value.split(":");
486 switch (namesParts.length) {
488 localName = namesParts[0];
489 qNameModule = StmtContextUtils.getRootModuleQName(ctx);
492 prefix = namesParts[0];
493 localName = namesParts[1];
494 qNameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
495 // in case of unknown statement argument, we're not going to parse it
496 if (qNameModule == null && isUnknownStatement(ctx)) {
498 qNameModule = StmtContextUtils.getRootModuleQName(ctx);
500 if (qNameModule == null
501 && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
502 ctx = ctx.getOriginalCtx().orElse(null);
503 qNameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
508 qNameModule = InferenceException.throwIfNull(qNameModule, ctx.getStatementSourceReference(),
509 "Cannot resolve QNameModule for '%s'", value);
511 final QNameModule resultQNameModule;
512 if (qNameModule.getRevision() == null) {
513 resultQNameModule = QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV)
516 resultQNameModule = qNameModule;
519 return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(resultQNameModule, localName));
522 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
527 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
528 final QNameModule qNameModule;
530 if (producesDeclared(rootCtx, ModuleStatement.class)) {
531 qNameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
532 } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
533 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
534 BelongsToStatement.class);
535 qNameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
540 Preconditions.checkArgument(qNameModule != null, "Failed to look up root QNameModule for %s", ctx);
541 if (qNameModule.getRevision() != null) {
545 return QNameModule.create(qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV).intern();
548 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
549 final ModuleIdentifier modId = ctx.getRoot().getFromNamespace(ImpPrefixToModuleIdentifier.class, prefix);
550 final QNameModule qNameModule = ctx.getFromNamespace(ModuleIdentifierToModuleQName.class, modId);
552 if (qNameModule == null && producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
553 final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
554 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
559 public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
560 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
561 if (qNameModule != null) {
562 // creates SourceIdentifier for a module
563 return RevisionSourceIdentifier.create((String) root.getStatementArgument(),
564 qNameModule.getFormattedRevision());
567 // creates SourceIdentifier for a submodule
568 final Date revision = Optional.ofNullable(getLatestRevision(root.declaredSubstatements()))
569 .orElse(SimpleDateFormatUtil.DEFAULT_DATE_REV);
570 final String formattedRevision = SimpleDateFormatUtil.getRevisionFormat().format(revision);
571 return RevisionSourceIdentifier.create((String) root.getStatementArgument(), formattedRevision);
574 public static Date getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
575 Date revision = null;
576 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
577 if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(RevisionStatement
579 if (revision == null && subStmt.getStatementArgument() != null) {
580 revision = (Date) subStmt.getStatementArgument();
581 } else if (subStmt.getStatementArgument() != null && ((Date) subStmt.getStatementArgument()).compareTo
583 revision = (Date) subStmt.getStatementArgument();