contrib/jwrapper: enable serialization of 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 # All analyzed classes
256 var classes = new HashMap[String, JavaClass]
257
258 # Add a class in `classes`
259 fun add_class(jclass: JavaClass)
260 do
261 var key = jclass.class_type.package_name
262 classes[key] = jclass
263 end
264
265 # Unknown types, not already wrapped and not in this pass
266 var unknown_types = new HashMap[JavaType, NitType] is noserialize
267
268 # Wrapped types, or classes analyzed in this pass
269 var known_types = new HashMap[JavaType, NitType] is noserialize
270
271 # Get the `NitType` corresponding to the `JavaType`
272 #
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
276 do
277 # Check cache
278 if known_types.keys.has(jtype) then return known_types[jtype]
279 if unknown_types.keys.has(jtype) then return unknown_types[jtype]
280
281 # Is it a compatible primitive type?
282 if not jtype.is_primitive_array then
283 var name = converter.to_nit_type(jtype.id)
284 if name != null then
285 # We got a Nit equivalent
286 var nit_type = new NitType(name)
287 known_types[jtype] = nit_type
288 return nit_type
289 end
290 end
291
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
298 return nit_type
299 end
300 end
301
302 # Search in lib
303 var nit_type = find_extern_class[jtype.extern_equivalent]
304 if nit_type != null then
305 known_types[jtype] = nit_type
306 return nit_type
307 end
308
309 # Unknown type
310 nit_type = new NitType(jtype.extern_name)
311 nit_type.is_known = false
312 unknown_types[jtype] = nit_type
313 return nit_type
314 end
315
316 # Resolve the types in methods and attributes of this class
317 fun resolve_types
318 do
319 for id, java_class in classes do
320 java_class.resolve_types_of java_class
321
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
329 end
330 end
331 end
332 end
333
334 # Specialization hierarchy of `classes`
335 var class_hierarchy = new POSet[JavaClass] is noserialize
336
337 # Fill `class_hierarchy`
338 fun build_class_hierarchy
339 do
340 var object_type = new JavaType
341 object_type.identifier = ["java","lang","Object"]
342
343 # Fill POSet
344 for name, java_class in classes do
345 # Skip anonymous classes
346 if java_class.class_type.is_anonymous then continue
347
348 java_class.in_hierarchy = class_hierarchy.add_node(java_class)
349
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
354
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)
359 end
360
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
364 end
365
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
369
370 var super_class = classes[super_type.package_name]
371 class_hierarchy.add_edge(java_class, super_class)
372 end
373 end
374
375 # Flatten classes from the top one (Object like)
376 var linearized = class_hierarchy.linearize(class_hierarchy)
377
378 # Methods intro
379 for java_class in linearized do
380 var in_hierarchy = class_hierarchy[java_class]
381 var greaters = in_hierarchy.greaters
382
383 for mid, signatures in java_class.methods do
384 for signature in signatures do
385 if signature.is_static then continue
386
387 # Check if this signature exists in a parent
388 for parent in greaters do
389 if parent == java_class then continue
390
391 if not parent.methods.keys.has(mid) then continue
392
393 if parent.methods[mid].has(signature) then continue label
394 end
395
396 # This is an introduction! register it
397 java_class.local_intro_methods[mid].add signature
398
399 end label
400 end
401 end
402 end
403 end
404
405 # A property to a Java class
406 abstract class JavaProperty
407
408 # Is this property marked static?
409 var is_static: Bool
410 end
411
412 # A Java method, with its signature
413 class JavaMethod
414 super JavaProperty
415
416 # Type returned by the method
417 var return_type: JavaType
418
419 # Type of the arguments of the method
420 var params: Array[JavaType]
421
422 # Generic parameters of this method
423 var generic_params: Array[JavaType]
424
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
427 end
428
429 # An attribute in a Java class
430 class JavaAttribute
431 super JavaProperty
432
433 # Type of the attribute
434 var java_type: JavaType
435 end
436
437 # A Java method, with its signature
438 class JavaConstructor
439 # Type of the parameters of this constructor
440 var params: Array[JavaType]
441
442 # Generic parameters of this constructor
443 var generic_params: Array[JavaType]
444 end
445
446 # A Nit module, use to import the referenced extern classes
447 class NitModule
448 # Relative path to the module
449 var path: String
450
451 # Name of the module
452 var name: String is lazy do return path.basename(".nit")
453
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
457 end
458
459 redef class Sys
460 # Collection of Java classes already wrapped in the library
461 #
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]
467
468 var lib_paths = opt_libs.value
469 if lib_paths == null then lib_paths = new Array[String]
470
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
479 end
480 end
481
482 if lib_paths.is_empty then return map
483
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
488
489 var grep = new ProcessReader("grep", grep_args...)
490 var lines = grep.read_lines
491 grep.close
492 grep.wait
493
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
496 for line in lines do
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
502
503 # Debug code
504 # print "+ Found {nit_name}: {java_name} at {path}"
505
506 var mod = modules.get_or_null(path)
507 if mod == null then
508 mod = new NitModule(path)
509 modules[path] = mod
510 end
511
512 map[java_name] = new NitType(nit_name, mod)
513 end
514 end
515
516 return map
517 end
518
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")
521
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
524
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")
527
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")
530 end
531
532 redef abstract class Text
533 # Get a copy of `self` where the first letter is capitalized
534 fun simple_capitalized: String
535 do
536 if is_empty then return to_s
537
538 var c = chars.first.to_upper
539 var s = c.to_s + substring_from(1)
540 return s
541 end
542 end