bindGen.rb 38.6 KB
Newer Older
1
2
#!/usr/bin/env ruby

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# This script generates a fortran source file that uses the ISO_C_BINDINGS to interface to the functions defined in the given C header file.
# The basic approach is, that every C function is wrapped in a fortran function/subroutine, which internally uses a bind(c) interface to the C code.
# This wrapper based approach has the advantage that the wrapper is free to provide a true fortran interface
# that enables full type checking of its arguments; the pure bind(c) interface would not be able to distinguish
# between different opaque pointer types, for instance, nor would it be able to infer the size of a static string returned by a C function.
#
# Within this header file, the following constructs are recognized:
#
#   * #define FOO 123
#   * typedef struct foo foo;
#   * typedef struct foo { ... } foo;
#   * ... foo(...);
#
# These constructs are used to divide a source line into parts that are recognizable by the templates defined below.
# A function definition, for instance, is divided into a return type, a function name, and a number of argument definitions,
# the return type and argument descriptions are matched against templates which define the translation of these parts into fortran code.
# Note that all these constructs must be one-liners since processing in this script is line based.
#
# Every template is a hash that contains an entry :regex, which is used to match it against the corresponding C declaration.
# There are a couple of placeholders that may be used within these regex strings, they are expanded by matchTemplate() before a Regexp object is constructed from the string in :regex.
# These placeholders are:
#	<integerTypes>	matches the C integer types that can be used within Fortran by prefixing 'c_' to the type
#	<floatTypes>	matches the C floating point types that can be used within Fortran by prefixing 'c_' to the type
#	<opaqueTypes>	matches all the opaque types defined within the header
#	<publicTypes>	matches all the public types defined within the header
#
# In the case of argument and type templates, this :regex may contain one or more named subexpressions /(?<name>...)/,
# which can be included in the other fields by means of a corresponding placeholder "<name>".
# The names of the subexpressions that are to be substituted in this way need to be listed in the :placeholders key.
# This is usually used to capture the variable name, and then use "<name>_foo" to derive fortran variable names from the argument name,
# but it may also be used to capture the size of an array declaration.
# Since fortran uses so many keywords that can easily conflict with C argument names, it is a good idea not to use a naked "<name>";
# always append something to it as in "<name>_dummy"
#
# Argument templates must provide the following fields:
#	:regex	A regex that matches the whole definition of a C argument. Make sure it only matches the cases that the template can actually handle!
#	:placeholders	An array of the name of the named subexpressions used in the regex. For the :regex => /(?<foo>.),(?<bar>.)/ you would use :placeholders => %w[foo bar]
#	:dummyName	The name of the fortran dummy argument. Both the wrapper function and the `bind(c)` interface use the same name.
#	:acceptAs	The declaration of the dummy argument in the fortran wrapper.
#	:helperVars	Declarations of additional variables needed to provide the desired functionality in the wrapper function.
#	:precallStatements	Code that needs to be executed before the C function is called.
#	:callExpression	The actual argument that the wrapper passes to the C function.
#	:passAs	The declaration of the dummy argument in the `bind(c)` interface.
#	:postcallStatements	Code that needs to be executed after the C function returns.
#
#
#
# Return type templates are similar to argument templates, but they have to deal with the fact that fortran differentiates between subroutines and functions. Because of this, return type templates add the :isVoid key which is only true if the C function returns `void`.
#
# Return type templates must provide the following fields:
#	:regex	A regex that matches the whole definition of a C return type. Make sure it only matches the cases that the template can actually handle!
#	:isVoid	Always false, except for the template for `void`.
#	:returnAs	The type of the fortran wrapper function.
#	:helperVars	Declarations of additional variables needed to provide the desired functionality in the wrapper function.
#	:precallStatements	Code that needs to be executed before the C function is called.
58
#	:receiveAs	The type of the `bind(c)` interface function.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#	:assignVariable	The expression that the result of the C function is assigned to.
#	:postcallStatements	Code that needs to be executed after the C function returns.
#
#
#
# Type templates are used for the variables in public `struct` definitions. These are much simpler as they only have to translate a C variable declaration into an interoperable fortran variable declaration.
#
# Type templates must provide the following fields:
#	:regex	A regex that matches the whole C variable definition. Make sure it only matches the cases that the template can actually handle!
#	:placeholders	An array of the name of the named subexpressions used in the regex. Same semantics as in an argument template.
#	:declareAs	The declaration of the corresponding fortran derived type member.
#
#
#
# The wrapper that is generated for a non-void C function looks like this:
#
#	function fname(:dummyName...) result(result)
#		:returnAs :: result
#		:acceptAs...
#		:helperVars...
#		interface
80
#			:receiveAs function lib_fname(:dummyName...) bind(c, name = 'fname')
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#				import <importConstants>
#				:passAs...
#			end function lib_fname
#		end interface
#		:precallStatements
#		:assignVariable = lib_fname(:callExpression)
#		:postcallStatements
#	end function fname
#
#
#
# The wrapper that is generated for a void C function looks like this:
#
#	subroutine fname(:dummyName...)
#		:acceptAs...
#		:helperVars...
#		interface
#			subroutine lib_fname(:dummyName...) bind(c, name = 'fname')
#				import <importConstants>
#				:passAs...
#			end subroutine lib_fname
#		end interface
#		:precallStatements
#		call lib_fname(:callExpression)
#		:postcallStatements
#	end subroutine fname

108
$debug = 0
Thomas Jahns's avatar
Thomas Jahns committed
109
$wrapperResultVarName = 'f_result'
110

111
112
113
114
####################################################################################################
# Template definitions #############################################################################
####################################################################################################

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
$argumentTemplates =
	[
	 {	#Dummy for declarations using foo(void).
		 :regex => '^\s*void\s*$',
		 :placeholders => %w[],
		 :dummyName => '',
		 :acceptAs => '',
		 :helperVars => '',
		 :precallStatements => '',
		 :callExpression => '',
		 :passAs => '',
		 :postcallStatements => ''
	 }, {	#<integerTypes>
		 :regex => '^\s*(?<type><integerTypes>)\s+(?<name>\w+)\s*$',
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(c_<type>), value :: <name>_dummy',
		 :helperVars => '',
		 :precallStatements => '',
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(c_<type>), value :: <name>_dummy',
		 :postcallStatements => ''
	 }, {	#<floatTypes>
		 :regex => '^\s*(?<type><floatTypes>)\s+(?<name>\w+)\s*$',
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'real(c_<type>), value :: <name>_dummy',
		 :helperVars => '',
		 :precallStatements => '',
		 :callExpression => '<name>_dummy',
		 :passAs => 'real(c_<type>), value :: <name>_dummy',
		 :postcallStatements => ''
	 },
	 #Array arguments. These are marked by a `_vec` suffix by convention.
	 #Since it's near impossible to write regexs that only match names that do *not* end in a given suffix,
	 #these templates must precede the more general templates for pointer arguments.
	 #That way, we can override the more general template with the more special one if both match.
	 {	#<integerTypes>* <name>_vec
153
		 :regex => '^\s*(?<type><integerTypes>)\s*(?:\*\s*(?<name>\w+_vec)|(?<name>\w+)\[\])\s*$',
154
155
156
157
158
159
160
161
162
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(c_<type>), intent(inout) :: <name>_dummy(*)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(c_<type>), intent(inout) :: <name>_dummy(*)',
		 :postcallStatements => ""
	 }, {	#<floatTypes>* <name>_vec
163
		 :regex => '^\s*(?<type><floatTypes>)\s*(?:\*\s*(?<name>\w+_vec)|(?<name>\w+)\[\])\s*$',
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'real(c_<type>), intent(inout) :: <name>_dummy(*)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'real(c_<type>), intent(inout) :: <name>_dummy(*)',
		 :postcallStatements => ""
	 }, {	#unsigned char <name>[<size>]
		 :regex => '^\s*unsigned\s+char\s+(?<name>\w+)\s*\[\s*(?<size>[^\]]+)\s*\]\s*$',
		 :placeholders => %w[name size],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(kind = c_signed_char), intent(inout) :: <name>_dummy(<size>)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(kind = c_signed_char), intent(inout) :: <name>_dummy(<size>)',
		 :postcallStatements => ""
	 }, {	#const <integerTypes>* <name>_vec
183
		 :regex => '^\s*const\s+(?<type><integerTypes>)\s*(?:\*\s*(?<name>\w+_vec)|(?<name>\w+)\[\])\s*$',
184
185
186
187
188
189
190
191
192
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(c_<type>), intent(in) :: <name>_dummy(*)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(c_<type>), intent(in) :: <name>_dummy(*)',
		 :postcallStatements => ""
	 }, {	#const <floatTypes>* <name>_vec
193
		 :regex => '^\s*const\s+(?<type><floatTypes>)\s*(?:\*\s*(?<name>\w+_vec)|(?<name>\w+)\[\])\s*$',
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'real(c_<type>), intent(in) :: <name>_dummy(*)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'real(c_<type>), intent(in) :: <name>_dummy(*)',
		 :postcallStatements => ""
	 }, {	#const unsigned char <name>[<size>]
		 :regex => '^\s*(const\s+unsigned\s+char|unsigned\s+char\s+const)\s+(?<name>\w+)\s*\[\s*(?<size>[^\]]+)\s*\]\s*$',
		 :placeholders => %w[name size],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(kind = c_signed_char), intent(in) :: <name>_dummy(<size>)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(kind = c_signed_char), intent(in) :: <name>_dummy(<size>)',
		 :postcallStatements => ""
	 }, {	#const <integerTypes> <name>[<lineCount>][<lineSize>]
		 :regex => '^\s*const\s+(?<type><integerTypes>)\s+(?<name>\w+)\s*\[\s*(?<lineCount>[^\]]+)\s*\]\s*\[\s*(?<lineSize>[^\]]+)\s*\]\s*$',
		 :placeholders => %w[name type lineCount lineSize],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(c_<type>), intent(in) :: <name>_dummy(<lineSize>, <lineCount>)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(c_<type>), intent(in) :: <name>_dummy(<lineSize>, <lineCount>)',
		 :postcallStatements => ""
	 },
	 #Optional pointer arguments. These match both pointers and arrays,
	 #so they must appear after the more special array templates.  Most
	 #of these are wrapped by optional arguments which have to be named
	 #in calling code, which is why we don't use the _dummy suffix for
	 #them.
	 {	#<integerTypes>*
		 :regex => '^\s*(?<type><integerTypes>)\s*\*\s*(?<name>\w+_optional)\s*$',
		 :placeholders => %w[name type],
		 :dummyName => '<name>',
		 :acceptAs => 'integer(c_<type>), optional, intent(inout) :: <name>',
		 :helperVars => "integer(c_<type>), target :: <name>_temp\ntype(c_ptr) :: <name>_ptr",
		 :precallStatements => "<name>_ptr = c_null_ptr\nif(present(<name>)) <name>_ptr = c_loc(<name>_temp)",
		 :callExpression => '<name>_ptr',
		 :passAs => 'type(c_ptr), value :: <name>',
		 :postcallStatements => "if(present(<name>)) <name> = <name>_temp"
	 }, {	#<floatTypes>*
		 :regex => '^\s*(?<type><floatTypes>)\s*\*\s*(?<name>\w+_optional)\s*$',
		 :placeholders => %w[name type],
		 :dummyName => '<name>',
		 :acceptAs => 'real(c_<type>), optional, intent(inout) :: <name>',
		 :helperVars => "real(c_<type>), target :: <name>_temp\ntype(c_ptr) :: <name>_ptr",
		 :precallStatements => "<name>_ptr = c_null_ptr\nif(present(<name>)) <name>_ptr = c_loc(<name>_temp)",
		 :callExpression => '<name>_ptr',
		 :passAs => 'type(c_ptr), value :: <name>',
		 :postcallStatements => "if(present(<name>)) <name> = <name>_temp"
	 }, {	#unsigned char (*<name>)[<size>]
		 :regex => '^\s*unsigned\s+char\s*\(\s*\*\s*(?<name>\w+_optional)\s*\)\s*\[\s*(?<size>[^\]]+)\s*\]\s*$',
		 :placeholders => %w[name size],
		 :dummyName => '<name>',
		 :acceptAs => 'integer(kind = c_signed_char), optional, intent(inout) :: <name>(<size>)',
		 :helperVars => "integer(kind = c_signed_char), target :: <name>_temp(<size>)\ntype(c_ptr) :: <name>_ptr",
		 :precallStatements => "<name>_ptr = c_null_ptr\nif(present(<name>)) <name>_ptr = c_loc(<name>_temp)",
		 :callExpression => '<name>_ptr',
		 :passAs => 'type(c_ptr), value :: <name>',
		 :postcallStatements => "if(present(<name>)) <name> = <name>_temp"
	 },
	 #Non-optional pointer arguments. These match both pointers and
	 #arrays, so they must appear after the more special array templates.
	 {	#<integerTypes>*
		 :regex => '^\s*(?<type><integerTypes>)\s*\*\s*(?<name>\w+)\s*$',
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(c_<type>), intent(inout) :: <name>_dummy',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(c_<type>), intent(inout) :: <name>_dummy',
		 :postcallStatements => ""
	 }, {	#<floatTypes>*
		 :regex => '^\s*(?<type><floatTypes>)\s*\*\s*(?<name>\w+)\s*$',
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'real(c_<type>), intent(inout) :: <name>_dummy',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'real(c_<type>), intent(inout) :: <name>_dummy',
		 :postcallStatements => ""
	 }, {	#unsigned char (*<name>)[<size>]
		 :regex => '^\s*unsigned\s+char\s*\(\s*\*\s*(?<name>\w+)\s*\)\s*\[\s*(?<size>[^\]]+)\s*\]\s*$',
		 :placeholders => %w[name size],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'integer(kind = c_signed_char), intent(inout) :: <name>(<size>)',
		 :helperVars => "",
		 :precallStatements => "",
		 :callExpression => '<name>_dummy',
		 :passAs => 'integer(kind = c_signed_char), intent(inout) :: <name>(<size>)',
		 :postcallStatements => ""
	 },
	 #String arguments.
	 {	#char*	Unsafe buffer passing
		 :regex => '^\s*char\s*\*\s*(?<name>\w+)\s*$',
		 :placeholders => %w[name],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'character(kind = c_char, len = *), intent(inout) :: <name>_dummy',
		 :helperVars => "character(kind = c_char) :: <name>_temp(len(<name>_dummy) + 1)\n" +
		 "integer :: <name>_i",
		 :precallStatements => "<name>_temp(len(<name>_dummy) + 1) = c_null_char\n" +
		 "do <name>_i = len(<name>_dummy), 1, -1\n" +
		 "\tif(<name>_dummy(<name>_i:<name>_i) /= ' ') exit\n" +
		 "\t<name>_temp(<name>_i) = c_null_char\n" +
		 "end do\n" +
		 "do <name>_i = <name>_i, 1, -1\n" +
		 "\t\t<name>_temp(<name>_i) = <name>_dummy(<name>_i:<name>_i)\n" +
		 "end do",
		 :callExpression => '<name>_temp',
		 :passAs => 'character(kind = c_char) :: <name>_dummy(*)',
		 :postcallStatements => "do <name>_i = 1, len(<name>_dummy)\n" +
		 "\tif(<name>_temp(<name>_i) == c_null_char) exit\n" +
		 "\t<name>_dummy(<name>_i:<name>_i) = <name>_temp(<name>_i)\n" +
		 "end do\n" +
		 "do <name>_i = <name>_i, len(<name>_dummy)\n" +
		 "\t<name>_dummy(<name>_i:<name>_i) = ' '\n" +
		 "end do"
	 }, {	#const char*	Safe passing of an input string.
		 :regex => '^\s*(const\s+char|char\sconst)\s*\*\s*(?<name>\w+)\s*$',
		 :placeholders => %w[name],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'character(kind = c_char, len = *), intent(in) :: <name>_dummy',
		 :helperVars => "character(kind = c_char) :: <name>_temp(len(<name>_dummy) + 1)\ninteger :: <name>_i",
		 :precallStatements => "do <name>_i = 1, len(<name>_dummy)\n\t<name>_temp(<name>_i) = <name>_dummy(<name>_i:<name>_i)\nend do\n<name>_temp(len(<name>_dummy) + 1) = c_null_char",
		 :callExpression => '<name>_temp',
		 :passAs => 'character(kind = c_char) :: <name>_dummy(*)',
		 :postcallStatements => ''
	 }, {	#char**	Safe returning of an output string.
		 :regex => '^\s*char\s*\*\s*\*\s*(?<name>\w+)\s*$',
		 :placeholders => %w[name],
		 :dummyName => '<name>',
		 :acceptAs => 'character(kind = c_char), pointer, optional, intent(inout) :: <name>(:)',
		 :helperVars => "type(c_ptr), target :: <name>_ptr\n" +
		 "type(c_ptr) :: <name>_handle\n" +
		 "integer :: <name>_shape(1)\n" +
		 "character(kind = c_char), pointer :: <name>_fptr(:)",
		 :precallStatements => "<name>_handle = c_null_ptr\n" +
		 "if(present(<name>)) <name>_handle = c_loc(<name>_ptr)",
		 :callExpression => '<name>_handle',
		 :passAs => 'type(c_ptr), value :: <name>',
		 :postcallStatements => "if(present(<name>)) then\n" +
		 "\tif(c_associated(<name>_ptr)) then\n" +
		 "\t\t<name>_shape(1) = int(lib_strlen(<name>_ptr))\n" +
		 "\t\tcall c_f_pointer(<name>_ptr, <name>_fptr, <name>_shape)\n" +
		 "\t\tallocate(<name>(<name>_shape(1)))\n" +
		 "\t\t<name> = <name>_fptr\n" +
		 "\t\tcall lib_free(<name>_ptr)\n" +
		 "\telse\n" +
		 "\t\t<name> => null()\n" +
		 "\tend if\n" +
		 "end if"
	 },
	 #Public and opaque types
	 {	#[const] <opaqueTypes>*
		 :regex => '^\s*(const\s+|)(?<type><opaqueTypes>)(\s+const|)\s*\*\s*(?<name>\w+)\s*$',
		 :placeholders => %w[name type],
		 :dummyName => '<name>_dummy',
		 :acceptAs => 'type(t_<type>), intent(in) :: <name>_dummy',
		 :helperVars => '',
		 :precallStatements => '',
		 :callExpression => '<name>_dummy%ptr',
		 :passAs => 'type(c_ptr), value :: <name>_dummy',
		 :postcallStatements => ''
	 }
	]
365
366
367
368
369
370
371
372
373
374
375
376
377

$returnTypeTemplates = [
	{	#void
		:regex => '^\s*void\s*$',
		:placeholders => %w[],
		:isVoid => true
	}, {	#<integerTypes>
		:regex => '^\s*(?<type><integerTypes>)\s*$',
		:placeholders => %w[type],
		:isVoid => false,
		:returnAs => 'integer(c_<type>)',
		:helperVars => '',
		:precallStatements => '',
378
		:receiveAs => 'integer(c_<type>)',
Thomas Jahns's avatar
Thomas Jahns committed
379
		:assignVariable => $wrapperResultVarName,
380
381
382
383
384
385
386
387
		:postcallStatements => ''
	}, {	#<floatTypes>
		:regex => '^\s*(?<type><floatTypes>)\s*$',
		:placeholders => %w[type],
		:isVoid => false,
		:returnAs => 'real(c_<type>)',
		:helperVars => '',
		:precallStatements => '',
388
		:receiveAs => 'real(c_<type>)',
Thomas Jahns's avatar
Thomas Jahns committed
389
		:assignVariable => $wrapperResultVarName,
390
391
392
393
394
395
396
397
398
399
		:postcallStatements => ''
	}, {	#char*
		:regex => '^\s*char\s*\*\s*$',
		:placeholders => %w[],
		:isVoid => false,
		:returnAs => 'character(kind = c_char), dimension(:), pointer',
		:helperVars => "type(c_ptr) :: cString\n" +
		               "integer :: shape(1)\n" +
		               "character(kind = c_char), dimension(:), pointer :: temp",
		:precallStatements => '',
400
		:receiveAs => 'type(c_ptr)',
401
402
403
404
		:assignVariable => 'cString',
		:postcallStatements => "if(c_associated(cString)) then\n" +
		                       "\tshape(1) = int(lib_strlen(cString))\n" +
		                       "\tcall c_f_pointer(cString, temp, shape)\n" +
Thomas Jahns's avatar
Thomas Jahns committed
405
406
		                       "\tallocate(#{$wrapperResultVarName}(shape(1)))\n" +
		                       "\t#{$wrapperResultVarName} = temp\n" +
407
408
		                       "\tcall lib_free(cString)\n" +
		                       "else\n" +
Thomas Jahns's avatar
Thomas Jahns committed
409
		                       "\t#{$wrapperResultVarName} => null()\n" +
410
411
412
413
414
415
416
		                       "end if"
	}, {	#const char*
		:regex => '^\s*const\s+char\s*\*\s*$',
		:placeholders => %w[],
		:isVoid => false,
		:returnAs => 'character(kind = c_char), dimension(:), pointer',
		:helperVars => "type(c_ptr) :: ptr\ninteger :: shape(1)",
Thomas Jahns's avatar
Thomas Jahns committed
417
		:precallStatements => $wrapperResultVarName + ' => null()',
418
		:receiveAs => 'type(c_ptr)',
419
420
421
		:assignVariable => 'ptr',
		:postcallStatements => "if(c_associated(ptr)) then\n" +
		                       "\tshape(1) = int(lib_strlen(ptr))\n" +
Thomas Jahns's avatar
Thomas Jahns committed
422
		                       "\tcall c_f_pointer(ptr, #{$wrapperResultVarName}, shape)\n" +
423
424
425
426
427
428
429
430
		                       "end if"
	}, {	#const int*	This returns the naked pointer because we can't know the length of the returned array within the wrapper. The user has to call c_f_pointer() himself.
		:regex => '^\s*const\s+(?<type><integerTypes>)\s*\*\s*$',
		:placeholders => %w[type],
		:isVoid => false,
		:returnAs => 'type(c_ptr)',
		:helperVars => '',
		:precallStatements => '',
431
		:receiveAs => 'type(c_ptr)',
Thomas Jahns's avatar
Thomas Jahns committed
432
		:assignVariable => $wrapperResultVarName,
433
434
435
436
437
438
439
440
		:postcallStatements => ''
	}, {	#const double*	This returns the naked pointer because we can't know the length of the returned array within the wrapper. The user has to call c_f_pointer() himself.
		:regex => '^\s*const\s+(?<type><floatTypes>)\s*\*\s*$',
		:placeholders => %w[type],
		:isVoid => false,
		:returnAs => 'type(c_ptr)',
		:helperVars => '',
		:precallStatements => '',
441
		:receiveAs => 'type(c_ptr)',
Thomas Jahns's avatar
Thomas Jahns committed
442
		:assignVariable => $wrapperResultVarName,
443
444
445
446
447
448
449
450
451
452
		:postcallStatements => ''
	},
	#Public and opaque types.
	{	#<publicTypes>
		:regex => '^\s*(?<type><publicTypes>)\s+$',
		:placeholders => %w[type],
		:isVoid => false,
		:returnAs => 'type(t_<type>)',
		:helperVars => '',
		:precallStatements => '',
453
		:receiveAs => 'type(t_<type>)',
Thomas Jahns's avatar
Thomas Jahns committed
454
		:assignVariable => $wrapperResultVarName,
455
456
457
458
459
460
461
462
		:postcallStatements => ''
	}, {	#<opaqueTypes>*
		:regex => '^\s*(?<type><opaqueTypes>)\s*\*\s*$',
		:placeholders => %w[type],
		:isVoid => false,
		:returnAs => 'type(t_<type>)',
		:helperVars => '',
		:precallStatements => '',
463
		:receiveAs => 'type(c_ptr)',
Thomas Jahns's avatar
Thomas Jahns committed
464
		:assignVariable => "#{$wrapperResultVarName}%ptr",
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
		:postcallStatements => ''
	}
]

$typeTemplates = [
	{	#<integerTypes>
		:regex => '^\s*(?<type><integerTypes>)\s+(?<name>\w+)\s*;$',
		:placeholders => %w[name type],
		:declareAs => "integer(c_<type>) :: <name>"
	}, {	#<floatTypes>
		:regex => '^\s*(?<type><floatTypes>)\s+(?<name>\w+)\s*;$',
		:placeholders => %w[name type],
		:declareAs => "real(c_<type>) :: <name>"
	}
]

####################################################################################################
# Verbatim Fortran Code ############################################################################
####################################################################################################

$verbatimDeclarations = '
	public ctrim
	public c_len

	interface
		integer(c_size_t) function lib_strlen(charPtr) bind(c, name = "strlen")
			import c_size_t, c_ptr
			type(c_ptr), value :: charPtr
		end function lib_strlen

		subroutine lib_free(pointer) bind(c, name = "free")
			import c_ptr
			type(c_ptr), value :: pointer
		end subroutine lib_free
	end interface
'

$verbatimDefinitions = "
	subroutine ctrim(str)
		character(kind = c_char, len = *), intent(inout) :: str
		integer :: i

		do i=1,len(str)
			if (str(i:i) == c_null_char) then
				str(i:len(str)) = ' '
				exit
			end if
		end do
	end subroutine ctrim

	function c_len(s) result(i)
		character(kind = c_char, len = *), intent(in) :: s
		integer :: i

		do i = 1, len(s)
			if (s(i:i) == c_null_char) exit
		end do
		i = i - 1
	end function
"

####################################################################################################
# Code to interpret the templates ##################################################################
####################################################################################################

$declarationLines = []
$definitionLines = []
532
$interfaceLines = []
533
534
535
$opaqueTypes = []
$publicTypes = []

Uwe Schulzweida's avatar
Uwe Schulzweida committed
536
537
538
539
540
541
542
543
544
545
546
def rubyVersionOk()
       version = RUBY_VERSION.split(".")
       if version[0].to_i > 1
               return true
       elsif version[0].to_i == 1
               return version[1].to_i >= 9
       else
               return false
       end
end

547
548
#This substitutes the placeholders <opaqueTypes> and <publicTypes> in the regexString prior to constructing a Regexp out of it.
def matchTemplate(regexString, matchString)
549
	opaqueTypesString = '(' + $opaqueTypes.collect{ |type| type	}.join('|') + ')'
550
	regexString = regexString.gsub("<opaqueTypes>", opaqueTypesString)
551
552
553
554
	publicTypesString = '(' + $publicTypes.collect{ |type| type }.join('|') + ')'
	regexString = regexString.gsub('<publicTypes>', publicTypesString)
	regexString = regexString.gsub('<integerTypes>', '(short|int|long|size_t|intmax_t|int_(least|fast)(8|16|32|64)_t)')
	regexString = regexString.gsub('<floatTypes>',  '(float|double)')
555
	return Regexp.new(regexString).match(matchString)
556
557
end

558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
class TemplateInstanciation
	def initialize(argumentString, template)
		@template = template
		@matchData = matchTemplate(template[:regex], argumentString)
		@placeholders = []
		template[:placeholders].each { |placeholder|
			@placeholders.push({ :name => placeholder, :regex => Regexp.new("<#{placeholder}>") })
		}
	end

	def expandTemplate(templateKey)
		result = @template[templateKey]
		#Replace all placeholders with their expansion.
		@placeholders.each { |current|
			result = result.gsub(current[:regex], @matchData[current[:name]])
		}
		return result
	end
576
577
578
579
580
	def nonEmptyKey?(templateKey)
		result = @template[templateKey] != ''
		return result
	end
	attr_reader :template
581
582
end

583
def formatLines(lineArray, indentation, string)
584
	$stderr.puts("Formatting '" + string + "'") if $debug > 3
585
586
587
588
589
590
	if string == "" && indentation == 0
		lineArray.push("")	#split() does not return anything if the string is empty, killing our empty lines
	end
	string.split("\n").each { |line|
		lineArray.push("\t"*indentation + line)
	}
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
	tail = ''
	if lineArray.length > 1
		tail = lineArray[-2..-1].join("\n")
	else
		tail = lineArray[-1]
	end
	$stderr.puts("Tail '" + tail + "'") if $debug > 3
end

def haveTemplateKey(templates, templateKey)
	result = false
	templates.count{ |template|
		result ||= template.nonEmptyKey?(templateKey)
		break if result
	}
	return result
607
608
end

609
610

def dumpStatements(indentation, argumentArray, templateKey, outputArray)
611
	argumentArray.each{ |argument|
612
		formatLines(outputArray, indentation, argument.expandTemplate(templateKey))
613
	}
614
615
end

616
617
618
619
def defineConstant(name, value)
	if /^(\+|-|)\d+$/.match(value)
		formatLines($declarationLines, 1, "integer(c_int), public, parameter :: #{name} = #{value}")
	else
620
		$stderr.puts("Error: value '#{value}' of constant '#{name}' is not an integer literal")
621
	end
622
end
623
624
625

def defineOpaqueType(name)
	formatLines($declarationLines, 0, "")
626
627
	formatLines($declarationLines, 1, "public :: t_#{name}")
	formatLines($declarationLines, 1, "type :: t_#{name}")
628
629
630
	formatLines($declarationLines, 2, "type(c_ptr) :: ptr")
	formatLines($declarationLines, 1, "end type t_#{name}")
	$opaqueTypes.push(name)
631
632
end

633
634
635
636
637
638
639
def findTemplate(string, templateArray)
	templateArray.each do |template|
		if matchTemplate(template[:regex], string)
			return template
		end
	end
	return nil
640
641
end

642
643
644
645
646
647
648
649
650
def definePublicType(name, body)
	formatLines($declarationLines, 0, "")
	formatLines($declarationLines, 1, "public t_#{name}")
	formatLines($declarationLines, 1, "type, bind(c) :: t_#{name}")
	body.gsub(/[^;]+;/) do |variableDeclaration|
		if template = findTemplate(variableDeclaration, $typeTemplates)
			variable = TemplateInstanciation.new(variableDeclaration, template)
			formatLines($declarationLines, 2, "#{variable.expandTemplate(:declareAs)}")
		else
651
			$stderr.puts("Error: Can't translate the declaration '#{variableDeclaration}'")
652
653
654
655
		end
	end
	formatLines($declarationLines, 1, "end type t_#{name}")
	$publicTypes.push(name)
656
657
end

658
def collectImportConstants(importConstantsArray, typeString)
659
	$stderr.puts('Considering \'' + typeString + "' for import\n") if $debug > 2
660
661
662
	if importConstant = typeString[/\b[ct]_\w+\b/]
		importConstantsArray.push(importConstant)
	end
Thomas Jahns's avatar
Thomas Jahns committed
663
664
end

665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def collectArrayBoundImports(importConstantsArray, argPassString)
	if array_bounds_match =
			/(?<=\()\s*(?:[a-zA-Z_]\w*|:|\d+)\s*(?:,\s*(?:[a-zA-Z_]\w*|:|\d+)\s*?)*(?=\s*\)$)/.match(argPassString)
		$stderr.puts('Found array bounds: \'' +
								 array_bounds_match.to_a.join('\', \'') + "'",
								 'for \'' + argPassString + "'") if $debug > 3
		array_bounds_match = array_bounds_match[0]
		array_bounds_match.lstrip!
		array_bounds_match = array_bounds_match.split(/\s*,\s*/)
		array_bounds_match.select! do |bound|
			bound != ':' && bound !~ /^\d+$/
		end
		$stderr.puts('Possible import symbols in array bounds: \'' +
								 array_bounds_match.join('\', \'') + "'") if $debug > 3
		importConstantsArray.push(*array_bounds_match)
	end
end

683
684
685
686
687
#Collect the c_* and t_* constants/types from the arguments and the return type and build the corresponding `import` statement from them.
def importStatement(returnType, argumentArray)
	importConstants = []
	collectImportConstants(importConstants, returnType)
	argumentArray.each { |arg|
688
689
690
		argStr = arg.expandTemplate(:passAs)
		collectArrayBoundImports(importConstants, argStr)
		collectImportConstants(importConstants, argStr)
691
	}
692
693
694
	$stderr.puts('Returning \'' + importConstants.sort.uniq.join(', ') +
							 "' for import\n") if $debug > 2
	return (importConstants.length != 0) ? ('import ' + importConstants.sort.uniq.join(', ')) : ''
695
end
696
697
698
699
700
701
702
703
704
705

def defineFunction(name, arguments, returnType)
	#Find the relevant templates.
	if returnTemplate = findTemplate(returnType, $returnTypeTemplates)
		returnData = TemplateInstanciation.new(returnType, returnTemplate)
		argArray = []
		arguments.gsub(/[^,]+/) do |argument|
			if template = findTemplate(argument, $argumentTemplates)
				argArray.push(TemplateInstanciation.new(argument, template))
			else
706
				$stderr.puts("Error: type of argument '#{argument}' to function #{name}() is not supported")
707
708
709
710
				return
			end
		end
	else
711
		$stderr.puts("Error: Can't translate return type '#{returnType}' of function #{name}()")
712
713
714
		return
	end

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
	needArgPrologue = haveTemplateKey(argArray, :precallStatements)
	needRetValPrologue = !returnTemplate[:isVoid] &&
		returnData.nonEmptyKey?(:precallStatements)
	needArgEpilogue = haveTemplateKey(argArray, :postcallStatements)
	needRetValEpilogue = !returnTemplate[:isVoid] &&
		returnData.nonEmptyKey?(:postcallStatements)
	needRetValConversion = !returnTemplate[:isVoid] &&
		returnTemplate[:returnAs] != returnTemplate[:receiveAs]
	needArgConversion = false
	argArray.each do |arg|
		needArgConversion = (arg.template[:passAs] != arg.template[:acceptAs])
		break if needArgConversion
	end

	needWrapper = needArgPrologue || needRetValPrologue ||
		needArgEpilogue || needRetValEpilogue ||
		needRetValConversion || needArgConversion
	baseIndent = 0
	formatLines($declarationLines, 1, 'public :: ' + name)
	$stderr.puts(name + "\n" +
							 [ "\t"+'needArgPrologue => ' + needArgPrologue.to_s,
								 "\t"+'needRetValPrologue => ' + needRetValPrologue.to_s,
								 "\t"+'needArgEpilogue => ' + needArgEpilogue.to_s,
								 "\t"+'needRetValEpilogue => ' + needRetValEpilogue.to_s,
								 "\t"+'needRetValConversion => ' + needRetValConversion.to_s,
								 "\t"+'needArgConversion => ' + needArgConversion.to_s,
								 "\t"+'needWrapper => ' +
		needWrapper.to_s].join("\n")) if $debug > 1
	subprogramtype = returnTemplate[:isVoid] ? 'subroutine' : 'function'
744
745
746
	dummyArguments = argArray.collect{ |arg|
		arg.expandTemplate(:dummyName)
	}.join(", ")
747
748
749
	if needWrapper
		#Generate the wrapper function.
		line = subprogramtype + ' ' + name + '(' + dummyArguments + ')' +
Thomas Jahns's avatar
Thomas Jahns committed
750
			(returnTemplate[:isVoid] ? '' : " result(#{$wrapperResultVarName})")
751
752
753
		formatLines($definitionLines, 1, line)
		if !returnTemplate[:isVoid]
			formatLines($definitionLines, 2,
Thomas Jahns's avatar
Thomas Jahns committed
754
755
									returnData.expandTemplate(:returnAs) + ' :: ' +
									$wrapperResultVarName)
756
757
758
759
760
761
762
763
764
765
766
		end
		dumpStatements(               2, argArray, :acceptAs, $definitionLines)
		dumpStatements(               2, argArray, :helperVars, $definitionLines)
		if !returnTemplate[:isVoid]
			formatLines($definitionLines, 2, returnData.expandTemplate(:helperVars))
		end
		formatLines($definitionLines, 2, 'interface')
		line=subprogramtype + ' lib_' + name + '(' + dummyArguments + ') ' +
			'bind(c, name = \'' + name + '\')' +
			(returnTemplate[:isVoid] ? '' : ' result(c_result)')
		formatLines($definitionLines, 3, line)
767
		formatLines($definitionLines, 4,
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
								importStatement(returnTemplate[:isVoid] ? '' :
																returnData.expandTemplate(:receiveAs), argArray))
		if !returnTemplate[:isVoid]
			formatLines($definitionLines, 4,
									returnData.expandTemplate(:receiveAs) + ' :: c_result')
		end
		dumpStatements(               4, argArray, :passAs, $definitionLines)
		formatLines($definitionLines, 3, 'end ' + subprogramtype + ' lib_' + name)
		formatLines($definitionLines, 2, 'end interface')
		if needArgPrologue
			dumpStatements(               2, argArray, :precallStatements, $definitionLines)
		end
		if !returnTemplate[:isVoid]
			formatLines($definitionLines, 2,
									returnData.expandTemplate(:precallStatements))
		end
784
		formatLines($definitionLines, 2,
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
								(returnTemplate[:isVoid] ? 'call' :
								 (returnData.expandTemplate(:assignVariable) + ' =')) +
								' lib_' + name + '(' + argArray.collect{ |arg|
									arg.expandTemplate(:callExpression)
								}.join(', ') + ')')
		if (needArgEpilogue)
			dumpStatements(               2, argArray, :postcallStatements, $definitionLines)
		end
		if needRetValEpilogue
			formatLines($definitionLines, 2,
									returnData.expandTemplate(:postcallStatements))
		end
		formatLines($definitionLines, 1, 'end ' + subprogramtype + ' ' + name)
		formatLines($definitionLines, 0, '')
	else
		#Generate interface block only
		baseIndent = 1
		line = subprogramtype + ' ' + name + '(' + dummyArguments +
			') bind(c, name = \'' + name + '\')' +
Thomas Jahns's avatar
Thomas Jahns committed
804
			(returnTemplate[:isVoid] ? '' : " result(#{$wrapperResultVarName})")
805
806
807
808
809
810
811
812
813
814
		formatLines($interfaceLines, baseIndent + 1, line)
		line = importStatement(returnTemplate[:isVoid] ? '' :
													 returnData.expandTemplate(:returnAs),
													 argArray)
		$stderr.puts('Emitting \'' + line + "'") if $debug > 2
		formatLines($interfaceLines, baseIndent + 2, line)

		dumpStatements(baseIndent + 2, argArray, :passAs, $interfaceLines)
		if !returnTemplate[:isVoid]
			formatLines($interfaceLines, baseIndent + 2,
Thomas Jahns's avatar
Thomas Jahns committed
815
816
									returnData.expandTemplate(:returnAs) + ' :: ' +
									$wrapperResultVarName)
817
818
819
		end
		formatLines($interfaceLines, baseIndent + 1, 'end ' + subprogramtype + ' ' + name)
		formatLines($interfaceLines, 0, '')
820
	end
821
end
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852

#Scan the given header and collect the interface information in the global variables.
def scanHeader(headerPath)
	#Scan the given header.
	headerLines = IO.popen("cpp -fpreprocessed -dD #{headerPath}").readlines	#The options cause the preprocessor to strip all comments, but retain all #defines, and ignore #includes.
	headerLines.each do |line|
		line.chomp!

		if /^\s*$/.match(line)
			#Empty lines are ignored.

		#Preprocessor stuff
		elsif matchedLine = /^\s*#\s*define\s+(?<symbol>\w+)\s+(?<value>.+)$/.match(line)
			defineConstant(matchedLine['symbol'], matchedLine['value'])
		elsif /^\s*#/.match(line)
			#All other preprocessor directives are ignored.

		#User defined types
		elsif matchedLine = /^\s*typedef\s+struct\s+(?<typeName>\w+)\s+\k<typeName>\s*;\s*$/.match(line)
			defineOpaqueType(matchedLine['typeName'])
		elsif matchedLine = /^\s*typedef\s+struct\s+(?<typeName>\w+)\s*{(?<body>.*)}\s*\k<typeName>\s*;\s*$/.match(line)
			definePublicType(matchedLine['typeName'], matchedLine['body'])

		#Function declarations
		elsif matchedLine = /^\s*(?<returnType>[^()]+)\b(?<functionName>\w+)\s*\((?<arguments>.*)\)\s*;\s*$/.match(line)
			defineFunction(matchedLine['functionName'], matchedLine['arguments'], matchedLine['returnType'])

		else
			puts("Warning: Unrecognized line '#{line}'")
		end
	end
Thomas Jahns's avatar
Thomas Jahns committed
853
854
end

855
856
857
#Prints the line if it does not consist only of indentation, adding continuation lines as necessary.
def fortranLine(file, line)
	unless /^\t+$/.match(line)	#Intentionally empty lines don't contain indentation, so we preserve totally empty lines while throwing away the ones with leading tabs.
858
859
860
		# replace tabs with spaces first
		spacesPerTab = 2
		mline = line.gsub("\t", ' '*spacesPerTab)
861
		charsPerLine=79
862
		indentation = /^ */.match(mline)[0]
863
864
865
		if not /^ *!/.match(mline)
			while mline.length > charsPerLine
				# last position of space preceding line break
866
				tspos = mline[0..charsPerLine].rindex(' ') || charsPerLine
867
868
869
				file.puts(mline[0...tspos] + "&")
				mline = indentation + "&" + mline[tspos...mline.length]
			end
870
		end
871
		file.puts(mline)
872
	end
873
end
Thomas Jahns's avatar
Thomas Jahns committed
874

875
876
877
878
879
880
881
882
883
884
885
886
887
#Output the interface information in the global variables to a fortran file.
def writeFortranModule(scriptPath, headerPath, modulePath, moduleName)
	file = File.new(modulePath, "w")
	fortranLine(file, "! >>> Warning: This is a generated file. If you modify it, you get what you deserve. <<<")
	fortranLine(file, "!")
	fortranLine(file, "! Generated by \"#{scriptPath}\" from input file \"#{headerPath}\".")
	fortranLine(file, "");

	fortranLine(file, "module #{moduleName}")
	fortranLine(file, "\tuse iso_c_binding")
	fortranLine(file, "\timplicit none")
	fortranLine(file, "\tprivate")

888
889
890
	$verbatimDeclarations.each_line do |line|
		fortranLine(file, line)
	end
891
	fortranLine(file, '')
892
893
894
	$declarationLines.each do |line|
		fortranLine(file, line)
	end
895
896
897
898
899
900
901
902
903
	fortranLine(file, '')
	unless $interfaceLines.empty?
		fortranLine(file, "\tinterface")
		$interfaceLines.each do |line|
			fortranLine(file, line)
		end
		fortranLine(file, "\tend interface")
		fortranLine(file, '')
	end
904
	fortranLine(file, "contains")
905
906
907
	$verbatimDefinitions.each_line do |line|
		fortranLine(file, line)
	end
908
	fortranLine(file, '')
909
910
911
912
913
914
	$definitionLines.each do |line|
		fortranLine(file, line)
	end

	fortranLine(file, "end module #{moduleName}")
end
915

916
917
918
919
920
921
922
923
924
925
def main
	printUsage = false
	ARGV.each { |argument|
		if argument == "-h" || argument == "--help"
			printUsage = true
		end
	}
	unless printUsage
		case ARGV.length
			when 0
926
				$stderr.puts("Error: no input file given")
927
928
				printUsage = true
			when 1
929
				$stderr.puts("Error: no output file given")
930
931
932
933
934
935
				printUsage = true
			when 2
				moduleName = /(?<basename>[^.\/]+)\.[^\/]+/.match(ARGV[1])['basename']
			when 3
				moduleName = ARGV[2]
			else
936
				$stderr.puts("Error: too many arguments")
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
				printUsage = true
		end
	end
	unless printUsage
		headerPath = ARGV[0]
		outputPath = ARGV[1]
		scanHeader(headerPath)
		writeFortranModule($0, headerPath, outputPath, moduleName)
	else
		puts("Usage:")
		puts("#{$0} cHeader outputPath [ moduleName ]")
		puts("#{$0} ( -h | --help )")
		puts("")
		puts("\tcHeader:    input C header file")
		puts("\toutputPath: output fortran file name")
		puts("\tmoduleName: name of the resulting fortran module, defaults to the basename of outputPath")
	end
954
end
955

Uwe Schulzweida's avatar
Uwe Schulzweida committed
956
if rubyVersionOk()
957
	main()
Uwe Schulzweida's avatar
Uwe Schulzweida committed
958
else
959
	$stderr.puts("Error: Ruby version #{RUBY_VERSION} is too old (version 1.9 is required). Skipping fortran interface generation.")
Uwe Schulzweida's avatar
Uwe Schulzweida committed
960
end
961
962
963
964
965
966
967
968
969
#
# Local Variables:
# mode: ruby
# tab-always-indent: nil
# tab-width: 2
# ruby-indent-tabs-mode: t
# indent-tabs-mode: t
# End:
#