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
25 import jtype_converter
30 # Identifiers composing the namespace and class name
32 # An array of all the names that would be separated by `.`.
33 # Each name may contain `$`.
34 var identifier
= new Array[String]
36 var generic_params
: nullable Array[JavaType] = null
38 # Is this a void return type?
41 # Is this type a vararg?
42 var is_vararg
= false is writable
44 # Is this type based on an anonymous class?
45 var is_anonymous
: Bool is lazy
do
46 for id
in identifier
do
47 for part
in id
.split
("$") do
48 if part
.chars
.first
.is_digit
then return true
54 # Has some generic type to be resolved (T extends foo => T is resolved to foo)
55 var has_unresolved_types
= false
57 # Dimension of primitive array: `int[][]` is 2d
58 var array_dimension
= 0
60 fun is_primitive_array
: Bool do return array_dimension
> 0
62 fun has_generic_params
: Bool do return not generic_params
== null
64 fun return_cast
: String do return converter
.cast_as_return
(self.id
)
66 fun param_cast
: String
68 if self.has_generic_params
then
69 return converter
.cast_as_param
(self.generic_params
[0].id
)
72 return converter
.cast_as_param
(self.id
)
75 # Name to give an extern class wrapping this type
76 fun extern_name
: String
79 var prefix
= extern_class_prefix
80 if prefix
== null then
81 # Use the namespace, e.g. java.lang.String -> Java_lang_String
82 assert not identifier
.is_empty
83 if identifier
.length
== 1 then
84 name
= identifier
.last
86 var first
= identifier
.first
87 var last
= identifier
.last
88 var mid
= identifier
.subarray
(1, identifier
.length-2
)
89 name
= first
.simple_capitalized
+ "_"
90 if mid
.not_empty
then name
+= mid
.join
("_") + "_"
94 # Use the prefix and the short class name
95 # e.g. given the prefix Native: java.lang.String -> NativeString
99 if is_primitive_array
then
100 name
+= "_" + "Array" * array_dimension
103 name
= name
.replace
("-", "_")
104 name
= name
.replace
("$", "_")
108 # Short name of the class, mangled to remove `$` (e.g. `Set`)
109 fun id
: String do return identifier
.last
.replace
("$", "")
111 # Full name of this class as used in an importation (e.g. `java.lang.Set`)
112 fun package_name
: String do return identifier
.join
(".")
114 # Name of this class for the extern declaration in Nit (e.g. `java.lang.Set[]`)
115 fun extern_equivalent
: String do return package_name
+ "[]" * array_dimension
117 # Full name of this class with arrays and generic values (e.g. `java.lang.Set<E>[]`)
119 var id
= self.package_name
121 if self.is_primitive_array
then
122 id
+= "[]" * array_dimension
123 else if self.has_generic_params
then
124 var params
= [for param
in generic_params
do param
.to_s
]
125 id
+= "<{params.join(", ")}>"
131 # Get a copy of `self`
134 var jtype
= new JavaType
135 jtype
.identifier
= identifier
136 jtype
.generic_params
= generic_params
137 jtype
.is_void
= is_void
138 jtype
.is_vararg
= is_vararg
139 jtype
.array_dimension
= array_dimension
143 # Comparison based on fully qualified named
144 redef fun ==(other
) do return other
isa JavaType and
145 self.package_name
== other
.package_name
and
146 self.array_dimension
== other
.array_dimension
148 redef fun hash
do return self.package_name
.hash
153 var identifier
: String
155 # If this NitType was found in `lib/android`, contains the module name to import
156 var mod
: nullable NitModule
158 # Is this type known, wrapped and available in Nit?
159 var is_known
: Bool = true
161 redef fun to_s
do return identifier
164 # Model of a single Java class
167 var class_type
: JavaType
169 # Attributes of this class
170 var attributes
= new HashMap[String, JavaAttribute]
172 # Methods of this class organized by their name
173 var methods
= new MultiHashMap[String, JavaMethod]
175 # Constructors of this class
176 var constructors
= new Array[JavaConstructor]
178 # Importations from this class
179 var imports
= new HashSet[NitModule]
181 # Interfaces implemented by this class
182 var implements
= new HashSet[JavaType]
184 # Super classes of this class
185 var extends
= new HashSet[JavaType]
187 # Position of self in `model.class_hierarchy`
188 var in_hierarchy
: nullable POSetElement[JavaClass] = null is noserialize
190 redef fun to_s
do return class_type
.to_s
192 # Resolve the types in `other` in the context of this class
193 private fun resolve_types_of
(other
: JavaClass)
196 for mid
, method
in other
.methods
do
197 for signature
in method
do
198 self.resolve
(signature
.return_type
, signature
.generic_params
)
199 for param
in signature
.params
do self.resolve
(param
, signature
.generic_params
)
204 for signature
in other
.constructors
do
205 for param
in signature
.params
do self.resolve
(param
, signature
.generic_params
)
209 for aid
, attribute
in other
.attributes
do
210 self.resolve attribute
.java_type
214 # Resolve `java_type` in the context of this class
216 # Replace, in place, parameter types by their bound.
217 private fun resolve
(java_type
: JavaType, property_generic_params
: nullable Array[JavaType])
219 # Skip types with a full package name
220 if java_type
.identifier
.length
!= 1 then return
222 # Skip primitive types
223 if converter
.type_map
.keys
.has
(java_type
.id
) then return
225 # Gather the generic parameters of the method, then the class
226 var params
= new Array[JavaType]
227 if property_generic_params
!= null then params
.add_all property_generic_params
228 var class_generic_params
= class_type
.generic_params
229 if class_generic_params
!= null then params
.add_all class_generic_params
231 # Skip if there is not parameters usable to resolve
232 if params
.is_empty
then return
234 for param
in params
do
235 if param
.identifier
== java_type
.identifier
then
236 # Found a marching parameter type
237 # TODO use a more precise bound
238 java_type
.identifier
= ["java", "lang", "Object"]
244 redef fun hash
do return class_type
.hash
245 redef fun ==(o
) do return o
isa JavaClass and o
.class_type
== class_type
248 # Model of all the Java class analyzed in one run
251 # All analyzed classes
252 var classes
= new HashMap[String, JavaClass]
254 # Add a class in `classes`
255 fun add_class
(jclass
: JavaClass)
257 var key
= jclass
.class_type
.package_name
258 classes
[key
] = jclass
261 # Unknown types, not already wrapped and not in this pass
262 var unknown_types
= new HashMap[JavaType, NitType]
264 # Wrapped types, or classes analyzed in this pass
265 var known_types
= new HashMap[JavaType, NitType]
267 # Get the `NitType` corresponding to the `JavaType`
269 # Also registers types so they can be reused and
270 # to keep track of unknown types.
271 fun java_to_nit_type
(jtype
: JavaType): NitType
274 if known_types
.keys
.has
(jtype
) then return known_types
[jtype
]
275 if unknown_types
.keys
.has
(jtype
) then return unknown_types
[jtype
]
277 # Is it a compatible primitive type?
278 if not jtype
.is_primitive_array
then
279 var name
= converter
.to_nit_type
(jtype
.id
)
281 # We got a Nit equivalent
282 var nit_type
= new NitType(name
)
283 known_types
[jtype
] = nit_type
288 # Is being wrapped in this pass?
289 var key
= jtype
.package_name
290 if classes
.keys
.has
(key
) then
291 if jtype
.array_dimension
<= opt_arrays
.value
then
292 var nit_type
= new NitType(jtype
.extern_name
)
293 known_types
[jtype
] = nit_type
299 var nit_type
= find_extern_class
[jtype
.extern_equivalent
]
300 if nit_type
!= null then
301 known_types
[jtype
] = nit_type
306 nit_type
= new NitType(jtype
.extern_name
)
307 nit_type
.is_known
= false
308 unknown_types
[jtype
] = nit_type
312 # Resolve the types in methods and attributes of this class
315 for id
, java_class
in classes
do
316 java_class
.resolve_types_of java_class
318 # Ask nester classes for resolve too
319 var matches
= id
.search_all
("$")
320 for match
in matches
do
321 var nester_name
= id
.substring
(0, match
.from
)
322 if classes
.keys
.has
(nester_name
) then
323 var nester
= classes
[nester_name
]
324 nester
.resolve_types_of java_class
330 # Specialization hierarchy of `classes`
331 var class_hierarchy
= new POSet[JavaClass]
333 # Fill `class_hierarchy`
334 fun build_class_hierarchy
336 var object_type
= new JavaType
337 object_type
.identifier
= ["java","lang","Object"]
340 for name
, java_class
in classes
do
341 # Skip anonymous classes
342 if java_class
.class_type
.is_anonymous
then continue
344 java_class
.in_hierarchy
= class_hierarchy
.add_node
(java_class
)
346 # Collect explicit super classes
347 var super_classes
= new Array[JavaType]
348 super_classes
.add_all java_class
.implements
349 super_classes
.add_all java_class
.extends
351 # Remove unavailable super classes
352 for super_type
in super_classes
.reverse_iterator
do
353 # Is the super class available?
354 if not classes
.keys
.has
(super_type
.package_name
) then super_classes
.remove
(super_type
)
357 # If the is no explicit supers, add `java.lang.Object`
358 if super_classes
.is_empty
and java_class
.class_type
!= object_type
then
359 super_classes
.add object_type
362 for super_type
in super_classes
do
363 # Is the super class available?
364 if not classes
.keys
.has
(super_type
.package_name
) then continue
366 var super_class
= classes
[super_type
.package_name
]
367 class_hierarchy
.add_edge
(java_class
, super_class
)
373 # A property to a Java class
374 abstract class JavaProperty
376 # Is this property marked static?
380 # A Java method, with its signature
384 # Type returned by the method
385 var return_type
: JavaType
387 # Type of the arguments of the method
388 var params
: Array[JavaType]
390 # Generic parameters of this method
391 var generic_params
: Array[JavaType]
393 redef fun ==(o
) do return o
isa JavaMethod and o
.is_static
== is_static
and o
.params
== params
394 redef fun hash
do return params
.hash
397 # An attribute in a Java class
401 # Type of the attribute
402 var java_type
: JavaType
405 # A Java method, with its signature
406 class JavaConstructor
407 # Type of the parameters of this constructor
408 var params
: Array[JavaType]
410 # Generic parameters of this constructor
411 var generic_params
: Array[JavaType]
414 # A Nit module, use to import the referenced extern classes
416 # Relative path to the module
420 var name
: String is lazy
do return path
.basename
(".nit")
422 redef fun to_s
do return self.name
423 redef fun ==(other
) do return other
isa NitModule and self.path
== other
.path
424 redef fun hash
do return self.path
.hash
428 # Collection of Java classes already wrapped in the library
430 # * The key uses `JavaType.to_s`.
431 # * The value is the corresponding `NitType`.
432 var find_extern_class
: DefaultMap[String, nullable NitType] is lazy
do
433 var map
= new DefaultMap[String, nullable NitType](null)
434 var modules
= new HashMap[String, NitModule]
436 var lib_paths
= opt_libs
.value
437 if lib_paths
== null then lib_paths
= new Array[String]
439 if lib_paths
.has
("auto") then
440 lib_paths
.remove
"auto"
441 var nit_dir
= "NIT_DIR".environ
442 if nit_dir
.is_empty
then
443 # Simple heuristic to find the Nit lib
444 var dir
= sys
.program_name
.dirname
/ "../../../lib/"
445 dir
= dir
.simplify_path
446 if dir
.file_exists
then lib_paths
.add dir
.simplify_path
450 if lib_paths
.is_empty
then return map
452 # Use grep to find all extern classes implemented in Java
453 var grep_regex
= "extern class [a-zA-Z0-9_]\\\+[ ]\\\+in[ ]\\\+\"Java\
""
454 var grep_args
= ["-r", "--with-filename", grep_regex
]
455 grep_args
.add_all lib_paths
457 var grep
= new ProcessReader("grep", grep_args
...)
458 var lines
= grep
.read_lines
462 # Sort out the modules, Nit class names and Java types
463 var regex
= """(.+):\\s*extern +class +([a-zA-Z0-9_]+) *in *"Java" *`\\{(.+)`\\}""".to_re
465 var matches
= line
.search_all
(regex
)
466 for match
in matches
do
467 var path
= match
[1].to_s
468 var nit_name
= match
[2].to_s
469 var java_name
= match
[3].to_s
.trim
472 # print "+ Found {nit_name}: {java_name} at {path}"
474 var mod
= modules
.get_or_null
(path
)
476 mod
= new NitModule(path
)
480 map
[java_name
] = new NitType(nit_name
, mod
)
487 # Option to set `extern_class_prefix`
488 var opt_extern_class_prefix
= new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
490 # Prefix used to name extern classes, if `null` use the full namespace
491 var extern_class_prefix
: nullable String is lazy
do return opt_extern_class_prefix
.value
493 # Libraries to search for existing wrappers
494 var opt_libs
= new OptionArray("Paths to libraries with wrappers of Java classes ('auto' to use the full Nit lib)", "-i")
496 # Generate the primitive array version of each class up to the given depth
497 var opt_arrays
= new OptionInt("Depth of the primitive array for each wrapped class (default: 1)", 1, "-a")
501 # Get a copy of `self` where the first letter is capitalized
502 fun simple_capitalized
: String
504 if is_empty
then return to_s
506 var c
= chars
.first
.to_upper
507 var s
= c
.to_s
+ substring_from
(1)