<commit_before>/* Copyright (c) 2013, <NAME>
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met: 

   1. Redistributions of source code must retain the above copyright notice, this
      list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
package afc.ant.modular;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class SerialDependencyResolver implements DependencyResolver
{
    private ArrayList<Node> shortlist;
    private Module moduleAcquired;
    
    public void init(final Collection<Module> rootModules) throws CyclicDependenciesDetectedException
    {
        if (rootModules == null) {
            throw new NullPointerException("rootModules");
        }
        for (final Module module : rootModules) {
            if (module == null) {
                throw new NullPointerException("rootModules contains null element.");
            }
        }
        ensureNoLoops(rootModules);
        shortlist = buildNodeGraph(rootModules);
        moduleAcquired = null;
    }
    
    // returns a module that does not have dependencies
    public Module getFreeModule()
    {
        ensureInitialised();
        if (moduleAcquired != null) {
            throw new IllegalStateException("#getFreeModule() is called when there is a module being processed.");
        }
        if (shortlist.isEmpty()) {
            return null;
        }
        /* Removing node from the graph here instead of #moduleProcessed to avoid searching
         * for the node when #moduleProcessed is invoked. All consistency and input validity
         * checks are performed so that the caller must follow the correct workflow.
         */
        final Node node = shortlist.remove(shortlist.size()-1);
        
        for (int j = 0, n = node.dependencyOf.size(); j < n; ++j) {
            final Node depOf = node.dependencyOf.get(j);
            if (--depOf.dependencyCount == 0) {
                // all modules with no dependencies go to the shortlist
                shortlist.add(depOf);
            }
        }
        return moduleAcquired = node.module;
    }
    
    public void moduleProcessed(final Module module)
    {
        ensureInitialised();
        if (module == null) {
            throw new NullPointerException("module");
        }
        if (moduleAcquired == null) {
            throw new IllegalStateException("No module is being processed.");
        }
        if (moduleAcquired != module) {
            throw new IllegalArgumentException(MessageFormat.format(
                    "The module ''{0}'' is not being processed.", module.getPath()));
        }
        moduleAcquired = null;
    }
    
    private void ensureInitialised()
    {
        if (shortlist == null) {
            throw new IllegalStateException("Resolver is not initialised.");
        }
    }
    
    private static class Node
    {
        private Node(final Module module)
        {
            this.module = module;
            dependencyCount = module.getDependencies().size();
            dependencyOf = new ArrayList<Node>();
        }
        
        private final Module module;
        /* Knowing just dependency count is enough to detect the moment
           when this node has no dependencies remaining. */
        private int dependencyCount;
        private final ArrayList<Node> dependencyOf;
    }
    
    private static ArrayList<Node> buildNodeGraph(final Collection<Module> rootModules)
    {
        /* TODO it is known that there are no loops in the dependency graph.
           Use it knowledge to eliminate unnecessary checks OR merge buildNodeGraph() with
           ensureNoLoops() so that loops are checked for while the node graph is being built. */
        final IdentityHashMap<Module, Node> registry = new IdentityHashMap<Module, Node>();
        // shortlist stores the leaves of the inverted dependency graph.<commit_msg>A comment is added for SerialDependencyResolver#buildNodeGraph.<commit_after>/* Copyright (c) 2013, <NAME>
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met: 

   1. Redistributions of source code must retain the above copyright notice, this
      list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
package afc.ant.modular;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class SerialDependencyResolver implements DependencyResolver
{
    private ArrayList<Node> shortlist;
    private Module moduleAcquired;
    
    public void init(final Collection<Module> rootModules) throws CyclicDependenciesDetectedException
    {
        if (rootModules == null) {
            throw new NullPointerException("rootModules");
        }
        for (final Module module : rootModules) {
            if (module == null) {
                throw new NullPointerException("rootModules contains null element.");
            }
        }
        ensureNoLoops(rootModules);
        shortlist = buildNodeGraph(rootModules);
        moduleAcquired = null;
    }
    
    // returns a module that does not have dependencies
    public Module getFreeModule()
    {
        ensureInitialised();
        if (moduleAcquired != null) {
            throw new IllegalStateException("#getFreeModule() is called when there is a module being processed.");
        }
        if (shortlist.isEmpty()) {
            return null;
        }
        /* Removing the node from the graph here instead of #moduleProcessed to avoid searching
         * for this node when #moduleProcessed is invoked. All consistency and input validity
         * checks are performed so that the caller must follow the correct workflow.
         */
        final Node node = shortlist.remove(shortlist.size()-1);
        
        for (int j = 0, n = node.dependencyOf.size(); j < n; ++j) {
            final Node depOf = node.dependencyOf.get(j);
            if (--depOf.dependencyCount == 0) {
                // all modules with no dependencies go to the shortlist
                shortlist.add(depOf);
            }
        }
        return moduleAcquired = node.module;
    }
    
    public void moduleProcessed(final Module module)
    {
        ensureInitialised();
        if (module == null) {
            throw new NullPointerException("module");
        }
        if (moduleAcquired == null) {
            throw new IllegalStateException("No module is being processed.");
        }
        if (moduleAcquired != module) {
            throw new IllegalArgumentException(MessageFormat.format(
                    "The module ''{0}'' is not being processed.", module.getPath()));
        }
        moduleAcquired = null;
    }
    
    private void ensureInitialised()
    {
        if (shortlist == null) {
            throw new IllegalStateException("Resolver is not initialised.");
        }
    }
    
    private static class Node
    {
        private Node(final Module module)
        {
            this.module = module;
            dependencyCount = module.getDependencies().size();
            dependencyOf = new ArrayList<Node>();
        }
        
        private final Module module;
        /* Knowing just dependency count is enough to detect the moment
           when this node has no dependencies remaining. */
        private int dependencyCount;
        private final ArrayList<Node> dependencyOf;
    }
    
    /*
     * Builds a DAG which nodes hold modules and arcs that represent inverted module dependencies.
     * The list of nodes returned contains the ending vertices of the graph. The modules that
     * are bound to these vertices do not have dependencies on other modules and are used
     * as modules to start unwinding dependencies from.
     */
    private static ArrayList<Node> buildNodeGraph(final Collection<Module> rootModules)
    {
        /* TODO it is known that there are no loops in the dependency graph.
           Use it knowledge to eliminate unnecessary checks OR merge buildNodeGraph() with
           ensureNoLoops() so that loops are checked for while the node graph is being built. */
        final IdentityHashMap<Module, Node> registry = new IdentityHashMap<Module, Node>();
        // shortlist stores the leaves of the inverted dependency graph.
{'fraction_non_alphanumeric': 0.06651781561075448, 'fraction_numerical': 0.0018606381989022234, 'mean_word_length': 2.5941156803744567, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '369049', 'n_tokens_mistral': 2626, 'n_tokens_neox': 2498, 'n_words': 1070}