contrib/jwrapper: fix == between arrays of different dimensions
[nit.git] / contrib / jwrapper / src / model.nit
index 5dcd96d..25d9cd2 100644 (file)
 module model
 
 import more_collections
+import opts
 
 import jtype_converter
 
 class JavaType
-       private var converter: JavaTypeConverter
+       super Cloneable
+
+       # Identifiers composing the namespace and class name
+       #
+       # An array of all the names that would be separated by `.`.
+       # Each name may contain `$`.
        var identifier = new Array[String]
+
        var generic_params: nullable Array[JavaType] = null
+
+       # Is this a void return type?
        var is_void = false
 
+       # Is this type a vararg?
+       var is_vararg = false is writable
+
        # Has some generic type to be resolved (T extends foo => T is resolved to foo)
        var has_unresolved_types = false
 
@@ -37,10 +49,6 @@ class JavaType
        fun is_primitive_array: Bool do return array_dimension > 0
 
        fun has_generic_params: Bool do return not generic_params == null
-       fun full_id: String do return identifier.join(".")
-       fun id: String do return identifier.last.replace("$", "")
-
-       init(converter: JavaTypeConverter) do self.converter = converter
 
        fun return_cast: String do return converter.cast_as_return(self.id)
 
@@ -53,70 +61,51 @@ class JavaType
                return converter.cast_as_param(self.id)
        end
 
-       fun to_nit_type: NitType
+       # Name to give an extern class wrapping this type
+       fun extern_name: String
        do
-               var nit_type: NitType
-               var type_id = null
-
-               if not is_primitive_array then
-                       type_id = converter.to_nit_type(self.id)
-               end
-
-               if type_id == null then
-                       nit_type = self.extern_name
-                       nit_type.is_complete = false
+               var name
+               var prefix = extern_class_prefix
+               if prefix == null then
+                       # Use the namespace, e.g. java.lang.String -> Java_lang_String
+                       assert not identifier.is_empty
+                       if identifier.length == 1 then
+                               name = identifier.last
+                       else
+                               var first = identifier.first
+                               var last = identifier.last
+                               var mid = identifier.subarray(1, identifier.length-2)
+                               name = first.simple_capitalized + "_"
+                               if mid.not_empty then name += mid.join("_") + "_"
+                               name += last
+                       end
                else
-                       nit_type = new NitType(type_id)
-               end
-
-               if not self.has_generic_params then return nit_type
-
-               nit_type.generic_params = new Array[NitType]
-
-               for param in generic_params do
-                       var nit_param = param.to_nit_type
-
-                       nit_type.generic_params.add(nit_param)
-
-                       if not nit_param.is_complete then nit_type.is_complete = false
+                       # Use the prefix and the short class name
+                       # e.g. given the prefix Native: java.lang.String -> NativeString
+                       name = prefix + id
                end
 
-               return nit_type
-       end
-
-       fun is_collection: Bool do return is_primitive_array or collections_list.has(self.id)
-
-       fun is_wrapped: Bool do return find_extern_class != null
-
-       fun extern_name: NitType
-       do
-               if is_wrapped then return new NitType.with_module(find_extern_class.as(not null).first, find_extern_class.as(not null).second)
-
-               var name
                if is_primitive_array then
-                       # Primitive arrays have a special naming convention
-                       name = "Java" + extern_class_name.join.capitalized + "Array"
-               else
-                       name = "Java" + extern_class_name.join
+                       name += "_" + "Array" * array_dimension
                end
 
-               var nit_type = new NitType(name)
-               nit_type.is_complete = false
-               return nit_type
+               name = name.replace("-", "_")
+               name = name.replace("$", "_")
+               return name
        end
 
-       fun to_cast(jtype: String, is_param: Bool): String
-       do
-               if is_param then
-                       return converter.cast_as_param(jtype)
-               end
+       # Short name of the class, mangled to remove `$` (e.g. `Set`)
+       fun id: String do return identifier.last.replace("$", "")
 
-               return converter.cast_as_return(jtype)
-       end
+       # Full name of this class as used in an importation (e.g. `java.lang.Set`)
+       fun package_name: String do return identifier.join(".")
 
-       redef fun to_s
-       do
-               var id = self.full_id
+       # Name of this class for the extern declaration in Nit (e.g. `java.lang.Set[]`)
+       fun extern_equivalent: String do return package_name + "[]" * array_dimension
+
+       # Full name of this class with arrays and generic values (e.g. `java.lang.Set<E>[]`)
+       redef fun to_s do
+               var id = self.package_name
 
                if self.is_primitive_array then
                        id += "[]" * array_dimension
@@ -128,16 +117,6 @@ class JavaType
                return id
        end
 
-       # To fully qualified package name
-       # Cuts the primitive array `[]`
-       fun to_package_name: String
-       do
-               var str = self.to_s
-               var len = str.length
-
-               return str.substring(0, len - (2*array_dimension))
-       end
-
        fun resolve_types(conversion_map: HashMap[String, Array[String]])
        do
                if identifier.length == 1 then
@@ -150,175 +129,250 @@ class JavaType
                end
        end
 
-       private fun extern_class_name: Array[String]
+       # Get a copy of `self`
+       redef fun clone
        do
-               var class_name = new Array[String]
-               class_name.add(self.id)
+               var jtype = new JavaType
+               jtype.identifier = identifier
+               jtype.generic_params = generic_params
+               jtype.is_void = is_void
+               jtype.is_vararg = is_vararg
+               jtype.array_dimension = array_dimension
+               return jtype
+       end
 
-               if not self.has_generic_params then return class_name
+       # Comparison based on fully qualified named
+       redef fun ==(other) do return other isa JavaType and
+               self.package_name == other.package_name and
+               self.array_dimension == other.array_dimension
 
-               class_name.add "Of"
+       redef fun hash do return self.package_name.hash
+end
 
-               for param in generic_params do class_name.add_all param.extern_class_name
+class NitType
+       # Nit class name
+       var identifier: String
 
-               return class_name
-       end
+       # If this NitType was found in `lib/android`, contains the module name to import
+       var mod: nullable NitModule
 
-       # Search inside `lib/android` directory for already wrapped classes
-       # If found, contains the class identifier and the Nit Module name
-       var find_extern_class: nullable Couple[String, NitModule] is lazy do
+       # Is this type known, wrapped and available in Nit?
+       var is_known: Bool = true
 
-               var regex = "extern class [a-zA-Z1-9]\\\+[ ]\\\+in[ ]\\\+\"Java\"[ ]*`\{[ ]*" + self.to_s + "\\\+[ ]*`\}"
-               var nit_dir = "NIT_DIR".environ
-               var grep = new ProcessReader("grep", "-r", regex, nit_dir/"lib/android/", nit_dir/"lib/java/")
-               var to_eat = ["private", "extern", "class"]
+       redef fun to_s do return identifier
+end
 
-               var output = grep.read_line
+# Model of a single Java class
+class JavaClass
+       # Type of this class
+       var class_type: JavaType
 
-               var output_class = output.substring_from(output.index_of(':') + 1)
-               var tokens = output_class.split(" ")
+       # Attributes of this class
+       var attributes = new HashMap[String, JavaAttribute]
 
-               var nclass_name = ""
+       # Methods of this class organized by their name
+       var methods = new MultiHashMap[String, JavaMethod]
 
-               for token in tokens do
-                       if to_eat.has(token) then continue
-                       nclass_name = token
-                       break
-               end
+       # Constructors of this class
+       var constructors = new Array[JavaConstructor]
 
-               if nclass_name == "" then return null
+       # Importations from this class
+       var imports = new HashSet[NitModule]
 
-               var str = output.substring(0, output.search(".nit").from)
-               str = str.substring_from(str.last_index_of('/') + 1)
-               var mod = new NitModule(str)
+       redef fun to_s do return class_type.to_s
+end
 
-               return new Couple[String, NitModule](nclass_name, mod)
-       end
+# Model of all the Java class analyzed in one run
+class JavaModel
 
-       # Comparison based on fully qualified named and generic params
-       # Ignores primitive array so `a.b.c[][] == a.b.c`
-       redef fun ==(other)
+       # All analyzed classes
+       var classes = new HashMap[String, JavaClass]
+
+       # Add a class in `classes`
+       fun add_class(jclass: JavaClass)
        do
-               if other isa JavaType then
-                       return self.repr == other.repr
-               end
-               return false
+               var key = jclass.class_type.package_name
+               classes[key] = jclass
        end
 
-       redef fun hash do return self.repr.hash
+       # Unknown types, not already wrapped and not in this pass
+       var unknown_types = new HashMap[JavaType, NitType]
 
-       private fun repr: String
-       do
-               var id = self.full_id
+       # Wrapped types, or classes analyzed in this pass
+       var known_types = new HashMap[JavaType, NitType]
 
-               if self.has_generic_params then
-                       var gen_list = new Array[String]
+       # Get the `NitType` corresponding to the `JavaType`
+       #
+       # Also registers types so they can be reused and
+       # to keep track of unknown types.
+       fun java_to_nit_type(jtype: JavaType): NitType
+       do
+               # Check cache
+               if known_types.keys.has(jtype) then return known_types[jtype]
+               if unknown_types.keys.has(jtype) then return unknown_types[jtype]
+
+               # Is it a compatible primitive type?
+               if not jtype.is_primitive_array then
+                       var name = converter.to_nit_type(jtype.id)
+                       if name != null then
+                               # We got a Nit equivalent
+                               var nit_type = new NitType(name)
+                               known_types[jtype] = nit_type
+                               return nit_type
+                       end
+               end
 
-                       for param in generic_params do
-                               gen_list.add(param.to_s)
+               # Is being wrapped in this pass?
+               var key = jtype.package_name
+               if classes.keys.has(key) then
+                       if jtype.array_dimension <= opt_arrays.value then
+                               var nit_type = new NitType(jtype.extern_name)
+                               known_types[jtype] = nit_type
+                               return nit_type
                        end
+               end
 
-                       id += "<{gen_list.join(", ")}>"
+               # Search in lib
+               var nit_type = find_extern_class[jtype.extern_equivalent]
+               if nit_type != null then
+                       known_types[jtype] = nit_type
+                       return nit_type
                end
 
-               return id
+               # Unknown type
+               nit_type = new NitType(jtype.extern_name)
+               nit_type.is_known = false
+               unknown_types[jtype] = nit_type
+               return nit_type
        end
-
-       var collections_list: Array[String] is lazy do return ["List", "ArrayList", "LinkedList", "Vector", "Set", "SortedSet", "HashSet", "TreeSet", "LinkedHashSet", "Map", "SortedMap", "HashMap", "TreeMap", "Hashtable", "LinkedHashMap"]
-       var iterable: Array[String] is lazy do return ["ArrayList", "Set", "HashSet", "LinkedHashSet", "LinkedList", "Stack", "TreeSet", "Vector"]
-       var maps: Array[String] is lazy do return ["Map", "SortedMap", "HashMap", "TreeMap", "Hashtable", "LinkedHashMap"]
 end
 
-class NitType
-       var identifier: String
-       var arg_id: String
-       var generic_params: nullable Array[NitType] = null
+# A property to a Java class
+abstract class JavaProperty
 
-       # If this NitType was found in `lib/android`, contains the module name to import
-       var mod: nullable NitModule
+       # Is this property marked static?
+       var is_static: Bool
+end
 
-       # Returns `true` if all types have been successfully converted to Nit type
-       var is_complete: Bool = true
+# A Java method, with its signature
+class JavaMethod
+       super JavaProperty
 
-       fun has_generic_params: Bool do return not generic_params == null
+       # Type returned by the method
+       var return_type: JavaType
 
-       fun id: String do return identifier
+       # Type of the arguments of the method
+       var params: Array[JavaType]
+end
 
-       init (id: String)
-       do
-               self.identifier = id
-       end
+# An attribute in a Java class
+class JavaAttribute
+       super JavaProperty
 
-       init with_generic_params(id: String, gen_params: String...)
-       do
-               self.init(id)
-               self.generic_params = new Array[NitType]
-               for param in gen_params do self.generic_params.add new NitType(param)
-       end
+       # Type of the attribute
+       var java_type: JavaType
+end
 
-       init with_module(id: String, mod: NitModule)
-       do
-               self.init(id)
-               self.mod = mod
-       end
+# A Java method, with its signature
+class JavaConstructor
+       # Type of the parameters of this constructor
+       var params: Array[JavaType]
+end
 
-       redef fun to_s: String
-       do
-               var id = self.identifier
+# A Nit module, use to import the referenced extern classes
+class NitModule
+       # Relative path to the module
+       var path: String
 
-               if self.has_generic_params then
-                       var gen_list = new Array[String]
+       # Name of the module
+       var name: String is lazy do return path.basename(".nit")
+
+       redef fun to_s do return self.name
+       redef fun ==(other) do return other isa NitModule and self.path == other.path
+       redef fun hash do return self.path.hash
+end
 
-                       for param in generic_params do
-                               gen_list.add(param.to_s)
+redef class Sys
+       # Collection of Java classes already wrapped in the library
+       #
+       # * The key uses `JavaType.to_s`.
+       # * The value is the corresponding `NitType`.
+       var find_extern_class: DefaultMap[String, nullable NitType] is lazy do
+               var map = new DefaultMap[String, nullable NitType](null)
+               var modules = new HashMap[String, NitModule]
+
+               var lib_paths = opt_libs.value
+               if lib_paths == null then lib_paths = new Array[String]
+
+               if lib_paths.has("auto") then
+                       lib_paths.remove "auto"
+                       var nit_dir = "NIT_DIR".environ
+                       if nit_dir.is_empty then
+                               # Simple heuristic to find the Nit lib
+                               var dir = sys.program_name.dirname / "../../../lib/"
+                               dir = dir.simplify_path
+                               if dir.file_exists then lib_paths.add dir.simplify_path
                        end
+               end
 
-                       id += "[{gen_list.join(", ")}]"
+               if lib_paths.is_empty then return map
+
+               # Use grep to find all extern classes implemented in Java
+               var grep_regex = "extern class [a-zA-Z0-9_]\\\+[ ]\\\+in[ ]\\\+\"Java\""
+               var grep_args = ["-r", "--with-filename", grep_regex]
+               grep_args.add_all lib_paths
+
+               var grep = new ProcessReader("grep", grep_args...)
+               var lines = grep.read_lines
+               grep.close
+               grep.wait
+
+               # Sort out the modules, Nit class names and Java types
+               var regex = """(.+):\\s*extern +class +([a-zA-Z0-9_]+) *in *"Java" *`\\{(.+)`\\}""".to_re
+               for line in lines do
+                       var matches = line.search_all(regex)
+                       for match in matches do
+                               var path = match[1].to_s
+                               var nit_name = match[2].to_s
+                               var java_name = match[3].to_s.trim
+
+                               # Debug code
+                               # print "+ Found {nit_name}: {java_name} at {path}"
+
+                               var mod = modules.get_or_null(path)
+                               if mod == null then
+                                       mod = new NitModule(path)
+                                       modules[path] = mod
+                               end
+
+                               map[java_name] = new NitType(nit_name, mod)
+                       end
                end
 
-               return id
+               return map
        end
-end
 
-# Model of a single Java class
-class JavaClass
-       # Type of this class
-       var class_type = new JavaType(new JavaTypeConverter)
+       # Option to set `extern_class_prefix`
+       var opt_extern_class_prefix = new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
 
-       # Attributes of this class
-       var attributes = new HashMap[String, JavaType]
+       # Prefix used to name extern classes, if `null` use the full namespace
+       var extern_class_prefix: nullable String is lazy do return opt_extern_class_prefix.value
 
-       # Methods of this class organized by their name
-       var methods = new MultiHashMap[String, JavaMethod]
+       # Libraries to search for existing wrappers
+       var opt_libs = new OptionArray("Paths to libraries with wrappers of Java classes ('auto' to use the full Nit lib)", "-i")
 
-       # Importations from this class
-       var imports = new HashSet[NitModule]
+       # Generate the primitive array version of each class up to the given depth
+       var opt_arrays = new OptionInt("Depth of the primitive array for each wrapped class (default: 1)", 1, "-a")
 end
 
-# Model of all the Java class analyzed in one run
-class JavaModel
-       # Unknown Java types used in `classes`
-       var unknown_types = new HashSet[JavaType]
-
-       # All analyzed classes
-       var classes = new Array[JavaClass]
-end
-
-# A Java method, with its signature
-class JavaMethod
-       # Type returned by the method
-       var return_type: JavaType
-
-       # Type of the arguments of the method
-       var params: Array[JavaType]
-end
-
-# A Nit module, use to import the referenced extern classes
-class NitModule
-       # Name of the module
-       var name: String
+redef class Text
+       # Get a copy of `self` where the first letter is capitalized
+       fun simple_capitalized: String
+       do
+               if is_empty then return to_s
 
-       redef fun ==(other): Bool do return self.to_s == other.to_s
-       redef fun to_s: String do return self.name
-       redef fun hash: Int do return self.name.hash
+               var c = chars.first.to_upper
+               var s = c.to_s + substring_from(1)
+               return s
+       end
 end