<commit_before>/*
 * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.yangtools.yang.parser.stmt.reactor;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
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 org.eclipse.jdt.annotation.NonNull;
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.XMLNamespace;
import org.opendaylight.yangtools.yang.common.YangVersion;
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.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.ParserNamespace;
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.StatementSupportNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
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.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;
import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
    enum PhaseCompletionProgress {
        NO_PROGRESS,
        PROGRESS,
        FINISHED
    }

    private static final class SupportedStatements
            extends NamespaceBehaviour<QName, StatementSupport<?, ?, ?>, StatementSupportNamespace> {
        private final QNameToStatementDefinitionMap statementDefinitions;

        SupportedStatements(final QNameToStatementDefinitionMap statementDefinitions) {
            super(StatementSupportNamespace.class);
            this.statementDefinitions = requireNonNull(statementDefinitions);
        }

        @Override
        public StatementSupport<?, ?, ?> getFrom(final NamespaceStorageNode storage, final QName key) {
            return statementDefinitions.getSupport(key);
        }

        @Override
        public Map<QName, StatementSupport<?, ?, ?>> getAllFrom(final NamespaceStorageNode storage) {
            throw uoe();
        }

        @Override
        public void addTo(final NamespaceStorageNode storage, final QName key, final StatementSupport<?, ?, ?> value) {
            throw uoe();
        }

        private static UnsupportedOperationException uoe() {
            return new UnsupportedOperationException("StatementSupportNamespace is immutable");
        }
    }

    private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);

    // TODO: consider keying by Byte equivalent of ExecutionOrder
    private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
    private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
    private final SupportedStatements statementSupports = new SupportedStatements(qnameToStmtDefMap);
    private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
    private final @NonNull BuildGlobalContext globalContext;

    // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
    private StatementStreamSource source;

    /*
     * "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 RootStatementContext<?, ?, ?> root;
    // TODO: consider using ExecutionOrder byte for these two
    private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
    private ModelProcessingPhase inProgressPhase;

    // If not null, do not add anything to modifiers, but record it here.
    private List<Entry<ModelProcessingPhase, ModifierImpl>> delayedModifiers;

    SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
        this.globalContext = requireNonNull(globalContext);
        this.source = requireNonNull(source);
    }

    @NonNull BuildGlobalContext globalContext() {
        return globalContext;
    }

    ModelProcessingPhase getInProgressPhase() {
        return inProgressPhase;
    }

    AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
            final int childId, final QName name, final String argument, final StatementSourceReference ref) {
        StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
        if (def == null) {
            def = globalContext.getModelDefinedStatementDefinition(name);
            if (def == null) {
                final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.getSupport(name);
                if (extension != null) {
                    def = new StatementDefinitionContext<>(extension);
                    globalContext.putModelDefinedStatementDefinition(name, def);
                }
            }
        } else if (current != null) {
            def = current.definition().overrideDefinition(def);
        }

        if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
                .getArgumentDefinition().isPresent()) {
            SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
        } else {
            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);
        }

        /*
         * If root is null or root version is other than default,
         * we need to create new root.
         */
        if (root == null) {
            root = new RootStatementContext<>(this, def, ref, argument);
        } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
                && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
            root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
                    root.getRootIdentifier());
        } else {
            final QName rootStatement = root.definition().getStatementName();
            final String rootArgument = root.rawArgument();

            checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
                "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
        }
        return root;
    }

    RootStatementContext<?, ?, ?> getRoot() {
        return root;
    }

    /**
     * Return version of root statement context.
     *
     * @return version of root statement context
     */
    YangVersion getRootVersion() {
        return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
    }

    void startPhase(final ModelProcessingPhase phase) {
        final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
        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);
        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);
    }

    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);
            }

            verify(value instanceof RootStatementContext);
            importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
        }
    }

    @Override
    public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
           final V value) {
        // RootStatementContext takes care of IncludedModuleContext and the rest...
        final V ret = getRoot().putToLocalStorage(type, key, value);
        // FIXME: what about duplicates?
        updateImportedNamespaces(type, value);
        return ret;
    }

    @Override
    public <K, V, N extends ParserNamespace<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;
    }
<commit_msg>Use List for importedNamespace<commit_after>/*
 * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.yangtools.yang.parser.stmt.reactor;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
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 org.eclipse.jdt.annotation.NonNull;
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.XMLNamespace;
import org.opendaylight.yangtools.yang.common.YangVersion;
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.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.ParserNamespace;
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.StatementSupportNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToModuleContext;
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.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;
import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinitionMap;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBehaviour.Registry, Mutable {
    enum PhaseCompletionProgress {
        NO_PROGRESS,
        PROGRESS,
        FINISHED
    }

    private static final class SupportedStatements
            extends NamespaceBehaviour<QName, StatementSupport<?, ?, ?>, StatementSupportNamespace> {
        private final QNameToStatementDefinitionMap statementDefinitions;

        SupportedStatements(final QNameToStatementDefinitionMap statementDefinitions) {
            super(StatementSupportNamespace.class);
            this.statementDefinitions = requireNonNull(statementDefinitions);
        }

        @Override
        public StatementSupport<?, ?, ?> getFrom(final NamespaceStorageNode storage, final QName key) {
            return statementDefinitions.getSupport(key);
        }

        @Override
        public Map<QName, StatementSupport<?, ?, ?>> getAllFrom(final NamespaceStorageNode storage) {
            throw uoe();
        }

        @Override
        public void addTo(final NamespaceStorageNode storage, final QName key, final StatementSupport<?, ?, ?> value) {
            throw uoe();
        }

        private static UnsupportedOperationException uoe() {
            return new UnsupportedOperationException("StatementSupportNamespace is immutable");
        }
    }

    private static final Logger LOG = LoggerFactory.getLogger(SourceSpecificContext.class);

    // TODO: consider keying by Byte equivalent of ExecutionOrder
    private final Multimap<ModelProcessingPhase, ModifierImpl> modifiers = HashMultimap.create();
    private final QNameToStatementDefinitionMap qnameToStmtDefMap = new QNameToStatementDefinitionMap();
    private final SupportedStatements statementSupports = new SupportedStatements(qnameToStmtDefMap);
    private final PrefixToModuleMap prefixToModuleMap = new PrefixToModuleMap();
    private final @NonNull BuildGlobalContext globalContext;

    // Freed as soon as we complete ModelProcessingPhase.EFFECTIVE_MODEL
    private StatementStreamSource source;

    /*
     * "imported" namespaces in this source -- this points to RootStatementContexts of
     * - modules imported via 'import' statement
     * - parent module, declared via 'belongs-to' statement
     */
    private List<RootStatementContext<?, ?, ?>> importedNamespaces = ImmutableList.of();
    private RootStatementContext<?, ?, ?> root;
    // TODO: consider using ExecutionOrder byte for these two
    private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
    private ModelProcessingPhase inProgressPhase;

    // If not null, do not add anything to modifiers, but record it here.
    private List<Entry<ModelProcessingPhase, ModifierImpl>> delayedModifiers;

    SourceSpecificContext(final BuildGlobalContext globalContext, final StatementStreamSource source) {
        this.globalContext = requireNonNull(globalContext);
        this.source = requireNonNull(source);
    }

    @NonNull BuildGlobalContext globalContext() {
        return globalContext;
    }

    ModelProcessingPhase getInProgressPhase() {
        return inProgressPhase;
    }

    AbstractResumedStatement<?, ?, ?> createDeclaredChild(final AbstractResumedStatement<?, ?, ?> current,
            final int childId, final QName name, final String argument, final StatementSourceReference ref) {
        StatementDefinitionContext<?, ?, ?> def = globalContext.getStatementDefinition(getRootVersion(), name);
        if (def == null) {
            def = globalContext.getModelDefinedStatementDefinition(name);
            if (def == null) {
                final StatementSupport<?, ?, ?> extension = qnameToStmtDefMap.getSupport(name);
                if (extension != null) {
                    def = new StatementDefinitionContext<>(extension);
                    globalContext.putModelDefinedStatementDefinition(name, def);
                }
            }
        } else if (current != null) {
            def = current.definition().overrideDefinition(def);
        }

        if (InferenceException.throwIfNull(def, ref, "Statement %s does not have type mapping defined.", name)
                .getArgumentDefinition().isPresent()) {
            SourceException.throwIfNull(argument, ref, "Statement %s requires an argument", name);
        } else {
            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);
        }

        /*
         * If root is null or root version is other than default,
         * we need to create new root.
         */
        if (root == null) {
            root = new RootStatementContext<>(this, def, ref, argument);
        } else if (!RootStatementContext.DEFAULT_VERSION.equals(root.yangVersion())
                && inProgressPhase == ModelProcessingPhase.SOURCE_LINKAGE) {
            root = new RootStatementContext<>(this, def, ref, argument, root.yangVersion(),
                    root.getRootIdentifier());
        } else {
            final QName rootStatement = root.definition().getStatementName();
            final String rootArgument = root.rawArgument();

            checkState(Objects.equals(def.getStatementName(), rootStatement) && Objects.equals(argument, rootArgument),
                "Root statement was already defined as '%s %s'.", rootStatement, rootArgument);
        }
        return root;
    }

    RootStatementContext<?, ?, ?> getRoot() {
        return root;
    }

    /**
     * Return version of root statement context.
     *
     * @return version of root statement context
     */
    YangVersion getRootVersion() {
        return root != null ? root.yangVersion() : RootStatementContext.DEFAULT_VERSION;
    }

    void startPhase(final ModelProcessingPhase phase) {
        final ModelProcessingPhase previousPhase = phase.getPreviousPhase();
        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);
        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);
    }

    private void updateImportedNamespaces(final Class<?> type, final Object value) {
        if (BelongsToModuleContext.class.isAssignableFrom(type) || ImportedModuleContext.class.isAssignableFrom(type)) {
            verify(value instanceof RootStatementContext, "Unexpected imported value %s", value);

            if (importedNamespaces.isEmpty()) {
                importedNamespaces = new ArrayList<>(1);
            }
            importedNamespaces.add((RootStatementContext<?, ?, ?>) value);
        }
    }

    @Override
    public <K, V, N extends ParserNamespace<K, V>> V putToLocalStorage(final Class<N> type, final K key,
           final V value) {
        // RootStatementContext takes care of IncludedModuleContext and the rest...
        final V ret = getRoot().putToLocalStorage(type, key, value);
        // FIXME: what about duplicates?
        updateImportedNamespaces(type, value);
        return ret;
    }

    @Override
    public <K, V, N extends ParserNamespace<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;
    }

{'fraction_non_alphanumeric': 0.09194567816877348, 'fraction_numerical': 0.0009395285275025624, 'mean_word_length': 3.5128155714010405, 'pattern_counts': {'":': 0, '<': 63, '<?xml version=': 0, '>': 63, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '383008', 'n_tokens_mistral': 6318, 'n_tokens_neox': 6093, 'n_words': 1416}