1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Copyright 2014 Frédéric Vachon <fredvac@gmail.com>
4 # Copyright 2015 Alexis Laferrière <alexis.laf@xymus.net>
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
18 # Contains the java and nit type representation used to convert java to nit code
21 import more_collections
24 import jtype_converter
29 # Identifiers composing the namespace and class name
31 # An array of all the names that would be separated by `.`.
32 # Each name may contain `$`.
33 var identifier
= new Array[String]
35 var generic_params
: nullable Array[JavaType] = null
37 # Is this a void return type?
40 # Is this type a vararg?
41 var is_vararg
= false is writable
43 # Has some generic type to be resolved (T extends foo => T is resolved to foo)
44 var has_unresolved_types
= false
46 # Dimension of primitive array: `int[][]` is 2d
47 var array_dimension
= 0
49 fun is_primitive_array
: Bool do return array_dimension
> 0
51 fun has_generic_params
: Bool do return not generic_params
== null
53 fun return_cast
: String do return converter
.cast_as_return
(self.id
)
55 fun param_cast
: String
57 if self.has_generic_params
then
58 return converter
.cast_as_param
(self.generic_params
[0].id
)
61 return converter
.cast_as_param
(self.id
)
64 # Name to give an extern class wrapping this type
65 fun extern_name
: String
68 var prefix
= extern_class_prefix
69 if prefix
== null then
70 # Use the namespace, e.g. java.lang.String -> Java_lang_String
71 assert not identifier
.is_empty
72 if identifier
.length
== 1 then
73 name
= identifier
.last
75 var first
= identifier
.first
76 var last
= identifier
.last
77 var mid
= identifier
.subarray
(1, identifier
.length-2
)
78 name
= first
.simple_capitalized
+ "_"
79 if mid
.not_empty
then name
+= mid
.join
("_") + "_"
83 # Use the prefix and the short class name
84 # e.g. given the prefix Native: java.lang.String -> NativeString
88 if is_primitive_array
then
89 name
+= "_" + "Array" * array_dimension
92 name
= name
.replace
("-", "_")
93 name
= name
.replace
("$", "_")
97 # Short name of the class, mangled to remove `$` (e.g. `Set`)
98 fun id
: String do return identifier
.last
.replace
("$", "")
100 # Full name of this class as used in an importation (e.g. `java.lang.Set`)
101 fun package_name
: String do return identifier
.join
(".")
103 # Name of this class for the extern declaration in Nit (e.g. `java.lang.Set[]`)
104 fun extern_equivalent
: String do return package_name
+ "[]" * array_dimension
106 # Full name of this class with arrays and generic values (e.g. `java.lang.Set<E>[]`)
108 var id
= self.package_name
110 if self.is_primitive_array
then
111 id
+= "[]" * array_dimension
112 else if self.has_generic_params
then
113 var params
= [for param
in generic_params
do param
.to_s
]
114 id
+= "<{params.join(", ")}>"
120 fun resolve_types
(conversion_map
: HashMap[String, Array[String]])
122 if identifier
.length
== 1 then
123 var resolved_id
= conversion_map
.get_or_null
(self.id
)
124 if resolved_id
!= null then self.identifier
= new Array[String].from
(resolved_id
)
127 if self.has_generic_params
then
128 for params
in generic_params
do params
.resolve_types
(conversion_map
)
132 # Get a copy of `self`
135 var jtype
= new JavaType
136 jtype
.identifier
= identifier
137 jtype
.generic_params
= generic_params
138 jtype
.is_void
= is_void
139 jtype
.is_vararg
= is_vararg
140 jtype
.array_dimension
= array_dimension
144 # Comparison based on fully qualified named
145 redef fun ==(other
) do return other
isa JavaType and
146 self.package_name
== other
.package_name
and
147 self.is_primitive_array
== other
.is_primitive_array
149 redef fun hash
do return self.package_name
.hash
154 var identifier
: String
156 # If this NitType was found in `lib/android`, contains the module name to import
157 var mod
: nullable NitModule
159 # Is this type known, wrapped and available in Nit?
160 var is_known
: Bool = true
162 redef fun to_s
do return identifier
165 # Model of a single Java class
168 var class_type
: JavaType
170 # Attributes of this class
171 var attributes
= new HashMap[String, JavaAttribute]
173 # Methods of this class organized by their name
174 var methods
= new MultiHashMap[String, JavaMethod]
176 # Constructors of this class
177 var constructors
= new Array[JavaConstructor]
179 # Importations from this class
180 var imports
= new HashSet[NitModule]
182 redef fun to_s
do return class_type
.to_s
185 # Model of all the Java class analyzed in one run
188 # All analyzed classes
189 var classes
= new HashMap[String, JavaClass]
191 # Add a class in `classes`
192 fun add_class
(jclass
: JavaClass)
194 var key
= jclass
.class_type
.package_name
195 classes
[key
] = jclass
198 # Unknown types, not already wrapped and not in this pass
199 private var unknown_types
= new HashMap[JavaType, NitType]
201 # Wrapped types, or classes analyzed in this pass
202 private var known_types
= new HashMap[JavaType, NitType]
204 # Get the `NitType` corresponding to the `JavaType`
206 # Also registers types so they can be reused and
207 # to keep track of unknown types.
208 fun java_to_nit_type
(jtype
: JavaType): NitType
211 if known_types
.keys
.has
(jtype
) then return known_types
[jtype
]
212 if unknown_types
.keys
.has
(jtype
) then return unknown_types
[jtype
]
214 # Is it a compatible primitive type?
215 if not jtype
.is_primitive_array
then
216 var name
= converter
.to_nit_type
(jtype
.id
)
218 # We got a Nit equivalent
219 var nit_type
= new NitType(name
)
220 known_types
[jtype
] = nit_type
225 # Is being wrapped in this pass?
226 var key
= jtype
.package_name
227 if classes
.keys
.has
(key
) then
228 if jtype
.array_dimension
<= opt_arrays
.value
then
229 var nit_type
= new NitType(jtype
.extern_name
)
230 known_types
[jtype
] = nit_type
236 var nit_type
= find_extern_class
[jtype
.extern_equivalent
]
237 if nit_type
!= null then
238 known_types
[jtype
] = nit_type
243 nit_type
= new NitType(jtype
.extern_name
)
244 nit_type
.is_known
= false
245 unknown_types
[jtype
] = nit_type
250 # A property to a Java class
251 abstract class JavaProperty
253 # Is this property marked static?
257 # A Java method, with its signature
261 # Type returned by the method
262 var return_type
: JavaType
264 # Type of the arguments of the method
265 var params
: Array[JavaType]
268 # An attribute in a Java class
272 # Type of the attribute
273 var java_type
: JavaType
276 # A Java method, with its signature
277 class JavaConstructor
278 # Type of the parameters of this constructor
279 var params
: Array[JavaType]
282 # A Nit module, use to import the referenced extern classes
284 # Relative path to the module
288 var name
: String is lazy
do return path
.basename
(".nit")
290 redef fun to_s
do return self.name
291 redef fun ==(other
) do return other
isa NitModule and self.path
== other
.path
292 redef fun hash
do return self.path
.hash
296 # Collection of Java classes already wrapped in the library
298 # * The key uses `JavaType.to_s`.
299 # * The value is the corresponding `NitType`.
300 var find_extern_class
: DefaultMap[String, nullable NitType] is lazy
do
301 var map
= new DefaultMap[String, nullable NitType](null)
302 var modules
= new HashMap[String, NitModule]
304 var lib_paths
= opt_libs
.value
305 if lib_paths
== null then lib_paths
= new Array[String]
307 if lib_paths
.has
("auto") then
308 lib_paths
.remove
"auto"
309 var nit_dir
= "NIT_DIR".environ
310 if nit_dir
.is_empty
then
311 # Simple heuristic to find the Nit lib
312 var dir
= sys
.program_name
.dirname
/ "../../../lib/"
313 dir
= dir
.simplify_path
314 if dir
.file_exists
then lib_paths
.add dir
.simplify_path
318 if lib_paths
.is_empty
then return map
320 # Use grep to find all extern classes implemented in Java
321 var grep_regex
= "extern class [a-zA-Z0-9_]\\\+[ ]\\\+in[ ]\\\+\"Java\
""
322 var grep_args
= ["-r", "--with-filename", grep_regex
]
323 grep_args
.add_all lib_paths
325 var grep
= new ProcessReader("grep", grep_args
...)
326 var lines
= grep
.read_lines
330 # Sort out the modules, Nit class names and Java types
331 var regex
= """(.+):\\s*extern +class +([a-zA-Z0-9_]+) *in *"Java" *`\\{(.+)`\\}""".to_re
333 var matches
= line
.search_all
(regex
)
334 for match
in matches
do
335 var path
= match
[1].to_s
336 var nit_name
= match
[2].to_s
337 var java_name
= match
[3].to_s
.trim
340 # print "+ Found {nit_name}: {java_name} at {path}"
342 var mod
= modules
.get_or_null
(path
)
344 mod
= new NitModule(path
)
348 map
[java_name
] = new NitType(nit_name
, mod
)
355 # Option to set `extern_class_prefix`
356 var opt_extern_class_prefix
= new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
358 # Prefix used to name extern classes, if `null` use the full namespace
359 var extern_class_prefix
: nullable String is lazy
do return opt_extern_class_prefix
.value
361 # Libraries to search for existing wrappers
362 var opt_libs
= new OptionArray("Paths to libraries with wrappers of Java classes ('auto' to use the full Nit lib)", "-i")
364 # Generate the primitive array version of each class up to the given depth
365 var opt_arrays
= new OptionInt("Depth of the primitive array for each wrapped class (default: 1)", 1, "-a")
369 # Get a copy of `self` where the first letter is capitalized
370 fun simple_capitalized
: String
372 if is_empty
then return to_s
374 var c
= chars
.first
.to_upper
375 var s
= c
.to_s
+ substring_from
(1)