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 # All analyzed classes
256 var classes
= new HashMap[String, JavaClass]
258 # Add a class in `classes`
259 fun add_class
(jclass
: JavaClass)
261 var key
= jclass
.class_type
.package_name
262 classes
[key
] = jclass
265 # Unknown types, not already wrapped and not in this pass
266 var unknown_types
= new HashMap[JavaType, NitType] is noserialize
268 # Wrapped types, or classes analyzed in this pass
269 var known_types
= new HashMap[JavaType, NitType] is noserialize
271 # Get the `NitType` corresponding to the `JavaType`
273 # Also registers types so they can be reused and
274 # to keep track of unknown types.
275 fun java_to_nit_type
(jtype
: JavaType): NitType
278 if known_types
.keys
.has
(jtype
) then return known_types
[jtype
]
279 if unknown_types
.keys
.has
(jtype
) then return unknown_types
[jtype
]
281 # Is it a compatible primitive type?
282 if not jtype
.is_primitive_array
then
283 var name
= converter
.to_nit_type
(jtype
.id
)
285 # We got a Nit equivalent
286 var nit_type
= new NitType(name
)
287 known_types
[jtype
] = nit_type
292 # Is being wrapped in this pass?
293 var key
= jtype
.package_name
294 if classes
.keys
.has
(key
) then
295 if jtype
.array_dimension
<= opt_arrays
.value
then
296 var nit_type
= new NitType(jtype
.extern_name
)
297 known_types
[jtype
] = nit_type
303 var nit_type
= find_extern_class
[jtype
.extern_equivalent
]
304 if nit_type
!= null then
305 known_types
[jtype
] = nit_type
310 nit_type
= new NitType(jtype
.extern_name
)
311 nit_type
.is_known
= false
312 unknown_types
[jtype
] = nit_type
316 # Resolve the types in methods and attributes of this class
319 for id
, java_class
in classes
do
320 java_class
.resolve_types_of java_class
322 # Ask nester classes for resolve too
323 var matches
= id
.search_all
("$")
324 for match
in matches
do
325 var nester_name
= id
.substring
(0, match
.from
)
326 if classes
.keys
.has
(nester_name
) then
327 var nester
= classes
[nester_name
]
328 nester
.resolve_types_of java_class
334 # Specialization hierarchy of `classes`
335 var class_hierarchy
= new POSet[JavaClass] is noserialize
337 # Fill `class_hierarchy`
338 fun build_class_hierarchy
340 var object_type
= new JavaType
341 object_type
.identifier
= ["java","lang","Object"]
344 for name
, java_class
in classes
do
345 # Skip anonymous classes
346 if java_class
.class_type
.is_anonymous
then continue
348 java_class
.in_hierarchy
= class_hierarchy
.add_node
(java_class
)
350 # Collect explicit super classes
351 var super_classes
= new Array[JavaType]
352 super_classes
.add_all java_class
.implements
353 super_classes
.add_all java_class
.extends
355 # Remove unavailable super classes
356 for super_type
in super_classes
.reverse_iterator
do
357 # Is the super class available?
358 if not classes
.keys
.has
(super_type
.package_name
) then super_classes
.remove
(super_type
)
361 # If the is no explicit supers, add `java.lang.Object`
362 if super_classes
.is_empty
and java_class
.class_type
!= object_type
then
363 super_classes
.add object_type
366 for super_type
in super_classes
do
367 # Is the super class available?
368 if not classes
.keys
.has
(super_type
.package_name
) then continue
370 var super_class
= classes
[super_type
.package_name
]
371 class_hierarchy
.add_edge
(java_class
, super_class
)
375 # Flatten classes from the top one (Object like)
376 var linearized
= class_hierarchy
.linearize
(class_hierarchy
)
379 for java_class
in linearized
do
380 var in_hierarchy
= class_hierarchy
[java_class
]
381 var greaters
= in_hierarchy
.greaters
383 for mid
, signatures
in java_class
.methods
do
384 for signature
in signatures
do
385 if signature
.is_static
then continue
387 # Check if this signature exists in a parent
388 for parent
in greaters
do
389 if parent
== java_class
then continue
391 if not parent
.methods
.keys
.has
(mid
) then continue
393 if parent
.methods
[mid
].has
(signature
) then continue label
396 # This is an introduction! register it
397 java_class
.local_intro_methods
[mid
].add signature
405 # A property to a Java class
406 abstract class JavaProperty
408 # Is this property marked static?
412 # A Java method, with its signature
416 # Type returned by the method
417 var return_type
: JavaType
419 # Type of the arguments of the method
420 var params
: Array[JavaType]
422 # Generic parameters of this method
423 var generic_params
: Array[JavaType]
425 redef fun ==(o
) do return o
isa JavaMethod and o
.is_static
== is_static
and o
.params
== params
426 redef fun hash
do return params
.hash
429 # An attribute in a Java class
433 # Type of the attribute
434 var java_type
: JavaType
437 # A Java method, with its signature
438 class JavaConstructor
439 # Type of the parameters of this constructor
440 var params
: Array[JavaType]
442 # Generic parameters of this constructor
443 var generic_params
: Array[JavaType]
446 # A Nit module, use to import the referenced extern classes
448 # Relative path to the module
452 var name
: String is lazy
do return path
.basename
(".nit")
454 redef fun to_s
do return self.name
455 redef fun ==(other
) do return other
isa NitModule and self.path
== other
.path
456 redef fun hash
do return self.path
.hash
460 # Collection of Java classes already wrapped in the library
462 # * The key uses `JavaType.to_s`.
463 # * The value is the corresponding `NitType`.
464 var find_extern_class
: DefaultMap[String, nullable NitType] is lazy
do
465 var map
= new DefaultMap[String, nullable NitType](null)
466 var modules
= new HashMap[String, NitModule]
468 var lib_paths
= opt_libs
.value
469 if lib_paths
== null then lib_paths
= new Array[String]
471 if lib_paths
.has
("auto") then
472 lib_paths
.remove
"auto"
473 var nit_dir
= "NIT_DIR".environ
474 if nit_dir
.is_empty
then
475 # Simple heuristic to find the Nit lib
476 var dir
= sys
.program_name
.dirname
/ "../../../lib/"
477 dir
= dir
.simplify_path
478 if dir
.file_exists
then lib_paths
.add dir
.simplify_path
482 if lib_paths
.is_empty
then return map
484 # Use grep to find all extern classes implemented in Java
485 var grep_regex
= "extern class [a-zA-Z0-9_]\\\+[ ]\\\+in[ ]\\\+\"Java\
""
486 var grep_args
= ["-r", "--with-filename", grep_regex
]
487 grep_args
.add_all lib_paths
489 var grep
= new ProcessReader("grep", grep_args
...)
490 var lines
= grep
.read_lines
494 # Sort out the modules, Nit class names and Java types
495 var regex
= """(.+):\\s*extern +class +([a-zA-Z0-9_]+) *in *"Java" *`\\{(.+)`\\}""".to_re
497 var matches
= line
.search_all
(regex
)
498 for match
in matches
do
499 var path
= match
[1].to_s
500 var nit_name
= match
[2].to_s
501 var java_name
= match
[3].to_s
.trim
504 # print "+ Found {nit_name}: {java_name} at {path}"
506 var mod
= modules
.get_or_null
(path
)
508 mod
= new NitModule(path
)
512 map
[java_name
] = new NitType(nit_name
, mod
)
519 # Option to set `extern_class_prefix`
520 var opt_extern_class_prefix
= new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
522 # Prefix used to name extern classes, if `null` use the full namespace
523 var extern_class_prefix
: nullable String is lazy
do return opt_extern_class_prefix
.value
525 # Libraries to search for existing wrappers
526 var opt_libs
= new OptionArray("Paths to libraries with wrappers of Java classes ('auto' to use the full Nit lib)", "-i")
528 # Generate the primitive array version of each class up to the given depth
529 var opt_arrays
= new OptionInt("Depth of the primitive array for each wrapped class (default: 1)", 1, "-a")
532 redef abstract class Text
533 # Get a copy of `self` where the first letter is capitalized
534 fun simple_capitalized
: String
536 if is_empty
then return to_s
538 var c
= chars
.first
.to_upper
539 var s
= c
.to_s
+ substring_from
(1)