src: update most tools to new constructors
[nit.git] / src / modelbuilder.nit
index 51d2886..76a6305 100644 (file)
 # FIXME add missing error checks
 module modelbuilder
 
-import parser
 import model
-import poset
-import opts
-import toolcontext
 import phase
 
 private import more_collections
@@ -35,16 +31,16 @@ private import more_collections
 
 redef class ToolContext
        # Option --path
-       var opt_path: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
+       var opt_path = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
 
        # Option --only-metamodel
-       var opt_only_metamodel: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
+       var opt_only_metamodel = new OptionBool("Stop after meta-model processing", "--only-metamodel")
 
        # Option --only-parse
-       var opt_only_parse: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
+       var opt_only_parse = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
 
        # Option --ignore-visibility
-       var opt_ignore_visibility: OptionBool = new OptionBool("Do not check, and produce errors, on visibility issues.", "--ignore-visibility")
+       var opt_ignore_visibility = new OptionBool("Do not check, and produce errors, on visibility issues.", "--ignore-visibility")
 
        redef init
        do
@@ -52,11 +48,13 @@ redef class ToolContext
                option_context.add_option(opt_path, opt_only_parse, opt_only_metamodel, opt_ignore_visibility)
        end
 
+       # The modelbuilder 1-to-1 associated with the toolcontext
        fun modelbuilder: ModelBuilder do return modelbuilder_real.as(not null)
+
        private var modelbuilder_real: nullable ModelBuilder = null
 
-       # Run `process_mainmodule` on all phases
-       fun run_global_phases(mmodules: Array[MModule])
+       # Combine module to make a single one if required.
+       fun make_main_module(mmodules: Array[MModule]): MModule
        do
                assert not mmodules.is_empty
                var mainmodule
@@ -64,9 +62,17 @@ redef class ToolContext
                        mainmodule = mmodules.first
                else
                        # We need a main module, so we build it by importing all modules
-                       mainmodule = new MModule(modelbuilder.model, null, "<main>", new Location(null, 0, 0, 0, 0))
+                       mainmodule = new MModule(modelbuilder.model, null, mmodules.first.name + "-m", new Location(mmodules.first.location.file, 0, 0, 0, 0))
+                       mainmodule.is_fictive = true
                        mainmodule.set_imported_mmodules(mmodules)
                end
+               return mainmodule
+       end
+
+       # Run `process_mainmodule` on all phases
+       fun run_global_phases(mmodules: Array[MModule])
+       do
+               var mainmodule = make_main_module(mmodules)
                for phase in phases_list do
                        if phase.disabled then continue
                        phase.process_mainmodule(mainmodule, mmodules)
@@ -79,7 +85,7 @@ redef class Phase
        # Called by the `ToolContext::run_global_phases`.
        #
        # `mainmodule` is the main module of the program.
-       # It could be an implicit module (called "<main>").
+       # It could be an implicit module (called like the first given_mmodules).
        #
        # `given_modules` is the list of explicitely requested modules.
        # from the command-line for instance.
@@ -119,10 +125,8 @@ class ModelBuilder
 
        # Instantiate a modelbuilder for a model and a toolcontext
        # Important, the options of the toolcontext must be correctly set (parse_option already called)
-       init(model: Model, toolcontext: ToolContext)
+       init
        do
-               self.model = model
-               self.toolcontext = toolcontext
                assert toolcontext.modelbuilder_real == null
                toolcontext.modelbuilder_real = self
 
@@ -134,14 +138,11 @@ class ModelBuilder
                        paths.append(path_env.split_with(':'))
                end
 
-               path_env = "NIT_DIR".environ
-               if not path_env.is_empty then
-                       var libname = "{path_env}/lib"
+               var nit_dir = toolcontext.nit_dir
+               if nit_dir != null then
+                       var libname = "{nit_dir}/lib"
                        if libname.file_exists then paths.add(libname)
                end
-
-               var libname = "{sys.program_name.dirname}/../lib"
-               if libname.file_exists then paths.add(libname.simplify_path)
        end
 
        # Load a bunch of modules.
@@ -222,37 +223,70 @@ class ModelBuilder
                for mprop in props do
                        if not mtype.has_mproperty(mmodule, mprop) then continue
                        if not mmodule.is_visible(mprop.intro_mclassdef.mmodule, mprop.visibility) then continue
+
+                       # new-factories are invisible outside of the class
+                       if mprop isa MMethod and mprop.is_new and (not mtype isa MClassType or mprop.intro_mclassdef.mclass != mtype.mclass) then
+                               continue
+                       end
+
                        if res == null then
                                res = mprop
-                       else
+                               continue
+                       end
+
+                       # Two global properties?
+                       # First, special case for init, keep the most specific ones
+                       if res isa MMethod and mprop isa MMethod and res.is_init and mprop.is_init then
                                var restype = res.intro_mclassdef.bound_mtype
                                var mproptype = mprop.intro_mclassdef.bound_mtype
-                               if restype.is_subtype(mmodule, null, mproptype) then
-                                       # we keep res
-                               else if mproptype.is_subtype(mmodule, null, restype) then
+                               if mproptype.is_subtype(mmodule, null, restype) then
+                                       # found a most specific constructor, so keep it
                                        res = mprop
-                               else
-                                       if ress == null then ress = new Array[MProperty]
-                                       ress.add(mprop)
+                                       continue
                                end
                        end
+
+                       # Ok, just keep all prop in the ress table
+                       if ress == null then
+                               ress = new Array[MProperty]
+                               ress.add(res)
+                       end
+                       ress.add(mprop)
                end
-               if ress != null then
+
+               # There is conflict?
+               if ress != null and res isa MMethod and res.is_init then
+                       # special case forinit again
                        var restype = res.intro_mclassdef.bound_mtype
+                       var ress2 = new Array[MProperty]
                        for mprop in ress do
                                var mproptype = mprop.intro_mclassdef.bound_mtype
                                if not restype.is_subtype(mmodule, null, mproptype) then
-                                       self.error(anode, "Ambigous property name '{name}' for {mtype}; conflict between {mprop.full_name} and {res.full_name}")
-                                       return null
+                                       ress2.add(mprop)
+                               else if not mprop isa MMethod or not mprop.is_init then
+                                       ress2.add(mprop)
                                end
                        end
+                       if ress2.is_empty then
+                               ress = null
+                       else
+                               ress = ress2
+                               ress.add(res)
+                       end
+               end
+
+               if ress != null then
+                       assert ress.length > 1
+                       var s = new Array[String]
+                       for mprop in ress do s.add mprop.full_name
+                       self.error(anode, "Ambigous property name '{name}' for {mtype}; conflict between {s.join(" and ")}")
                end
 
                self.try_get_mproperty_by_name2_cache[mmodule, mtype, name] = res
                return res
        end
 
-       private var try_get_mproperty_by_name2_cache: HashMap3[MModule, MType, String, nullable MProperty] = new HashMap3[MModule, MType, String, nullable MProperty]
+       private var try_get_mproperty_by_name2_cache = new HashMap3[MModule, MType, String, nullable MProperty]
 
 
        # Alias for try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.mtype, name)
@@ -265,9 +299,9 @@ class ModelBuilder
        # The list is initially set with :
        #   * the toolcontext --path option
        #   * the NIT_PATH environment variable
-       #   * some heuristics including the NIT_DIR environment variable and the progname of the process
+       #   * `toolcontext.nit_dir`
        # Path can be added (or removed) by the client
-       var paths: Array[String] = new Array[String]
+       var paths = new Array[String]
 
        # Like (an used by) `get_mmodule_by_name` but just return the ModulePath
        private fun search_mmodule_by_name(anode: ANode, mgroup: nullable MGroup, name: String): nullable ModulePath
@@ -444,11 +478,22 @@ class ModelBuilder
                        return mgroups[rdp]
                end
 
-               # Hack, a dir is determined by the presence of a honomymous nit file
+               # Hack, a group is determined by:
+               # * the presence of a honomymous nit file
+               # * the fact that the directory is named `src`
                var pn = rdp.basename(".nit")
                var mp = dirpath.join_path(pn + ".nit").simplify_path
 
-               if not mp.file_exists then return null
+               var dirpath2 = dirpath
+               if not mp.file_exists then
+                       if pn == "src" then
+                               # With a src directory, the group name is the name of the parent directory
+                               dirpath2 = rdp.dirname
+                               pn = dirpath2.basename("")
+                       else
+                               return null
+                       end
+               end
 
                # check parent directory
                var parentpath = dirpath.join_path("..").simplify_path
@@ -465,6 +510,17 @@ class ModelBuilder
                        mgroup = new MGroup(pn, parent.mproject, parent)
                        toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
                end
+               var readme = dirpath2.join_path("README.md")
+               if not readme.file_exists then readme = dirpath2.join_path("README")
+               if readme.file_exists then
+                       var mdoc = new MDoc
+                       var s = new IFStream.open(readme)
+                       while not s.eof do
+                               mdoc.content.add(s.read_line)
+                       end
+                       mgroup.mdoc = mdoc
+                       mdoc.original_mentity = mgroup
+               end
                mgroup.filepath = dirpath
                mgroups[rdp] = mgroup
                return mgroup
@@ -496,7 +552,6 @@ class ModelBuilder
                var parser = new Parser(lexer)
                var tree = parser.parse
                file.close
-               var mod_name = filename.basename(".nit")
 
                # Handle lexer and parser error
                var nmodule = tree.n_base
@@ -543,20 +598,27 @@ class ModelBuilder
                return nmodule
        end
 
-       fun load_rt_module(parent: MModule, nmodule: AModule, mod_name: String): nullable AModule
+       # Injection of a new module without source.
+       # Used by the interpreted
+       fun load_rt_module(parent: nullable MModule, nmodule: AModule, mod_name: String): nullable AModule
        do
                # Create the module
-               var mmodule = new MModule(model, parent.mgroup, mod_name, nmodule.location)
+
+               var mgroup = null
+               if parent != null then mgroup = parent.mgroup
+               var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
                nmodule.mmodule = mmodule
                nmodules.add(nmodule)
                self.mmodule2nmodule[mmodule] = nmodule
 
-               var imported_modules = new Array[MModule]
-
-               imported_modules.add(parent)
-               mmodule.set_visibility_for(parent, intrude_visibility)
-
-               mmodule.set_imported_mmodules(imported_modules)
+               if parent!= null then
+                       var imported_modules = new Array[MModule]
+                       imported_modules.add(parent)
+                       mmodule.set_visibility_for(parent, intrude_visibility)
+                       mmodule.set_imported_mmodules(imported_modules)
+               else
+                       build_module_importation(nmodule)
+               end
 
                return nmodule
        end
@@ -583,7 +645,13 @@ class ModelBuilder
 
                if decl != null then
                        var ndoc = decl.n_doc
-                       if ndoc != null then mmodule.mdoc = ndoc.to_mdoc
+                       if ndoc != null then
+                               var mdoc = ndoc.to_mdoc
+                               mmodule.mdoc = mdoc
+                               mdoc.original_mentity = mmodule
+                       else
+                               advice(decl, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
+                       end
                end
 
                return mmodule
@@ -602,8 +670,15 @@ class ModelBuilder
                        if not aimport isa AStdImport then
                                continue
                        end
+                       var mgroup = mmodule.mgroup
+                       if aimport.n_name.n_quad != null then mgroup = null # Start from top level
+                       for grp in aimport.n_name.n_path do
+                               var path = search_mmodule_by_name(grp, mgroup, grp.text)
+                               if path == null then return # Skip error
+                               mgroup = path.mgroup
+                       end
                        var mod_name = aimport.n_name.n_id.text
-                       var sup = self.get_mmodule_by_name(aimport.n_name, mmodule.mgroup, mod_name)
+                       var sup = self.get_mmodule_by_name(aimport.n_name, mgroup, mod_name)
                        if sup == null then continue # Skip error
                        aimport.mmodule = sup
                        imported_modules.add(sup)
@@ -631,14 +706,26 @@ class ModelBuilder
                end
                self.toolcontext.info("{mmodule} imports {imported_modules.join(", ")}", 3)
                mmodule.set_imported_mmodules(imported_modules)
+
+               # TODO: Correctly check for useless importation
+               # It is even doable?
+               var directs = mmodule.in_importation.direct_greaters
+               for nim in nmodule.n_imports do
+                       if not nim isa AStdImport then continue
+                       var im = nim.mmodule
+                       if im == null then continue
+                       if directs.has(im) then continue
+                       # This generates so much noise that it is simpler to just comment it
+                       #warning(nim, "Warning: possible useless importation of {im}")
+               end
        end
 
        # All the loaded modules
-       var nmodules: Array[AModule] = new Array[AModule]
+       var nmodules = new Array[AModule]
 
        # Register the nmodule associated to each mmodule
        # FIXME: why not refine the `MModule` class with a nullable attribute?
-       var mmodule2nmodule: HashMap[MModule, AModule] = new HashMap[MModule, AModule]
+       var mmodule2nmodule = new HashMap[MModule, AModule]
 
        # Helper function to display an error on a node.
        # Alias for `self.toolcontext.error(n.hot_location, text)`
@@ -649,17 +736,26 @@ class ModelBuilder
 
        # Helper function to display a warning on a node.
        # Alias for: `self.toolcontext.warning(n.hot_location, text)`
-       fun warning(n: ANode, text: String)
+       fun warning(n: ANode, tag, text: String)
+       do
+               self.toolcontext.warning(n.hot_location, tag, text)
+       end
+
+       # Helper function to display an advice on a node.
+       # Alias for: `self.toolcontext.advice(n.hot_location, text)`
+       fun advice(n: ANode, tag, text: String)
        do
-               self.toolcontext.warning(n.hot_location, text)
+               self.toolcontext.advice(n.hot_location, tag, 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: MClass, mmodule: MModule): MMethod
+       fun force_get_primitive_method(n: nullable ANode, name: String, recv: MClass, mmodule: MModule): MMethod
        do
                var res = mmodule.try_get_primitive_method(name, recv)
                if res == null then
-                       self.toolcontext.fatal_error(n.hot_location, "Fatal Error: {recv} must have a property named {name}.")
+                       var l = null
+                       if n != null then l = n.hot_location
+                       self.toolcontext.fatal_error(l, "Fatal Error: {recv} must have a property named {name}.")
                        abort
                end
                return res