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 # Model of the parsed Java classes and their corresponding Nit types
19 module model
is serialize
21 import more_collections
24 import binary
::serialization
26 import jtype_converter
31 # Identifiers composing the namespace and class name
33 # An array of all the names that would be separated by `.`.
34 # Each name may contain `$`.
35 var identifier
= new Array[String]
37 var generic_params
: nullable Array[JavaType] = null
39 # Is this a void return type?
42 # Is this type a vararg?
43 var is_vararg
= false is writable
45 # Is this type based on an anonymous class?
46 var is_anonymous
: Bool is lazy
do
47 for id
in identifier
do
48 for part
in id
.split
("$") do
49 if part
.chars
.first
.is_digit
then return true
55 # Has some generic type to be resolved (T extends foo => T is resolved to foo)
56 var has_unresolved_types
= false
58 # Dimension of primitive array: `int[][]` is 2d
59 var array_dimension
= 0
61 fun is_primitive_array
: Bool do return array_dimension
> 0
63 fun has_generic_params
: Bool do return not generic_params
== null
65 fun return_cast
: String do return converter
.cast_as_return
(self.id
)
67 fun param_cast
: String
69 if self.has_generic_params
then
70 return converter
.cast_as_param
(self.generic_params
[0].id
)
73 return converter
.cast_as_param
(self.id
)
76 # Name to give an extern class wrapping this type
77 fun extern_name
: String
80 var prefix
= extern_class_prefix
81 if prefix
== null then
82 # Use the namespace, e.g. java.lang.String -> Java_lang_String
83 assert not identifier
.is_empty
84 if identifier
.length
== 1 then
85 name
= identifier
.last
87 var first
= identifier
.first
88 var last
= identifier
.last
89 var mid
= identifier
.subarray
(1, identifier
.length-2
)
90 name
= first
.simple_capitalized
+ "_"
91 if mid
.not_empty
then name
+= mid
.join
("_") + "_"
95 # Use the prefix and the short class name
96 # e.g. given the prefix Native: java.lang.String -> NativeString
100 if is_primitive_array
then
101 name
+= "_" + "Array" * array_dimension
104 name
= name
.replace
("-", "_")
105 name
= name
.replace
("$", "_")
109 # Short name of the class, mangled to remove `$` (e.g. `Set`)
110 fun id
: String do return identifier
.last
.replace
("$", "")
112 # Full name of this class as used in an importation (e.g. `java.lang.Set`)
113 fun package_name
: String do return identifier
.join
(".")
115 # Name of this class for the extern declaration in Nit (e.g. `java.lang.Set[]`)
116 fun extern_equivalent
: String do return package_name
+ "[]" * array_dimension
118 # Full name of this class with arrays and generic values (e.g. `java.lang.Set<E>[]`)
120 var id
= self.package_name
122 if self.is_primitive_array
then
123 id
+= "[]" * array_dimension
124 else if self.has_generic_params
then
125 var params
= [for param
in generic_params
do param
.to_s
]
126 id
+= "<{params.join(", ")}>"
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.array_dimension
== other
.array_dimension
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 # Methods signatures introduced by this class
177 var local_intro_methods
= new MultiHashMap[String, JavaMethod]
179 # Constructors of this class
180 var constructors
= new Array[JavaConstructor]
182 # Importations from this class
183 var imports
= new HashSet[NitModule]
185 # Interfaces implemented by this class
186 var implements
= new HashSet[JavaType]
188 # Super classes of this class
189 var extends
= new HashSet[JavaType]
191 # Position of self in `model.class_hierarchy`
192 var in_hierarchy
: nullable POSetElement[JavaClass] = null is noserialize
194 redef fun to_s
do return class_type
.to_s
196 # Resolve the types in `other` in the context of this class
197 private fun resolve_types_of
(other
: JavaClass)
200 for mid
, method
in other
.methods
do
201 for signature
in method
do
202 self.resolve
(signature
.return_type
, signature
.generic_params
)
203 for param
in signature
.params
do self.resolve
(param
, signature
.generic_params
)
208 for signature
in other
.constructors
do
209 for param
in signature
.params
do self.resolve
(param
, signature
.generic_params
)
213 for aid
, attribute
in other
.attributes
do
214 self.resolve attribute
.java_type
218 # Resolve `java_type` in the context of this class
220 # Replace, in place, parameter types by their bound.
221 private fun resolve
(java_type
: JavaType, property_generic_params
: nullable Array[JavaType])
223 # Skip types with a full package name
224 if java_type
.identifier
.length
!= 1 then return
226 # Skip primitive types
227 if converter
.type_map
.keys
.has
(java_type
.id
) then return
229 # Gather the generic parameters of the method, then the class
230 var params
= new Array[JavaType]
231 if property_generic_params
!= null then params
.add_all property_generic_params
232 var class_generic_params
= class_type
.generic_params
233 if class_generic_params
!= null then params
.add_all class_generic_params
235 # Skip if there is not parameters usable to resolve
236 if params
.is_empty
then return
238 for param
in params
do
239 if param
.identifier
== java_type
.identifier
then
240 # Found a marching parameter type
241 # TODO use a more precise bound
242 java_type
.identifier
= ["java", "lang", "Object"]
248 redef fun hash
do return class_type
.hash
249 redef fun ==(o
) do return o
isa JavaClass and o
.class_type
== class_type
252 # Model of all the Java class analyzed in one run
255 # Classes analyzed in this pass
256 var classes
= new HashMap[String, JavaClass]
258 # All classes, from this pass and from other passes
259 var all_classes
: HashMap[String, JavaClass] is noserialize
, lazy
do
260 var classes
= new HashMap[String, JavaClass]
261 classes
.recover_with
self.classes
263 for model_path
in sys
.opt_load_models
.value
do
264 if not model_path
.file_exists
then
265 print_error
"Error: model file '{model_path}' does not exist"
269 var file
= model_path
.to_path
.open_ro
270 var d
= new BinaryDeserializer(file
)
271 var model
= d
.deserialize
274 if d
.errors
.not_empty
then
275 print_error
"Error: failed to deserialize model file '{model_path}' with: {d.errors.join(", ")}"
279 if not model
isa JavaModel then
280 print_error
"Error: model file contained a '{if model == null then "null" else model.class_name}'"
284 classes
.recover_with model
.classes
290 # Add a class in `classes`
291 fun add_class
(jclass
: JavaClass)
293 var key
= jclass
.class_type
.package_name
294 classes
[key
] = jclass
297 # Unknown types, not already wrapped and not in this pass
298 var unknown_types
= new HashMap[JavaType, NitType] is noserialize
300 # Wrapped types, or classes analyzed in this pass
301 var known_types
= new HashMap[JavaType, NitType] is noserialize
303 # Get the `NitType` corresponding to the `JavaType`
305 # Also registers types so they can be reused and
306 # to keep track of unknown types.
307 fun java_to_nit_type
(jtype
: JavaType): NitType
310 if known_types
.keys
.has
(jtype
) then return known_types
[jtype
]
311 if unknown_types
.keys
.has
(jtype
) then return unknown_types
[jtype
]
313 # Is it a compatible primitive type?
314 if not jtype
.is_primitive_array
then
315 var name
= converter
.to_nit_type
(jtype
.id
)
317 # We got a Nit equivalent
318 var nit_type
= new NitType(name
)
319 known_types
[jtype
] = nit_type
324 # Is being wrapped in this pass?
325 var key
= jtype
.package_name
326 if classes
.keys
.has
(key
) then
327 if jtype
.array_dimension
<= opt_arrays
.value
then
328 var nit_type
= new NitType(jtype
.extern_name
)
329 known_types
[jtype
] = nit_type
335 var nit_type
= find_extern_class
[jtype
.extern_equivalent
]
336 if nit_type
!= null then
337 known_types
[jtype
] = nit_type
342 nit_type
= new NitType(jtype
.extern_name
)
343 nit_type
.is_known
= false
344 unknown_types
[jtype
] = nit_type
348 # Resolve the types in methods and attributes of this class
351 for id
, java_class
in classes
do
352 java_class
.resolve_types_of java_class
354 # Ask nester classes for resolve too
355 var matches
= id
.search_all
("$")
356 for match
in matches
do
357 var nester_name
= id
.substring
(0, match
.from
)
358 if classes
.keys
.has
(nester_name
) then
359 var nester
= classes
[nester_name
]
360 nester
.resolve_types_of java_class
366 # Specialization hierarchy of `classes`
367 var class_hierarchy
= new POSet[JavaClass] is noserialize
369 # Fill `class_hierarchy`
370 fun build_class_hierarchy
372 var object_type
= new JavaType
373 object_type
.identifier
= ["java","lang","Object"]
376 for name
, java_class
in all_classes
do
377 # Skip anonymous classes
378 if java_class
.class_type
.is_anonymous
then continue
380 java_class
.in_hierarchy
= class_hierarchy
.add_node
(java_class
)
382 # Collect explicit super classes
383 var super_classes
= new Array[JavaType]
384 super_classes
.add_all java_class
.implements
385 super_classes
.add_all java_class
.extends
387 # Remove unavailable super classes
388 for super_type
in super_classes
.reverse_iterator
do
389 # Is the super class available?
390 if not all_classes
.keys
.has
(super_type
.package_name
) then super_classes
.remove
(super_type
)
393 # If the is no explicit supers, add `java.lang.Object`
394 if super_classes
.is_empty
and java_class
.class_type
!= object_type
then
395 super_classes
.add object_type
398 for super_type
in super_classes
do
399 # Is the super class available?
400 if not all_classes
.keys
.has
(super_type
.package_name
) then continue
402 var super_class
= all_classes
[super_type
.package_name
]
403 class_hierarchy
.add_edge
(java_class
, super_class
)
407 # Flatten classes from the top one (Object like)
408 var linearized
= class_hierarchy
.linearize
(class_hierarchy
)
411 for java_class
in linearized
do
412 var greaters
= java_class
.in_hierarchy
.greaters
414 for mid
, signatures
in java_class
.methods
do
415 for signature
in signatures
do
416 if signature
.is_static
then continue
418 # Check if this signature exists in a parent
419 for parent
in greaters
do
420 if parent
== java_class
then continue
422 if not parent
.methods
.keys
.has
(mid
) then continue
424 if parent
.methods
[mid
].has
(signature
) then continue label
427 # This is an introduction! register it
428 java_class
.local_intro_methods
[mid
].add signature
436 # A property to a Java class
437 abstract class JavaProperty
439 # Is this property marked static?
443 # A Java method, with its signature
447 # Type returned by the method
448 var return_type
: JavaType
450 # Type of the arguments of the method
451 var params
: Array[JavaType]
453 # Generic parameters of this method
454 var generic_params
: Array[JavaType]
456 redef fun ==(o
) do return o
isa JavaMethod and o
.is_static
== is_static
and o
.params
== params
457 redef fun hash
do return params
.hash
460 # An attribute in a Java class
464 # Type of the attribute
465 var java_type
: JavaType
468 # A Java method, with its signature
469 class JavaConstructor
470 # Type of the parameters of this constructor
471 var params
: Array[JavaType]
473 # Generic parameters of this constructor
474 var generic_params
: Array[JavaType]
477 # A Nit module, use to import the referenced extern classes
479 # Relative path to the module
483 var name
: String is lazy
do return path
.basename
(".nit")
485 redef fun to_s
do return self.name
486 redef fun ==(other
) do return other
isa NitModule and self.path
== other
.path
487 redef fun hash
do return self.path
.hash
491 # Collection of Java classes already wrapped in the library
493 # * The key uses `JavaType.to_s`.
494 # * The value is the corresponding `NitType`.
495 var find_extern_class
: DefaultMap[String, nullable NitType] is lazy
do
496 var map
= new DefaultMap[String, nullable NitType](null)
497 var modules
= new HashMap[String, NitModule]
499 var lib_paths
= opt_libs
.value
500 if lib_paths
== null then lib_paths
= new Array[String]
502 if lib_paths
.has
("auto") then
503 lib_paths
.remove
"auto"
504 var nit_dir
= "NIT_DIR".environ
505 if nit_dir
.is_empty
then
506 # Simple heuristic to find the Nit lib
507 var dir
= sys
.program_name
.dirname
/ "../../../lib/"
508 dir
= dir
.simplify_path
509 if dir
.file_exists
then lib_paths
.add dir
.simplify_path
513 if lib_paths
.is_empty
then return map
515 # Use grep to find all extern classes implemented in Java
516 var grep_regex
= "extern class [a-zA-Z0-9_]\\\+[ ]\\\+in[ ]\\\+\"Java\
""
517 var grep_args
= ["-r", "--with-filename", grep_regex
]
518 grep_args
.add_all lib_paths
520 var grep
= new ProcessReader("grep", grep_args
...)
521 var lines
= grep
.read_lines
525 # Sort out the modules, Nit class names and Java types
526 var regex
= """(.+):\\s*extern +class +([a-zA-Z0-9_]+) *in *"Java" *`\\{(.+)`\\}""".to_re
528 var matches
= line
.search_all
(regex
)
529 for match
in matches
do
530 var path
= match
[1].to_s
531 var nit_name
= match
[2].to_s
532 var java_name
= match
[3].to_s
.trim
535 # print "+ Found {nit_name}: {java_name} at {path}"
537 var mod
= modules
.get_or_null
(path
)
539 mod
= new NitModule(path
)
543 map
[java_name
] = new NitType(nit_name
, mod
)
550 # Option to set `extern_class_prefix`
551 var opt_extern_class_prefix
= new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
553 # Prefix used to name extern classes, if `null` use the full namespace
554 var extern_class_prefix
: nullable String is lazy
do return opt_extern_class_prefix
.value
556 # Libraries to search for existing wrappers
557 var opt_libs
= new OptionArray("Paths to libraries with wrappers of Java classes ('auto' to use the full Nit lib)", "-i")
559 # Generate the primitive array version of each class up to the given depth
560 var opt_arrays
= new OptionInt("Depth of the primitive array for each wrapped class (default: 1)", 1, "-a")
562 # Generate the primitive array version of each class up to the given depth
563 var opt_load_models
= new OptionArray("Saved models to search for super-classes", "-m")
566 redef abstract class Text
567 # Get a copy of `self` where the first letter is capitalized
568 fun simple_capitalized
: String
570 if is_empty
then return to_s
572 var c
= chars
.first
.to_upper
573 var s
= c
.to_s
+ substring_from
(1)