nitc/ffi: allows to declare C type of extern classes from Nit
[nit.git] / src / native_interface / frontier.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2011 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Information and tools relevant to the frontier files
18 module frontier
19
20 import metamodel
21
22 import ni_tools
23 import ni_metamodel
24
25 import syntax # FIXME: to remove since it breaks modularity
26
27 # Transitive variable through the frontier file
28 # Represents a variable going from Nit to C or from C to Nit
29 abstract class NiVariable
30 fun ni_from_name : String is abstract
31 fun ni_to_name : String is abstract
32 fun ni_type : MMType is abstract
33
34 # needs to be boxed or unboxed
35 # anything using the GC
36 fun needs_preparation : Bool
37 do
38 return ni_type.local_class.primitive_info == null or
39 ni_type.local_class.primitive_info.tagged or
40 ni_type.is_nullable
41 end
42
43 # prepare variable to callback to Nit
44 fun prepare_for_nit( fc : FunctionCompiler )
45 do
46 if needs_preparation then
47 fc.decls.add( "val_t {ni_to_name};\n" )
48 fc.exprs.add( "{ni_type.assign_from_friendly( ni_to_name, ni_from_name )};\n" )
49 end
50 end
51
52 fun prepare_for_c( fc : FunctionCompiler )
53 do
54 if needs_preparation then
55 ni_type.compile_new_local_ref( ni_to_name, fc, not self isa ReturnVariable ) # TODO
56 fc.exprs.add( "{ni_type.assign_to_friendly( ni_to_name, ni_from_name )};\n" )
57 end
58 end
59
60 # format of the variable to callback to Nit
61 fun as_arg_to_nit : String
62 do
63 if needs_preparation then
64 return ni_to_name
65 else if ( ni_type.local_class.primitive_info != null or ni_type.local_class.global.is_extern ) and
66 not ni_type.is_nullable then # int, float, point/void* ...
67 return ni_type.boxtype(ni_from_name)
68 else
69 return "{ni_from_name}->ref.val"
70 end
71 end
72
73 # format of the variable to call C implementation functions
74 fun as_arg_to_c : String
75 do
76 if needs_preparation then
77 return ni_to_name
78 else
79 return ni_type.unboxtype( ni_from_name )
80 end
81 end
82 end
83
84 redef class MMParam
85 super NiVariable
86
87 redef fun ni_from_name do return name.to_s
88 redef fun ni_to_name do return "trans___{name}"
89 redef fun ni_type do return mmtype
90 end
91
92 class ReceiverVariable
93 super NiVariable
94
95 redef fun ni_from_name do return "recv"
96 redef fun ni_to_name do return "trans_recv"
97
98 redef var ni_type : MMType
99 init ( t : MMType ) do ni_type = t
100 end
101
102 class ReturnVariable
103 super NiVariable
104
105 redef fun ni_from_name do return "orig_return"
106 redef fun ni_to_name do return "trans_return"
107
108 redef var ni_type : MMType
109 init ( t : MMType ) do ni_type = t
110
111 # used only by friendly callbacks to Nit
112 redef fun prepare_for_c( fc )
113 do
114 fc.decls.add( "val_t {ni_from_name};\n" )
115 ni_type.compile_new_local_ref( ni_to_name, fc, true )
116 end
117 redef fun prepare_for_nit( fc )
118 do
119 ni_type.compile_new_local_ref( ni_from_name, fc, false )
120 fc.decls.add( "val_t {ni_to_name};\n" )
121 end
122 end
123
124 redef class MMSrcModule
125 fun compile_frontier( v : FrontierVisitor )
126 do
127 # assumes is extern hybrid (verified by caller)
128
129 v.body.add( "#include \"{name}._nitni.h\"\n" )
130
131 # guard
132 v.header_top.add( "#include <nit_common.h>\n" )
133 v.header_top.add( "#include \"{v.cprogram.module_header_name(self)}\"\n" )
134
135 var guard_name = "{name.to_s.to_upper}_NITNI_H"
136 v.header_top.add( "#ifndef {guard_name}\n" )
137 v.header_top.add( "#define {guard_name}\n\n" )
138
139 # import custom _nit.h file from frontier
140 var native_header = "{directory.path}/{name}.nit.h"
141 if not native_header.file_exists then # try old style
142 native_header = "{directory.path}/{name}_nit.h"
143 end
144 if native_header.file_exists then
145 var path = "..".join_path(native_header).simplify_path
146 v.body.add( "#include \"{path}\"\n" )
147 v.header.add( "#include \"{path}\"\n" )
148 end
149
150 for local_class in local_classes do
151 ### extern methods
152 for prop in local_class.local_local_properties do
153 # if defined of redefined in this module
154 # and is extern
155 if prop.mmmodule == self and
156 prop isa MMSrcMethod and prop.is_extern then
157 prop.compile_extern_to_frontier( v )
158 end
159 end
160 end
161
162 v.header.add( "#endif\n" )
163 end
164 end
165
166 redef class MMSrcMethod
167 fun compile_extern_to_frontier( v : FrontierVisitor )
168 do
169 # defines types used in signature
170 if signature != null then
171 signature.compile_frontier( v )
172 end
173
174 for imported in explicit_imports do
175 # adds friendly access to property
176 v.friendlys.add( imported )
177
178 # defines relevant types
179 imported.signature.compile_frontier( v )
180 end
181
182 # adds casts and as verifications
183 for cast in explicit_casts do
184 v.casts.add( cast )
185
186 v.types.add( cast.from.direct_type )
187 v.types.add( cast.to.direct_type )
188 end
189
190 # adds super
191 if need_super then
192 compile_super_to_frontier( v )
193 end
194
195 # adds function in frontier to be called by pure nit
196 compile_out_to_frontier( v )
197 end
198
199 # Compiles body and header for the friendly super method.
200 # The friendly super method is called by custom native code and
201 # calls the generated C code to execute the real implementation.
202 # It handles types conversion and verifications.
203 fun compile_super_to_frontier( v : FrontierVisitor )
204 do
205 # header
206 v.header.add( "\n/* friendly for super of {full_name} */\n" )
207 v.header.add( "{frontier_super_csignature_from( mmmodule )};\n" )
208
209 # Defines a local name for simplier use, as with friendlys.
210 v.header.add( "#ifndef {friendly_super_cname}\n" )
211 v.header.add( "#define {friendly_super_cname} {local_friendly_super_name_from( mmmodule )}\n" )
212 v.header.add( "#endif\n" )
213
214 # body
215 v.body.add( "\n/* friendly for super of {full_name} */\n" )
216 var fc = new FunctionCompiler( friendly_super_csignature )
217
218 # params
219 var params = new Array[NiVariable]
220 params.add( signature.recv_ni_variable )
221 params.add_all( signature.params )
222
223 # prepare transition
224 for p in params do p.prepare_for_nit( fc )
225
226 # extract strings
227 var args = new Array[String]
228 for p in params do args.add( p.as_arg_to_nit )
229
230 # hook to generated C
231 var rnv = signature.return_ni_variable
232 var s = new Buffer
233 if rnv != null then
234 rnv.prepare_for_c( fc )
235 s.append( "{rnv.ni_from_name} = " )
236 end
237
238 s.append( "{super_meth_call}( {signature.recv_ni_variable.as_arg_to_nit} )" )
239 s.append( "( {args.join( ", " )} );\n" )
240
241 fc.exprs.add( s.to_s )
242
243 # return
244 if rnv != null then
245 fc.exprs.add( "{rnv.ni_type.assign_to_friendly( rnv.ni_to_name, rnv.ni_from_name )};\n" )
246 fc.exprs.add( "return {rnv.ni_to_name};\n" )
247 end
248
249 v.body.append( fc.to_writer )
250 end
251
252 # Compiles body and header for the out method.
253 # The out method is called by generated C code
254 # It handles variables conversions and verification
255 fun compile_out_to_frontier( v : FrontierVisitor )
256 do
257 # a simple out method can be optimized
258 # To qualify as simple this method must:
259 # - have no explicit imports (including super and casts)
260 # - return nothing or return a primitive to C
261 var is_simple = explicit_imports.is_empty and not need_super and
262 explicit_casts.is_empty and (signature.return_type == null or
263 signature.return_type.local_class.primitive_info != null )
264
265 # header
266 v.header.add( "\n/* out/indirect function for {full_name} */\n" )
267 v.header.add( "{out_csignature};\n" ) # incoming types boxed
268
269 # body
270 v.body.add( "/* out/indirect function for {full_name} */\n" )
271 var fc = new FunctionCompiler( out_csignature )
272
273 # params
274 var params = new List[NiVariable]
275 if not is_init then params.add( signature.recv_ni_variable )
276 params.add_all( signature.params )
277
278 var args = new List[String]
279
280 for nv in params do
281 if not is_simple or nv.ni_type.local_class.primitive_info != null then
282 nv.prepare_for_c( fc )
283 args.add( nv.as_arg_to_c )
284 else
285 args.add( "NULL" )
286 end
287 end
288
289 # call to impl
290 var rnv = signature.return_ni_variable
291 if rnv == null and is_init then
292 rnv = new ReturnVariable( signature.recv )
293 end
294
295 var s = new Buffer
296 if rnv != null then
297 rnv.prepare_for_nit( fc )
298 s.append( "{rnv.ni_from_name} = " )
299 end
300
301 s.append( "{extern_name.as(not null)}( {args.join( ", " )} );\n" )
302
303 fc.exprs.add( s.to_s )
304
305 if rnv != null then
306 fc.exprs.add( "{rnv.ni_type.assign_from_friendly( rnv.ni_to_name, rnv.ni_from_name )};\n" )
307 end
308
309 fc.exprs.add( "nitni_local_ref_clean( );\n" )
310
311 # return
312 if rnv != null then
313 fc.exprs.add( "return {rnv.ni_to_name};\n" )
314 end
315
316 v.body.append( fc.to_writer )
317 end
318
319 end
320
321 redef class MMSignature
322 var recv_ni_variable : ReceiverVariable
323 var return_ni_variable : nullable ReturnVariable
324 redef init( params, return_type, recv_type )
325 do
326 super
327
328 if return_type != null then
329 return_ni_variable = new ReturnVariable( return_type )
330 else
331 return_ni_variable = null
332 end
333 recv_ni_variable = new ReceiverVariable( recv_type )
334 end
335
336 fun compile_frontier( v : FrontierVisitor )
337 do
338 # receiver
339 v.types.add( recv.direct_type )
340
341 # params
342 for p in params do v.types.add( p.mmtype.direct_type )
343
344 # return
345 var rt = return_type
346 if rt != null then
347 v.types.add( rt.direct_type )
348 end
349 end
350 end
351
352 class FrontierVisitor
353 # frontier file header
354
355 # header comments, imports, guard and types
356 var header_top : Writer = new Writer
357
358 # rest of header
359 var header : Writer = new Writer
360
361 # frontier file body
362 var body : Writer = new Writer
363
364 # set of imported functions, cached to avoid repetitions
365 var friendlys : Set[ MMExplicitImport ] = new HashSet[ MMExplicitImport ]
366
367 # set of relevant types, cached to avoid repetitions
368 var types : Set[ MMType ] = new HashSet[ MMType ]
369
370 # set of imported casts and as, cached to avoid repetitions
371 var casts : Set[ MMImportedCast ] = new HashSet[ MMImportedCast ]
372
373 var mmmodule : MMModule
374
375 var cprogram : CProgram
376
377 fun compile_cached
378 do
379 # types
380 for t in types do t.compile_to_frontier( self )
381
382 # friendlys
383 for friendly in friendlys do friendly.compile_friendly_to_frontier( self )
384
385 # casts
386 for cast in casts do cast.compile_to_frontier( self )
387 end
388
389 fun write_to_files( base_path : String )
390 do
391 var path = "{base_path}._nitni.h"
392 var stream = new OFStream.open( path )
393 header_top.write_to_stream( stream )
394 header.write_to_stream( stream )
395 stream.close
396
397 path = "{base_path}._nitni.c"
398 stream = new OFStream.open( path )
399 body.write_to_stream( stream )
400 stream.close
401 end
402 end
403
404 redef class MMImportedCast
405 # Defines functions to cast types and verify the type of an object.
406 fun compile_to_frontier( v : FrontierVisitor )
407 do
408 # compile isa check
409 if not ( is_about_nullable_only and is_not_null_to_nullable ) then
410 v.header.add( "\n/* Type check for {from} with {to} */\n" )
411 v.header.add( "{is_a_local_csignature( v.mmmodule )};\n" )
412
413 v.header.add( "#ifndef {is_a_friendly_extern_name}\n" )
414 v.header.add( "#define {is_a_friendly_extern_name} {is_a_local_cname( v.mmmodule )}\n" )
415 v.header.add( "#endif\n" )
416
417 var fc = compile_is( v.mmmodule )
418 v.body.append( fc.to_writer )
419 end
420
421 # compile cast itself
422 v.header.add( "\n/* Cast for {from} to {to} */\n" )
423 v.header.add( "{as_local_csignature( v.mmmodule )};\n" )
424
425 v.header.add( "#ifndef {as_friendly_extern_name}\n" )
426 v.header.add( "#define {as_friendly_extern_name} {as_local_cname( v.mmmodule )}\n" )
427 v.header.add( "#endif\n" )
428
429 var fc = compile_as( v.mmmodule )
430 v.body.append( fc.to_writer )
431 end
432
433 # Compiles a function to cast an object to a different type.
434 # Verify type and if it is null.
435 fun compile_as( m : MMModule ) : FunctionCompiler
436 do
437 var fc = new FunctionCompiler( as_local_csignature( m ) )
438
439 var out_name = "out"
440 var temp_name = "temp"
441
442 fc.decls.add( "val_t {temp_name};\n" )
443 to.compile_new_local_ref( out_name, fc, true )
444
445 fc.exprs.add( "{from.assign_from_friendly(temp_name, in_name)};\n" )
446
447 # makes sur it is not null if it cannot be
448 if not to.is_nullable then
449 compile_check_is_not_null( fc, temp_name )
450 end
451
452 # makes sure it's the right type, unless it's only a cast about null
453 if not is_about_nullable_only then # inter types
454 to.compile_check_isa( fc, temp_name )
455 end
456
457 fc.exprs.add( "{to.assign_to_friendly(out_name, temp_name)};\n" )
458
459 fc.exprs.add( "return {out_name};\n" )
460
461 return fc
462 end
463
464 # Compiles a function to verify if an object is of the given type.
465 # Verify type and if it is null.
466 fun compile_is( m : MMModule ) : FunctionCompiler
467 do
468 var fc = new FunctionCompiler( is_a_local_csignature( m ) )
469
470 var temp_name = "temp"
471 fc.decls.add( "val_t {temp_name};\n" )
472
473 fc.exprs.add( "{from.assign_from_friendly(temp_name, in_name)};\n" )
474
475 if is_nullable_to_not_null then # from null
476 if is_about_nullable_only then # opposite, we want to know if null
477 fc.exprs.add( "if ( ! ISNULL({temp_name}) ) return 0;\n" )
478 else
479 fc.exprs.add( "if ( ISNULL({temp_name}) ) return 0;\n" )
480 end
481 end
482
483 if not is_about_nullable_only then # inter types
484 fc.exprs.add( "if ( ! {to.compile_condition_isa( temp_name )} ) return 0;\n" )
485 end
486
487 fc.exprs.add( "return 1;\n" )
488
489 return fc
490 end
491
492 # Compiles lines of code to check if an object is not null.
493 # Is to be nested within another function.
494 fun compile_check_is_not_null( fc : FunctionCompiler, name : String )
495 do
496 fc.exprs.add( "if ( ISNULL({name}) )\{" )
497 fc.exprs.add( "\tfprintf( stderr, \"Casting from {from} to {to} failed because value is null.\" );\n" )
498 fc.exprs.add( "\tabort();\n" )
499 fc.exprs.add( "\}" )
500 end
501
502 redef fun ==( other )
503 do
504 return other isa MMImportedCast and
505 other.from == from and other.to == to
506 end
507 redef fun hash
508 do
509 return from.hash + to.hash
510 end
511 end
512
513 redef class MMType
514 # Compiles a lines of code to ensure that an object is of the given type.
515 # Aborts when it is of the wrong type
516 # Does not check if it is null.
517 # Is to be nested within another function.
518 fun compile_check_isa( fc : FunctionCompiler, name : String )
519 do
520 fc.exprs.add( "if ( ! {compile_condition_isa( name )} )\{\n" )
521 fc.exprs.add( "\tfprintf( stderr, \"Casting to {self} failed because value is not a {self}.\" );\n" )
522 fc.exprs.add( "\tabort();\n" )
523 fc.exprs.add( "\}\n" )
524 end
525
526 # Compiles an expression to verify if an object is of the given type.
527 # To be nested within a condition.
528 fun compile_condition_isa( var_name : String ) : String
529 do
530 return "( ISOBJ( {var_name} ) ? OBJISA( {var_name}, {local_class.cname} ): VALISA( {var_name}, {local_class.cname} ) )"
531 end
532
533 # Defines a friendly type in C for a given Nit type.
534 # Standard Nit classes are kept within a struct.
535 fun compile_to_frontier( v : FrontierVisitor )
536 do
537 var pi = local_class.primitive_info
538 if pi == null or is_nullable then
539 var name = friendly_extern_name
540 var guard = "{name.to_s.to_upper}_TYPE"
541
542 # defines struct
543 v.header_top.add( "#ifndef {guard}\n" )
544 v.header_top.add( "#define {guard}\n" )
545 v.header_top.add( "struct s_{name}\{\n" )
546 v.header_top.add( "\t\tstruct nitni_ref ref; /* real ref struct, must be first */\n" )
547 v.header_top.add( "\};\n" )
548 v.header_top.add( "typedef struct s_{name} *{name};\n" )
549
550 # add null version, as a struct
551 if is_nullable then
552 var local_null_getter = local_friendly_null_getter_from( mmmodule )
553
554 v.header_top.add( "#ifndef {friendly_null_getter}\n" )
555 v.header_top.add( "#define {friendly_null_getter} {local_null_getter}\n" )
556 v.header_top.add( "#endif\n" )
557
558 v.header_top.add( "{name} {local_null_getter}();\n" )
559
560 var fc = new FunctionCompiler( "{name} {local_null_getter}()" )
561 compile_new_local_ref( "n", fc, true )
562 fc.exprs.add( "return n;\n" )
563 v.body.append( fc.to_writer )
564 end
565
566 # reference incr
567 var incr_name = "{as_notnull.mangled_name}_incr_ref"
568 v.header_top.add( "#define {incr_name}( x ) nitni_global_ref_incr( (struct nitni_ref*)(x) )\n" )
569
570 # reference decr
571 var decr_name = "{as_notnull.mangled_name}_decr_ref"
572 v.header_top.add( "#define {decr_name}( x ) nitni_global_ref_decr( (struct nitni_ref*)(x) )\n" )
573
574 v.header_top.add( "#endif\n" )
575 end
576 end
577
578 fun compile_new_local_ref( var_name : String, fc : FunctionCompiler, stack_it : Bool )
579 do
580 var type_name = friendly_extern_name
581
582 fc.decls.add( "{type_name} {var_name};\n" )
583 if uses_nitni_ref then
584 fc.exprs.add( "{var_name} = malloc( sizeof( struct s_{type_name} ) );\n" )
585 fc.exprs.add( "{var_name}->ref.val = NIT_NULL;\n" )
586 fc.exprs.add( "{var_name}->ref.count = 0;\n" )
587 if stack_it then
588 fc.exprs.add( "nitni_local_ref_add( (struct nitni_ref *){var_name} );\n" )
589 end
590 end
591 end
592
593 # compiles a stub local reference for unused references
594 # allows to maintain static typing but avoids malloc and free
595 fun compile_stub_local_ref( var_name : String, fc : FunctionCompiler )
596 do
597 var type_name = friendly_extern_name
598 fc.decls.add( "{type_name} {var_name};\n" )
599 if uses_nitni_ref then
600 fc.exprs.add( "{var_name} = ({type_name})NULL;\n" )
601 end
602 end
603 end
604
605 redef class MMExplicitImport
606 fun compile_friendly_to_frontier( v : FrontierVisitor )
607 do
608 # prototype in header
609 v.header.add( "/* friendly for {method.full_name} */\n" )
610 v.header.add( "{method.frontier_csignature_from( v.mmmodule, local_class )};\n" )
611
612 # Defines a simplier name to be used within this module and to prevent
613 # conflict with other modules importing the same friendly.
614 v.header.add( "#ifndef {method.friendly_extern_name( local_class )}\n" )
615 v.header.add( "#define {method.friendly_extern_name( local_class )} {method.local_friendly_name_from( v.mmmodule, local_class )}\n" )
616 v.header.add( "#endif\n" )
617
618 # implementation in body
619 v.body.add( "/* friendly for {method.full_name} */\n" )
620
621 var fc = new FunctionCompiler( method.frontier_csignature_from( v.mmmodule, local_class ) )
622
623 # params
624 var params = new Array[NiVariable]
625 if not method.is_init then params.add( signature.recv_ni_variable )
626 params.add_all( signature.params )
627
628 for nv in params do nv.prepare_for_nit( fc )
629
630 # handles return of method or constructor
631 var rnv = signature.return_ni_variable
632 if rnv == null and method.is_init then
633 rnv = new ReturnVariable( signature.recv )
634 end
635 var s = new Buffer
636 if rnv != null then
637 rnv.prepare_for_c( fc )
638 s.append( "{rnv.ni_from_name} = " )
639 end
640
641 # hook to generated C code
642 if method.is_init then
643 s.append( "NEW_{local_class}_{method.global.intro.cname}" )
644 else
645 s.append( "{method.global.meth_call}( {signature.recv_ni_variable.as_arg_to_nit} )" )
646 end
647
648 var args = new Array[String]
649 for p in params do args.add( p.as_arg_to_nit )
650
651 s.append( "( {args.join( ", " )} );\n" )
652
653 fc.exprs.add( s.to_s )
654
655 # return
656 if rnv != null then
657 fc.exprs.add( "{rnv.ni_type.assign_to_friendly( rnv.ni_to_name, rnv.ni_from_name )};\n" )
658 fc.exprs.add( "return {rnv.ni_to_name};\n" )
659 end
660
661 v.body.append( fc.to_writer )
662 end
663
664 redef fun hash
665 do
666 return method.global.to_s.hash + local_class.to_s.hash
667 end
668 redef fun == ( other )
669 do
670 return other isa MMExplicitImport and
671 method == other.method and local_class == other.local_class
672 end
673 end