contrib/jwrapper: only reference to `java.lang.Object` if known by the model
[nit.git] / contrib / jwrapper / src / model.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Copyright 2014 Frédéric Vachon <fredvac@gmail.com>
4 # Copyright 2015 Alexis Laferrière <alexis.laf@xymus.net>
5 #
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
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
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.
17
18 # Model of the parsed Java classes and their corresponding Nit types
19 module model is serialize
20
21 import more_collections
22 import opts
23 import poset
24 import binary::serialization
25
26 import jtype_converter
27
28 class JavaType
29 super Cloneable
30
31 # Identifiers composing the namespace and class name
32 #
33 # An array of all the names that would be separated by `.`.
34 # Each name may contain `$`.
35 var identifier = new Array[String]
36
37 var generic_params: nullable Array[JavaType] = null
38
39 # Is this a void return type?
40 var is_void = false
41
42 # Is this type a vararg?
43 var is_vararg = false is writable
44
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
50 end
51 end
52 return false
53 end
54
55 # Has some generic type to be resolved (T extends foo => T is resolved to foo)
56 var has_unresolved_types = false
57
58 # Dimension of primitive array: `int[][]` is 2d
59 var array_dimension = 0
60
61 fun is_primitive_array: Bool do return array_dimension > 0
62
63 fun has_generic_params: Bool do return not generic_params == null
64
65 fun return_cast: String do return converter.cast_as_return(self.id)
66
67 fun param_cast: String
68 do
69 if self.has_generic_params then
70 return converter.cast_as_param(self.generic_params[0].id)
71 end
72
73 return converter.cast_as_param(self.id)
74 end
75
76 # Name to give an extern class wrapping this type
77 fun extern_name: String
78 do
79 var name
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
86 else
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("_") + "_"
92 name += last
93 end
94 else
95 # Use the prefix and the short class name
96 # e.g. given the prefix Native: java.lang.String -> NativeString
97 name = prefix + id
98 end
99
100 if is_primitive_array then
101 name += "_" + "Array" * array_dimension
102 end
103
104 name = name.replace("-", "_")
105 name = name.replace("$", "_")
106 return name
107 end
108
109 # Short name of the class, mangled to remove `$` (e.g. `Set`)
110 fun id: String do return identifier.last.replace("$", "")
111
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(".")
114
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
117
118 # Full name of this class with arrays and generic values (e.g. `java.lang.Set<E>[]`)
119 redef fun to_s do
120 var id = self.package_name
121
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(", ")}>"
127 end
128
129 return id
130 end
131
132 # Get a copy of `self`
133 redef fun clone
134 do
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
141 return jtype
142 end
143
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
148
149 redef fun hash do return self.package_name.hash
150 end
151
152 class NitType
153 # Nit class name
154 var identifier: String
155
156 # If this NitType was found in `lib/android`, contains the module name to import
157 var mod: nullable NitModule
158
159 # Is this type known, wrapped and available in Nit?
160 var is_known: Bool = true
161
162 redef fun to_s do return identifier
163 end
164
165 # Model of a single Java class
166 class JavaClass
167 # Type of this class
168 var class_type: JavaType
169
170 # Attributes of this class
171 var attributes = new HashMap[String, JavaAttribute]
172
173 # Methods of this class organized by their name
174 var methods = new MultiHashMap[String, JavaMethod]
175
176 # Methods signatures introduced by this class
177 var local_intro_methods = new MultiHashMap[String, JavaMethod]
178
179 # Constructors of this class
180 var constructors = new Array[JavaConstructor]
181
182 # Importations from this class
183 var imports = new HashSet[NitModule]
184
185 # Interfaces implemented by this class
186 var implements = new HashSet[JavaType]
187
188 # Super classes of this class
189 var extends = new HashSet[JavaType]
190
191 # Position of self in `model.class_hierarchy`
192 var in_hierarchy: nullable POSetElement[JavaClass] = null is noserialize
193
194 redef fun to_s do return class_type.to_s
195
196 # Resolve the types in `other` in the context of this class
197 private fun resolve_types_of(other: JavaClass)
198 do
199 # Methods
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)
204 end
205 end
206
207 # Constructors
208 for signature in other.constructors do
209 for param in signature.params do self.resolve(param, signature.generic_params)
210 end
211
212 # Attributes
213 for aid, attribute in other.attributes do
214 self.resolve attribute.java_type
215 end
216 end
217
218 # Resolve `java_type` in the context of this class
219 #
220 # Replace, in place, parameter types by their bound.
221 private fun resolve(java_type: JavaType, property_generic_params: nullable Array[JavaType])
222 do
223 # Skip types with a full package name
224 if java_type.identifier.length != 1 then return
225
226 # Skip primitive types
227 if converter.type_map.keys.has(java_type.id) then return
228
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
234
235 # Skip if there is not parameters usable to resolve
236 if params.is_empty then return
237
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"]
243 return
244 end
245 end
246 end
247
248 redef fun hash do return class_type.hash
249 redef fun ==(o) do return o isa JavaClass and o.class_type == class_type
250 end
251
252 # Model of all the Java class analyzed in one run
253 class JavaModel
254
255 # Classes analyzed in this pass
256 var classes = new HashMap[String, JavaClass]
257
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
262
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"
266 continue
267 end
268
269 var file = model_path.to_path.open_ro
270 var d = new BinaryDeserializer(file)
271 var model = d.deserialize
272 file.close
273
274 if d.errors.not_empty then
275 print_error "Error: failed to deserialize model file '{model_path}' with: {d.errors.join(", ")}"
276 continue
277 end
278
279 if not model isa JavaModel then
280 print_error "Error: model file contained a '{if model == null then "null" else model.class_name}'"
281 continue
282 end
283
284 classes.recover_with model.classes
285 end
286
287 return classes
288 end
289
290 # Does this model have access to the `java.lang.Object`?
291 var knows_the_object_class: Bool = all_classes.keys.has("java.lang.Object") is lazy
292
293 # Add a class in `classes`
294 fun add_class(jclass: JavaClass)
295 do
296 var key = jclass.class_type.package_name
297 classes[key] = jclass
298 end
299
300 # Unknown types, not already wrapped and not in this pass
301 var unknown_types = new HashMap[JavaType, NitType] is noserialize
302
303 # Wrapped types, or classes analyzed in this pass
304 var known_types = new HashMap[JavaType, NitType] is noserialize
305
306 # Get the `NitType` corresponding to the `JavaType`
307 #
308 # Also registers types so they can be reused and
309 # to keep track of unknown types.
310 fun java_to_nit_type(jtype: JavaType): NitType
311 do
312 # Check cache
313 if known_types.keys.has(jtype) then return known_types[jtype]
314 if unknown_types.keys.has(jtype) then return unknown_types[jtype]
315
316 # Is it a compatible primitive type?
317 if not jtype.is_primitive_array then
318 var name = converter.to_nit_type(jtype.id)
319 if name != null then
320 # We got a Nit equivalent
321 var nit_type = new NitType(name)
322 known_types[jtype] = nit_type
323 return nit_type
324 end
325 end
326
327 # Is being wrapped in this pass?
328 var key = jtype.package_name
329 if classes.keys.has(key) then
330 if jtype.array_dimension <= opt_arrays.value then
331 var nit_type = new NitType(jtype.extern_name)
332 known_types[jtype] = nit_type
333 return nit_type
334 end
335 end
336
337 # Search in lib
338 var nit_type = find_extern_class[jtype.extern_equivalent]
339 if nit_type != null then
340 known_types[jtype] = nit_type
341 return nit_type
342 end
343
344 # Unknown type
345 nit_type = new NitType(jtype.extern_name)
346 nit_type.is_known = false
347 unknown_types[jtype] = nit_type
348 return nit_type
349 end
350
351 # Resolve the types in methods and attributes of this class
352 fun resolve_types
353 do
354 for id, java_class in classes do
355 java_class.resolve_types_of java_class
356
357 # Ask nester classes for resolve too
358 var matches = id.search_all("$")
359 for match in matches do
360 var nester_name = id.substring(0, match.from)
361 if classes.keys.has(nester_name) then
362 var nester = classes[nester_name]
363 nester.resolve_types_of java_class
364 end
365 end
366 end
367 end
368
369 # Specialization hierarchy of `classes`
370 var class_hierarchy = new POSet[JavaClass] is noserialize
371
372 # Fill `class_hierarchy`
373 fun build_class_hierarchy
374 do
375 var object_type = new JavaType
376 object_type.identifier = ["java","lang","Object"]
377
378 # Fill POSet
379 for name, java_class in all_classes do
380 # Skip anonymous classes
381 if java_class.class_type.is_anonymous then continue
382
383 java_class.in_hierarchy = class_hierarchy.add_node(java_class)
384
385 # Collect explicit super classes
386 var super_classes = new Array[JavaType]
387 super_classes.add_all java_class.implements
388 super_classes.add_all java_class.extends
389
390 # Remove unavailable super classes
391 for super_type in super_classes.reverse_iterator do
392 # Is the super class available?
393 if not all_classes.keys.has(super_type.package_name) then super_classes.remove(super_type)
394 end
395
396 # If the is no explicit supers, add `java.lang.Object` (if it is known)
397 if super_classes.is_empty and java_class.class_type != object_type and
398 knows_the_object_class then
399 super_classes.add object_type
400 end
401
402 for super_type in super_classes do
403 # Is the super class available?
404 if not all_classes.keys.has(super_type.package_name) then continue
405
406 var super_class = all_classes[super_type.package_name]
407 class_hierarchy.add_edge(java_class, super_class)
408 end
409 end
410
411 # Flatten classes from the top one (Object like)
412 var linearized = class_hierarchy.linearize(class_hierarchy)
413
414 # Methods intro
415 for java_class in linearized do
416 var greaters = java_class.in_hierarchy.greaters
417
418 for mid, signatures in java_class.methods do
419 for signature in signatures do
420 if signature.is_static then continue
421
422 # Check if this signature exists in a parent
423 for parent in greaters do
424 if parent == java_class then continue
425
426 if not parent.methods.keys.has(mid) then continue
427
428 if parent.methods[mid].has(signature) then continue label
429 end
430
431 # This is an introduction! register it
432 java_class.local_intro_methods[mid].add signature
433
434 end label
435 end
436 end
437 end
438 end
439
440 # A property to a Java class
441 abstract class JavaProperty
442
443 # Is this property marked static?
444 var is_static: Bool
445 end
446
447 # A Java method, with its signature
448 class JavaMethod
449 super JavaProperty
450
451 # Type returned by the method
452 var return_type: JavaType
453
454 # Type of the arguments of the method
455 var params: Array[JavaType]
456
457 # Generic parameters of this method
458 var generic_params: Array[JavaType]
459
460 redef fun ==(o) do return o isa JavaMethod and o.is_static == is_static and o.params == params
461 redef fun hash do return params.hash
462 end
463
464 # An attribute in a Java class
465 class JavaAttribute
466 super JavaProperty
467
468 # Type of the attribute
469 var java_type: JavaType
470 end
471
472 # A Java method, with its signature
473 class JavaConstructor
474 # Type of the parameters of this constructor
475 var params: Array[JavaType]
476
477 # Generic parameters of this constructor
478 var generic_params: Array[JavaType]
479 end
480
481 # A Nit module, use to import the referenced extern classes
482 class NitModule
483 # Relative path to the module
484 var path: String
485
486 # Name of the module
487 var name: String is lazy do return path.basename(".nit")
488
489 redef fun to_s do return self.name
490 redef fun ==(other) do return other isa NitModule and self.path == other.path
491 redef fun hash do return self.path.hash
492 end
493
494 redef class Sys
495 # Collection of Java classes already wrapped in the library
496 #
497 # * The key uses `JavaType.to_s`.
498 # * The value is the corresponding `NitType`.
499 var find_extern_class: DefaultMap[String, nullable NitType] is lazy do
500 var map = new DefaultMap[String, nullable NitType](null)
501 var modules = new HashMap[String, NitModule]
502
503 var lib_paths = opt_libs.value
504 if lib_paths == null then lib_paths = new Array[String]
505
506 if lib_paths.has("auto") then
507 lib_paths.remove "auto"
508 var nit_dir = "NIT_DIR".environ
509 if nit_dir.is_empty then
510 # Simple heuristic to find the Nit lib
511 var dir = sys.program_name.dirname / "../../../lib/"
512 dir = dir.simplify_path
513 if dir.file_exists then lib_paths.add dir.simplify_path
514 end
515 end
516
517 if lib_paths.is_empty then return map
518
519 # Use grep to find all extern classes implemented in Java
520 var grep_regex = "extern class [a-zA-Z0-9_]\\\+[ ]\\\+in[ ]\\\+\"Java\""
521 var grep_args = ["-r", "--with-filename", grep_regex]
522 grep_args.add_all lib_paths
523
524 var grep = new ProcessReader("grep", grep_args...)
525 var lines = grep.read_lines
526 grep.close
527 grep.wait
528
529 # Sort out the modules, Nit class names and Java types
530 var regex = """(.+):\\s*extern +class +([a-zA-Z0-9_]+) *in *"Java" *`\\{(.+)`\\}""".to_re
531 for line in lines do
532 var matches = line.search_all(regex)
533 for match in matches do
534 var path = match[1].to_s
535 var nit_name = match[2].to_s
536 var java_name = match[3].to_s.trim
537
538 # Debug code
539 # print "+ Found {nit_name}: {java_name} at {path}"
540
541 var mod = modules.get_or_null(path)
542 if mod == null then
543 mod = new NitModule(path)
544 modules[path] = mod
545 end
546
547 map[java_name] = new NitType(nit_name, mod)
548 end
549 end
550
551 return map
552 end
553
554 # Option to set `extern_class_prefix`
555 var opt_extern_class_prefix = new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
556
557 # Prefix used to name extern classes, if `null` use the full namespace
558 var extern_class_prefix: nullable String is lazy do return opt_extern_class_prefix.value
559
560 # Libraries to search for existing wrappers
561 var opt_libs = new OptionArray("Paths to libraries with wrappers of Java classes ('auto' to use the full Nit lib)", "-i")
562
563 # Generate the primitive array version of each class up to the given depth
564 var opt_arrays = new OptionInt("Depth of the primitive array for each wrapped class (default: 1)", 1, "-a")
565
566 # Generate the primitive array version of each class up to the given depth
567 var opt_load_models = new OptionArray("Saved models to search for super-classes", "-m")
568 end
569
570 redef abstract class Text
571 # Get a copy of `self` where the first letter is capitalized
572 fun simple_capitalized: String
573 do
574 if is_empty then return to_s
575
576 var c = chars.first.to_upper
577 var s = c.to_s + substring_from(1)
578 return s
579 end
580 end