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;
89 public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext,
90 int startIndex, final Class<? extends DeclaredStatement<?>>... types) {
91 if (startIndex >= types.length) {
95 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
96 if (producesDeclared(subStmtContext, types[startIndex])) {
97 return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext,
104 @SuppressWarnings("unchecked")
105 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllDeclaredSubstatements(
106 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
107 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
108 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) {
109 if (producesDeclared(subStmtContext, declaredType)) {
110 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
113 return listBuilder.build();
116 @SuppressWarnings("unchecked")
117 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllEffectiveSubstatements(
118 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
119 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
120 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
121 if (producesDeclared(subStmtContext, type)) {
122 listBuilder.add((StmtContext<A, D, ?>) subStmtContext);
125 return listBuilder.build();
128 public static <A, D extends DeclaredStatement<A>> Collection<StmtContext<A, D, ?>> findAllSubstatements(
129 final StmtContext<?, ?, ?> stmtContext, final Class<D> type) {
130 final ImmutableList.Builder<StmtContext<A, D, ?>> listBuilder = ImmutableList.builder();
131 listBuilder.addAll(findAllDeclaredSubstatements(stmtContext, type));
132 listBuilder.addAll(findAllEffectiveSubstatements(stmtContext, type));
133 return listBuilder.build();
136 @SuppressWarnings("unchecked")
137 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstEffectiveSubstatement(
138 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
139 for (final StmtContext<?, ?, ?> subStmtContext : stmtContext.effectiveSubstatements()) {
140 if (producesDeclared(subStmtContext, declaredType)) {
141 return (StmtContext<A, ?, ?>) subStmtContext;
148 * Searches for the first substatement of the specified type in the specified statement context.
149 * First, it tries to find the substatement in the effective substatements of the statement context.
150 * If it was not found, then it proceeds to search in the declared substatements. If it still was not found,
151 * the method returns null.
153 * @param stmtContext statement context to search in
154 * @param declaredType substatement type to search for
155 * @param <A> statement argument type
156 * @param <D> declared statement type
157 * @return statement context that was searched for or null if was not found
159 public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
160 final StmtContext<?, ?, ?> stmtContext, final Class<D> declaredType) {
161 final StmtContext<A, ?, ?> effectiveSubstatement = findFirstEffectiveSubstatement(stmtContext, declaredType);
162 return effectiveSubstatement != null ? effectiveSubstatement : findFirstDeclaredSubstatement(stmtContext,
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 from a collection of statement
344 * StatementContext to be checked
345 * @param ancestorTypes
346 * collection of statement definitions
347 * @return true if at least one ancestor of a StatementContext matches one
348 * from collection of statement definitions, otherwise false.
350 public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> ctx,
351 final Collection<StatementDefinition> ancestorTypes) {
352 Preconditions.checkNotNull(ctx);
353 Preconditions.checkNotNull(ancestorTypes);
354 StmtContext<?, ?, ?> current = ctx.getParentContext();
355 while (current != null) {
356 if (ancestorTypes.contains(current.getPublicDefinition())) {
359 current = current.getParentContext();
365 * Checks whether all of StmtContext's ancestors of specified type have a child of specified type.
367 * @param ctx StmtContext to be checked
368 * @param ancestorType type of ancestor to search for
369 * @param ancestorChildType type of child to search for in the specified ancestor type
370 * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
372 public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(
373 final StmtContext<?, ?, ?> ctx, final StatementDefinition ancestorType,
374 final StatementDefinition ancestorChildType) {
375 Preconditions.checkNotNull(ctx);
376 Preconditions.checkNotNull(ancestorType);
377 Preconditions.checkNotNull(ancestorChildType);
379 StmtContext<?, ?, ?> current = ctx.getParentContext();
380 StmtContext<?, ?, ?> parent = current.getParentContext();
381 while (parent != null) {
382 if (ancestorType.equals(current.getPublicDefinition())) {
383 @SuppressWarnings("unchecked")
384 final Class<D> ancestorChildTypeClass = (Class<D>) ancestorChildType.getDeclaredRepresentationClass();
385 if (findFirstSubstatement(current, ancestorChildTypeClass) == null) {
391 parent = current.getParentContext();
398 * Checks whether the parent of StmtContext is of specified type.
401 * StmtContext to be checked
403 * type of parent to check
404 * @return true if the parent of StmtContext is of specified type, otherwise false
406 public static boolean hasParentOfType(final StmtContext<?, ?, ?> ctx, final StatementDefinition parentType) {
407 Preconditions.checkNotNull(ctx);
408 Preconditions.checkNotNull(parentType);
409 final StmtContext<?, ?, ?> parentContext = ctx.getParentContext();
410 return parentContext != null ? parentType.equals(parentContext.getPublicDefinition()) : false;
414 * Validates the specified statement context with regards to if-feature and when statement on list keys.
415 * The context can either be a leaf which is defined directly in the substatements of a keyed list or a uses
416 * statement defined in a keyed list (a uses statement may add leaves into the list).
419 * If one of the list keys contains an if-feature or a when statement in YANG 1.1 model, an exception is thrown.
421 * @param ctx statement context to be validated
423 public static void validateIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> ctx) {
424 Preconditions.checkNotNull(ctx);
426 if (!isRelevantForIfFeatureAndWhenOnListKeysCheck(ctx)) {
430 final StmtContext<?, ?, ?> listStmtCtx = ctx.getParentContext();
431 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx =
432 StmtContextUtils.findFirstDeclaredSubstatement(listStmtCtx, KeyStatement.class);
434 if (YangStmtMapping.LEAF.equals(ctx.getPublicDefinition())) {
435 if (isListKey(ctx, keyStmtCtx)) {
436 disallowIfFeatureAndWhenOnListKeys(ctx);
438 } else if (YangStmtMapping.USES.equals(ctx.getPublicDefinition())) {
439 StmtContextUtils.findAllEffectiveSubstatements(listStmtCtx, LeafStatement.class).forEach(leafStmtCtx -> {
440 if (isListKey(leafStmtCtx, keyStmtCtx)) {
441 disallowIfFeatureAndWhenOnListKeys(leafStmtCtx);
447 private static boolean isRelevantForIfFeatureAndWhenOnListKeysCheck(final StmtContext<?, ?, ?> ctx) {
448 return YangVersion.VERSION_1_1.equals(ctx.getRootVersion())
449 && StmtContextUtils.hasParentOfType(ctx, YangStmtMapping.LIST)
450 && StmtContextUtils.findFirstDeclaredSubstatement(ctx.getParentContext(), KeyStatement.class) != null;
453 private static boolean isListKey(final StmtContext<?, ?, ?> leafStmtCtx,
454 final StmtContext<Collection<SchemaNodeIdentifier>, ?, ?> keyStmtCtx) {
455 for (final SchemaNodeIdentifier keyIdentifier : keyStmtCtx.getStatementArgument()) {
456 if (leafStmtCtx.getStatementArgument().equals(keyIdentifier.getLastComponent())) {
464 private static void disallowIfFeatureAndWhenOnListKeys(final StmtContext<?, ?, ?> leafStmtCtx) {
465 leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
466 final StatementDefinition statementDef = leafSubstmtCtx.getPublicDefinition();
467 SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
468 || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.getStatementSourceReference(),
469 "%s statement is not allowed in %s leaf statement which is specified as a list key.",
470 statementDef.getStatementName(), leafStmtCtx.getStatementArgument());
474 public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
475 if (Strings.isNullOrEmpty(value)) {
476 return ctx.getPublicDefinition().getStatementName();
480 QNameModule qnameModule = null;
481 String localName = null;
483 final String[] namesParts = value.split(":");
484 switch (namesParts.length) {
486 localName = namesParts[0];
487 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
490 prefix = namesParts[0];
491 localName = namesParts[1];
492 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
493 // in case of unknown statement argument, we're not going to parse it
494 if (qnameModule == null && isUnknownStatement(ctx)) {
496 qnameModule = StmtContextUtils.getRootModuleQName(ctx);
498 if (qnameModule == null && ctx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
499 ctx = ctx.getOriginalCtx().orElse(null);
500 qnameModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
505 qnameModule = InferenceException.throwIfNull(qnameModule, ctx.getStatementSourceReference(),
506 "Cannot resolve QNameModule for '%s'", value);
508 final QNameModule resultQNameModule;
509 if (qnameModule.getRevision() == null) {
510 resultQNameModule = QNameModule.create(qnameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV)
513 resultQNameModule = qnameModule;
516 return ctx.getFromNamespace(QNameCacheNamespace.class, QName.create(resultQNameModule, localName));
519 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
524 final StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
525 final QNameModule qnameModule;
527 if (producesDeclared(rootCtx, ModuleStatement.class)) {
528 qnameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
529 } else if (producesDeclared(rootCtx, SubmoduleStatement.class)) {
530 final String belongsToModuleName = firstAttributeOf(rootCtx.declaredSubstatements(),
531 BelongsToStatement.class);
532 qnameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
537 Preconditions.checkArgument(qnameModule != null, "Failed to look up root QNameModule for %s", ctx);
538 if (qnameModule.getRevision() != null) {
542 return QNameModule.create(qnameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV).intern();
545 public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
546 final ModuleIdentifier modId = ctx.getRoot().getFromNamespace(ImpPrefixToModuleIdentifier.class, prefix);
547 final QNameModule qnameModule = ctx.getFromNamespace(ModuleIdentifierToModuleQName.class, modId);
549 if (qnameModule == null && producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
550 final String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
551 return ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
556 public static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
557 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
558 if (qNameModule != null) {
559 // creates SourceIdentifier for a module
560 return RevisionSourceIdentifier.create((String) root.getStatementArgument(),
561 qNameModule.getFormattedRevision());
564 // creates SourceIdentifier for a submodule
565 final Date revision = Optional.ofNullable(getLatestRevision(root.declaredSubstatements()))
566 .orElse(SimpleDateFormatUtil.DEFAULT_DATE_REV);
567 final String formattedRevision = SimpleDateFormatUtil.getRevisionFormat().format(revision);
568 return RevisionSourceIdentifier.create((String) root.getStatementArgument(), formattedRevision);
571 public static Date getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
572 Date revision = null;
573 for (final StmtContext<?, ?, ?> subStmt : subStmts) {
574 if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(
575 RevisionStatement.class)) {
576 if (revision == null && subStmt.getStatementArgument() != null) {
577 revision = (Date) subStmt.getStatementArgument();
578 } else if (subStmt.getStatementArgument() != null
579 && ((Date) subStmt.getStatementArgument()).compareTo(revision) > 0) {
580 revision = (Date) subStmt.getStatementArgument();