Bug 6873: [Yang 1.1] Add support for "require-instance" in leafref
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SourceSpecificContext.java
index ed32ec142d4e11a9fee2833a6c1a9d1c2fdf06b8..dadc28d952e0a8920f7e3bc64cf5ddc4cbb8ec7e 100644 (file)
@@ -8,29 +8,32 @@
 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
 
 import com.google.common.base.Preconditions;
+import com.google.common.base.Verify;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableTable;
 import com.google.common.collect.Multimap;
+import com.google.common.collect.Table;
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.Set;
 import javax.annotation.Nullable;
 import org.opendaylight.yangtools.concepts.Mutable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.common.YangConstants;
+import org.opendaylight.yangtools.yang.common.YangVersion;
 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
+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.IdentifierNamespace;
-import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
-import org.opendaylight.yangtools.yang.parser.spi.meta.ImportedNamespaceContext;
 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.ModelProcessingPhase;
@@ -39,9 +42,12 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Namesp
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementDefinitionNamespace;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
+import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleIdentifier;
 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.source.ImportedModuleContext;
 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
@@ -61,6 +67,7 @@ import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnionSpecificationImpl;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
+import org.opendaylight.yangtools.yang.parser.stmt.rfc7950.LeafrefSpecificationRfc7950Support;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -72,17 +79,50 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         FINISHED
     }
 
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    private final class RootContextBuilder extends ContextBuilder {
+        RootContextBuilder(final StatementDefinitionContext def, final StatementSourceReference sourceRef) {
+            super(def, sourceRef);
+        }
+
+        @Override
+        public StatementContextBase build() {
+            /*
+             * If root is null or root version is other than default,
+             * we need to create new root.
+             */
+            if (root == null) {
+                root = new RootStatementContext(this, SourceSpecificContext.this);
+            } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
+                    && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
+                root = new RootStatementContext(this, SourceSpecificContext.this, root.getRootVersion());
+            } else {
+                final QName rootStatement = root.definition().getStatementName();
+                final String rootArgument = root.rawStatementArgument();
+
+                Preconditions.checkState(Objects.equals(getDefinition().getStatementName(), rootStatement)
+                    && Objects.equals(getRawArgument(), rootArgument),
+                    "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
+            }
+            root.resetLists();
+            return root;
+        }
+    }
+
     private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
-    private static final Map<String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
-            ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
-            .put(TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
-            .put(TypeUtils.UNION, new UnionSpecificationImpl.Definition())
-            .put(TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
-            .put(TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
-            .put(TypeUtils.BITS, new BitsSpecificationImpl.Definition())
-            .put(TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
-            .put(TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
-            .build();
+    private static final Table<YangVersion, String, StatementSupport<?, ?, ?>> BUILTIN_TYPE_SUPPORTS =
+            ImmutableTable.<YangVersion, String, StatementSupport<?, ?, ?>>builder()
+            .put(YangVersion.VERSION_1, TypeUtils.DECIMAL64, new Decimal64SpecificationImpl.Definition())
+            .put(YangVersion.VERSION_1, TypeUtils.UNION, new UnionSpecificationImpl.Definition())
+            .put(YangVersion.VERSION_1, TypeUtils.ENUMERATION, new EnumSpecificationImpl.Definition())
+            .put(YangVersion.VERSION_1, TypeUtils.LEAF_REF, new LeafrefSpecificationImpl.Definition())
+            .put(YangVersion.VERSION_1_1, TypeUtils.LEAF_REF, new LeafrefSpecificationRfc7950Support())
+            .put(YangVersion.VERSION_1, TypeUtils.BITS, new BitsSpecificationImpl.Definition())
+            .put(YangVersion.VERSION_1, TypeUtils.IDENTITY_REF, new IdentityRefSpecificationImpl.Definition())
+            .put(YangVersion.VERSION_1, TypeUtils.INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationImpl.Definition())
+                    .build();
+
+    private static final QName TYPE = YangStmtMapping.TYPE.getStatementName();
 
     private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
     private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
@@ -90,7 +130,12 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     private final BuildGlobalContext currentContext;
     private final StatementStreamSource source;
 
-    private Collection<NamespaceStorageNode> importedNamespaces = ImmutableList.of();
+    /*
+     * "imported" namespaces in this source -- this points to RootStatementContexts of
+     * - modules imported via 'import' statement
+     * - parent module, declared via 'belongs-to' statement
+     */
+    private Collection<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
     private ModelProcessingPhase inProgressPhase;
     private RootStatementContext<?, ?, ?> root;
@@ -108,9 +153,19 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         return inProgressPhase;
     }
 
-    ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
-                                                final StatementSourceReference ref) {
-        StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(name);
+    ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
+            QName name, final String argument, final StatementSourceReference ref) {
+        // FIXME: BUG-7038: Refactor/clean up this special case
+        if (TYPE.equals(name)) {
+            SourceException.throwIfNull(argument, ref, "Type statement requires an argument");
+            if (TypeUtils.isYangTypeBodyStmtString(argument)) {
+                name = QName.create(YangConstants.RFC6020_YIN_MODULE, argument);
+            } else {
+                name = QName.create(YangConstants.RFC6020_YIN_MODULE, TYPE.getLocalName());
+            }
+        }
+
+        StatementDefinitionContext<?, ?, ?> def = currentContext.getStatementDefinition(getRootVersion(), name);
 
         if (def == null) {
             final StatementSupport<?, ?, ?> extension = qNameToStmtDefMap.get(name);
@@ -118,7 +173,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
                 def = new StatementDefinitionContext<>(extension);
             } else {
                 // type-body-stmts
-                def = resolveTypeBodyStmts(name.getLocalName());
+                def = resolveTypeBodyStmts(name.getLocalName(), getRootVersion());
             }
         } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
             /*
@@ -135,36 +190,33 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         }
 
         Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
+        final ContextBuilder<?, ?, ?> ret;
         if (current == null) {
-            return createDeclaredRoot(def, ref);
+            ret = new RootContextBuilder(def, ref);
+        } else {
+            ret = current.substatementBuilder(childId, def, ref);
         }
-        return current.substatementBuilder(def, ref);
-    }
 
-    @SuppressWarnings({"rawtypes", "unchecked"})
-    private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
-                                                       final StatementSourceReference ref) {
-        return new ContextBuilder(def, ref) {
-
-            @Override
-            public StatementContextBase build() {
-                if (root == null) {
-                    root = new RootStatementContext(this, SourceSpecificContext.this);
-                } else {
-                    Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
-                            "Root statement was already defined as %s.", root.getIdentifier());
-                }
-                root.resetLists();
-                return root;
-            }
+        if (argument != null) {
+            ret.setArgument(argument, ref);
+        }
 
-        };
+        return ret;
     }
 
     RootStatementContext<?, ?, ?> getRoot() {
         return root;
     }
 
+    /**
+     * Return version of root statement context.
+     *
+     * @return version of root statement context
+     */
+    YangVersion getRootVersion() {
+        return root != null ? root.getRootVersion() : RootStatementContext.DEFAULT_VERSION;
+    }
+
     DeclaredStatement<?> buildDeclared() {
         return root.buildDeclared();
     }
@@ -175,8 +227,15 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
 
     void startPhase(final ModelProcessingPhase phase) {
         @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
-        Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
-        Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
+        Verify.verify(Objects.equals(previousPhase, finishedPhase),
+            "Phase sequencing violation: previous phase should be %s, source %s has %s", previousPhase, source,
+            finishedPhase);
+
+        final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
+        Preconditions.checkState(previousModifiers.isEmpty(),
+            "Previous phase %s has unresolved modifiers %s in source %s",
+            previousPhase, previousModifiers, source);
+
         inProgressPhase = phase;
         LOG.debug("Source {} started phase {}", source, phase);
     }
@@ -184,12 +243,17 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     @Override
     public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
            final V value) {
-        if (ImportedNamespaceContext.class.isAssignableFrom(type)) {
+
+        if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
             if (importedNamespaces.isEmpty()) {
                 importedNamespaces = new ArrayList<>(1);
             }
-            importedNamespaces.add((NamespaceStorageNode) value);
+
+            Verify.verify(value instanceof RootStatementContext);
+            importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
         }
+
+        // RootStatementContext takes care of IncludedModuleContext and the rest...
         getRoot().addToLocalStorage(type, key, value);
     }
 
@@ -306,10 +370,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         final String message = String.format("Yang model processing phase %s failed", identifier);
         final InferenceException e = new InferenceException(message, root.getStatementSourceReference(),
             exceptions.get(0));
-        final Iterator<SourceException> it = exceptions.listIterator(1);
-        while (it.hasNext()) {
-            e.addSuppressed(it.next());
-        }
+        exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
 
         return Optional.of(e);
     }
@@ -335,8 +396,14 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         }
     }
 
-    private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument) {
-        final StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(typeArgument);
+    private static StatementDefinitionContext<?, ?, ?> resolveTypeBodyStmts(final String typeArgument,
+            final YangVersion version) {
+        StatementSupport<?, ?, ?> support = BUILTIN_TYPE_SUPPORTS.get(version, typeArgument);
+
+        if (support == null) {
+            support = BUILTIN_TYPE_SUPPORTS.get(YangVersion.VERSION_1, typeArgument);
+        }
+
         return support == null ? null : new StatementDefinitionContext<>(support);
     }
 
@@ -347,10 +414,8 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             //:FIXME if it is a submodule without any import, the map is null. Handle also submodules and includes...
             return null;
         }
-        for (final Entry<String, URI> prefixToNamespace : prefixToNamespaceMap.entrySet()) {
-            preLinkagePrefixes.put(prefixToNamespace.getKey(), QNameModule.create(prefixToNamespace.getValue(), null));
-        }
 
+        prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
         return preLinkagePrefixes;
     }
 
@@ -363,43 +428,41 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             allPrefixes.putAll(belongsToPrefixes);
         }
 
-        for (final Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
-            final QNameModule namespace = getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class,
-                stringModuleIdentifierEntry.getValue());
-            prefixToModuleMap.put(stringModuleIdentifierEntry.getKey(), namespace);
-        }
+        allPrefixes.forEach((key, value) ->
+            prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
+
         return prefixToModuleMap;
     }
 
     private QNameToStatementDefinition stmtDef() {
         // regular YANG statements and extension supports added
-        final Map<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(inProgressPhase)
-                .getDefinitions();
-        for (final Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
-            qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
+        final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
+        qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
+        qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
+
+        // No further actions needed
+        if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
+            return qNameToStmtDefMap;
         }
 
-        // extensions added
-        if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
-            final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
+        // We need to any and all extension statements which have been declared in the context
+        final Map<QName, StatementSupport<?, ?, ?>> extensions = currentContext.getAllFromNamespace(
                 StatementDefinitionNamespace.class);
-            if (extensions != null) {
-                for (final Entry<QName, StatementSupport<?, ?, ?>> e : extensions.entrySet()) {
-                    final StatementDefinition previous = qNameToStmtDefMap.get(e.getKey());
-                    if (previous != null) {
-                        LOG.debug("Source {} already defines statement {} as {}", source, e.getKey(), previous);
-                        if (!(previous instanceof StatementSupport)) {
-                            LOG.warn("Source {} statement for {} definition {} is not a StatementSupport", source,
-                                e.getKey(), previous);
-                        }
-                    } else {
-                        qNameToStmtDefMap.put(e.getKey(), e.getValue());
-                        LOG.debug("Source {} defined statement {} as {}", source, e.getKey(), e.getValue());
-                    }
+        if (extensions != null) {
+            extensions.forEach((qname, support) -> {
+                final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
+                if (existing != null) {
+                    LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
+                } else {
+                    LOG.debug("Source {} defined statement {} as {}", source, qname, support);
                 }
-            }
+            });
         }
 
         return qNameToStmtDefMap;
     }
+
+    public Set<YangVersion> getSupportedVersions() {
+        return currentContext.getSupportedVersions();
+    }
 }