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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Optional;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.common.QNameModule;
17 import org.opendaylight.yangtools.yang.common.YangVersion;
18 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
19 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
20 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
21 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
22 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
25 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace;
26 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
27 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
28 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractQNameStatementSupport;
29 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
30 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
40 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
41 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
42 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
44 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public final class UsesStatementSupport
49 extends AbstractQNameStatementSupport<UsesStatement, UsesEffectiveStatement> {
50 private static final Logger LOG = LoggerFactory.getLogger(UsesStatementSupport.class);
51 private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping
53 .addAny(YangStmtMapping.AUGMENT)
54 .addOptional(YangStmtMapping.DESCRIPTION)
55 .addAny(YangStmtMapping.IF_FEATURE)
56 .addAny(YangStmtMapping.REFINE)
57 .addOptional(YangStmtMapping.REFERENCE)
58 .addOptional(YangStmtMapping.STATUS)
59 .addOptional(YangStmtMapping.WHEN)
61 private static final UsesStatementSupport INSTANCE = new UsesStatementSupport();
63 private UsesStatementSupport() {
64 super(YangStmtMapping.USES);
67 public static UsesStatementSupport getInstance() {
72 public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
73 return StmtContextUtils.parseNodeIdentifier(ctx, value);
77 public void onFullDefinitionDeclared(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
78 if (!usesNode.isSupportedByFeatures()) {
81 super.onFullDefinitionDeclared(usesNode);
83 final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
84 final QName groupingName = usesNode.getStatementArgument();
86 final Prerequisite<StmtContext<?, ?, ?>> sourceGroupingPre = usesAction.requiresCtx(usesNode,
87 GroupingNamespace.class, groupingName, ModelProcessingPhase.EFFECTIVE_MODEL);
88 final Prerequisite<? extends StmtContext.Mutable<?, ?, ?>> targetNodePre = usesAction.mutatesEffectiveCtx(
89 usesNode.getParentContext());
91 usesAction.apply(new InferenceAction() {
94 public void apply(final InferenceContext ctx) {
95 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
96 (StatementContextBase<?, ?, ?>) targetNodePre.resolve(ctx);
97 final StatementContextBase<?, ?, ?> sourceGrpStmtCtx =
98 (StatementContextBase<?, ?, ?>) sourceGroupingPre.resolve(ctx);
100 copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
101 resolveUsesNode(usesNode, targetNodeStmtCtx);
102 StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
106 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
107 InferenceException.throwIf(failed.contains(sourceGroupingPre),
108 usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName);
109 throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
115 public UsesStatement createDeclared(final StmtContext<QName, UsesStatement, ?> ctx) {
116 return new UsesStatementImpl(ctx);
120 public UsesEffectiveStatement createEffective(final StmtContext<QName, UsesStatement, UsesEffectiveStatement> ctx) {
121 return new UsesEffectiveStatementImpl(ctx);
125 protected SubstatementValidator getSubstatementValidator() {
126 return SUBSTATEMENT_VALIDATOR;
130 * Copy statements from a grouping to a target node.
132 * @param sourceGrpStmtCtx
133 * source grouping statement context
138 * @throws SourceException
139 * instance of SourceException
141 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
142 justification = "https://github.com/spotbugs/spotbugs/issues/811")
143 private static void copyFromSourceToTarget(final Mutable<?, ?, ?> sourceGrpStmtCtx,
144 final StatementContextBase<?, ?, ?> targetCtx,
145 final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
146 final Collection<? extends Mutable<?, ?, ?>> declared = sourceGrpStmtCtx.mutableDeclaredSubstatements();
147 final Collection<? extends Mutable<?, ?, ?>> effective = sourceGrpStmtCtx.mutableEffectiveSubstatements();
148 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
149 final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
151 for (final Mutable<?, ?, ?> original : declared) {
152 if (original.isSupportedByFeatures() && shouldCopy(original)) {
153 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
157 for (final Mutable<?, ?, ?> original : effective) {
158 if (shouldCopy(original)) {
159 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
163 targetCtx.addEffectiveSubstatements(buffer);
164 usesNode.addAsEffectOfStatement(buffer);
167 private static boolean shouldCopy(final StmtContext<?, ?, ?> stmt) {
168 // https://tools.ietf.org/html/rfc7950#section-7.13:
170 // The effect of a "uses" reference to a grouping is that the nodes
171 // defined by the grouping are copied into the current schema tree and
172 // are then updated according to the "refine" and "augment" statements.
174 // This means that the statement that is about to be copied (and can be subjected to buildEffective() I think)
175 // is actually a SchemaTreeEffectiveStatement
176 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(
177 stmt.getPublicDefinition().getEffectiveRepresentationClass())) {
181 // As per https://tools.ietf.org/html/rfc7950#section-7.13.2:
183 // o Any node can get refined extensions, if the extension allows
184 // refinement. See Section 7.19 for details.
186 // and https://tools.ietf.org/html/rfc7950#section-7.19:
188 // An extension can allow refinement (see Section 7.13.2) and deviations
189 // (Section 7.20.3.2), but the mechanism for how this is defined is
190 // outside the scope of this specification.
192 // This is actively used out there (tailf-common.yang's tailf:action), which is incorrect, though. They do
193 // publish a bunch of metadata (through tailf-meta-extension.yang), but fail to publish a key aspect of the
194 // statement: it attaches to schema tree namespace (just as RFC7950 action does). Such an extension would
195 // automatically result in the extension being picked up by the above check and everybody would live happily
198 // We do not live in that world yet, hence we do the following and keep our fingers crossed.
199 // FIXME: YANGTOOLS-403: this should not be necessary once we implement the above (although tests will complain)
200 return StmtContextUtils.isUnknownStatement(stmt);
203 private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
204 final StmtContext<?, ?, ?> stmtContext) {
205 if (targetCtx.getParentContext() == null) {
206 return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
208 if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
209 return StmtContextUtils.getRootModuleQName(targetCtx);
212 final Object targetStmtArgument = targetCtx.getStatementArgument();
213 final Object sourceStmtArgument = stmtContext.getStatementArgument();
214 if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
215 return ((QName) targetStmtArgument).getModule();
221 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
222 justification = "https://github.com/spotbugs/spotbugs/issues/811")
223 private static void resolveUsesNode(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode,
224 final StmtContext<?, ?, ?> targetNodeStmtCtx) {
225 for (final Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
226 if (subStmtCtx.producesDeclared(RefineStatement.class) && areFeaturesSupported(subStmtCtx)) {
227 performRefine(subStmtCtx, targetNodeStmtCtx);
232 private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
234 * In case of Yang 1.1, checks whether features are supported.
236 return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || subStmtCtx.isSupportedByFeatures();
239 private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
240 final Object refineArgument = subStmtCtx.getStatementArgument();
241 InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
242 subStmtCtx.getStatementSourceReference(),
243 "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
245 final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = ChildSchemaNodeNamespace.findNode(
246 usesParentCtx, (SchemaNodeIdentifier) refineArgument);
247 InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.getStatementSourceReference(),
248 "Refine target node %s not found.", refineArgument);
250 final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
251 if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
252 LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
253 + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(),
254 subStmtCtx.coerceParentContext().getStatementArgument(),
255 refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference());
256 subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
260 Verify.verify(refineTargetNodeCtx instanceof StatementContextBase);
261 addOrReplaceNodes(subStmtCtx, (StatementContextBase<?, ?, ?>) refineTargetNodeCtx);
262 subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
265 private static void addOrReplaceNodes(final Mutable<?, ?, ?> subStmtCtx,
266 final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
267 for (final Mutable<?, ?, ?> refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) {
268 if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
269 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
274 private static void addOrReplaceNode(final Mutable<?, ?, ?> refineSubstatementCtx,
275 final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
277 final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
279 SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
280 refineSubstatementCtx.getStatementSourceReference(),
281 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
282 refineSubstatementCtx.getRoot().getStatementArgument(),
283 refineSubstatementCtx.coerceParentContext().getStatementArgument(),
284 refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition());
286 if (isAllowedToAddByRefine(refineSubstatementDef)) {
287 refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
289 refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
290 refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
294 private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
295 return YangStmtMapping.MUST.equals(publicDefinition);
298 private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
299 final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
300 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
302 return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
303 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
304 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
307 private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
308 final StmtContext<?, ?, ?> refineTargetNodeCtx) {
309 final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
310 refineSubstatementCtx.getPublicDefinition());
312 return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
313 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());