Throw SourceException instead of IllegalArgumentException
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / UsesStatementImpl.java
index 1fa72be8ffdc9bb5e58c34c9e0c4dce2d77a04c0..7e39d918d5e61975e4c620eb2065e94a708b2b18 100644 (file)
@@ -7,13 +7,15 @@
  */
 package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableSet;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Set;
+import javax.annotation.Nonnull;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.model.api.Rfc6020Mapping;
+import org.opendaylight.yangtools.yang.common.YangVersion;
+import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
@@ -26,18 +28,19 @@ import org.opendaylight.yangtools.yang.model.api.stmt.StatusStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.WhenStatement;
 import org.opendaylight.yangtools.yang.parser.spi.GroupingNamespace;
-import org.opendaylight.yangtools.yang.parser.spi.SubstatementValidator;
 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractDeclaredStatement;
-import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
+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;
@@ -47,17 +50,16 @@ import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.UsesEffecti
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-
 public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implements UsesStatement {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(Rfc6020Mapping
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(YangStmtMapping
             .USES)
-            .addAny(Rfc6020Mapping.AUGMENT)
-            .addOptional(Rfc6020Mapping.DESCRIPTION)
-            .addAny(Rfc6020Mapping.IF_FEATURE)
-            .addAny(Rfc6020Mapping.REFINE)
-            .addOptional(Rfc6020Mapping.REFERENCE)
-            .addOptional(Rfc6020Mapping.STATUS)
-            .addOptional(Rfc6020Mapping.WHEN)
+            .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 Logger LOG = LoggerFactory.getLogger(UsesStatementImpl.class);
@@ -67,31 +69,26 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
     }
 
     public static class Definition extends
-            AbstractStatementSupport<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> {
+            AbstractQNameStatementSupport<UsesStatement, EffectiveStatement<QName, UsesStatement>> {
 
         public Definition() {
-            super(Rfc6020Mapping.USES);
+            super(YangStmtMapping.USES);
         }
 
         @Override
         public QName parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
-            return Utils.qNameFromArgument(ctx, value);
+            return StmtContextUtils.qnameFromArgument(ctx, value);
         }
 
         @Override
         public void onFullDefinitionDeclared(
-                final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode) {
-            if (!StmtContextUtils.areFeaturesSupported(usesNode)) {
-                return;
-            }
-
-            SUBSTATEMENT_VALIDATOR.validate(usesNode);
-
-            if (StmtContextUtils.isInExtensionBody(usesNode)) {
+                final Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode) {
+            if (!usesNode.isSupportedByFeatures()) {
                 return;
             }
+            super.onFullDefinitionDeclared(usesNode);
 
-            ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
+            final ModelActionBuilder usesAction = usesNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
             final QName groupingName = usesNode.getStatementArgument();
 
             final Prerequisite<StmtContext<?, ?, ?>> sourceGroupingPre = usesAction.requiresCtx(usesNode,
@@ -102,14 +99,15 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
             usesAction.apply(new InferenceAction() {
 
                 @Override
-                public void apply() {
-                    StatementContextBase<?, ?, ?> targetNodeStmtCtx = (StatementContextBase<?, ?, ?>) targetNodePre.get();
-                    StatementContextBase<?, ?, ?> sourceGrpStmtCtx = (StatementContextBase<?, ?, ?>) sourceGroupingPre.get();
+                public void apply(final InferenceContext ctx) {
+                    final StatementContextBase<?, ?, ?> targetNodeStmtCtx = (StatementContextBase<?, ?, ?>) targetNodePre.resolve(ctx);
+                    final StatementContextBase<?, ?, ?> sourceGrpStmtCtx = (StatementContextBase<?, ?, ?>) sourceGroupingPre.resolve(ctx);
 
                     try {
                         copyFromSourceToTarget(sourceGrpStmtCtx, targetNodeStmtCtx, usesNode);
                         resolveUsesNode(usesNode, targetNodeStmtCtx);
-                    } catch (SourceException e) {
+                        StmtContextUtils.validateIfFeatureAndWhenOnListKeys(usesNode);
+                    } catch (final SourceException e) {
                         LOG.warn(e.getMessage(), e);
                         throw e;
                     }
@@ -135,8 +133,14 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
             return new UsesEffectiveStatementImpl(ctx);
         }
 
+        @Override
+        protected SubstatementValidator getSubstatementValidator() {
+            return SUBSTATEMENT_VALIDATOR;
+        }
+
     }
 
+    @Nonnull
     @Override
     public QName getName() {
         return argument();
@@ -147,6 +151,7 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
         return firstDeclared(WhenStatement.class);
     }
 
+    @Nonnull
     @Override
     public Collection<? extends IfFeatureStatement> getIfFeatures() {
         return allDeclared(IfFeatureStatement.class);
@@ -167,11 +172,13 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
         return firstDeclared(ReferenceStatement.class);
     }
 
+    @Nonnull
     @Override
     public Collection<? extends AugmentStatement> getAugments() {
         return allDeclared(AugmentStatement.class);
     }
 
+    @Nonnull
     @Override
     public Collection<? extends RefineStatement> getRefines() {
         return allDeclared(RefineStatement.class);
@@ -187,53 +194,55 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
      * @throws SourceException
      *             instance of SourceException
      */
-    private static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceGrpStmtCtx,
+    static void copyFromSourceToTarget(final Mutable<?, ?, ?> sourceGrpStmtCtx,
             final StatementContextBase<?, ?, ?> targetCtx,
             final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode) {
-
+        final Collection<? extends Mutable<?, ?, ?>> declared = sourceGrpStmtCtx.mutableDeclaredSubstatements();
+        final Collection<? extends Mutable<?, ?, ?>> effective = sourceGrpStmtCtx.mutableEffectiveSubstatements();
+        final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
         final QNameModule newQNameModule = getNewQNameModule(targetCtx, sourceGrpStmtCtx);
-        for (final StatementContextBase<?, ?, ?> original : sourceGrpStmtCtx.declaredSubstatements()) {
-            if (StmtContextUtils.areFeaturesSupported(original)) {
-                copyStatement(original, targetCtx, usesNode, newQNameModule);
+
+        for (final Mutable<?, ?, ?> original : declared) {
+            if (original.isSupportedByFeatures()) {
+                copyStatement(original, targetCtx, newQNameModule, buffer);
             }
         }
 
-        for (final StatementContextBase<?, ?, ?> original : sourceGrpStmtCtx.effectiveSubstatements()) {
-            copyStatement(original, targetCtx, usesNode, newQNameModule);
+        for (final Mutable<?, ?, ?> original : effective) {
+            copyStatement(original, targetCtx, newQNameModule, buffer);
         }
+
+        targetCtx.addEffectiveSubstatements(buffer);
+        usesNode.addAsEffectOfStatement(buffer);
     }
 
-    private static void copyStatement(final StatementContextBase<?, ?, ?> original,
-            final StatementContextBase<?, ?, ?> targetCtx,
-            final StmtContext.Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> targetUses,
-            final QNameModule targetModule) {
+    private static void copyStatement(final Mutable<?, ?, ?> original,
+            final StatementContextBase<?, ?, ?> targetCtx, final QNameModule targetModule,
+            final Collection<Mutable<?, ?, ?>> buffer) {
         if (needToCopyByUses(original)) {
-            final StatementContextBase<?, ?, ?> copy = original.createCopy(targetModule, targetCtx,
-                    CopyType.ADDED_BY_USES);
-            targetCtx.addEffectiveSubstatement(copy);
-            targetUses.addAsEffectOfStatement(copy);
+            final Mutable<?, ?, ?> copy = targetCtx.childCopyOf(original, CopyType.ADDED_BY_USES, targetModule);
+            buffer.add(copy);
         } else if (isReusedByUsesOnTop(original)) {
-            targetCtx.addEffectiveSubstatement(original);
-            targetUses.addAsEffectOfStatement(original);
+            buffer.add(original);
         }
     }
 
-    private static final Set<Rfc6020Mapping> TOP_REUSED_DEF_SET = ImmutableSet.of(
-        Rfc6020Mapping.TYPE,
-        Rfc6020Mapping.TYPEDEF);
+    private static final Set<YangStmtMapping> TOP_REUSED_DEF_SET = ImmutableSet.of(
+        YangStmtMapping.TYPE,
+        YangStmtMapping.TYPEDEF);
 
     private static boolean isReusedByUsesOnTop(final StmtContext<?, ?, ?> stmtContext) {
         return TOP_REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
     }
 
-    private static final Set<Rfc6020Mapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
-        Rfc6020Mapping.DESCRIPTION,
-        Rfc6020Mapping.REFERENCE,
-        Rfc6020Mapping.STATUS);
-    private static final Set<Rfc6020Mapping> REUSED_DEF_SET = ImmutableSet.of(
-        Rfc6020Mapping.TYPE,
-        Rfc6020Mapping.TYPEDEF,
-        Rfc6020Mapping.USES);
+    private static final Set<YangStmtMapping> NOCOPY_FROM_GROUPING_SET = ImmutableSet.of(
+        YangStmtMapping.DESCRIPTION,
+        YangStmtMapping.REFERENCE,
+        YangStmtMapping.STATUS);
+    private static final Set<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(
+        YangStmtMapping.TYPE,
+        YangStmtMapping.TYPEDEF,
+        YangStmtMapping.USES);
 
     public static boolean needToCopyByUses(final StmtContext<?, ?, ?> stmtContext) {
         final StatementDefinition def = stmtContext.getPublicDefinition();
@@ -242,7 +251,7 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
             return false;
         }
         if (NOCOPY_FROM_GROUPING_SET.contains(def)) {
-            return !Rfc6020Mapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
+            return !YangStmtMapping.GROUPING.equals(stmtContext.getParentContext().getPublicDefinition());
         }
 
         LOG.debug("Will copy {} statement {}", def, stmtContext);
@@ -251,50 +260,59 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
 
     public static void resolveUsesNode(
             final Mutable<QName, UsesStatement, EffectiveStatement<QName, UsesStatement>> usesNode,
-            final StatementContextBase<?, ?, ?> targetNodeStmtCtx) {
-        for (final StatementContextBase<?, ?, ?> subStmtCtx : usesNode.declaredSubstatements()) {
-            if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)) {
+            final StmtContext<?, ?, ?> targetNodeStmtCtx) {
+        for (final Mutable<?, ?, ?> subStmtCtx : usesNode.mutableDeclaredSubstatements()) {
+            if (StmtContextUtils.producesDeclared(subStmtCtx, RefineStatement.class)
+                    && areFeaturesSupported(subStmtCtx)) {
                 performRefine(subStmtCtx, targetNodeStmtCtx);
             }
         }
     }
 
-    private static void performRefine(final StatementContextBase<?, ?, ?> refineCtx,
-            final StatementContextBase<?, ?, ?> usesParentCtx) {
+    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 = refineCtx.getStatementArgument();
-        Preconditions.checkArgument(refineArgument instanceof SchemaNodeIdentifier,
-                "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier. At %s", refineArgument,
-                refineCtx.getStatementSourceReference());
+        final Object refineArgument = subStmtCtx.getStatementArgument();
+        InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier),
+            subStmtCtx.getStatementSourceReference(),
+            "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
 
         final SchemaNodeIdentifier refineTargetNodeIdentifier = (SchemaNodeIdentifier) refineArgument;
         final StatementContextBase<?, ?, ?> refineTargetNodeCtx = Utils.findNode(usesParentCtx,
                 refineTargetNodeIdentifier);
-        Preconditions.checkArgument(refineTargetNodeCtx != null, "Refine target node %s not found. At %s",
-                refineTargetNodeIdentifier, refineCtx.getStatementSourceReference());
+
+        InferenceException.throwIfNull(refineTargetNodeCtx, subStmtCtx.getStatementSourceReference(),
+            "Refine target node %s not found.", refineTargetNodeIdentifier);
+
         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
-            LOG.debug(
-                    "Refine node '{}' in uses '{}' has target node unknown statement '{}'. Refine has been skipped. At line: {}",
-                    refineCtx.getStatementArgument(), refineCtx.getParentContext().getStatementArgument(),
-                    refineTargetNodeCtx.getStatementArgument(), refineCtx.getStatementSourceReference());
-            refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
+            LOG.debug("Refine node '{}' in uses '{}' has target node unknown statement '{}'. "
+                + "Refine has been skipped. At line: {}", subStmtCtx.getStatementArgument(),
+                subStmtCtx.getParentContext().getStatementArgument(),
+                refineTargetNodeCtx.getStatementArgument(), subStmtCtx.getStatementSourceReference());
+            subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
             return;
         }
 
-        addOrReplaceNodes(refineCtx, refineTargetNodeCtx);
-        refineCtx.addAsEffectOfStatement(refineTargetNodeCtx);
+        addOrReplaceNodes(subStmtCtx, refineTargetNodeCtx);
+        subStmtCtx.addAsEffectOfStatement(refineTargetNodeCtx);
     }
 
-    private static void addOrReplaceNodes(final StatementContextBase<?, ?, ?> refineCtx,
+    private static void addOrReplaceNodes(final Mutable<?, ?, ?> subStmtCtx,
             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
-        for (final StatementContextBase<?, ?, ?> refineSubstatementCtx : refineCtx.declaredSubstatements()) {
+        for (final Mutable<?, ?, ?> refineSubstatementCtx : subStmtCtx.mutableDeclaredSubstatements()) {
             if (isSupportedRefineSubstatement(refineSubstatementCtx)) {
                 addOrReplaceNode(refineSubstatementCtx, refineTargetNodeCtx);
             }
         }
     }
 
-    private static void addOrReplaceNode(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
+    private static void addOrReplaceNode(final Mutable<?, ?, ?> refineSubstatementCtx,
             final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
 
         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.getPublicDefinition();
@@ -314,13 +332,13 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
         }
     }
 
-    private static final Set<Rfc6020Mapping> ALLOWED_TO_ADD_BY_REFINE_DEF_SET = ImmutableSet.of(Rfc6020Mapping.MUST);
+    private static final Set<YangStmtMapping> ALLOWED_TO_ADD_BY_REFINE_DEF_SET = ImmutableSet.of(YangStmtMapping.MUST);
 
     private static boolean isAllowedToAddByRefine(final StatementDefinition publicDefinition) {
         return ALLOWED_TO_ADD_BY_REFINE_DEF_SET.contains(publicDefinition);
     }
 
-    private static boolean isSupportedRefineSubstatement(final StatementContextBase<?, ?, ?> refineSubstatementCtx) {
+    private static boolean isSupportedRefineSubstatement(final StmtContext<?, ?, ?> refineSubstatementCtx) {
         final Collection<?> supportedRefineSubstatements = refineSubstatementCtx.getFromNamespace(
                 ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_REFINE_SUBSTATEMENTS);
 
@@ -329,9 +347,8 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
                 || StmtContextUtils.isUnknownStatement(refineSubstatementCtx);
     }
 
-    private static boolean isSupportedRefineTarget(final StatementContextBase<?, ?, ?> refineSubstatementCtx,
-            final StatementContextBase<?, ?, ?> refineTargetNodeCtx) {
-
+    private static boolean isSupportedRefineTarget(final StmtContext<?, ?, ?> refineSubstatementCtx,
+            final StmtContext<?, ?, ?> refineTargetNodeCtx) {
         final Collection<?> supportedRefineTargets = YangValidationBundles.SUPPORTED_REFINE_TARGETS
                 .get(refineSubstatementCtx.getPublicDefinition());
 
@@ -340,13 +357,13 @@ public class UsesStatementImpl extends AbstractDeclaredStatement<QName> implemen
     }
 
 
-    private static QNameModule getNewQNameModule(final StatementContextBase<?, ?, ?> targetCtx,
+    private static QNameModule getNewQNameModule(final StmtContext<?, ?, ?> targetCtx,
             final StmtContext<?, ?, ?> stmtContext) {
-        if (targetCtx.isRootContext()) {
+        if (targetCtx.getParentContext() == null) {
             return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx);
         }
-        if (targetCtx.getPublicDefinition() == Rfc6020Mapping.AUGMENT) {
-            return targetCtx.getFromNamespace(ModuleCtxToModuleQName.class, targetCtx.getRoot());
+        if (targetCtx.getPublicDefinition() == YangStmtMapping.AUGMENT) {
+            return StmtContextUtils.getRootModuleQName(targetCtx);
         }
 
         final Object targetStmtArgument = targetCtx.getStatementArgument();