modelbuilder: Remove duplicates from modules list
[nit.git] / src / modelbuilder.nit
index aee1ea3..a93ca81 100644 (file)
@@ -35,13 +35,13 @@ private import more_collections
 
 redef class ToolContext
        # Option --path
-       readable var _opt_path: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
+       var opt_path: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
 
        # Option --only-metamodel
-       readable var _opt_only_metamodel: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
+       var opt_only_metamodel: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
 
        # Option --only-parse
-       readable var _opt_only_parse: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
+       var opt_only_parse: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
 
        redef init
        do
@@ -52,8 +52,22 @@ redef class ToolContext
        fun modelbuilder: ModelBuilder do return modelbuilder_real.as(not null)
        private var modelbuilder_real: nullable ModelBuilder = null
 
+       fun run_global_phases(mainmodule: MModule)
+       do
+               for phase in phases_list do
+                       phase.process_mainmodule(mainmodule)
+               end
+       end
 end
 
+redef class Phase
+       # Specific action to execute on the whole program
+       # Called by the `ToolContext::run_global_phases`
+       # @toimplement
+       fun process_mainmodule(mainmodule: MModule) do end
+end
+
+
 # A model builder knows how to load nit source files and build the associated model
 class ModelBuilder
        # The model where new modules, classes and properties are added
@@ -107,7 +121,7 @@ class ModelBuilder
        end
 
        # Load a bunch of modules.
-       # `modules' can contains filenames or module names.
+       # `modules` can contains filenames or module names.
        # Imported modules are automatically loaded and modelized.
        # The result is the corresponding model elements.
        # Errors and warnings are printed with the toolcontext.
@@ -118,7 +132,7 @@ class ModelBuilder
                var time0 = get_time
                # Parse and recursively load
                self.toolcontext.info("*** PARSE ***", 1)
-               var mmodules = new Array[MModule]
+               var mmodules = new ArraySet[MModule]
                for a in modules do
                        var nmodule = self.load_module(null, a)
                        if nmodule == null then continue # Skip error
@@ -134,13 +148,13 @@ class ModelBuilder
                        exit(0)
                end
 
-               return mmodules
+               return mmodules.to_a
        end
 
-       # Return a class named `name' visible by the module `mmodule'.
+       # Return a class named `name` visible by the module `mmodule`.
        # Visibility in modules is correctly handled.
        # If no such a class exists, then null is returned.
-       # If more than one class exists, then an error on `anode' is displayed and null is returned.
+       # If more than one class exists, then an error on `anode` is displayed and null is returned.
        # FIXME: add a way to handle class name conflict
        fun try_get_mclass_by_name(anode: ANode, mmodule: MModule, name: String): nullable MClass
        do
@@ -163,11 +177,11 @@ class ModelBuilder
                return res
        end
 
-       # Return a property named `name' on the type `mtype' visible in the module `mmodule'.
+       # Return a property named `name` on the type `mtype` visible in the module `mmodule`.
        # Visibility in modules is correctly handled.
        # Protected properties are returned (it is up to the caller to check and reject protected properties).
        # If no such a property exists, then null is returned.
-       # If more than one property exists, then an error on `anode' is displayed and null is returned.
+       # If more than one property exists, then an error on `anode` is displayed and null is returned.
        # FIXME: add a way to handle property name conflict
        fun try_get_mproperty_by_name2(anode: ANode, mmodule: MModule, mtype: MType, name: String): nullable MProperty
        do
@@ -232,9 +246,9 @@ class ModelBuilder
        var paths: Array[String] = new Array[String]
 
        # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
-       # If `mmodule' is set, then the module search starts from it up to the top level (see `paths');
-       # if `mmodule' is null then the module is searched in the top level only.
-       # If no module exists or there is a name conflict, then an error on `anode' is displayed and null is returned.
+       # If `mmodule` is set, then the module search starts from it up to the top level (see `paths`);
+       # if `mmodule` is null then the module is searched in the top level only.
+       # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
        # FIXME: add a way to handle module name conflict
        fun get_mmodule_by_name(anode: ANode, mmodule: nullable MModule, name: String): nullable MModule
        do
@@ -316,7 +330,12 @@ class ModelBuilder
                                if candidate == null then
                                        candidate = try_file
                                else if candidate != try_file then
-                                       error(anode, "Error: conflicting module file for {name}: {candidate} {try_file}")
+                                       # try to disambiguate conflicting modules
+                                       var abs_candidate = module_absolute_path(candidate)
+                                       var abs_try_file = module_absolute_path(try_file)
+                                       if abs_candidate != abs_try_file then
+                                               error(anode, "Error: conflicting module file for {name}: {candidate} {try_file}")
+                                       end
                                end
                        end
                        try_file = (dirname + "/" + name + "/" + name + ".nit").simplify_path
@@ -324,7 +343,12 @@ class ModelBuilder
                                if candidate == null then
                                        candidate = try_file
                                else if candidate != try_file then
-                                       error(anode, "Error: conflicting module file for {name}: {candidate} {try_file}")
+                                       # try to disambiguate conflicting modules
+                                       var abs_candidate = module_absolute_path(candidate)
+                                       var abs_try_file = module_absolute_path(try_file)
+                                       if abs_candidate != abs_try_file then
+                                               error(anode, "Error: conflicting module file for {name}: {candidate} {try_file}")
+                                       end
                                end
                        end
                end
@@ -341,16 +365,36 @@ class ModelBuilder
                return res.mmodule.as(not null)
        end
 
+       # Transform relative paths (starting with '../') into absolute paths
+       private fun module_absolute_path(path: String): String do
+               if path.has_prefix("..") then
+                       return getcwd.join_path(path).simplify_path
+               end
+               return path
+       end
+
+       # loaded module by absolute path
+       private var loaded_nmodules = new HashMap[String, AModule]
+
        # Try to load a module using a path.
        # Display an error if there is a problem (IO / lexer / parser) and return null
        # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
        fun load_module(owner: nullable MModule, filename: String): nullable AModule
        do
+               if filename.file_extension != "nit" then
+                       self.toolcontext.error(null, "Error: file {filename} is not a valid nit module.")
+                       return null
+               end
                if not filename.file_exists then
                        self.toolcontext.error(null, "Error: file {filename} not found.")
                        return null
                end
 
+               var module_path = module_absolute_path(filename)
+               if loaded_nmodules.keys.has(module_path) then
+                       return loaded_nmodules[module_path]
+               end
+
                var x = if owner != null then owner.to_s else "."
                self.toolcontext.info("load module {filename} in {x}", 2)
 
@@ -360,7 +404,37 @@ class ModelBuilder
                var parser = new Parser(lexer)
                var tree = parser.parse
                file.close
+               var mod_name = filename.basename(".nit")
+
+               var nmodule = load_module_commons(owner, tree, mod_name)
+               if nmodule != null then loaded_nmodules[module_path] = nmodule
+
+               return nmodule
+       end
+
+       fun load_rt_module(owner: MModule, nmodule: AModule, mod_name: String): nullable AModule
+       do
+               # Create the module
+               var mmodule = new MModule(model, owner, mod_name, nmodule.location)
+               nmodule.mmodule = mmodule
+               nmodules.add(nmodule)
+               self.mmodule2nmodule[mmodule] = nmodule
+
+               var imported_modules = new Array[MModule]
+
+               imported_modules.add(owner)
+               mmodule.set_visibility_for(owner, intrude_visibility)
+
+               mmodule.set_imported_mmodules(imported_modules)
 
+               return nmodule
+       end
+
+       # Try to load a module using a path.
+       # Display an error if there is a problem (IO / lexer / parser) and return null
+       # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
+       private fun load_module_commons(owner: nullable MModule, tree: Start, mod_name: String): nullable AModule
+       do
                # Handle lexer and parser error
                var nmodule = tree.n_base
                if nmodule == null then
@@ -371,7 +445,6 @@ class ModelBuilder
                end
 
                # Check the module name
-               var mod_name = filename.basename(".nit")
                var decl = nmodule.n_moduledecl
                if decl == null then
                        #warning(nmodule, "Warning: Missing 'module' keyword") #FIXME: NOT YET FOR COMPATIBILITY
@@ -409,8 +482,13 @@ class ModelBuilder
                        var mod_name = aimport.n_name.n_id.text
                        var sup = self.get_mmodule_by_name(aimport.n_name, mmodule, mod_name)
                        if sup == null then continue # Skip error
+                       aimport.mmodule = sup
                        imported_modules.add(sup)
                        var mvisibility = aimport.n_visibility.mvisibility
+                       if mvisibility == protected_visibility then
+                               error(aimport.n_visibility, "Error: only properties can be protected.")
+                               return
+                       end
                        mmodule.set_visibility_for(sup, mvisibility)
                end
                if stdimport then
@@ -429,25 +507,25 @@ class ModelBuilder
        var nmodules: Array[AModule] = new Array[AModule]
 
        # Register the nmodule associated to each mmodule
-       # FIXME: why not refine the MModule class with a nullable attribute?
+       # FIXME: why not refine the `MModule` class with a nullable attribute?
        var mmodule2nmodule: HashMap[MModule, AModule] = new HashMap[MModule, AModule]
 
        # Helper function to display an error on a node.
-       # Alias for `self.toolcontext.error(n.hot_location, text)'
+       # Alias for `self.toolcontext.error(n.hot_location, text)`
        fun error(n: ANode, text: String)
        do
                self.toolcontext.error(n.hot_location, text)
        end
 
        # Helper function to display a warning on a node.
-       # Alias for: `self.toolcontext.warning(n.hot_location, text)'
+       # Alias for: `self.toolcontext.warning(n.hot_location, text)`
        fun warning(n: ANode, text: String)
        do
                self.toolcontext.warning(n.hot_location, text)
        end
 
-       # Force to get the primitive method named `name' on the type `recv' or do a fatal error on `n'
-       fun force_get_primitive_method(n: ANode, name: String, recv: MType, mmodule: MModule): MMethod
+       # Force to get the primitive method named `name` on the type `recv` or do a fatal error on `n`
+       fun force_get_primitive_method(n: ANode, name: String, recv: MClass, mmodule: MModule): MMethod
        do
                var res = mmodule.try_get_primitive_method(name, recv)
                if res == null then
@@ -458,8 +536,13 @@ class ModelBuilder
        end
 end
 
+redef class AStdImport
+       # The imported module once determined
+       var mmodule: nullable MModule = null
+end
+
 redef class AModule
-       # The associated MModule once build by a `ModelBuilder'
+       # The associated MModule once build by a `ModelBuilder`
        var mmodule: nullable MModule
        # Flag that indicate if the importation is already completed
        var is_importation_done: Bool = false