contrib/objcwrapper: avoid conflicts with Nit keywords and top-level methods
[nit.git] / contrib / objcwrapper / src / objc_generator.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Code generation
16 module objc_generator
17
18 import opts
19 import gen_nit
20
21 import objc_model
22
23 redef class Sys
24
25 # Path to the output file
26 var opt_output = new OptionString("Output file", "-o")
27
28 # Shall `init` methods/constructors be wrapped as methods?
29 #
30 # By default, these methods/constructors are wrapped as extern constructors.
31 # So initializing an extern Objective-C object looks like:
32 # ~~~nitish
33 # var o = new NSArray.init_with_array(some_other_array)
34 # ~~~
35 #
36 # If this option is set, the object must first be allocated and then initialized.
37 # This is closer to the Objective-C behavior:
38 # ~~~nitish
39 # var o = new NSArray
40 # o.init_with_array(some_other_array)
41 # ~~~
42 var opt_init_as_methods = new OptionBool(
43 "Wrap `init...` constructors as Nit methods instead of Nit constructors",
44 "--init-as-methods")
45
46 private var objc_to_nit_types: Map[String, String] is lazy do
47 var types = new HashMap[String, String]
48 types["char"] = "Byte"
49 types["short"] = "Int"
50 types["short int"] = "Int"
51 types["int"] = "Int"
52 types["long"] = "Int"
53 types["long int"] = "Int"
54 types["long long"] = "Int"
55 types["long long int"] = "Int"
56 types["float"] = "Float"
57 types["double"] = "Float"
58 types["long double"] = "Float"
59
60 types["NSUInteger"] = "Int"
61 types["NSInteger"] = "Int"
62 types["CGFloat"] = "Float"
63 types["BOOL"] = "Bool"
64
65 types["id"] = "NSObject"
66 types["constid"] = "NSObject"
67 types["SEL"] = "NSObject"
68 types["void"] = "Pointer"
69
70 return types
71 end
72 end
73
74 redef class ObjcModel
75 redef fun knows_type(objc_type) do return super or
76 objc_to_nit_types.keys.has(objc_type)
77 end
78
79 # Wrapper generator
80 class CodeGenerator
81
82 # `ObjcModel` to wrap
83 var model: ObjcModel
84
85 # Generate Nit code to wrap `classes`
86 fun generate
87 do
88 var classes = model.classes
89
90 # Open specified path or stdin
91 var file
92 var path = opt_output.value
93 if path != null then
94 if path.file_extension != "nit" then
95 print_error "Warning: output file path does not end with '.nit'"
96 end
97
98 file = new FileWriter.open(path)
99 else
100 file = stdout
101 end
102
103 # Generate code
104 file.write """
105 # File generated by objcwrapper with the following command:
106 # {{{program_name}}} {{{args.join(" ")}}}
107
108 """
109
110 file.write "import cocoa::foundation\n"
111 for classe in classes do
112 write_class(classe, file)
113 end
114
115 if path != null then file.close
116 end
117
118 private fun write_class(classe: ObjcClass, file: Writer)
119 do
120 # Class header
121 file.write """
122
123 extern class {{{classe.name}}} in "ObjC" `{ {{{classe.name}}} * `}
124 """
125
126 # Supers
127 for super_name in classe.super_names do file.write """
128 super {{{super_name}}}
129 """
130 if classe.super_names.is_empty then file.write """
131 super NSObject
132 """
133
134 # Constructor or constructors
135 write_constructors(classe, file)
136
137 # Attributes
138 for attribute in classe.attributes do
139 write_attribute(attribute, file)
140 end
141
142 # Instance methods '-'
143 for method in classe.methods do
144 if not model.knows_all_types(method) then method.is_commented = true
145
146 if not opt_init_as_methods.value and method.is_init then continue
147 if method.is_class_property then continue
148
149 write_method_signature(method, file)
150 write_objc_method_call(method, file)
151 end
152
153 file.write """
154 end
155 """
156
157 # Class methods '+'
158 for method in classe.methods do
159 if not method.is_class_property then continue
160
161 write_method_signature(method, file)
162 write_objc_method_call(method, file)
163 end
164 end
165
166 private fun write_constructors(classe: ObjcClass, file: Writer)
167 do
168 if opt_init_as_methods.value then
169 # A single constructor for `alloc`
170 file.write """
171
172 new in "ObjC" `{
173 return [{{{classe.name}}} alloc];
174 `}
175 """
176 return
177 end
178
179 # A constructor per `init...` method
180 for method in classe.methods do
181 if not method.is_init then continue
182
183 if not model.knows_all_types(method) then method.is_commented = true
184
185 write_method_signature(method, file)
186
187 write_objc_init_call(classe.name, method, file)
188 end
189 end
190
191 private fun write_attribute(attribute: ObjcAttribute, file: Writer)
192 do
193 if not model.knows_type(attribute.return_type) then attribute.is_commented = true
194
195 write_attribute_getter(attribute, file)
196 # TODO write_attribute_setter if there is no `readonly` annotation
197 end
198
199 private fun write_attribute_getter(attribute: ObjcAttribute, file: Writer)
200 do
201 var nit_attr_name = attribute.name.to_snake_case
202 var nit_attr_type = attribute.return_type.objc_to_nit_type
203
204 var c = attribute.comment_str
205
206 file.write """
207
208 {{{attribute.doc}}}
209 {{{c}}} fun {{{nit_attr_name}}}: {{{nit_attr_type}}} in "ObjC" `{
210 {{{c}}} return [self {{{attribute.name}}}];
211 {{{c}}} `}
212 """
213 end
214
215 private fun write_attribute_setter(attribute: ObjcAttribute, file: Writer)
216 do
217 var nit_attr_name = attribute.name.to_snake_case
218 var nit_attr_type = attribute.return_type.objc_to_nit_type
219
220 var c = attribute.comment_str
221
222 file.write """
223
224 {{{attribute.doc}}}
225 {{{c}}} fun {{{nit_attr_name}}}=(value: {{{nit_attr_type}}}) in "ObjC" `{
226 {{{c}}} return self.{{{attribute.name}}} = value;
227 {{{c}}} `}
228 """
229 end
230
231 private fun write_method_signature(method: ObjcMethod, file: Writer)
232 do
233 var c = method.comment_str
234
235 # Build Nit method name
236 var name = ""
237 for param in method.params do
238 name += param.name[0].to_upper.to_s + param.name.substring_from(1)
239 end
240 name = name.to_snake_case
241
242 if name == "init" then name = ""
243
244 name = name.to_nit_name(property=true, pointer=true)
245
246 # If class method, prefix with class name
247 if method.is_class_property then name = "{method.objc_class.name.to_snake_case}_{name}"
248
249 # Kind of method
250 var fun_keyword = "fun"
251 if not opt_init_as_methods.value and method.is_init then
252 fun_keyword = "new"
253 end
254
255 # Params
256 var params = new Array[String]
257 for param in method.params do
258 if param.is_single then break
259 params.add "{param.nit_variable_name}: {param.return_type.objc_to_nit_type}"
260 end
261
262 var params_with_par = ""
263 if params.not_empty then params_with_par = "({params.join(", ")})"
264
265 # Return
266 var ret = ""
267 if method.return_type != "void" and fun_keyword != "new" then
268 ret = ": {method.return_type.objc_to_nit_type}"
269 end
270
271 file.write """
272
273 {{{method.doc}}}
274 {{{c}}}{{{fun_keyword}}} {{{name}}}{{{params_with_par}}}{{{ret}}} in "ObjC" `{
275 """
276 end
277
278 # Write a combined call to alloc and to a constructor/method
279 private fun write_objc_init_call(class_name: String, method: ObjcMethod, file: Writer)
280 do
281 # Method name and other params
282 var params = new Array[String]
283 for param in method.params do
284 if not param.is_single then
285 params.add "{param.name}: {param.nit_variable_name}"
286 else params.add param.name
287 end
288
289 var c = method.comment_str
290
291 file.write """
292 {{{c}}} return [[{{{class_name}}} alloc] {{{params.join(" ")}}}];
293 {{{c}}}`}
294 """
295 end
296
297 private fun write_objc_method_call(method: ObjcMethod, file: Writer)
298 do
299 # Is there a value to return?
300 var ret = ""
301 if method.return_type != "void" then ret = "return "
302
303 # Method name and other params
304 var params = new Array[String]
305 for param in method.params do
306 if not param.is_single then
307 params.add "{param.name}: {param.nit_variable_name}"
308 else params.add param.name
309 end
310
311 # Receiver, instance or class
312 var recv = "self"
313 if method.is_class_property then recv = method.objc_class.name
314
315 var c = method.comment_str
316
317 file.write """
318 {{{c}}} {{{ret}}}[{{{recv}}} {{{params.join(" ")}}}];
319 {{{c}}}`}
320 """
321 end
322 end
323
324 redef class Text
325 # Nit equivalent to this type
326 private fun objc_to_nit_type: String
327 do
328 var types = sys.objc_to_nit_types
329
330 if types.has_key(self) then
331 return types[self]
332 else
333 return to_s
334 end
335 end
336
337 # Convert to a safe Nit name for a `property`, a property in a subclass of `pointer` or a variable
338 private fun to_nit_name(property, pointer: nullable Bool): String
339 do
340 var name = to_s
341 name = name.to_snake_case
342
343 while not name.is_empty and name.chars.first == '_' do name = name.substring_from(1)
344
345 if keywords.has(name) then name = name + "0"
346
347 if property == true then
348 if methods_in_object.has(name) then name = name + "0"
349 if pointer == true and methods_in_pointer.has(name) then name = name + "0"
350 end
351
352 return name.to_s
353 end
354 end
355
356 redef class ObjcProperty
357 private fun comment_str: String do if is_commented then
358 return "#"
359 else return ""
360
361 # Full documentation to be generated for the Nit code
362 private fun doc: String is abstract
363 end
364
365 redef class ObjcMethod
366 private fun indent: String do return if is_class_property then "" else "\t"
367
368 redef fun comment_str do return indent + super
369
370 redef fun doc
371 do
372 var recv = if is_class_property then objc_class.name else "self"
373 return "{indent}# Wraps: `[{recv} {params.join(" ")}]`"
374 end
375 end
376
377 redef class ObjcAttribute
378 redef fun doc do return "\t# Wraps: `{objc_class.name}.{name}`"
379 end
380
381 redef class ObjcParam
382 # `variable_name` mangled for the Nit language
383 private fun nit_variable_name: String do return variable_name.to_nit_name
384 end