contrib/jwrapper: use serialized models to build the complete class hierarchy
[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 # Add a class in `classes`
291 fun add_class(jclass: JavaClass)
292 do
293 var key = jclass.class_type.package_name
294 classes[key] = jclass
295 end
296
297 # Unknown types, not already wrapped and not in this pass
298 var unknown_types = new HashMap[JavaType, NitType] is noserialize
299
300 # Wrapped types, or classes analyzed in this pass
301 var known_types = new HashMap[JavaType, NitType] is noserialize
302
303 # Get the `NitType` corresponding to the `JavaType`
304 #
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
308 do
309 # Check cache
310 if known_types.keys.has(jtype) then return known_types[jtype]
311 if unknown_types.keys.has(jtype) then return unknown_types[jtype]
312
313 # Is it a compatible primitive type?
314 if not jtype.is_primitive_array then
315 var name = converter.to_nit_type(jtype.id)
316 if name != null then
317 # We got a Nit equivalent
318 var nit_type = new NitType(name)
319 known_types[jtype] = nit_type
320 return nit_type
321 end
322 end
323
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
330 return nit_type
331 end
332 end
333
334 # Search in lib
335 var nit_type = find_extern_class[jtype.extern_equivalent]
336 if nit_type != null then
337 known_types[jtype] = nit_type
338 return nit_type
339 end
340
341 # Unknown type
342 nit_type = new NitType(jtype.extern_name)
343 nit_type.is_known = false
344 unknown_types[jtype] = nit_type
345 return nit_type
346 end
347
348 # Resolve the types in methods and attributes of this class
349 fun resolve_types
350 do
351 for id, java_class in classes do
352 java_class.resolve_types_of java_class
353
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
361 end
362 end
363 end
364 end
365
366 # Specialization hierarchy of `classes`
367 var class_hierarchy = new POSet[JavaClass] is noserialize
368
369 # Fill `class_hierarchy`
370 fun build_class_hierarchy
371 do
372 var object_type = new JavaType
373 object_type.identifier = ["java","lang","Object"]
374
375 # Fill POSet
376 for name, java_class in all_classes do
377 # Skip anonymous classes
378 if java_class.class_type.is_anonymous then continue
379
380 java_class.in_hierarchy = class_hierarchy.add_node(java_class)
381
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
386
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)
391 end
392
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
396 end
397
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
401
402 var super_class = all_classes[super_type.package_name]
403 class_hierarchy.add_edge(java_class, super_class)
404 end
405 end
406
407 # Flatten classes from the top one (Object like)
408 var linearized = class_hierarchy.linearize(class_hierarchy)
409
410 # Methods intro
411 for java_class in linearized do
412 var greaters = java_class.in_hierarchy.greaters
413
414 for mid, signatures in java_class.methods do
415 for signature in signatures do
416 if signature.is_static then continue
417
418 # Check if this signature exists in a parent
419 for parent in greaters do
420 if parent == java_class then continue
421
422 if not parent.methods.keys.has(mid) then continue
423
424 if parent.methods[mid].has(signature) then continue label
425 end
426
427 # This is an introduction! register it
428 java_class.local_intro_methods[mid].add signature
429
430 end label
431 end
432 end
433 end
434 end
435
436 # A property to a Java class
437 abstract class JavaProperty
438
439 # Is this property marked static?
440 var is_static: Bool
441 end
442
443 # A Java method, with its signature
444 class JavaMethod
445 super JavaProperty
446
447 # Type returned by the method
448 var return_type: JavaType
449
450 # Type of the arguments of the method
451 var params: Array[JavaType]
452
453 # Generic parameters of this method
454 var generic_params: Array[JavaType]
455
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
458 end
459
460 # An attribute in a Java class
461 class JavaAttribute
462 super JavaProperty
463
464 # Type of the attribute
465 var java_type: JavaType
466 end
467
468 # A Java method, with its signature
469 class JavaConstructor
470 # Type of the parameters of this constructor
471 var params: Array[JavaType]
472
473 # Generic parameters of this constructor
474 var generic_params: Array[JavaType]
475 end
476
477 # A Nit module, use to import the referenced extern classes
478 class NitModule
479 # Relative path to the module
480 var path: String
481
482 # Name of the module
483 var name: String is lazy do return path.basename(".nit")
484
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
488 end
489
490 redef class Sys
491 # Collection of Java classes already wrapped in the library
492 #
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]
498
499 var lib_paths = opt_libs.value
500 if lib_paths == null then lib_paths = new Array[String]
501
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
510 end
511 end
512
513 if lib_paths.is_empty then return map
514
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
519
520 var grep = new ProcessReader("grep", grep_args...)
521 var lines = grep.read_lines
522 grep.close
523 grep.wait
524
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
527 for line in lines do
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
533
534 # Debug code
535 # print "+ Found {nit_name}: {java_name} at {path}"
536
537 var mod = modules.get_or_null(path)
538 if mod == null then
539 mod = new NitModule(path)
540 modules[path] = mod
541 end
542
543 map[java_name] = new NitType(nit_name, mod)
544 end
545 end
546
547 return map
548 end
549
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")
552
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
555
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")
558
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")
561
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")
564 end
565
566 redef abstract class Text
567 # Get a copy of `self` where the first letter is capitalized
568 fun simple_capitalized: String
569 do
570 if is_empty then return to_s
571
572 var c = chars.first.to_upper
573 var s = c.to_s + substring_from(1)
574 return s
575 end
576 end