2 * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.rfc7950.stmt.uses;
10 import com.google.common.base.Verify;
11 import com.google.common.collect.ImmutableList;
12 import com.google.common.collect.ImmutableMap;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.LinkedHashMap;
18 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.common.YangVersion;
23 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
24 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
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.EffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
29 import org.opendaylight.yangtools.yang.model.api.stmt.RefineEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseQNameStatementSupport;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.refine.RefineEffectiveStatementImpl;
39 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
53 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
55 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
56 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
57 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 public final class UsesStatementSupport
62 extends BaseQNameStatementSupport<UsesStatement, UsesEffectiveStatement> {
63 private static final Logger LOG = LoggerFactory.getLogger(UsesStatementSupport.class);
64 private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping
66 .addAny(YangStmtMapping.AUGMENT)
67 .addOptional(YangStmtMapping.DESCRIPTION)
68 .addAny(YangStmtMapping.IF_FEATURE)
69 .addAny(YangStmtMapping.REFINE)
70 .addOptional(YangStmtMapping.REFERENCE)
71 .addOptional(YangStmtMapping.STATUS)
72 .addOptional(YangStmtMapping.WHEN)
74 private static final UsesStatementSupport INSTANCE = new UsesStatementSupport();
76 private UsesStatementSupport() {
77 super(YangStmtMapping.USES);
80 public static UsesStatementSupport getInstance() {
85 public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
86 return StmtContextUtils.parseNodeIdentifier(ctx, value);
90 public void onFullDefinitionDeclared(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
91 if (!usesNode.isSupportedByFeatures()) {
94 super.onFullDefinitionDeclared(usesNode);
96 final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
97 final QName groupingName = usesNode.argument();
99 final Prerequisite<StmtContext<?, ?, ?>> sourceGroupingPre = usesAction.requiresCtx(usesNode,
100 GroupingNamespace.class, groupingName, ModelProcessingPhase.EFFECTIVE_MODEL);
101 final Prerequisite<? extends StmtContext.Mutable<?, ?, ?>> targetNodePre = usesAction.mutatesEffectiveCtx(
102 usesNode.getParentContext());
104 usesAction.apply(new InferenceAction() {
107 public void apply(final InferenceContext ctx) {
108 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
109 (StatementContextBase<?, ?, ?>) targetNodePre.resolve(ctx);
110 final StatementContextBase<?, ?, ?> sourceGrpStmtCtx =
111 (StatementContextBase<?, ?, ?>) sourceGroupingPre.resolve(ctx);
113 copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
114 resolveUsesNode(usesNode, targetNodeStmtCtx);
115 StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
119 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
120 InferenceException.throwIf(failed.contains(sourceGroupingPre), usesNode.sourceReference(),
121 "Grouping '%s' was not resolved.", groupingName);
122 throw new InferenceException("Unknown error occurred.", usesNode.sourceReference());
128 protected SubstatementValidator getSubstatementValidator() {
129 return SUBSTATEMENT_VALIDATOR;
133 protected UsesStatement createDeclared(final StmtContext<QName, UsesStatement, ?> ctx,
134 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
135 return new RegularUsesStatement(ctx.getRawArgument(), ctx.getArgument(), substatements);
139 protected UsesStatement createEmptyDeclared(final StmtContext<QName, UsesStatement, ?> ctx) {
140 return new EmptyUsesStatement(ctx.getRawArgument(), ctx.getArgument());
144 protected UsesEffectiveStatement createEffective(final Current<QName, UsesStatement> stmt,
145 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
146 final GroupingDefinition sourceGrouping = getSourceGrouping(stmt);
147 final int flags = historyAndStatusFlags(stmt.history(), substatements);
148 final QName argument = stmt.getArgument();
149 final UsesStatement declared = stmt.declared();
151 if (substatements.isEmpty()) {
152 return argument.equals(declared.argument())
153 ? new EmptyLocalUsesEffectiveStatement(declared, sourceGrouping, flags)
154 : new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags);
157 if (declared.argument().equals(argument)) {
158 return new RegularLocalUsesEffectiveStatement(declared, sourceGrouping, flags, substatements);
160 if (findFirstStatement(substatements, RefineEffectiveStatement.class) == null) {
161 return new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
163 return new FullCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
166 static @NonNull ImmutableMap<Descendant, SchemaNode> indexRefines(
167 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
168 final Map<Descendant, SchemaNode> refines = new LinkedHashMap<>();
170 for (EffectiveStatement<?, ?> effectiveStatement : substatements) {
171 if (effectiveStatement instanceof RefineEffectiveStatementImpl) {
172 final RefineEffectiveStatementImpl refineStmt = (RefineEffectiveStatementImpl) effectiveStatement;
173 refines.put(refineStmt.argument(), refineStmt.getRefineTargetNode());
177 return ImmutableMap.copyOf(refines);
180 private static GroupingDefinition getSourceGrouping(final Current<QName, ?> stmt) {
181 return (GroupingDefinition) stmt.getFromNamespace(GroupingNamespace.class, stmt.getArgument()).buildEffective();
185 * Copy statements from a grouping to a target node.
187 * @param sourceGrpStmtCtx
188 * source grouping statement context
193 * @throws SourceException
194 * instance of SourceException
196 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
197 justification = "https://github.com/spotbugs/spotbugs/issues/811")
198 private static void copyFromSourceToTarget(final Mutable<?, ?, ?> sourceGrpStmtCtx,
199 final StatementContextBase<?, ?, ?> targetCtx,
200 final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
201 final Collection<? extends Mutable<?, ?, ?>> declared = sourceGrpStmtCtx.mutableDeclaredSubstatements();
202 final Collection<? extends Mutable<?, ?, ?>> effective = sourceGrpStmtCtx.mutableEffectiveSubstatements();
203 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
204 final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
206 for (final Mutable<?, ?, ?> original : declared) {
207 if (original.isSupportedByFeatures() && shouldCopy(original)) {
208 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
212 for (final Mutable<?, ?, ?> original : effective) {
213 if (shouldCopy(original)) {
214 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
218 targetCtx.addEffectiveSubstatements(buffer);
219 usesNode.addAsEffectOfStatement(buffer);
222 private static boolean shouldCopy(final StmtContext<?, ?, ?> stmt) {
223 // https://tools.ietf.org/html/rfc7950#section-7.13:
225 // The effect of a "uses" reference to a grouping is that the nodes
226 // defined by the grouping are copied into the current schema tree and
227 // are then updated according to the "refine" and "augment" statements.
229 // This means that the statement that is about to be copied (and can be subjected to buildEffective() I think)
230 // is actually a SchemaTreeEffectiveStatement
231 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(
232 stmt.publicDefinition().getEffectiveRepresentationClass())) {
236 // As per https://tools.ietf.org/html/rfc7950#section-7.13.2:
238 // o Any node can get refined extensions, if the extension allows
239 // refinement. See Section 7.19 for details.
241 // and https://tools.ietf.org/html/rfc7950#section-7.19:
243 // An extension can allow refinement (see Section 7.13.2) and deviations
244 // (Section 7.20.3.2), but the mechanism for how this is defined is
245 // outside the scope of this specification.
247 // This is actively used out there (tailf-common.yang's tailf:action), which is incorrect, though. They do
248 // publish a bunch of metadata (through tailf-meta-extension.yang), but fail to publish a key aspect of the
249 // statement: it attaches to schema tree namespace (just as RFC7950 action does). Such an extension would
250 // automatically result in the extension being picked up by the above check and everybody would live happily
253 // We do not live in that world yet, hence we do the following and keep our fingers crossed.
254 // FIXME: YANGTOOLS-403: this should not be necessary once we implement the above (although tests will complain)
255 return StmtContextUtils.isUnknownStatement(stmt);
258 private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
259 final StmtContext<?, ?, ?> stmtContext) {
260 if (targetCtx.getParentContext() == null) {
261 return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
263 if (targetCtx.publicDefinition() == YangStmtMapping.AUGMENT) {
264 return StmtContextUtils.getRootModuleQName(targetCtx);
267 final Object targetStmtArgument = targetCtx.argument();
268 final Object sourceStmtArgument = stmtContext.argument();
269 if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
270 return ((QName) targetStmtArgument).getModule();
276 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
277 justification = "https://github.com/spotbugs/spotbugs/issues/811")
278 private static void resolveUsesNode(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode,
279 final StmtContext<?, ?, ?> targetNodeStmtCtx) {
280 for (final Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
281 if (subStmtCtx.producesDeclared(RefineStatement.class) && areFeaturesSupported(subStmtCtx)) {
282 performRefine(subStmtCtx, targetNodeStmtCtx);
287 private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
289 * In case of Yang 1.1, checks whether features are supported.
291 return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || subStmtCtx.isSupportedByFeatures();
294 private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
295 final Object refineArgument = subStmtCtx.argument();
296 InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier), subStmtCtx.sourceReference(),
297 "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
299 final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = SchemaTreeNamespace.findNode(
300 usesParentCtx, (SchemaNodeIdentifier) refineArgument);
301 InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.sourceReference(),
302 "Refine target node %s not found.", refineArgument);
304 final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
305 if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
306 LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
307 + "Refine has been skipped. At line: {}", subStmtCtx.argument(),
308 subStmtCtx.coerceParentContext().argument(), refineTargetNodeCtx.argument(),
309 subStmtCtx.sourceReference());
310 subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
314 Verify.verify(refineTargetNodeCtx instanceof StatementContextBase);
315 addOrReplaceNodes(subStmtCtx, (StatementContextBase<?, ?, ?>) refineTargetNodeCtx);
316 subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
319 private static void addOrReplaceNodes(final Mutable<?, ?, ?> subStmtCtx,
320 final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
321 for (final Mutable<?, ?, ?> refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) {
322 if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
323 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
328 private static void addOrReplaceNode(final Mutable<?, ?, ?> refineSubstatementCtx,
329 final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
331 final StatementDefinition refineSubstatementDef = refineSubstatementCtx.publicDefinition();
333 SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
334 refineSubstatementCtx.sourceReference(),
335 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
336 refineSubstatementCtx.getRoot().rawArgument(), refineSubstatementCtx.coerceParentContext().argument(),
337 refineSubstatementCtx.publicDefinition(), refineTargetNodeCtx.publicDefinition());
339 if (isAllowedToAddByRefine(refineSubstatementDef)) {
340 refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
342 refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
343 refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
347 private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
348 return YangStmtMapping.MUST.equals(publicDefinition);
351 private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
352 final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
353 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
355 return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
356 || supportedRefineSubstatements.contains(refineSubstatementCtx.publicDefinition())
357 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
360 private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
361 final StmtContext<?, ?, ?> refineTargetNodeCtx) {
362 final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
363 refineSubstatementCtx.publicDefinition());
365 return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
366 || supportedRefineTargets.contains(refineTargetNodeCtx.publicDefinition());