c390d1b1a9e80a65b8177ebe754ed93aa474c6e0
[nit.git] / contrib / jwrapper / src / code_generator.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 # Services to generate extern class `in "Java"`
19 module code_generator
20
21 intrude import model
22
23 class CodeGenerator
24
25 # Path to the output file
26 var file_name: String
27
28 # Model of Java class being wrapped
29 var model: JavaModel
30
31 # Comment out methods with unknown (unwrapped) types
32 var comment_unknown_types: Bool
33
34 # Generate stub classes for unknown types used in the generated module
35 var stub_for_unknown_types: Bool
36
37 # Output file
38 var file_out: Writer = new FileWriter.open(file_name) is lazy, writable
39
40 # Name of the Nit module to generate
41 var module_name: nullable String is lazy do
42 if file_name.file_extension == "nit" then
43 # Output file ends with .nit, we expect it to be a valid name
44 return file_name.basename(".nit")
45 else return null
46 end
47
48 # Generate the Nit module into `file_out`
49 fun generate
50 do
51 # License
52 file_out.write license
53
54 # Module declaration
55 var module_name = module_name
56 if module_name != null then file_out.write "module {module_name}\n"
57 file_out.write "\n"
58
59 # All importations
60 var imports = new HashSet[String]
61 imports.add "import java\n"
62 for key, jclass in model.classes do
63 for import_ in jclass.imports do imports.add "import android::{import_}\n"
64 end
65 file_out.write imports.join("\n")
66 file_out.write "\n"
67
68 for key, jclass in model.classes do
69
70 generate_class_header(jclass.class_type)
71
72 for id, signatures in jclass.methods do
73 var c = 0
74 for signature in signatures do
75 var nid = id
76 if c > 0 then nid += c.to_s
77 c += 1
78
79 generate_method(jclass, id, nid, signature.return_type, signature.params)
80 file_out.write "\n"
81 end
82 end
83
84 # Constructors
85 for constructor in jclass.constructors do
86 var complex = jclass.constructors.length != 1 and constructor.params.not_empty
87 var base_name = if complex then "from" else ""
88 var name = jclass.nit_name_for(base_name, constructor.params, complex)
89
90 generate_constructor(jclass, constructor, name)
91 end
92
93 # Attributes
94 for id, java_type in jclass.attributes do
95 generate_getter_setter(jclass, id, java_type)
96 end
97
98 file_out.write "end\n\n"
99 end
100
101 if stub_for_unknown_types then
102 for jtype, nit_type in model.unknown_types do
103 generate_unknown_class_header(jtype)
104 file_out.write "\n"
105 end
106 end
107 end
108
109 # License for the header of the generated Nit module
110 var license = """
111 # This file is part of NIT (http://www.nitlanguage.org).
112 #
113 # Licensed under the Apache License, Version 2.0 (the "License");
114 # you may not use this file except in compliance with the License.
115 # You may obtain a copy of the License at
116 #
117 # http://www.apache.org/licenses/LICENSE-2.0
118 #
119 # Unless required by applicable law or agreed to in writing, software
120 # distributed under the License is distributed on an "AS IS" BASIS,
121 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
122 # See the License for the specific language governing permissions and
123 # limitations under the License.
124
125 # This code has been generated using `jwrapper`
126 """ is writable
127
128 private fun generate_class_header(jtype: JavaType)
129 do
130 var nit_type = model.java_to_nit_type(jtype)
131 file_out.write "# Java class: {jtype.to_package_name}\n"
132 file_out.write "extern class {nit_type} in \"Java\" `\{ {jtype.to_package_name} `\}\n"
133 file_out.write "\tsuper JavaObject\n\n"
134 end
135
136 private fun generate_unknown_class_header(jtype: JavaType)
137 do
138 var nit_type = jtype.extern_name
139
140 file_out.write "extern class {nit_type} in \"Java\" `\{ {jtype.to_package_name} `\}\n"
141 file_out.write "\tsuper JavaObject\n\nend\n"
142 end
143
144 private fun generate_method(java_class: JavaClass, jmethod_id, method_id: String,
145 jreturn_type: JavaType, jparam_list: Array[JavaType])
146 do
147 var java_params = ""
148 var nit_params = ""
149 var nit_id = "arg"
150 var nit_id_no = 0
151 var nit_types = new Array[NitType]
152 var comment = ""
153
154 # Parameters
155 for i in [0..jparam_list.length[ do
156 var jparam = jparam_list[i]
157 var nit_type = model.java_to_nit_type(jparam)
158
159 if not nit_type.is_known then comment = "#"
160
161 var cast = jparam.param_cast
162
163 nit_types.add(nit_type)
164
165 if i == jparam_list.length - 1 then
166 java_params += "{cast}{nit_id}{nit_id_no}"
167 nit_params += "{nit_id}{nit_id_no}: {nit_type}"
168 else
169 java_params += "{cast}{nit_id}{nit_id_no}" + ", "
170 nit_params += "{nit_id}{nit_id_no}: {nit_type}, "
171 end
172
173 nit_id_no += 1
174 end
175
176 # Method documentation
177 var doc = "\t# Java implementation: {java_class}.{jmethod_id}\n"
178
179 # Method identifier
180 method_id = method_id.to_nit_method_name
181 method_id = java_class.nit_name_for(method_id, jparam_list, java_class.methods[jmethod_id].length > 1)
182 var nit_signature = new Array[String]
183
184 nit_signature.add "\tfun {method_id}"
185
186 if not jparam_list.is_empty then
187 nit_signature.add "({nit_params})"
188 end
189
190 var return_type = null
191 if not jreturn_type.is_void then
192 return_type = model.java_to_nit_type(jreturn_type)
193
194 if not return_type.is_known then comment = "#"
195
196 nit_signature.add ": {return_type} "
197 end
198
199 file_out.write doc
200 file_out.write comment + nit_signature.join
201
202 if comment == "#" then
203 file_out.write " in \"Java\" `\{\n{comment}\t\tself.{jmethod_id}({java_params});\n{comment}\t`\}\n"
204 # Methods with return type
205 else if return_type != null then
206 file_out.write " in \"Java\" `\{\n{comment}\t\treturn {jreturn_type.return_cast}self.{jmethod_id}({java_params});\n{comment}\t`\}\n"
207 # Methods without return type
208 else if jreturn_type.is_void then
209 file_out.write " in \"Java\" `\{\n{comment}\t\tself.{jmethod_id}({java_params});\n{comment}\t`\}\n"
210 # No copy
211 else
212 file_out.write " in \"Java\" `\{\n{comment}\t\tself.{jmethod_id}({java_params});\n{comment}\t`\}\n"
213 end
214 end
215
216 # Generate getter and setter to access an attribute, of field
217 private fun generate_getter_setter(java_class: JavaClass, java_id: String, java_type: JavaType)
218 do
219 var nit_type = model.java_to_nit_type(java_type)
220 var nit_id = java_id.to_nit_method_name
221 nit_id = java_class.nit_name_for(nit_id, [java_type], false)
222
223 var c = ""
224 if not nit_type.is_known then c = "#"
225
226 file_out.write """
227 # Java getter: {{{java_class}}}.{{{java_id}}}
228 {{{c}}} fun {{{nit_id}}}: {{{nit_type}}} in "Java" `{
229 {{{c}}} return self.{{{java_id}}};
230 {{{c}}} `}
231
232 # Java setter: {{{java_class}}}.{{{java_id}}}
233 {{{c}}} fun {{{nit_id}}}=(value: {{{nit_type}}}) in "Java" `{
234 {{{c}}} self.{{{java_id}}} = value;
235 {{{c}}} `}
236
237 """
238 end
239
240 # Generate getter and setter to access an attribute, of field
241 private fun generate_constructor(java_class: JavaClass, constructor: JavaConstructor, name: String)
242 do
243 var c = ""
244 var nit_params_s = ""
245 var java_params_s = ""
246
247 if constructor.params.not_empty then
248 var nit_params = new Array[String]
249 var java_params = new Array[String]
250 var param_id = 'a'
251 for java_type in constructor.params do
252
253 java_params.add "{java_type.param_cast}{param_id}"
254
255 var nit_type = model.java_to_nit_type(java_type)
256 nit_params.add "{param_id}: {nit_type}"
257 param_id = param_id.successor(1)
258
259 if not nit_type.is_known then c = "#"
260 end
261
262 nit_params_s = "(" + nit_params.join(", ") + ")"
263 java_params_s = java_params.join(", ")
264 end
265
266 file_out.write """
267 # Java constructor: {{{java_class}}}
268 {{{c}}} new {{{name}}}{{{nit_params_s}}} in "Java" `{
269 {{{c}}} return new {{{java_class}}}({{{java_params_s}}});
270 {{{c}}} `}
271
272 """
273 end
274 end
275
276 redef class Sys
277 # List of Nit keywords
278 #
279 # These may also be keywords in Java, but there they would be used capitalized.
280 private var nit_keywords: Array[String] = ["abort", "abstract", "and", "assert",
281 "break", "class", "continue", "do", "else", "end", "enum", "extern", "false", "implies",
282 "import", "init", "interface", "intrude", "if", "in", "is", "isa", "isset", "for", "label",
283 "loop", "module", "new", "not", "null", "nullable", "or", "package", "private",
284 "protected", "public", "return", "self", "super", "then", "true", "type", "var", "while"]
285 end
286
287 redef class String
288
289 # Convert the Java method name `self` to the Nit style
290 #
291 # * Converts to snake case
292 # * Strips `Get` and `Set`
293 # * Add suffix `=` to setters
294 fun to_nit_method_name: String
295 do
296 var name = self.to_snake_case
297 if name.has_prefix("get_") then
298 name = name.substring_from(4)
299 else if name.has_prefix("set_") then
300 name = name.substring_from(4)
301 if nit_keywords.has(name) then name += "_"
302 name += "="
303 end
304
305 # Strip the '_' prefix
306 while name.has_prefix("_") do name = name.substring(1, name.length-1)
307
308 # Escape Nit keywords
309 if nit_keywords.has(name) then name += "_"
310
311 # If the name starts by something other than a letter, prefix with `java_`
312 if not name.chars.first.is_letter then name = "java_" + name
313
314 name = name.replace("$", "_")
315
316 return name
317 end
318 end
319
320 redef class JavaClass
321 # Property names used in this class
322 private var used_name = new HashSet[String]
323
324 # Get an available property name for the Java property with `name` and parameters
325 #
326 # If `use_parameters_name` then expect that there will be conflicts,
327 # so use the types of `parameters` to build the name.
328 private fun nit_name_for(name: String, parameters: Array[JavaType], use_parameters_name: Bool): String
329 do
330 # Append the name of each parameter
331 if use_parameters_name then
332 for param in parameters do
333 name += "_" + param.id
334 end
335 end
336
337 # As a last resort, append numbers to the name
338 var base_name = name
339 var count = 1
340 while used_name.has(name) do
341 name = base_name + count.to_s
342 count += 1
343 end
344
345 used_name.add name
346 return name
347 end
348 end