contrib/jwrapper: find extern classes with underscore in their names
[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 # Contains the java and nit type representation used to convert java to nit code
19 module model
20
21 import more_collections
22 import opts
23
24 import jtype_converter
25
26 class JavaType
27 var identifier = new Array[String]
28 var generic_params: nullable Array[JavaType] = null
29
30 # Is this a void return type?
31 var is_void = false
32
33 # Is this type a vararg?
34 var is_vararg = false is writable
35
36 # Has some generic type to be resolved (T extends foo => T is resolved to foo)
37 var has_unresolved_types = false
38
39 # Dimension of primitive array: `int[][]` is 2d
40 var array_dimension = 0
41
42 fun is_primitive_array: Bool do return array_dimension > 0
43
44 fun has_generic_params: Bool do return not generic_params == null
45 fun full_id: String do return identifier.join(".")
46 fun id: String do return identifier.last.replace("$", "")
47
48 fun return_cast: String do return converter.cast_as_return(self.id)
49
50 fun param_cast: String
51 do
52 if self.has_generic_params then
53 return converter.cast_as_param(self.generic_params[0].id)
54 end
55
56 return converter.cast_as_param(self.id)
57 end
58
59 # Name to give an extern class wrapping this type
60 fun extern_name: String
61 do
62 var name
63 var prefix = extern_class_prefix
64 if prefix == null then
65 # Use the namespace, e.g. java.lang.String -> Java_lang_String
66 assert not identifier.is_empty
67 if identifier.length == 1 then
68 name = identifier.last
69 else
70 var first = identifier.first
71 var last = identifier.last
72 var mid = identifier.subarray(1, identifier.length-2)
73 name = first.simple_capitalized + "_"
74 if mid.not_empty then name += mid.join("_") + "_"
75 name += last
76 end
77 else
78 # Use the prefix and the short class name
79 # e.g. given the prefix Native: java.lang.String -> NativeString
80 name = prefix + id
81 end
82
83 name = name.replace("-", "_")
84 name = name.replace("$", "_")
85 return name
86 end
87
88 redef fun to_s
89 do
90 var id = self.full_id
91
92 if self.is_primitive_array then
93 id += "[]" * array_dimension
94 else if self.has_generic_params then
95 var params = [for param in generic_params do param.to_s]
96 id += "<{params.join(", ")}>"
97 end
98
99 return id
100 end
101
102 # To fully qualified package name
103 # Cuts the primitive array `[]`
104 fun to_package_name: String
105 do
106 var str = self.to_s
107 var len = str.length
108
109 return str.substring(0, len - (2*array_dimension))
110 end
111
112 fun resolve_types(conversion_map: HashMap[String, Array[String]])
113 do
114 if identifier.length == 1 then
115 var resolved_id = conversion_map.get_or_null(self.id)
116 if resolved_id != null then self.identifier = new Array[String].from(resolved_id)
117 end
118
119 if self.has_generic_params then
120 for params in generic_params do params.resolve_types(conversion_map)
121 end
122 end
123
124 # Comparison based on fully qualified named
125 redef fun ==(other) do return other isa JavaType and
126 self.full_id == other.full_id and
127 self.is_primitive_array == other.is_primitive_array
128
129 redef fun hash do return self.full_id.hash
130 end
131
132 class NitType
133 # Nit class name
134 var identifier: String
135
136 # If this NitType was found in `lib/android`, contains the module name to import
137 var mod: nullable NitModule
138
139 # Is this type known, wrapped and available in Nit?
140 var is_known: Bool = true
141
142 redef fun to_s do return identifier
143 end
144
145 # Model of a single Java class
146 class JavaClass
147 # Type of this class
148 var class_type: JavaType
149
150 # Attributes of this class
151 var attributes = new HashMap[String, JavaType]
152
153 # Methods of this class organized by their name
154 var methods = new MultiHashMap[String, JavaMethod]
155
156 # Constructors of this class
157 var constructors = new Array[JavaConstructor]
158
159 # Importations from this class
160 var imports = new HashSet[NitModule]
161
162 redef fun to_s do return class_type.to_s
163 end
164
165 # Model of all the Java class analyzed in one run
166 class JavaModel
167
168 # All analyzed classes
169 var classes = new HashMap[String, JavaClass]
170
171 # Add a class in `classes`
172 fun add_class(jclass: JavaClass)
173 do
174 var key = jclass.class_type.full_id
175 classes[key] = jclass
176 end
177
178 # Unknown types, not already wrapped and not in this pass
179 private var unknown_types = new HashMap[JavaType, NitType]
180
181 # Wrapped types, or classes analyzed in this pass
182 private var known_types = new HashMap[JavaType, NitType]
183
184 # Get the `NitType` corresponding to the `JavaType`
185 #
186 # Also registers types so they can be reused and
187 # to keep track of unknown types.
188 fun java_to_nit_type(jtype: JavaType): NitType
189 do
190 # Check cache
191 if known_types.keys.has(jtype) then return known_types[jtype]
192 if unknown_types.keys.has(jtype) then return unknown_types[jtype]
193
194 # Is it a compatible primitive type?
195 if not jtype.is_primitive_array then
196 var name = converter.to_nit_type(jtype.id)
197 if name != null then
198 # We got a Nit equivalent
199 var nit_type = new NitType(name)
200 known_types[jtype] = nit_type
201 return nit_type
202 end
203 end
204
205 # Is being wrapped in this pass?
206 var key = jtype.full_id
207 if classes.keys.has(key) then
208 var nit_type = new NitType(jtype.extern_name)
209 known_types[jtype] = nit_type
210
211 return nit_type
212 end
213
214 # Search in lib
215 var nit_type = find_extern_class[jtype.full_id]
216 if nit_type != null then
217 known_types[jtype] = nit_type
218 return nit_type
219 end
220
221 # Unknown type
222 nit_type = new NitType(jtype.extern_name)
223 nit_type.is_known = false
224 unknown_types[jtype] = nit_type
225 return nit_type
226 end
227 end
228
229 # A Java method, with its signature
230 class JavaMethod
231 # Type returned by the method
232 var return_type: JavaType
233
234 # Type of the arguments of the method
235 var params: Array[JavaType]
236 end
237
238 # A Java method, with its signature
239 class JavaConstructor
240 # Type of the parameters of this constructor
241 var params: Array[JavaType]
242 end
243
244 # A Nit module, use to import the referenced extern classes
245 class NitModule
246 # Relative path to the module
247 var path: String
248
249 # Name of the module
250 var name: String is lazy do return path.basename(".nit")
251
252 redef fun to_s do return self.name
253 redef fun ==(other) do return other isa NitModule and self.path == other.path
254 redef fun hash do return self.path.hash
255 end
256
257 redef class Sys
258 # Collection of Java classes already wrapped in the library
259 #
260 # * The key is from `JavaType.full_id`.
261 # * The value is the corresponding `NitType`.
262 var find_extern_class: DefaultMap[String, nullable NitType] is lazy do
263 var map = new DefaultMap[String, nullable NitType](null)
264 var modules = new HashMap[String, NitModule]
265
266 var lib_paths = opt_libs.value
267 if lib_paths == null then lib_paths = new Array[String]
268
269 if lib_paths.has("auto") then
270 lib_paths.remove "auto"
271 var nit_dir = "NIT_DIR".environ
272 if nit_dir.is_empty then
273 # Simple heuristic to find the Nit lib
274 var dir = sys.program_name.dirname / "../../../lib/"
275 dir = dir.simplify_path
276 if dir.file_exists then lib_paths.add dir.simplify_path
277 end
278 end
279
280 if lib_paths.is_empty then return map
281
282 # Use grep to find all extern classes implemented in Java
283 var grep_regex = "extern class [a-zA-Z0-9_]\\\+[ ]\\\+in[ ]\\\+\"Java\""
284 var grep_args = ["-r", "--with-filename", grep_regex]
285 grep_args.add_all lib_paths
286
287 var grep = new ProcessReader("grep", grep_args...)
288 var lines = grep.read_lines
289 grep.close
290 grep.wait
291
292 # Sort out the modules, Nit class names and Java types
293 var regex = """(.+):\\s*extern +class +([a-zA-Z0-9_]+) *in *"Java" *`\\{ *([a-zA-Z0-9.$/]+) *`\\}""".to_re
294 for line in lines do
295 var matches = line.search_all(regex)
296 for match in matches do
297 var path = match[1].to_s
298 var nit_name = match[2].to_s
299 var java_name = match[3].to_s
300
301 # Debug code
302 # print "+ Found {nit_name}:{java_name} at {path}"
303
304 var mod = modules.get_or_null(path)
305 if mod == null then
306 mod = new NitModule(path)
307 modules[path] = mod
308 end
309
310 map[java_name] = new NitType(nit_name, mod)
311 end
312 end
313
314 return map
315 end
316
317 # Option to set `extern_class_prefix`
318 var opt_extern_class_prefix = new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
319
320 # Prefix used to name extern classes, if `null` use the full namespace
321 var extern_class_prefix: nullable String is lazy do return opt_extern_class_prefix.value
322
323 # Libraries to search for existing wrappers
324 var opt_libs = new OptionArray("Paths to libraries with wrappers of Java classes ('auto' to use the full Nit lib)", "-i")
325 end
326
327 redef class Text
328 # Get a copy of `self` where the first letter is capitalized
329 fun simple_capitalized: String
330 do
331 if is_empty then return to_s
332
333 var c = chars.first.to_upper
334 var s = c.to_s + substring_from(1)
335 return s
336 end
337 end