/* * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.uses; import com.google.common.base.Verify; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.common.YangVersion; import org.opendaylight.yangtools.yang.model.api.YangStmtMapping; import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition; import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement; import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier; import org.opendaylight.yangtools.yang.model.api.stmt.UsesEffectiveStatement; import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement; import org.opendaylight.yangtools.yang.parser.rfc7950.namespace.ChildSchemaNodeNamespace; import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.YangValidationBundles; import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace; import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractQNameStatementSupport; import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType; import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException; import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder; import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction; import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext; import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite; import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase; import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext; import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable; import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils; import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator; import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName; import org.opendaylight.yangtools.yang.parser.spi.source.SourceException; import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace; import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType; import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class UsesStatementSupport extends AbstractQNameStatementSupport { private static final Logger LOG = LoggerFactory.getLogger(UsesStatementSupport.class); private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping .USES) .addAny(YangStmtMapping.AUGMENT) .addOptional(YangStmtMapping.DESCRIPTION) .addAny(YangStmtMapping.IF_FEATURE) .addAny(YangStmtMapping.REFINE) .addOptional(YangStmtMapping.REFERENCE) .addOptional(YangStmtMapping.STATUS) .addOptional(YangStmtMapping.WHEN) .build(); private static final UsesStatementSupport INSTANCE = new UsesStatementSupport(); private UsesStatementSupport() { super(YangStmtMapping.USES); } public static UsesStatementSupport getInstance() { return INSTANCE; } @Override public QName parseArgumentValue(final StmtContext ctx, final String value) { return StmtContextUtils.parseNodeIdentifier(ctx, value); } @Override public void onFullDefinitionDeclared(final Mutable usesNode) { if (!usesNode.isSupportedByFeatures()) { return; } super.onFullDefinitionDeclared(usesNode); final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL); final QName groupingName = usesNode.getStatementArgument(); final Prerequisite> sourceGroupingPre = usesAction.requiresCtx(usesNode, GroupingNamespace.class, groupingName, ModelProcessingPhase.EFFECTIVE_MODEL); final Prerequisite> targetNodePre = usesAction.mutatesEffectiveCtx( usesNode.getParentContext()); usesAction.apply(new InferenceAction() { @Override public void apply(final InferenceContext ctx) { final StatementContextBase targetNodeStmtCtx = (StatementContextBase) targetNodePre.resolve(ctx); final StatementContextBase sourceGrpStmtCtx = (StatementContextBase) sourceGroupingPre.resolve(ctx); copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode); resolveUsesNode(usesNode, targetNodeStmtCtx); StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode); } @Override public void prerequisiteFailed(final Collection> failed) { InferenceException.throwIf(failed.contains(sourceGroupingPre), usesNode.getStatementSourceReference(), "Grouping '%s' was not resolved.", groupingName); throw new InferenceException("Unknown error occurred.", usesNode.getStatementSourceReference()); } }); } @Override public UsesStatement createDeclared(final StmtContext ctx) { return new UsesStatementImpl(ctx); } @Override public UsesEffectiveStatement createEffective(final StmtContext ctx) { return new UsesEffectiveStatementImpl(ctx); } @Override protected SubstatementValidator getSubstatementValidator() { return SUBSTATEMENT_VALIDATOR; } /** * Copy statements from a grouping to a target node. * * @param sourceGrpStmtCtx * source grouping statement context * @param targetCtx * target context * @param usesNode * uses node * @throws SourceException * instance of SourceException */ private static void copyFromSourceToTarget(final Mutable sourceGrpStmtCtx, final StatementContextBase targetCtx, final Mutable usesNode) { final Collection> declared = sourceGrpStmtCtx.mutableDeclaredSubstatements(); final Collection> effective = sourceGrpStmtCtx.mutableEffectiveSubstatements(); final Collection> buffer = new ArrayList<>(declared.size() + effective.size()); final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx); for (final Mutable original : declared) { if (original.isSupportedByFeatures()) { copyStatement(original, targetCtx, newQNameModule, buffer); } } for (final Mutable original : effective) { copyStatement(original, targetCtx, newQNameModule, buffer); } targetCtx.addEffectiveSubstatements(buffer); usesNode.addAsEffectOfStatement(buffer); } // FIXME: YANGTOOLS-652: this map looks very much like InferredStatementContext.REUSED_DEF_SET // FIXME: YANGTOOLS-694: we should take advantage of CopyPolicy private static final ImmutableSet TOP_REUSED_DEF_SET = ImmutableSet.of( YangStmtMapping.TYPE, YangStmtMapping.TYPEDEF); private static final ImmutableSet DOCUMENTATION_STATEMENTS = ImmutableSet.of( YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS); private static void copyStatement(final Mutable original, final StatementContextBase targetCtx, final QNameModule targetModule, final Collection> buffer) { // FIXME: YANGTOOLS-694: This method needs to be adjusted to account for RFC7950, // https://tools.ietf.org/html/rfc7950#section-7.13, which states that: // // The effect of a "uses" reference to a grouping is that the nodes // defined by the grouping are copied into the current schema tree and // are then updated according to the "refine" and "augment" statements. // // This means that the statement that is about to be copied (and can be subjected to // buildEffective() I think) is actually a SchemaTreeEffectiveStatement -- i.e. if it // is not a SchemaTreeEffectiveStatement, it just cannot be added to target's tree and // hence it should not be copied. final StatementDefinition def = original.getPublicDefinition(); if (DOCUMENTATION_STATEMENTS.contains(def)) { // We do not want to propagate description/reference/status statements, as they are the source grouping's // documentation, not target statement's return; } if (TOP_REUSED_DEF_SET.contains(def)) { // a grouping's type/typedef statements are fully defined at the grouping, we want the same effective // statement buffer.add(original); return; } if (YangStmtMapping.USES.equals(def)) { // Do not propagate uses, as their effects have been accounted for in effective statements // FIXME: YANGTOOLS-652: this check is different from InferredStatementContext. Why is that? We should // express a common condition in our own implementation of applyCopyPolicy() // FIXME: YANGTOOLS-694: note that if the above is true, why are we propagating grouping statements? return; } original.copyAsChildOf(targetCtx, CopyType.ADDED_BY_USES, targetModule).ifPresent(buffer::add); } private static QNameModule getNewQNameModule(final StmtContext targetCtx, final StmtContext stmtContext) { if (targetCtx.getParentContext() == null) { return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx); } if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) { return StmtContextUtils.getRootModuleQName(targetCtx); } final Object targetStmtArgument = targetCtx.getStatementArgument(); final Object sourceStmtArgument = stmtContext.getStatementArgument(); if (targetStmtArgument instanceof QName && sourceStmtArgument instanceof QName) { return ((QName) targetStmtArgument).getModule(); } return null; } private static void resolveUsesNode(final Mutable usesNode, final StmtContext targetNodeStmtCtx) { for (final Mutable subStmtCtx : usesNode.mutableDeclaredSubstatements()) { if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class) && areFeaturesSupported(subStmtCtx)) { performRefine(subStmtCtx, targetNodeStmtCtx); } } } private static boolean areFeaturesSupported(final StmtContext subStmtCtx) { /* * In case of Yang 1.1, checks whether features are supported. */ return !YangVersion.VERSION_1_1.equals(subStmtCtx.getRootVersion()) || subStmtCtx.isSupportedByFeatures(); } private static void performRefine(final Mutable subStmtCtx, final StmtContext usesParentCtx) { final Object refineArgument = subStmtCtx.getStatementArgument(); InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier), subStmtCtx.getStatementSourceReference(), "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument); final Optional> optRefineTargetCtx = ChildSchemaNodeNamespace.findNode( usesParentCtx, (SchemaNodeIdentifier) refineArgument); InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.getStatementSourceReference(), "Refine target node %s not found.", refineArgument); final StmtContext refineTargetNodeCtx = optRefineTargetCtx.get(); if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) { LOG.trace("Refine node '{}' in uses '{}' has target node unknown statement '{}'. " + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(), subStmtCtx.coerceParentContext().getStatementArgument(), refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference()); subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx); return; } Verify.verify(refineTargetNodeCtx instanceof StatementContextBase); addOrReplaceNodes(subStmtCtx, (StatementContextBase) refineTargetNodeCtx); subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx); } private static void addOrReplaceNodes(final Mutable subStmtCtx, final StatementContextBase refineTargetNodeCtx) { for (final Mutable refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) { if (isSupportedRefineSubstatement(refineSubstatementCtx)) { addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx); } } } private static void addOrReplaceNode(final Mutable refineSubstatementCtx, final StatementContextBase refineTargetNodeCtx) { final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition(); SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx), refineSubstatementCtx.getStatementSourceReference(), "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.", refineSubstatementCtx.getRoot().getStatementArgument(), refineSubstatementCtx.coerceParentContext().getStatementArgument(), refineSubstatementCtx.getPublicDefinition(), refineTargetNodeCtx.getPublicDefinition()); if (isAllowedToAddByRefine(refineSubstatementDef)) { refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx); } else { refineTargetNodeCtx.removeStatementFromEffectiveSubstatements(refineSubstatementDef); refineTargetNodeCtx.addEffectiveSubstatement(refineSubstatementCtx); } } private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) { return YangStmtMapping.MUST.equals(publicDefinition); } private static boolean isSupportedRefineSubstatement(final StmtContext refineSubstatementCtx) { final Collection supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace( ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS); return supportedRefineSubstatements == null || supportedRefineSubstatements.isEmpty() || supportedRefineSubstatements.contains(refineSubstatementCtx.getPublicDefinition()) || StmtContextUtils.isUnknownStatement(refineSubstatementCtx); } private static boolean isSupportedRefineTarget(final StmtContext refineSubstatementCtx, final StmtContext refineTargetNodeCtx) { final Collection supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS.get( refineSubstatementCtx.getPublicDefinition()); return supportedRefineTargets == null || supportedRefineTargets.isEmpty() || supportedRefineTargets.contains(refineTargetNodeCtx.getPublicDefinition()); } }