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.Status;
26 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
30 import org.opendaylight.yangtools.yang.model.api.stmt.RefineEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.StatusEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace;
39 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
40 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseQNameStatementSupport;
41 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.EffectiveStatementWithFlags.FlagsBuilder;
42 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.refine.RefineEffectiveStatementImpl;
43 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
55 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
56 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
57 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
58 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
59 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public final class UsesStatementSupport
64 extends BaseQNameStatementSupport<UsesStatement, UsesEffectiveStatement> {
65 private static final Logger LOG = LoggerFactory.getLogger(UsesStatementSupport.class);
66 private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping
68 .addAny(YangStmtMapping.AUGMENT)
69 .addOptional(YangStmtMapping.DESCRIPTION)
70 .addAny(YangStmtMapping.IF_FEATURE)
71 .addAny(YangStmtMapping.REFINE)
72 .addOptional(YangStmtMapping.REFERENCE)
73 .addOptional(YangStmtMapping.STATUS)
74 .addOptional(YangStmtMapping.WHEN)
76 private static final UsesStatementSupport INSTANCE = new UsesStatementSupport();
78 private UsesStatementSupport() {
79 super(YangStmtMapping.USES);
82 public static UsesStatementSupport getInstance() {
87 public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
88 return StmtContextUtils.parseNodeIdentifier(ctx, value);
92 public void onFullDefinitionDeclared(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
93 if (!usesNode.isSupportedByFeatures()) {
96 super.onFullDefinitionDeclared(usesNode);
98 final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
99 final QName groupingName = usesNode.getStatementArgument();
101 final Prerequisite<StmtContext<?, ?, ?>> sourceGroupingPre = usesAction.requiresCtx(usesNode,
102 GroupingNamespace.class, groupingName, ModelProcessingPhase.EFFECTIVE_MODEL);
103 final Prerequisite<? extends StmtContext.Mutable<?, ?, ?>> targetNodePre = usesAction.mutatesEffectiveCtx(
104 usesNode.getParentContext());
106 usesAction.apply(new InferenceAction() {
109 public void apply(final InferenceContext ctx) {
110 final StatementContextBase<?, ?, ?> targetNodeStmtCtx =
111 (StatementContextBase<?, ?, ?>) targetNodePre.resolve(ctx);
112 final StatementContextBase<?, ?, ?> sourceGrpStmtCtx =
113 (StatementContextBase<?, ?, ?>) sourceGroupingPre.resolve(ctx);
115 copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
116 resolveUsesNode(usesNode, targetNodeStmtCtx);
117 StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
121 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
122 InferenceException.throwIf(failed.contains(sourceGroupingPre),
123 usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName);
124 throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference());
130 protected SubstatementValidator getSubstatementValidator() {
131 return SUBSTATEMENT_VALIDATOR;
135 protected UsesStatement createDeclared(final StmtContext<QName, UsesStatement, ?> ctx,
136 final ImmutableList<? extends DeclaredStatement<?>> substatements) {
137 return new RegularUsesStatement(ctx, substatements);
141 protected UsesStatement createEmptyDeclared(final StmtContext<QName, UsesStatement, ?> ctx) {
142 return new EmptyUsesStatement(ctx);
146 protected UsesEffectiveStatement createEffective(
147 final StmtContext<QName, UsesStatement, UsesEffectiveStatement> ctx, final UsesStatement declared,
148 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
149 final GroupingDefinition sourceGrouping = getSourceGrouping(ctx);
150 final int flags = computeFlags(ctx, substatements);
151 final QName argument = ctx.coerceStatementArgument();
152 if (declared.argument().equals(argument)) {
153 return new RegularLocalUsesEffectiveStatement(declared, sourceGrouping, flags, substatements);
155 if (findFirstStatement(substatements, RefineEffectiveStatement.class) == null) {
156 return new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
158 return new FullCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
162 protected UsesEffectiveStatement createEmptyEffective(
163 final StmtContext<QName, UsesStatement, UsesEffectiveStatement> ctx, final UsesStatement declared) {
164 final GroupingDefinition sourceGrouping = getSourceGrouping(ctx);
165 final int flags = computeFlags(ctx, ImmutableList.of());
166 final QName argument = ctx.coerceStatementArgument();
167 return argument.equals(declared.argument())
168 ? new EmptyLocalUsesEffectiveStatement(declared, sourceGrouping, flags)
169 : new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags);
172 static @NonNull ImmutableMap<Descendant, SchemaNode> indexRefines(
173 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
174 final Map<Descendant, SchemaNode> refines = new LinkedHashMap<>();
176 for (EffectiveStatement<?, ?> effectiveStatement : substatements) {
177 if (effectiveStatement instanceof RefineEffectiveStatementImpl) {
178 final RefineEffectiveStatementImpl refineStmt = (RefineEffectiveStatementImpl) effectiveStatement;
179 refines.put(refineStmt.argument(), refineStmt.getRefineTargetNode());
183 return ImmutableMap.copyOf(refines);
186 private static GroupingDefinition getSourceGrouping(final StmtContext<QName, ?, ?> ctx) {
187 return (GroupingDefinition) ctx.getFromNamespace(GroupingNamespace.class, ctx.coerceStatementArgument())
191 private static int computeFlags(final StmtContext<QName, UsesStatement, UsesEffectiveStatement> ctx,
192 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
193 return new FlagsBuilder()
194 .setHistory(ctx.getCopyHistory())
195 .setStatus(findFirstArgument(substatements, StatusEffectiveStatement.class, Status.CURRENT))
200 * Copy statements from a grouping to a target node.
202 * @param sourceGrpStmtCtx
203 * source grouping statement context
208 * @throws SourceException
209 * instance of SourceException
211 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
212 justification = "https://github.com/spotbugs/spotbugs/issues/811")
213 private static void copyFromSourceToTarget(final Mutable<?, ?, ?> sourceGrpStmtCtx,
214 final StatementContextBase<?, ?, ?> targetCtx,
215 final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
216 final Collection<? extends Mutable<?, ?, ?>> declared = sourceGrpStmtCtx.mutableDeclaredSubstatements();
217 final Collection<? extends Mutable<?, ?, ?>> effective = sourceGrpStmtCtx.mutableEffectiveSubstatements();
218 final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
219 final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
221 for (final Mutable<?, ?, ?> original : declared) {
222 if (original.isSupportedByFeatures() && shouldCopy(original)) {
223 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
227 for (final Mutable<?, ?, ?> original : effective) {
228 if (shouldCopy(original)) {
229 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
233 targetCtx.addEffectiveSubstatements(buffer);
234 usesNode.addAsEffectOfStatement(buffer);
237 private static boolean shouldCopy(final StmtContext<?, ?, ?> stmt) {
238 // https://tools.ietf.org/html/rfc7950#section-7.13:
240 // The effect of a "uses" reference to a grouping is that the nodes
241 // defined by the grouping are copied into the current schema tree and
242 // are then updated according to the "refine" and "augment" statements.
244 // This means that the statement that is about to be copied (and can be subjected to buildEffective() I think)
245 // is actually a SchemaTreeEffectiveStatement
246 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(
247 stmt.getPublicDefinition().getEffectiveRepresentationClass())) {
251 // As per https://tools.ietf.org/html/rfc7950#section-7.13.2:
253 // o Any node can get refined extensions, if the extension allows
254 // refinement. See Section 7.19 for details.
256 // and https://tools.ietf.org/html/rfc7950#section-7.19:
258 // An extension can allow refinement (see Section 7.13.2) and deviations
259 // (Section 7.20.3.2), but the mechanism for how this is defined is
260 // outside the scope of this specification.
262 // This is actively used out there (tailf-common.yang's tailf:action), which is incorrect, though. They do
263 // publish a bunch of metadata (through tailf-meta-extension.yang), but fail to publish a key aspect of the
264 // statement: it attaches to schema tree namespace (just as RFC7950 action does). Such an extension would
265 // automatically result in the extension being picked up by the above check and everybody would live happily
268 // We do not live in that world yet, hence we do the following and keep our fingers crossed.
269 // FIXME: YANGTOOLS-403: this should not be necessary once we implement the above (although tests will complain)
270 return StmtContextUtils.isUnknownStatement(stmt);
273 private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
274 final StmtContext<?, ?, ?> stmtContext) {
275 if (targetCtx.getParentContext() == null) {
276 return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
278 if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
279 return StmtContextUtils.getRootModuleQName(targetCtx);
282 final Object targetStmtArgument = targetCtx.getStatementArgument();
283 final Object sourceStmtArgument = stmtContext.getStatementArgument();
284 if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) {
285 return ((QName) targetStmtArgument).getModule();
291 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
292 justification = "https://github.com/spotbugs/spotbugs/issues/811")
293 private static void resolveUsesNode(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode,
294 final StmtContext<?, ?, ?> targetNodeStmtCtx) {
295 for (final Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
296 if (subStmtCtx.producesDeclared(RefineStatement.class) && areFeaturesSupported(subStmtCtx)) {
297 performRefine(subStmtCtx, targetNodeStmtCtx);
302 private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
304 * In case of Yang 1.1, checks whether features are supported.
306 return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || subStmtCtx.isSupportedByFeatures();
309 private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
310 final Object refineArgument = subStmtCtx.getStatementArgument();
311 InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
312 subStmtCtx.getStatementSourceReference(),
313 "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
315 final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = ChildSchemaNodeNamespace.findNode(
316 usesParentCtx, (SchemaNodeIdentifier) refineArgument);
317 InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.getStatementSourceReference(),
318 "Refine target node %s not found.", refineArgument);
320 final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
321 if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
322 LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
323 + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(),
324 subStmtCtx.coerceParentContext().getStatementArgument(),
325 refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference());
326 subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
330 Verify.verify(refineTargetNodeCtx instanceof StatementContextBase);
331 addOrReplaceNodes(subStmtCtx, (StatementContextBase<?, ?, ?>) refineTargetNodeCtx);
332 subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
335 private static void addOrReplaceNodes(final Mutable<?, ?, ?> subStmtCtx,
336 final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
337 for (final Mutable<?, ?, ?> refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) {
338 if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
339 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
344 private static void addOrReplaceNode(final Mutable<?, ?, ?> refineSubstatementCtx,
345 final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
347 final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
349 SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
350 refineSubstatementCtx.getStatementSourceReference(),
351 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
352 refineSubstatementCtx.getRoot().getStatementArgument(),
353 refineSubstatementCtx.coerceParentContext().getStatementArgument(),
354 refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition());
356 if (isAllowedToAddByRefine(refineSubstatementDef)) {
357 refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
359 refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
360 refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx);
364 private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
365 return YangStmtMapping.MUST.equals(publicDefinition);
368 private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
369 final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
370 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
372 return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
373 || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition())
374 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
377 private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
378 final StmtContext<?, ?, ?> refineTargetNodeCtx) {
379 final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
380 refineSubstatementCtx.getPublicDefinition());
382 return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
383 || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition());