Fix checkstyle in yang-parser-impl and enable enforcement
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SourceSpecificContext.java
index 6da805f9ea6e5345340e434ac74112d7af711ca5..68c58b96acd251ac594fd68ead09fbeb9db33394 100644 (file)
@@ -11,9 +11,7 @@ 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.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;
@@ -27,28 +25,31 @@ 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.StatementSource;
+import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
 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;
+import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
 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.meta.StmtContext;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
 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.BelongsToPrefixToModuleCtx;
 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
 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.ModuleCtxToModuleQName;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
@@ -56,19 +57,6 @@ import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinit
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.BitsSpecificationImpl;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Decimal64SpecificationImpl;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.EnumSpecificationImpl;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.IdentityRefSpecificationImpl;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.InstanceIdentifierSpecificationImpl;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.LeafrefSpecificationImpl;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.ModelDefinedStatementDefinition;
-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.IdentityrefSpecificationRfc7950Support;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc7950.LeafrefSpecificationRfc7950Support;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -81,23 +69,9 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
-    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_1, TypeUtils.IDENTITY_REF, new IdentityrefSpecificationRfc7950Support())
-            .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();
+    private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
     private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
     private final BuildGlobalContext currentContext;
     private final StatementStreamSource source;
@@ -117,7 +91,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         this.source = Preconditions.checkNotNull(source);
     }
 
-    boolean isEnabledSemanticVersioning(){
+    boolean isEnabledSemanticVersioning() {
         return currentContext.isEnabledSemanticVersioning();
     }
 
@@ -126,46 +100,36 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     StatementContextBase<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final int childId,
-            QName name, final String argument, final StatementSourceReference ref) {
+            final QName name, final String argument, final StatementSourceReference ref) {
         if (current != null) {
             // Fast path: we are entering a statement which was emitted in previous phase
-            final StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
+            StatementContextBase<?, ?, ?> existing = current.lookupSubstatement(childId);
+            while (existing != null && StatementSource.CONTEXT == existing.getStatementSource()) {
+                existing = existing.lookupSubstatement(childId);
+            }
             if (existing != null) {
                 return existing;
             }
         }
 
-        // 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);
-            if (extension != null) {
-                def = new StatementDefinitionContext<>(extension);
-            } else {
-                // type-body-stmts
-                def = resolveTypeBodyStmts(name.getLocalName(), getRootVersion());
+            def = currentContext.getModelDefinedStatementDefinition(name);
+            if (def == null) {
+                final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.get(name);
+                if (extension != null) {
+                    def = new StatementDefinitionContext<>(extension);
+                    currentContext.putModelDefinedStatementDefinition(name, def);
+                }
             }
-        } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
+        } else if (current != null && StmtContextUtils.isUnrecognizedStatement(current)) {
             /*
-             * This code wraps statements encountered inside an extension so they do not get confused with regular
-             * statements.
-             *
-             * FIXME: BUG-7037: re-evaluate whether this is really needed, as this is a very expensive way of making
-             *        this work. We really should be peeking into the extension definition to find these nodes,
-             *        as otherwise we are not reusing definitions nor support for these nodes.
+             * This code wraps statements encountered inside an extension so
+             * they do not get confused with regular statements.
              */
-            final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
-            def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
-                new ModelDefinedStatementDefinition(qName, argument != null)));
+            def = Preconditions.checkNotNull(current.definition().getAsUnknownStatementDefinition(def),
+                    "Unable to create unknown statement definition of yang statement %s in unknown statement %s", def,
+                    current);
         }
 
         InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name);
@@ -175,6 +139,16 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             SourceException.throwIf(argument != null, ref, "Statement %s does not take argument", name);
         }
 
+        /*
+         * If the current statement definition has argument specific
+         * sub-definitions, get argument specific sub-definition based on given
+         * argument (e.g. type statement need to be specialized based on its
+         * argument).
+         */
+        if (def.hasArgumentSpecificSubDefinitions()) {
+            def = def.getSubDefinitionSpecificForArgument(argument);
+        }
+
         if (current != null) {
             return current.createSubstatement(childId, def, ref, argument);
         }
@@ -187,14 +161,15 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             root = new RootStatementContext<>(this, def, ref, argument);
         } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.getRootVersion())
                 && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
-            root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion());
+            root = new RootStatementContext<>(this, def, ref, argument, root.getRootVersion(),
+                    root.getRootIdentifier());
         } else {
             final QName rootStatement = root.definition().getStatementName();
             final String rootArgument = root.rawStatementArgument();
 
             Preconditions.checkState(Objects.equals(def.getStatementName(), rootStatement)
-                && Objects.equals(argument, rootArgument),
-                "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
+                && Objects.equals(argument, rootArgument), "Root statement was already defined as '%s %s'.",
+                rootStatement, rootArgument);
         }
         return root;
     }
@@ -228,17 +203,13 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
 
         final Collection<ModifierImpl> previousModifiers = modifiers.get(previousPhase);
         Preconditions.checkState(previousModifiers.isEmpty(),
-            "Previous phase %s has unresolved modifiers %s in source %s",
-            previousPhase, previousModifiers, source);
+            "Previous phase %s has unresolved modifiers %s in source %s", previousPhase, previousModifiers, source);
 
         inProgressPhase = phase;
         LOG.debug("Source {} started phase {}", source, phase);
     }
 
-    @Override
-    public <K, V, N extends IdentifierNamespace<K, V>> void addToLocalStorage(final Class<N> type, final K key,
-           final V value) {
-
+    private void updateImportedNamespaces(final Class<?> type, final Object value) {
         if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
             if (importedNamespaces.isEmpty()) {
                 importedNamespaces = new ArrayList<>(1);
@@ -247,9 +218,27 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             Verify.verify(value instanceof RootStatementContext);
             importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
         }
+    }
 
+    @Override
+    public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
+           final V value) {
         // RootStatementContext takes care of IncludedModuleContext and the rest...
-        getRoot().addToLocalStorage(type, key, value);
+        final V ret = getRoot().putToLocalStorage(type, key, value);
+        // FIXME: what about duplicates?
+        updateImportedNamespaces(type, value);
+        return ret;
+    }
+
+    @Override
+    public <K, V, N extends IdentifierNamespace<K, V>> V putToLocalStorageIfAbsent(final Class<N> type, final K key,
+           final V value) {
+        // RootStatementContext takes care of IncludedModuleContext and the rest...
+        final V ret = getRoot().putToLocalStorageIfAbsent(type, key, value);
+        if (ret == null) {
+            updateImportedNamespaces(type, value);
+        }
+        return ret;
     }
 
     @Override
@@ -325,6 +314,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
         boolean hasProgressed = false;
 
+        // Try making forward progress ...
         final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
         while (modifier.hasNext()) {
             if (modifier.next().tryApply()) {
@@ -337,7 +327,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
-        final ModifierImpl action = new ModifierImpl(phase);
+        final ModifierImpl action = new ModifierImpl();
         modifiers.put(phase, action);
         return action;
     }
@@ -378,30 +368,22 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
                 source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
                 break;
             case SOURCE_LINKAGE:
-                source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
+                source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes(),
+                    getRootVersion());
                 break;
             case STATEMENT_DEFINITION:
-                source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
+                source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(),
+                    prefixes(), getRootVersion());
                 break;
             case FULL_DECLARATION:
-                source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
+                source.writeFull(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes(),
+                    getRootVersion());
                 break;
             default:
                 break;
         }
     }
 
-    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);
-    }
-
     private PrefixToModule preLinkagePrefixes() {
         final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
         final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
@@ -410,21 +392,24 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             return null;
         }
 
-        prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value, null)));
+        prefixToNamespaceMap.forEach((key, value) -> preLinkagePrefixes.put(key, QNameModule.create(value)));
         return preLinkagePrefixes;
     }
 
     private PrefixToModule prefixes() {
-        final Map<String, ModuleIdentifier> allPrefixes = getRoot().getAllFromNamespace(ImpPrefixToModuleIdentifier
-                .class);
-        final Map<String, ModuleIdentifier> belongsToPrefixes = getRoot().getAllFromNamespace
-                (BelongsToPrefixToModuleIdentifier.class);
-        if (belongsToPrefixes != null) {
-            allPrefixes.putAll(belongsToPrefixes);
+        final Map<String, StmtContext<?, ?, ?>> allImports = getRoot().getAllFromNamespace(
+            ImportPrefixToModuleCtx.class);
+        if (allImports != null) {
+            allImports.forEach((key, value) ->
+                prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
         }
 
-        allPrefixes.forEach((key, value) ->
-            prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class, value)));
+        final Map<String, StmtContext<?, ?, ?>> allBelongsTo = getRoot().getAllFromNamespace(
+            BelongsToPrefixToModuleCtx.class);
+        if (allBelongsTo != null) {
+            allBelongsTo.forEach((key, value) ->
+                prefixToModuleMap.put(key, getRoot().getFromNamespace(ModuleCtxToModuleQName.class, value)));
+        }
 
         return prefixToModuleMap;
     }
@@ -432,12 +417,12 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     private QNameToStatementDefinition stmtDef() {
         // regular YANG statements and extension supports added
         final StatementSupportBundle supportsForPhase = currentContext.getSupportsForPhase(inProgressPhase);
-        qNameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
-        qNameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
+        qnameToStmtDefMap.putAll(supportsForPhase.getCommonDefinitions());
+        qnameToStmtDefMap.putAll(supportsForPhase.getDefinitionsSpecificForVersion(getRootVersion()));
 
         // No further actions needed
         if (inProgressPhase != ModelProcessingPhase.FULL_DECLARATION) {
-            return qNameToStmtDefMap;
+            return qnameToStmtDefMap;
         }
 
         // We need to any and all extension statements which have been declared in the context
@@ -445,7 +430,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
                 StatementDefinitionNamespace.class);
         if (extensions != null) {
             extensions.forEach((qname, support) -> {
-                final StatementSupport<?, ?, ?> existing = qNameToStmtDefMap.putIfAbsent(qname, support);
+                final StatementSupport<?, ?, ?> existing = qnameToStmtDefMap.putIfAbsent(qname, support);
                 if (existing != null) {
                     LOG.debug("Source {} already defines statement {} as {}", source, qname, existing);
                 } else {
@@ -454,10 +439,22 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             });
         }
 
-        return qNameToStmtDefMap;
+        return qnameToStmtDefMap;
     }
 
     public Set<YangVersion> getSupportedVersions() {
         return currentContext.getSupportedVersions();
     }
+
+    void addMutableStmtToSeal(final MutableStatement mutableStatement) {
+        currentContext.addMutableStmtToSeal(mutableStatement);
+    }
+
+    Collection<SourceIdentifier> getRequiredSources() {
+        return root.getRequiredSources();
+    }
+
+    ModuleIdentifier getRootIdentifier() {
+        return root.getRootIdentifier();
+    }
 }