Un-deprecate CopyableNode, AddedByUsesAware
[yangtools.git] / yang / yang-parser-spi / src / main / java / org / opendaylight / yangtools / yang / parser / spi / meta / StmtContextUtils.java
index ecdcd03efff7844af916f75e01e488dd1cc2336b..abefa2c75fb7c69283a60f317cbfd946e0b99c8a 100644 (file)
@@ -11,20 +11,24 @@ import static com.google.common.base.Preconditions.checkArgument;
 import static java.util.Objects.requireNonNull;
 
 import com.google.common.base.Strings;
+import com.google.common.base.VerifyException;
 import com.google.common.collect.ImmutableList;
+import java.util.ArrayList;
 import java.util.Collection;
+import java.util.List;
 import java.util.Optional;
 import java.util.Set;
 import java.util.function.Predicate;
+import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.common.Revision;
 import org.opendaylight.yangtools.yang.common.YangVersion;
 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
-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.BelongsToStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.KeyEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.LeafStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.MandatoryStatement;
@@ -35,7 +39,10 @@ import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.UnknownStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.UnrecognizedStatement;
-import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Parent;
+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.StmtContext.Mutable;
 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
@@ -151,7 +158,7 @@ public final class StmtContextUtils {
      * @param <A> statement argument type
      * @param <D> declared statement type
      * @return statement context that was searched for or null if was not found
-     * @deprecated Use {@link StmtContext#findSubstatementArgument(Class)} instead.
+     * @deprecated Use {@link BoundStmtCtx#findSubstatementArgument(Class)} instead.
      */
     @Deprecated(forRemoval = true)
     public static <A, D extends DeclaredStatement<A>> StmtContext<A, ?, ?> findFirstSubstatement(
@@ -336,63 +343,75 @@ public final class StmtContextUtils {
      * Checks whether at least one ancestor of a StatementContext matches one from a collection of statement
      * definitions.
      *
-     * @param stmt EffectiveStmtCtx to be checked
+     * @param stmt Statement context to be checked
      * @param ancestorTypes collection of statement definitions
      * @return true if at least one ancestor of a StatementContext matches one
      *         from collection of statement definitions, otherwise false.
      */
-    public static boolean hasAncestorOfType(final EffectiveStmtCtx stmt,
+    public static boolean hasAncestorOfType(final StmtContext<?, ?, ?> stmt,
             final Collection<StatementDefinition> ancestorTypes) {
         requireNonNull(ancestorTypes);
-        Parent current = stmt.effectiveParent();
+        StmtContext<?, ?, ?> current = stmt.getParentContext();
         while (current != null) {
             if (ancestorTypes.contains(current.publicDefinition())) {
                 return true;
             }
-            current = current.effectiveParent();
+            current = current.getParentContext();
         }
         return false;
     }
 
     /**
-     * Checks whether all of StmtContext's ancestors of specified type have a child of specified type.
+     * Check whether all of StmtContext's {@code list} ancestors have a {@code key}.
      *
      * @param stmt EffectiveStmtCtx to be checked
-     * @param ancestorType type of ancestor to search for
-     * @param ancestorChildType type of child to search for in the specified ancestor type
-     * @return true if all of StmtContext's ancestors of specified type have a child of specified type, otherwise false
+     * @param name Human-friendly statement name
+     * @throws SourceException if there is any keyless list ancestor
      */
-    public static <A, D extends DeclaredStatement<A>> boolean hasAncestorOfTypeWithChildOfType(
-            final EffectiveStmtCtx.Current<?, ?> stmt, final StatementDefinition ancestorType,
-            final StatementDefinition ancestorChildType) {
+    public static void validateNoKeylessListAncestorOf(final Mutable<?, ?, ?> stmt, final String name) {
         requireNonNull(stmt);
-        requireNonNull(ancestorType);
 
-        final Class<? extends EffectiveStatement<?, ?>> repr = ancestorChildType.getEffectiveRepresentationClass();
-        StmtContext<?, ?, ?> current = stmt.caerbannog().getParentContext();
-        StmtContext<?, ?, ?> parent = current.getParentContext();
+        // We do not expect this to by typically populated
+        final List<Mutable<?, ?, ?>> incomplete = new ArrayList<>(0);
+
+        Mutable<?, ?, ?> current = stmt.coerceParentContext();
+        Mutable<?, ?, ?> parent = current.getParentContext();
         while (parent != null) {
-            if (ancestorType.equals(current.publicDefinition()) && !current.hasSubstatement(repr)) {
-                return false;
+            if (YangStmtMapping.LIST == current.publicDefinition()
+                    && !current.hasSubstatement(KeyEffectiveStatement.class)) {
+                if (ModelProcessingPhase.FULL_DECLARATION.isCompletedBy(current.getCompletedPhase())) {
+                    throw new SourceException(stmt, "%s %s is defined within a list that has no key statement", name,
+                        stmt.argument());
+                }
+
+                // Ancestor has not completed full declaration yet missing 'key' statement may materialize later
+                incomplete.add(current);
             }
 
             current = parent;
             parent = current.getParentContext();
         }
 
-        return true;
-    }
+        // Deal with whatever incomplete ancestors we encountered
+        for (Mutable<?, ?, ?> ancestor : incomplete) {
+            // This check must complete during the ancestor's FULL_DECLARATION phase, i.e. the ancestor must not reach
+            // EFFECTIVE_MODEL until it is done.
+            final ModelActionBuilder action = ancestor.newInferenceAction(ModelProcessingPhase.FULL_DECLARATION);
+            action.apply(new InferenceAction() {
+                @Override
+                public void apply(final InferenceContext ctx) {
+                    if (!ancestor.hasSubstatement(KeyEffectiveStatement.class)) {
+                        throw new SourceException(stmt, "%s %s is defined within a list that has no key statement",
+                            name, stmt.argument());
+                    }
+                }
 
-    /**
-     * Checks whether the parent of EffectiveStmtCtx is of specified type.
-     *
-     * @param stmt EffectiveStmtCtx to be checked
-     * @param parentType type of parent to check
-     * @return true if the parent of StmtContext is of specified type, otherwise false
-     */
-    public static boolean hasParentOfType(final EffectiveStmtCtx.Current<?, ?> stmt,
-            final StatementDefinition parentType) {
-        return hasParentOfType(stmt.caerbannog(), parentType);
+                @Override
+                public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
+                    throw new VerifyException("Should never happen");
+                }
+            });
+        }
     }
 
     /**
@@ -453,13 +472,13 @@ public final class StmtContextUtils {
         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
             final StatementDefinition statementDef = leafSubstmtCtx.publicDefinition();
             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
-                    || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.sourceReference(),
+                    || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx,
                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
                     statementDef.getStatementName(), leafStmtCtx.argument());
         });
     }
 
-    public static QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
+    public static @NonNull QName qnameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
         if (Strings.isNullOrEmpty(value)) {
             return ctx.publicDefinition().getStatementName();
         }
@@ -489,7 +508,7 @@ public final class StmtContextUtils {
                 }
         }
 
-        return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx.sourceReference(),
+        return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
             "Cannot resolve QNameModule for '%s'", value), localName);
     }
 
@@ -502,15 +521,15 @@ public final class StmtContextUtils {
      * @throws NullPointerException if any of the arguments are null
      * @throws SourceException if the string is not a valid YANG identifier
      */
-    public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
-        SourceException.throwIf(str.isEmpty(), ctx.sourceReference(), "Identifier may not be an empty string");
+    public static @NonNull QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
+        SourceException.throwIf(str.isEmpty(), ctx, "Identifier may not be an empty string");
         return internedQName(ctx, str);
     }
 
-    public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
+    public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
             final String localName) {
         return internedQName(ctx,
-            InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx.sourceReference(),
+            InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx,
                 "Cannot resolve QNameModule for '%s'", prefix),
             localName);
     }
@@ -524,8 +543,8 @@ public final class StmtContextUtils {
      * @throws NullPointerException if any of the arguments are null
      * @throws SourceException if the string is not a valid YANG node identifier
      */
-    public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
-        SourceException.throwIf(str.isEmpty(), ctx.sourceReference(), "Node identifier may not be an empty string");
+    public static @NonNull QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
+        SourceException.throwIf(str.isEmpty(), ctx, "Node identifier may not be an empty string");
 
         final int colon = str.indexOf(':');
         if (colon == -1) {
@@ -533,24 +552,24 @@ public final class StmtContextUtils {
         }
 
         final String prefix = str.substring(0, colon);
-        SourceException.throwIf(prefix.isEmpty(), ctx.sourceReference(), "String '%s' has an empty prefix", str);
+        SourceException.throwIf(prefix.isEmpty(), ctx, "String '%s' has an empty prefix", str);
         final String localName = str.substring(colon + 1);
-        SourceException.throwIf(localName.isEmpty(), ctx.sourceReference(), "String '%s' has an empty identifier", str);
+        SourceException.throwIf(localName.isEmpty(), ctx, "String '%s' has an empty identifier", str);
 
         return parseNodeIdentifier(ctx, prefix, localName);
     }
 
-    private static QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
+    private static @NonNull QName internedQName(final StmtContext<?, ?, ?> ctx, final String localName) {
         return internedQName(ctx, getRootModuleQName(ctx), localName);
     }
 
-    private static QName internedQName(final StmtContext<?, ?, ?> ctx, final QNameModule module,
+    private static @NonNull QName internedQName(final CommonStmtCtx ctx, final QNameModule module,
             final String localName) {
         final QName template;
         try {
             template = QName.create(module, localName);
         } catch (IllegalArgumentException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Invalid identifier '%s'", localName);
+            throw new SourceException(ctx, e, "Invalid identifier '%s'", localName);
         }
         return template.intern();
     }