contrib/jwrapper: remove unused code
[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 and generic params
125 # Ignores primitive array so `a.b.c[][] == a.b.c`
126 redef fun ==(other) do return other isa JavaType and self.full_id == other.full_id
127
128 redef fun hash do return self.full_id.hash
129 end
130
131 class NitType
132 # Nit class name
133 var identifier: String
134
135 # If this NitType was found in `lib/android`, contains the module name to import
136 var mod: nullable NitModule
137
138 # Is this type known, wrapped and available in Nit?
139 var is_known: Bool = true
140
141 redef fun to_s do return identifier
142 end
143
144 # Model of a single Java class
145 class JavaClass
146 # Type of this class
147 var class_type: JavaType
148
149 # Attributes of this class
150 var attributes = new HashMap[String, JavaType]
151
152 # Methods of this class organized by their name
153 var methods = new MultiHashMap[String, JavaMethod]
154
155 # Constructors of this class
156 var constructors = new Array[JavaConstructor]
157
158 # Importations from this class
159 var imports = new HashSet[NitModule]
160
161 redef fun to_s do return class_type.to_s
162 end
163
164 # Model of all the Java class analyzed in one run
165 class JavaModel
166
167 # All analyzed classes
168 var classes = new HashMap[String, JavaClass]
169
170 # Add a class in `classes`
171 fun add_class(jclass: JavaClass)
172 do
173 var key = jclass.class_type.full_id
174 classes[key] = jclass
175 end
176
177 # Unknown types, not already wrapped and not in this pass
178 private var unknown_types = new HashMap[JavaType, NitType]
179
180 # Wrapped types, or classes analyzed in this pass
181 private var known_types = new HashMap[JavaType, NitType]
182
183 # Get the `NitType` corresponding to the `JavaType`
184 #
185 # Also registers types so they can be reused and
186 # to keep track of unknown types.
187 fun java_to_nit_type(jtype: JavaType): NitType
188 do
189 # Check cache
190 if known_types.keys.has(jtype) then return known_types[jtype]
191 if unknown_types.keys.has(jtype) then return unknown_types[jtype]
192
193 # Is it a compatible primitive type?
194 if not jtype.is_primitive_array then
195 var name = converter.to_nit_type(jtype.id)
196 if name != null then
197 # We got a Nit equivalent
198 var nit_type = new NitType(name)
199 known_types[jtype] = nit_type
200 return nit_type
201 end
202 end
203
204 # Is being wrapped in this pass?
205 var key = jtype.full_id
206 if classes.keys.has(key) then
207 var nit_type = new NitType(jtype.extern_name)
208 known_types[jtype] = nit_type
209
210 return nit_type
211 end
212
213 # Search in lib
214 var nit_type = find_extern_class[jtype.full_id]
215 if nit_type != null then
216 known_types[jtype] = nit_type
217 return nit_type
218 end
219
220 # Unknown type
221 nit_type = new NitType(jtype.extern_name)
222 nit_type.is_known = false
223 unknown_types[jtype] = nit_type
224 return nit_type
225 end
226 end
227
228 # A Java method, with its signature
229 class JavaMethod
230 # Type returned by the method
231 var return_type: JavaType
232
233 # Type of the arguments of the method
234 var params: Array[JavaType]
235 end
236
237 # A Java method, with its signature
238 class JavaConstructor
239 # Type of the parameters of this constructor
240 var params: Array[JavaType]
241 end
242
243 # A Nit module, use to import the referenced extern classes
244 class NitModule
245 # Relative path to the module
246 var path: String
247
248 # Name of the module
249 var name: String is lazy do return path.basename(".nit")
250
251 redef fun to_s do return self.name
252 redef fun ==(other) do return other isa NitModule and self.path == other.path
253 redef fun hash do return self.path.hash
254 end
255
256 redef class Sys
257 # Collection of Java classes already wrapped in the library
258 #
259 # * The key is from `JavaType.full_id`.
260 # * The value is the corresponding `NitType`.
261 var find_extern_class: DefaultMap[String, nullable NitType] is lazy do
262 var map = new DefaultMap[String, nullable NitType](null)
263 var modules = new HashMap[String, NitModule]
264
265 var nit_dir = "NIT_DIR".environ
266 if nit_dir.is_empty then
267 # Simple heuristic to find the Nit lib
268 var dir = sys.program_name.dirname / "../../../"
269 nit_dir = dir.simplify_path
270 if not nit_dir.file_exists then return map
271 end
272
273 # Use grep to find all extern classes implemented in Java
274 var grep_regex = "extern class [a-zA-Z0-9]\\\+[ ]\\\+in[ ]\\\+\"Java\""
275 var grep_args = ["-r", grep_regex,
276 nit_dir/"lib/android/",
277 nit_dir/"lib/java/"]
278
279 var grep = new ProcessReader("grep", grep_args...)
280 var lines = grep.read_lines
281 grep.close
282 grep.wait
283
284 # Sort out the modules, Nit class names and Java types
285 var regex = """(.+):\\s*extern +class +([a-zA-Z0-9]+) *in *"Java" *`\\{ *([a-zA-Z0-9.$/]+) *`\\}""".to_re
286 for line in lines do
287 var matches = line.search_all(regex)
288 for match in matches do
289 var path = match[1].to_s
290 var nit_name = match[2].to_s
291 var java_name = match[3].to_s
292
293 # Debug code
294 # print "+ Found {nit_name}:{java_name} at {path}"
295
296 var mod = modules.get_or_null(path)
297 if mod == null then
298 mod = new NitModule(path)
299 modules[path] = mod
300 end
301
302 map[java_name] = new NitType(nit_name, mod)
303 end
304 end
305
306 return map
307 end
308
309 # Option to set `extern_class_prefix`
310 var opt_extern_class_prefix = new OptionString("Prefix to extern classes (By default uses the full namespace)", "-p")
311
312 # Prefix used to name extern classes, if `null` use the full namespace
313 var extern_class_prefix: nullable String is lazy do return opt_extern_class_prefix.value
314 end
315
316 redef class Text
317 # Get a copy of `self` where the first letter is capitalized
318 fun simple_capitalized: String
319 do
320 if is_empty then return to_s
321
322 var c = chars.first.to_upper
323 var s = c.to_s + substring_from(1)
324 return s
325 end
326 end