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 static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.LinkedHashMap;
18 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.yang.common.Empty;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.common.QNameModule;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
25 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference;
28 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
31 import org.opendaylight.yangtools.yang.model.api.stmt.RefineEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
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.model.ri.stmt.DeclaredStatementDecorators;
39 import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatements;
40 import org.opendaylight.yangtools.yang.parser.api.YangParserConfiguration;
41 import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles;
42 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStmtUtils;
43 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.refine.RefineEffectiveStatementImpl;
44 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.refine.RefineTargetNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.ParserNamespaces;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractQNameStatementSupport;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.BoundStmtCtx;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
58 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
60 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles;
61 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles.ValidationBundleType;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 public final class UsesStatementSupport
66 extends AbstractQNameStatementSupport<UsesStatement, UsesEffectiveStatement> {
67 private static final Logger LOG = LoggerFactory.getLogger(UsesStatementSupport.class);
68 private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
69 SubstatementValidator.builder(YangStmtMapping.USES)
70 .addAny(YangStmtMapping.AUGMENT)
71 .addOptional(YangStmtMapping.DESCRIPTION)
72 .addAny(YangStmtMapping.IF_FEATURE)
73 .addAny(YangStmtMapping.REFINE)
74 .addOptional(YangStmtMapping.REFERENCE)
75 .addOptional(YangStmtMapping.STATUS)
76 .addOptional(YangStmtMapping.WHEN)
79 public UsesStatementSupport(final YangParserConfiguration config) {
80 super(YangStmtMapping.USES, StatementPolicy.exactReplica(), config, SUBSTATEMENT_VALIDATOR);
84 public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
85 return StmtContextUtils.parseNodeIdentifier(ctx, value);
89 public void onFullDefinitionDeclared(final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
90 if (!usesNode.isSupportedByFeatures()) {
93 super.onFullDefinitionDeclared(usesNode);
95 final var usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
96 final var groupingName = usesNode.argument();
98 final var sourceGroupingPre = usesAction.requiresCtx(usesNode, ParserNamespaces.GROUPING, groupingName,
99 ModelProcessingPhase.EFFECTIVE_MODEL);
100 final var targetNodePre = usesAction.mutatesEffectiveCtx(usesNode.getParentContext());
102 usesAction.apply(new InferenceAction() {
105 public void apply(final InferenceContext ctx) {
106 final var targetNodeStmtCtx = targetNodePre.resolve(ctx);
107 final var sourceGrpStmtCtx = sourceGroupingPre.resolve(ctx);
109 copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
111 // Apply any refine statements
112 for (var subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
113 if (subStmtCtx.producesDeclared(RefineStatement.class) && areFeaturesSupported(subStmtCtx)) {
114 performRefine(subStmtCtx, targetNodeStmtCtx);
118 StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
119 usesNode.addToNs(SourceGroupingNamespace.INSTANCE, Empty.value(), sourceGrpStmtCtx);
123 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
124 InferenceException.throwIf(failed.contains(sourceGroupingPre), usesNode,
125 "Grouping '%s' was not resolved.", groupingName);
126 throw new InferenceException("Unknown error occurred.", usesNode);
132 protected UsesStatement createDeclared(final BoundStmtCtx<QName> ctx,
133 final ImmutableList<DeclaredStatement<?>> substatements) {
134 return DeclaredStatements.createUses(ctx.getRawArgument(), ctx.getArgument(), substatements);
138 protected UsesStatement attachDeclarationReference(final UsesStatement stmt, final DeclarationReference reference) {
139 return DeclaredStatementDecorators.decorateUses(stmt, reference);
143 protected UsesEffectiveStatement createEffective(final Current<QName, UsesStatement> stmt,
144 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
145 final EffectiveStatement<?, ?> source =
146 verifyNotNull(stmt.getFromNamespace(SourceGroupingNamespace.INSTANCE, Empty.value())).buildEffective();
147 verify(source instanceof GroupingDefinition, "Unexpected source %s", source);
148 final GroupingDefinition sourceGrouping = (GroupingDefinition) source;
150 final int flags = EffectiveStmtUtils.historyAndStatusFlags(stmt.history(), substatements);
151 final QName argument = stmt.getArgument();
152 final UsesStatement declared = stmt.declared();
154 if (substatements.isEmpty()) {
155 return argument.equals(declared.argument())
156 ? new EmptyLocalUsesEffectiveStatement(declared, sourceGrouping, flags)
157 : new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags);
160 if (declared.argument().equals(argument)) {
161 return new RegularLocalUsesEffectiveStatement(declared, sourceGrouping, flags, substatements);
163 if (findFirstStatement(substatements, RefineEffectiveStatement.class) == null) {
164 return new SimpleCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
166 return new FullCopiedUsesEffectiveStatement(declared, argument, sourceGrouping, flags, substatements);
169 static @NonNull ImmutableMap<Descendant, SchemaNode> indexRefines(
170 final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
171 final var refines = new LinkedHashMap<Descendant, SchemaNode>();
172 for (var effectiveStatement : substatements) {
173 if (effectiveStatement instanceof RefineEffectiveStatementImpl refineStmt) {
174 refines.put(refineStmt.argument(), refineStmt.getRefineTargetNode());
177 return ImmutableMap.copyOf(refines);
181 * Copy statements from a grouping to a target node.
183 * @param sourceGrpStmtCtx
184 * source grouping statement context
189 * @throws SourceException
190 * instance of SourceException
192 private static void copyFromSourceToTarget(final StmtContext<?, ?, ?> sourceGrpStmtCtx,
193 final Mutable<?, ?, ?> targetCtx, final Mutable<QName, UsesStatement, UsesEffectiveStatement> usesNode) {
194 final var declared = sourceGrpStmtCtx.declaredSubstatements();
195 final var effective = sourceGrpStmtCtx.effectiveSubstatements();
196 final var buffer = new ArrayList<Mutable<?, ?, ?>>(declared.size() + effective.size());
197 final var newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
199 for (var original : declared) {
200 if (shouldCopy(original)) {
201 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(copy -> {
202 if (!original.isSupportedByFeatures() || !original.isSupportedToBuildEffective()) {
203 copy.setUnsupported();
210 for (var original : effective) {
211 if (shouldCopy(original)) {
212 original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, newQNameModule).ifPresent(buffer::add);
216 targetCtx.addEffectiveSubstatements(buffer);
217 usesNode.addAsEffectOfStatement(buffer);
220 private static boolean shouldCopy(final StmtContext<?, ?, ?> stmt) {
221 // https://tools.ietf.org/html/rfc7950#section-7.13:
223 // The effect of a "uses" reference to a grouping is that the nodes
224 // defined by the grouping are copied into the current schema tree and
225 // are then updated according to the "refine" and "augment" statements.
227 // This means that the statement that is about to be copied (and can be subjected to buildEffective() I think)
228 // is actually a SchemaTreeEffectiveStatement
229 if (SchemaTreeEffectiveStatement.class.isAssignableFrom(
230 stmt.publicDefinition().getEffectiveRepresentationClass())) {
234 // As per https://tools.ietf.org/html/rfc7950#section-7.13.2:
236 // o Any node can get refined extensions, if the extension allows
237 // refinement. See Section 7.19 for details.
239 // and https://tools.ietf.org/html/rfc7950#section-7.19:
241 // An extension can allow refinement (see Section 7.13.2) and deviations
242 // (Section 7.20.3.2), but the mechanism for how this is defined is
243 // outside the scope of this specification.
245 // This is actively used out there (tailf-common.yang's tailf:action), which is incorrect, though. They do
246 // publish a bunch of metadata (through tailf-meta-extension.yang), but fail to publish a key aspect of the
247 // statement: it attaches to schema tree namespace (just as RFC7950 action does). Such an extension would
248 // automatically result in the extension being picked up by the above check and everybody would live happily
251 // We do not live in that world yet, hence we do the following and keep our fingers crossed.
252 // FIXME: YANGTOOLS-403: this should not be necessary once we implement the above (although tests will complain)
253 return StmtContextUtils.isUnknownStatement(stmt);
256 private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
257 final StmtContext<?, ?, ?> stmtContext) {
258 if (targetCtx.getParentContext() == null) {
259 return targetCtx.getFromNamespace(ParserNamespaces.MODULECTX_TO_QNAME, targetCtx);
261 if (targetCtx.publicDefinition() == YangStmtMapping.AUGMENT) {
262 return StmtContextUtils.getRootModuleQName(targetCtx);
264 if (targetCtx.argument() instanceof QName targetQName && stmtContext.argument() instanceof QName) {
265 return targetQName.getModule();
271 private static boolean areFeaturesSupported(final StmtContext<?, ?, ?> subStmtCtx) {
273 * In case of Yang 1.1, checks whether features are supported.
275 return !YangVersion.VERSION_1_1.equals(subStmtCtx.yangVersion()) || subStmtCtx.isSupportedByFeatures();
278 private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
279 final Object refineArgument = subStmtCtx.argument();
280 InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier), subStmtCtx,
281 "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
283 // FIXME: this really should be handled via separate inference, i.e. we first instantiate the template and when
284 // it appears, this refine will trigger on it. This reinforces the FIXME below.
285 final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = ParserNamespaces.findSchemaTreeStatement(
286 usesParentCtx, (SchemaNodeIdentifier) refineArgument);
287 InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx, "Refine target node %s not found.",
290 // FIXME: This communicates the looked-up target node to RefineStatementSupport.buildEffective(). We should do
291 // this trick through a shared namespace or similar reactor-agnostic meeting place. It really feels like
292 // an inference action RefineStatementSupport should be doing.
293 final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
294 if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
295 LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
296 + "Refine has been skipped. At line: {}", subStmtCtx.argument(),
297 subStmtCtx.coerceParentContext().argument(), refineTargetNodeCtx.argument(),
298 subStmtCtx.sourceReference());
300 verify(refineTargetNodeCtx instanceof Mutable, "Unexpected target %s", refineTargetNodeCtx);
301 addOrReplaceNodes(subStmtCtx, (Mutable<?, ?, ?>) refineTargetNodeCtx);
304 // Target is a prerequisite for the 'refine', hence if the target is not supported, the refine is not supported
305 // as well. Otherwise add a pointer to the target into refine's local namespace.
306 if (refineTargetNodeCtx.isSupportedToBuildEffective()) {
307 subStmtCtx.addToNs(RefineTargetNamespace.INSTANCE, Empty.value(), refineTargetNodeCtx);
309 subStmtCtx.setUnsupported();
313 private static void addOrReplaceNodes(final StmtContext<?, ?, ?> subStmtCtx,
314 final Mutable<?, ?, ?> refineTargetNodeCtx) {
315 for (StmtContext<?, ?, ?> refineSubstatementCtx : subStmtCtx.declaredSubstatements()) {
316 if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
317 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
322 private static void addOrReplaceNode(final StmtContext<?, ?, ?> refineSubstatementCtx,
323 final Mutable<?, ?, ?> refineTargetNodeCtx) {
325 final StatementDefinition refineSubstatementDef = refineSubstatementCtx.publicDefinition();
327 // FIXME: this is quite costly, use an explicit block
328 SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
329 refineSubstatementCtx,
330 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
331 refineSubstatementCtx.getRoot().rawArgument(), refineSubstatementCtx.coerceParentContext().argument(),
332 refineSubstatementCtx.publicDefinition(), refineTargetNodeCtx.publicDefinition());
334 if (!isAllowedToAddByRefine(refineSubstatementDef)) {
335 refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef);
337 // FIXME: childCopyOf() should handle this through per-statement copy policy, right?
338 refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx.replicaAsChildOf(refineTargetNodeCtx));
341 // FIXME: clarify this and inline into single caller
342 private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
343 return YangStmtMapping.MUST.equals(publicDefinition);
346 private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
347 final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
348 ValidationBundles.NAMESPACE, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
350 return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty()
351 || supportedRefineSubstatements.contains(refineSubstatementCtx.publicDefinition())
352 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
355 private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
356 final StmtContext<?, ?, ?> refineTargetNodeCtx) {
357 final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get(
358 refineSubstatementCtx.publicDefinition());
360 return supportedRefineTargets == null || supportedRefineTargets.isEmpty()
361 || supportedRefineTargets.contains(refineTargetNodeCtx.publicDefinition());