3b53826b0f3706e0e8e8b0e0368a0d34612f5092
[nit.git] / src / ffi / ffi_base.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 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 # Tools and utilities for language targetted FFI implementations
18 module ffi_base
19
20 import c_tools
21 import parser
22 import modelbuilder
23 import nitni
24
25 redef class ToolContext
26 var ffi_language_assignation_phase: Phase = new FFILanguageAssignationPhase(self, null)
27 end
28
29 class FFILanguageAssignationPhase
30 super Phase
31
32 # All supported languages
33 var languages = new Array[FFILanguage]
34
35 redef fun process_nmodule(nmodule)
36 do
37 for block in nmodule.n_extern_code_blocks do
38 verify_foreign_code_on_node( block )
39 end
40 end
41
42 redef fun process_npropdef(npropdef)
43 do
44 if npropdef isa AMethPropdef then
45 var code_block = npropdef.n_extern_code_block
46 if code_block != null then
47 verify_foreign_code_on_node( code_block )
48 end
49 end
50 end
51
52 redef fun process_nclassdef(nclassdef)
53 do
54 if nclassdef isa AStdClassdef and nclassdef.n_extern_code_block != null then
55 verify_foreign_code_on_node( nclassdef.n_extern_code_block.as(not null) )
56 end
57 end
58
59 private fun verify_foreign_code_on_node(n: AExternCodeBlock)
60 do
61 var found = false
62 for v in languages do
63 var identified = v.identify_language(n)
64 if identified then
65 if found and identified then
66 toolcontext.error(n.location, "Two languages identified as possible handlers.")
67 end
68 n.language = v
69 found = true
70 end
71 end
72
73 if not found then toolcontext.error(n.location, "Unsupported language.")
74 end
75 end
76
77 redef class MModule
78 var ffi_files = new Array[ExternFile]
79
80 # Callbacks used by this module, classified by language
81 var ffi_callbacks = new HashMap[FFILanguage, Set[NitniCallback]]
82 end
83
84 redef class AExternCodeBlock
85 fun language_name: nullable String do
86 if n_in_language == null then return null
87 return n_in_language.n_string.without_quotes
88 end
89 fun language_name_lowered: nullable String do
90 if language_name == null then return null
91 return language_name.to_lower
92 end
93
94 fun code: String do return n_extern_code_segment.without_guard
95
96 var language: nullable FFILanguage = null
97 end
98
99 # Visitor for a specific languages. Works kinda like a `Phase` and is executed
100 # by a `Phase`.
101 class FFILanguage
102 init(ffi_language_assignation_phase: FFILanguageAssignationPhase)
103 do
104 ffi_language_assignation_phase.languages.add(self)
105 end
106
107 # Is this `block` written in this language?
108 fun identify_language(block: AExternCodeBlock ): Bool is abstract
109
110 # Generate wrapper code for this module/header code block
111 fun compile_module_block(block: AExternCodeBlock, ecc: CCompilationUnit, mmodule: MModule) is abstract
112
113 # Generate wrapper code for this extern method
114 fun compile_extern_method(block: AExternCodeBlock, m: AMethPropdef,
115 ecc: CCompilationUnit, nmodule: MModule) is abstract
116
117 # Generate wrapper code for this extern class
118 fun compile_extern_class(block: AExternCodeBlock, m: AClassdef,
119 ecc: CCompilationUnit, mmodule: MModule) is abstract
120
121 # Get the foreign type of this extern class definition
122 fun get_ftype(block: AExternCodeBlock, m: AClassdef): ForeignType is abstract
123
124 # Generate the code to offer this callback if foreign code
125 fun compile_callback(callback: NitniCallback, mmodule: MModule,
126 mainmmodule: MModule, ecc: CCompilationUnit) is abstract
127
128 # Complete compilation of generated code
129 fun compile_to_files(mmodule: MModule, directory: String) do end
130 end
131
132 redef class TString
133 # Returns the content of this node without both of the surrounding "
134 fun without_quotes: String
135 do
136 assert text.length >= 2
137 return text.substring(1, text.length-2)
138 end
139 end
140
141 redef class TExternCodeSegment
142 # Returns the content of this node without the surrounding `{ and `}
143 fun without_guard: String
144 do
145 assert text.length >= 4
146 return text.substring(2, text.length-4)
147 end
148 end
149
150 redef class CCompilationUnit
151 fun write_as_impl(mmodule: MModule, compdir: String)
152 do
153 var base_name = "{mmodule.name}._ffi"
154
155 var h_file = "{base_name}.h"
156 var guard = "{mmodule.cname.to_s.to_upper}_NIT_H"
157 write_header_to_file(mmodule, "{compdir}/{h_file}", new Array[String], guard)
158
159 var c_file = "{base_name}.c"
160 write_body_to_file(mmodule, "{compdir}/{c_file}", ["<stdlib.h>", "<stdio.h>", "\"{h_file}\""])
161
162 files.add( "{compdir}/{c_file}" )
163 end
164
165 fun write_header_to_file(mmodule: MModule, file: String, includes: Array[String], guard: String)
166 do
167 var stream = new OFStream.open( file )
168
169 # header comments
170 var module_info = "/*\n\tExtern implementation of Nit module {mmodule.name}\n*/\n"
171
172 stream.write( module_info )
173
174 stream.write( "#ifndef {guard}\n" )
175 stream.write( "#define {guard}\n\n" )
176
177 for incl in includes do stream.write( "#include {incl}\n" )
178
179 compile_header_core( stream )
180
181 # header file guard close
182 stream.write( "#endif\n" )
183 stream.close
184 end
185
186 fun write_body_to_file(mmodule: MModule, file: String, includes: Array[String])
187 do
188 var stream = new OFStream.open(file)
189
190 var module_info = "/*\n\tExtern implementation of Nit module {mmodule.name}\n*/\n"
191
192 stream.write( module_info )
193 for incl in includes do stream.write( "#include {incl}\n" )
194
195 compile_body_core( stream )
196
197 stream.close
198 end
199 end
200
201 class ForeignType
202 fun ctype: String do return "void*"
203 end