Scripted update of if statements
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / BuildGlobalContext.java
index 86307f2c821f9ced07d1a7bb2f4512127f6389d7..a4c0b4446b40dbc596e114a3ce6329b983133310 100644 (file)
@@ -22,6 +22,7 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.Set;
+import java.util.function.Predicate;
 import javax.annotation.Nonnull;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
@@ -39,14 +40,20 @@ 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.SourceException;
 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
+import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
+    private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
 
     private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList.<ModelProcessingPhase>builder()
+            .add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
             .add(ModelProcessingPhase.SOURCE_LINKAGE)
             .add(ModelProcessingPhase.STATEMENT_DEFINITION)
             .add(ModelProcessingPhase.FULL_DECLARATION)
@@ -56,26 +63,31 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
     private final Map<QName,StatementDefinitionContext<?,?,?>> definitions = new HashMap<>();
     private final Map<Class<?>,NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
 
-
     private final Map<ModelProcessingPhase,StatementSupportBundle> supports;
     private final Set<SourceSpecificContext> sources = new HashSet<>();
 
     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
 
-    public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports) {
+    public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
+                              final Predicate<QName> isFeatureSupported) {
         super();
         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
+
+        addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES, isFeatureSupported);
     }
 
-    public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,  final Map<ValidationBundleType,Collection<?>> supportedValidation) {
+    public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
+                              final Map<ValidationBundleType,Collection<?>> supportedValidation,
+                              final Predicate<QName> isFeatureSupported) {
         super();
         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
 
-        Set<Entry<ValidationBundleType, Collection<?>>> validationBundles = supportedValidation.entrySet();
-        for (Entry<ValidationBundleType, Collection<?>> validationBundle : validationBundles) {
+        for (Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
         }
+
+        addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES, isFeatureSupported);
     }
 
     public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
@@ -106,7 +118,7 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
         NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
         if (potential == null) {
             NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
-            if(potentialRaw != null) {
+            if (potentialRaw != null) {
                 potential = createNamespaceContext(potentialRaw);
                 supportedNamespaces.put(type, potential);
             } else {
@@ -116,7 +128,7 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
         }
 
         Verify.verify(type.equals(potential.getIdentifier()));
-            /*
+        /*
          * Safe cast, previous checkState checks equivalence of key from which type argument are
          * derived
          */
@@ -125,7 +137,7 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
 
     @SuppressWarnings({"unchecked", "rawtypes"})
     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
-            NamespaceBehaviour<K, V, N> potentialRaw) {
+            final NamespaceBehaviour<K, V, N> potentialRaw) {
         if (potentialRaw instanceof DerivedNamespaceBehaviour) {
             VirtualNamespaceContext derivedContext =
                     new VirtualNamespaceContext((DerivedNamespaceBehaviour) potentialRaw);
@@ -138,9 +150,9 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
 
     public StatementDefinitionContext<?, ?, ?> getStatementDefinition(final QName name) {
         StatementDefinitionContext<?, ?, ?> potential = definitions.get(name);
-        if(potential == null) {
+        if (potential == null) {
             StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(name);
-            if(potentialRaw != null) {
+            if (potentialRaw != null) {
                 potential = new StatementDefinitionContext<>(potentialRaw);
                 definitions.put(name, potential);
             }
@@ -149,7 +161,7 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
     }
 
     public EffectiveModelContext build() throws SourceException, ReactorException {
-        for(ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
+        for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
             startPhase(phase);
             loadPhaseStatements();
             completePhaseActions();
@@ -160,16 +172,15 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
 
     private EffectiveModelContext transform() {
         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
-        List<DeclaredStatement<?>> rootStatements = new ArrayList<>();
-        for(SourceSpecificContext source : sources) {
-            DeclaredStatement<?> root = source.getRoot().buildDeclared();
-            rootStatements.add(root);
+        List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
+        for (SourceSpecificContext source : sources) {
+            rootStatements.add(source.getRoot().buildDeclared());
         }
         return new EffectiveModelContext(rootStatements);
     }
 
     public EffectiveSchemaContext buildEffective() throws SourceException, ReactorException {
-        for(ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
+        for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
             startPhase(phase);
             loadPhaseStatements();
             completePhaseActions();
@@ -180,23 +191,21 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
 
     private EffectiveSchemaContext transformEffective() {
         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
-        List<DeclaredStatement<?>> rootStatements = new ArrayList<>();
-        List<EffectiveStatement<?,?>> rootEffectiveStatements = new ArrayList<>();
+        List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
+        List<EffectiveStatement<?,?>> rootEffectiveStatements = new ArrayList<>(sources.size());
 
-        for(SourceSpecificContext source : sources) {
-            DeclaredStatement<?> root = source.getRoot().buildDeclared();
-            rootStatements.add(root);
-
-            EffectiveStatement<?,?> rootEffective = source.getRoot().buildEffective();
-            rootEffectiveStatements.add(rootEffective);
+        for (SourceSpecificContext source : sources) {
+            final RootStatementContext<?, ?, ?> root = source.getRoot();
+            rootStatements.add(root.buildDeclared());
+            rootEffectiveStatements.add(root.buildEffective());
         }
 
-        return new EffectiveSchemaContext(rootStatements,rootEffectiveStatements);
+        return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
     }
 
     private void startPhase(final ModelProcessingPhase phase) {
         Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
-        for(SourceSpecificContext source : sources) {
+        for (SourceSpecificContext source : sources) {
             source.startPhase(phase);
         }
         currentPhase = phase;
@@ -204,16 +213,48 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
 
     private  void loadPhaseStatements() throws SourceException {
         Preconditions.checkState(currentPhase != null);
-        for(SourceSpecificContext source : sources) {
+        for (SourceSpecificContext source : sources) {
             source.loadStatements();
         }
     }
 
     private SomeModifiersUnresolvedException addSourceExceptions(final SomeModifiersUnresolvedException buildFailure,
             final List<SourceSpecificContext> sourcesToProgress) {
-        for(SourceSpecificContext failedSource : sourcesToProgress) {
-            SourceException sourceEx = failedSource.failModifiers(currentPhase);
-            buildFailure.addSuppressed(sourceEx);
+        boolean addedCause = false;
+        for (SourceSpecificContext failedSource : sourcesToProgress) {
+            final SourceException sourceEx = failedSource.failModifiers(currentPhase);
+
+            // Workaround for broken logging implementations which ignore suppressed exceptions
+            Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
+            if (LOG.isDebugEnabled()) {
+                LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
+            } else {
+                LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
+            }
+
+            final Throwable[] suppressed = sourceEx.getSuppressed();
+            if (suppressed.length > 0) {
+                LOG.error("{} additional errors reported:", suppressed.length);
+
+                int i = 1;
+                for (Throwable t : suppressed) {
+                    // FIXME: this should be configured in the appender, really
+                    if (LOG.isDebugEnabled()) {
+                        LOG.error("Error {}: {}", i, t.getMessage(), t);
+                    } else {
+                        LOG.error("Error {}: {}", i, t.getMessage());
+                    }
+
+                    i++;
+                }
+            }
+
+            if (!addedCause) {
+                addedCause = true;
+                buildFailure.initCause(sourceEx);
+            } else {
+                buildFailure.addSuppressed(sourceEx);
+            }
         }
         return buildFailure;
     }
@@ -223,11 +264,11 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
         List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
         try {
             boolean progressing = true;
-            while(progressing) {
+            while (progressing) {
                 // We reset progressing to false.
                 progressing = false;
                 Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
-                while(currentSource.hasNext()) {
+                while (currentSource.hasNext()) {
                     SourceSpecificContext nextSourceCtx = currentSource.next();
                     PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
                     switch (sourceProgress) {
@@ -248,7 +289,7 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
         } catch (SourceException e) {
             throw Throwables.propagate(e);
         }
-        if(!sourcesToProgress.isEmpty()) {
+        if (!sourcesToProgress.isEmpty()) {
             SomeModifiersUnresolvedException buildFailure = new SomeModifiersUnresolvedException(currentPhase);
             buildFailure = addSourceExceptions(buildFailure, sourcesToProgress);
             throw buildFailure;
@@ -263,5 +304,4 @@ class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBeh
     public Set<SourceSpecificContext> getSources() {
         return sources;
     }
-
 }