BUG-6522: Improve parser reactor logging
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / SourceSpecificContext.java
index 3f34be5ffb38b84388327172a199b8a482d9640b..48447300ef9699139cea6c389d23bf558ef650c1 100644 (file)
@@ -11,6 +11,7 @@ import com.google.common.base.Preconditions;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Multimap;
+import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Iterator;
@@ -18,6 +19,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Objects;
+import java.util.Optional;
 import javax.annotation.Nullable;
 import org.opendaylight.yangtools.concepts.Mutable;
 import org.opendaylight.yangtools.yang.common.QName;
@@ -36,11 +38,12 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
 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.QNameCacheNamespace;
+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.StmtContext;
 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.ModuleIdentifierToModuleQName;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModuleMap;
@@ -55,10 +58,13 @@ 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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
 
@@ -68,22 +74,28 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         FINISHED
     }
 
+    private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);
+
     private final StatementStreamSource source;
     private final BuildGlobalContext currentContext;
     private final Collection<NamespaceStorageNode> importedNamespaces = new ArrayList<>();
     private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
 
-    private RootStatementContext<?, ?, ?> root;
 
-    private ModelProcessingPhase inProgressPhase;
-    private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
     private final QNameToStatementDefinitionMap qNameToStmtDefMap = new QNameToStatementDefinitionMap();
     private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
 
+    private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
+    private ModelProcessingPhase inProgressPhase;
+    private RootStatementContext<?, ?, ?> root;
 
     SourceSpecificContext(final BuildGlobalContext currentContext, final StatementStreamSource source) {
-        this.source = source;
         this.currentContext = currentContext;
+        this.source = source;
+    }
+
+    public boolean isEnabledSemanticVersioning(){
+        return currentContext.isEnabledSemanticVersioning();
     }
 
     ModelProcessingPhase getInProgressPhase() {
@@ -94,37 +106,29 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         return currentContext.getStatementDefinition(name);
     }
 
-    ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name, final StatementSourceReference ref) {
+    ContextBuilder<?, ?, ?> createDeclaredChild(final StatementContextBase<?, ?, ?> current, final QName name,
+                                                final StatementSourceReference ref) {
         StatementDefinitionContext<?, ?, ?> def = getDefinition(name);
 
         if (def == null) {
-            //unknown-stmts (from import, include or local-scope)
-            if (qNameToStmtDefMap.get(Utils.trimPrefix(name)) != null) {
-                QName key = Utils.qNameFromArgument(current, name.getLocalName());
-                if (key != null) {
-                    final StatementContextBase<?,?,?> extension = (StatementContextBase<?, ?, ?>) currentContext
-                            .getAllFromNamespace(ExtensionNamespace.class).get(key);
-                    if (extension != null) {
-                        final QName arg = (QName) extension.getStatementArgument();
-                        final QName qName = current.getFromNamespace(QNameCacheNamespace.class,
-                            QName.create(arg, extension.getIdentifier().getArgument()));
-
-                        def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition
-                                (getNewStatementDefinition(qName)));
-                    } else {
-                        throw new IllegalArgumentException("Not found unknown statement: " + name);
-                    }
-                }
+            // unknown-stmts (from import, include or local-scope)
+            if (qNameToStmtDefMap.get(name) != null) {
+                final StatementDefinition extension = currentContext.getFromNamespace(
+                    StatementDefinitionNamespace.class, name);
+                SourceException.throwIfNull(extension, current.getStatementSourceReference(), "Extension %s not found",
+                    name);
+
+                def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(extension));
             } else {
-                //type-body-stmts
+                // type-body-stmts
                 def = resolveTypeBodyStmts(name.getLocalName());
             }
-        }
-        else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
-            QName qName = Utils.qNameFromArgument(current, name.getLocalName());
+        } else if (current != null && current.definition().getRepresentingClass().equals(UnknownStatementImpl.class)) {
+            // FIXME: What's going on here?
+            final QName qName = Utils.qNameFromArgument(current, name.getLocalName());
 
-            def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition
-                    (getNewStatementDefinition(qName)));
+            def = new StatementDefinitionContext<>(new UnknownStatementImpl.Definition(
+                new ModelDefinedStatementDefinition(qName)));
         }
 
         Preconditions.checkArgument(def != null, "Statement %s does not have type mapping defined.", name);
@@ -134,21 +138,18 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         return current.substatementBuilder(def, ref);
     }
 
-    // FIXME: This should be populated differently
-    StatementDefinition getNewStatementDefinition(final QName qName) {
-        return new ModelDefinedStatementDefinition(qName);
-    }
-
     @SuppressWarnings({"rawtypes", "unchecked"})
-    private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def, final StatementSourceReference ref) {
+    private ContextBuilder<?, ?, ?> createDeclaredRoot(final StatementDefinitionContext<?, ?, ?> def,
+                                                       final StatementSourceReference ref) {
         return new ContextBuilder(def, ref) {
 
             @Override
-            public StatementContextBase build() throws SourceException {
+            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());
+                    Preconditions.checkState(root.getIdentifier().equals(createIdentifier()),
+                            "Root statement was already defined as %s.", root.getIdentifier());
                 }
                 root.resetLists();
                 return root;
@@ -170,14 +171,16 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     void startPhase(final ModelProcessingPhase phase) {
-        @Nullable ModelProcessingPhase previousPhase = phase.getPreviousPhase();
+        @Nullable final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
         Preconditions.checkState(Objects.equals(previousPhase, finishedPhase));
         Preconditions.checkState(modifiers.get(previousPhase).isEmpty());
         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) {
+    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)) {
             importedNamespaces.add((NamespaceStorageNode) value);
         }
@@ -195,8 +198,8 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         if (potentialLocal != null) {
             return potentialLocal;
         }
-        for (NamespaceStorageNode importedSource : importedNamespaces) {
-            V potential = importedSource.getFromLocalStorage(type, key);
+        for (final NamespaceStorageNode importedSource : importedNamespaces) {
+            final V potential = importedSource.getFromLocalStorage(type, key);
             if (potential != null) {
                 return potential;
             }
@@ -224,7 +227,8 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     @Override
-    public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(final Class<N> type) {
+    public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviour<K, V, N> getNamespaceBehaviour(
+            final Class<N> type) {
         return currentContext.getNamespaceBehaviour(type);
     }
 
@@ -234,30 +238,30 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     PhaseCompletionProgress tryToCompletePhase(final ModelProcessingPhase phase) throws SourceException {
-        Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
+        final Collection<ModifierImpl> currentPhaseModifiers = modifiers.get(phase);
 
         boolean hasProgressed = tryToProgress(currentPhaseModifiers);
 
-        boolean phaseCompleted = root.tryToCompletePhase(phase);
+        Preconditions.checkNotNull(this.root, "Malformed source. Valid root element is missing.");
+        final boolean phaseCompleted = root.tryToCompletePhase(phase);
 
-        hasProgressed = (tryToProgress(currentPhaseModifiers) | hasProgressed);
+        hasProgressed |= tryToProgress(currentPhaseModifiers);
 
-        if (phaseCompleted && (currentPhaseModifiers.isEmpty())) {
+        if (phaseCompleted && currentPhaseModifiers.isEmpty()) {
             finishedPhase = phase;
+            LOG.debug("Source {} finished phase {}", source, phase);
             return PhaseCompletionProgress.FINISHED;
 
         }
-        if (hasProgressed) {
-            return PhaseCompletionProgress.PROGRESS;
-        }
-        return PhaseCompletionProgress.NO_PROGRESS;
+
+        return hasProgressed ? PhaseCompletionProgress.PROGRESS : PhaseCompletionProgress.NO_PROGRESS;
     }
 
 
     private static boolean tryToProgress(final Collection<ModifierImpl> currentPhaseModifiers) {
-
-        Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
         boolean hasProgressed = false;
+
+        final Iterator<ModifierImpl> modifier = currentPhaseModifiers.iterator();
         while (modifier.hasNext()) {
             if (modifier.next().tryApply()) {
                 modifier.remove();
@@ -270,7 +274,7 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
     }
 
     ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
-        ModifierImpl action = new ModifierImpl(phase);
+        final ModifierImpl action = new ModifierImpl(phase);
         modifiers.put(phase, action);
         return action;
     }
@@ -281,21 +285,21 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
                 + finishedPhase + "]";
     }
 
-    SourceException failModifiers(final ModelProcessingPhase identifier) {
+    Optional<SourceException> failModifiers(final ModelProcessingPhase identifier) {
         final List<SourceException> exceptions = new ArrayList<>();
-        for (ModifierImpl mod : modifiers.get(identifier)) {
+        for (final ModifierImpl mod : modifiers.get(identifier)) {
             try {
                 mod.failModifier();
-            } catch (SourceException e) {
+            } catch (final SourceException e) {
                 exceptions.add(e);
             }
         }
 
-        final String message = String.format("Yang model processing phase %s failed", identifier);
         if (exceptions.isEmpty()) {
-            return new InferenceException(message, root.getStatementSourceReference());
+            return Optional.empty();
         }
 
+        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);
@@ -303,13 +307,18 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
             e.addSuppressed(it.next());
         }
 
-        return e;
+        return Optional.of(e);
     }
 
     void loadStatements() throws SourceException {
+        LOG.trace("Source {} loading statements for phase {}", source, inProgressPhase);
+
         switch (inProgressPhase) {
+            case SOURCE_PRE_LINKAGE:
+                source.writePreLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
+                break;
             case SOURCE_LINKAGE:
-                source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef());
+                source.writeLinkage(new StatementContextWriter(this, inProgressPhase), stmtDef(), preLinkagePrefixes());
                 break;
             case STATEMENT_DEFINITION:
                 source.writeLinkageAndStatementDefinitions(new StatementContextWriter(this, inProgressPhase), stmtDef(), prefixes());
@@ -343,45 +352,61 @@ public class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeh
         }
     }
 
+    private PrefixToModule preLinkagePrefixes() {
+        final PrefixToModuleMap preLinkagePrefixes = new PrefixToModuleMap(true);
+        final Map<String, URI> prefixToNamespaceMap = getAllFromLocalStorage(ImpPrefixToNamespace.class);
+        if (prefixToNamespaceMap == null) {
+            //: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));
+        }
+
+        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)
+        if (belongsToPrefixes != null) {
             allPrefixes.putAll(belongsToPrefixes);
+        }
 
-        for (Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
+        for (final Entry<String, ModuleIdentifier> stringModuleIdentifierEntry : allPrefixes.entrySet()) {
             final QNameModule namespace = getRoot().getFromNamespace(ModuleIdentifierToModuleQName.class,
-                    stringModuleIdentifierEntry.getValue());
+                stringModuleIdentifierEntry.getValue());
             prefixToModuleMap.put(stringModuleIdentifierEntry.getKey(), namespace);
         }
         return prefixToModuleMap;
     }
 
     private QNameToStatementDefinition stmtDef() {
-        //regular YANG statements added
-        ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
+        // regular YANG statements and extension supports added
+        final ImmutableMap<QName, StatementSupport<?, ?, ?>> definitions = currentContext.getSupportsForPhase(
                 inProgressPhase).getDefinitions();
-        for (Map.Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
+        for (final Entry<QName, StatementSupport<?, ?, ?>> entry : definitions.entrySet()) {
             qNameToStmtDefMap.put(entry.getKey(), entry.getValue());
         }
 
-        //extensions added
+        // extensions added
         if (inProgressPhase.equals(ModelProcessingPhase.FULL_DECLARATION)) {
-            Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions = currentContext
-                    .getAllFromNamespace(ExtensionNamespace.class);
+            final Map<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extensions =
+                    currentContext.getAllFromNamespace(ExtensionNamespace.class);
             if (extensions != null) {
-                for (Map.Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension : extensions
-                        .entrySet()) {
-                    qNameToStmtDefMap
-                              .put((extension.getKey()),
-                                    (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension
-                                            .getValue()).definition()
-                                            .getFactory());
+                for (final Entry<QName, StmtContext<?, ExtensionStatement, EffectiveStatement<QName, ExtensionStatement>>> extension :
+                    extensions.entrySet()) {
+                    if(qNameToStmtDefMap.get(extension.getKey()) == null) {
+                        qNameToStmtDefMap.put((extension.getKey()),
+                        (StatementDefinition) ((StatementContextBase<?, ?, ?>) extension.getValue()).definition()
+                        .getFactory());
+                    }
                 }
             }
         }
+
         return qNameToStmtDefMap;
     }
 }