-
Notifications
You must be signed in to change notification settings - Fork 34
/
bindgen.clay
696 lines (613 loc) · 21.7 KB
/
bindgen.clay
1
2
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
108
109
110
111
112
113
114
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import llvm.libclang.*;
import printer.(print,println,printTo,printlnTo,str);
import printer.formatter.(stringRepr);
import data.hashmaps.*;
import data.algorithms.(in?);
import io.files.*;
import io.streams.*;
import data.strings.*;
import data.vectors.*;
import data.sequences.operators.*;
var clayKeywords = array(
"public", "private", "import", "as",
"record", "variant", "instance",
"define", "overload", "default",
"external", "alias",
"static", "rvalue",
"inline", "enum", "var", "ref", "forward",
"and", "or", "not",
"if", "else", "goto", "return", "while",
"switch", "case", "break", "continue", "for", "in",
"true", "false", "try", "catch", "throw",
"finally", "onerror",
"eval", "with",
"__FILE__", "__LINE__", "__COLUMN__", "__ARG__"
);
var g_declNames = HashMap[CXCursor, String]();
var g_unnamedDecl = HashMap[CXCursor, Bool]();
var g_unnamedIndex = 0;
var g_bindingsOut = stdoutFile();
var g_visitedSymbols = HashMap[String, Bool]();
overload printTo(stream, s:CXString) : {
printTo(stream, CStringRef(clang_getCString(s)));
}
clayKeyword?(s:String) : Bool = in?(clayKeywords, s);
clayIdentifier(s:String) : String {
if (clayKeyword?(s)) {
return str(s, "_");
} else {
return str(s);
}
}
unnamedName() : String {
inc(g_unnamedIndex);
return str("Unnamed",g_unnamedIndex);
}
nameForDeclaration(cursor:CXCursor) : String
{
var namep = lookup(g_declNames, cursor);
if (null?(namep)) {
var spelling = str(clang_getCursorSpelling(cursor));
var prefix = String();
switch (cursor.kind)
case (CXCursor_StructDecl)
prefix = String("Struct_");
case (CXCursor_UnionDecl)
prefix = String("Union_");
case (CXCursor_EnumDecl)
prefix = String("Enum_");
else
prefix = String("Other_");
var name = String();
if (empty?(spelling))
name = prefix ++ unnamedName();
else
name = prefix ++ spelling;
g_declNames[cursor] = name;
return move(name);
} else
return namep^;
}
convertPointerType(type:CXType, refCursor:CXCursor) : String {
switch (type.kind)
case (CXType_Void)
return str("OpaquePointer");
case (CXType_Unexposed, CXType_FunctionProto, CXType_FunctionNoProto) {
// XXX Function pointer types inside fields or parms show up as "unexposed"
// but we can still extract the return type and visit parms
// XXX Pointers to forward-declared structs also show up as "unexposed"
// XXX calling convention
var returnType = clang_getResultType(type);
var decl = clang_getTypeDeclaration(type);
if (returnType.kind != CXType_Invalid) {
var name = String();
var varargs = clang_isFunctionTypeVariadic(type) != 0;
switch (clang_getFunctionTypeCallingConv(type))
case (CXCallingConv_X86StdCall)
printTo(name, "StdCallCodePointer");
case (CXCallingConv_X86FastCall)
printTo(name, "FastCallCodePointer");
else if (varargs)
printTo(name, "VarArgsCCodePointer");
else
printTo(name, "CCodePointer");
printTo(name, "[[");
var numArgs = clang_getNumArgTypes(type);
assert(numArgs >= 0);
for (arg in range(UInt(numArgs))) {
if (arg > 0)
printTo(name, ", ");
printTo(name, convertType(clang_getArgType(type, arg), refCursor));
}
printTo(name,
"],[",
if (returnType.kind == CXType_Void) str("") else convertType(returnType, refCursor),
"]]");
return move(name);
} else if (decl.kind != CXCursor_NoDeclFound) {
return str("Pointer[", convertTypeFromDeclaration(decl), "]");
} else {
return str("OpaquePointer /* unknown ",
clang_getTypeKindSpelling(type.kind),
" referenced by ",
clang_getCursorKindSpelling(refCursor.kind),
" ",
clang_getCursorSpelling(refCursor),
" */");
}
}
case (CXType_Typedef) {
var decl = clang_getTypeDeclaration(type);
var typedefType = clang_getTypedefDeclUnderlyingType(decl);
if (inValues?(typedefType.kind, CXType_FunctionProto, CXType_FunctionNoProto))
return convertPointerType(typedefType, refCursor);
}
return str("Pointer[", convertType(type, refCursor), "]");
}
convertTypeFromDeclaration(declaration:CXCursor) : String {
switch (declaration.kind)
case (CXCursor_StructDecl, CXCursor_UnionDecl, CXCursor_EnumDecl)
return nameForDeclaration(declaration);
case (CXCursor_TypedefDecl)
return clayIdentifier(str(clang_getCursorSpelling(declaration)));
else
return str("Opaque /* unknown ",
clang_getCursorKindSpelling(clang_getCursorKind(declaration)), " ",
clang_getCursorSpelling(declaration), " */");
}
convertType(type:CXType, refCursor:CXCursor) : String {
switch (type.kind)
case (CXType_Bool)
return str("CBool");
case (CXType_SChar, CXType_Char_S)
return str("CChar");
case (CXType_UChar, CXType_Char_U)
return str("CUChar");
case (CXType_UShort)
return str("CUShort");
case (CXType_UInt)
return str("CUInt");
case (CXType_ULong)
return str("CULong");
case (CXType_ULongLong)
return str("CULongLong");
case (CXType_UInt128)
return str("UInt128");
case (CXType_Short)
return str("CShort");
case (CXType_Int)
return str("CInt");
case (CXType_Long)
return str("CLong");
case (CXType_LongLong)
return str("CLongLong");
case (CXType_Int128)
return str("Int128");
case (CXType_Float)
return str("CFloat");
case (CXType_Double)
return str("CDouble");
case (CXType_LongDouble)
return str("CLongDouble");
case (CXType_Complex) {
var elementType = clang_getElementType(type);
switch (elementType.kind)
case (CXType_Float)
return str("CComplexFloat");
case (CXType_LongDouble)
return str("CComplexLongDouble");
case (CXType_Double)
return str("CComplexDouble");
else
return str("Opaque /* unsupported complex type ",
clang_getTypeKindSpelling(elementType.kind), " */");
}
case (CXType_Pointer)
return convertPointerType(clang_getPointeeType(type), refCursor);
case (CXType_Record, CXType_Typedef, CXType_Unexposed, CXType_Enum) {
var typeCursor = clang_getTypeDeclaration(type);
return convertTypeFromDeclaration(typeCursor);
}
case (CXType_ConstantArray) {
return str("Array[",
convertType(clang_getArrayElementType(type), refCursor),
", ",
clang_getArraySize(type),
"]",
);
}
case (CXType_Vector) {
return str("Vec[",
convertType(clang_getElementType(type), refCursor),
", ",
clang_getNumElements(type),
"]",
);
}
return str("/* unknown kind ",
clang_getTypeKindSpelling(type.kind), " */ Opaque");
}
visitStruct(cursor:CXCursor, parent:CXCursor, data:CXClientData) : Int
{
ref unnamedFieldIndex = Pointer[Int](data)^;
assert(clang_getCursorKind(parent) == CXCursor_StructDecl);
var kind = clang_getCursorKind(cursor);
switch (kind)
case (CXCursor_FieldDecl) {
var type = clang_getCursorType(cursor);
var name = str(clang_getCursorSpelling(cursor));
if (empty?(name)) {
name = str("?padding", unnamedFieldIndex);
unnamedFieldIndex +: 1;
}
printlnTo(g_bindingsOut, " ", clayIdentifier(name), " : ",
convertType(type, cursor), ",");
}
else {}
return CXChildVisit_Continue;
}
visitUnion(cursor:CXCursor, parent:CXCursor, data:CXClientData) : Int
{
assert(clang_getCursorKind(parent) == CXCursor_UnionDecl);
var kind = clang_getCursorKind(cursor);
switch (kind)
case (CXCursor_FieldDecl) {
var type = clang_getCursorType(cursor);
printlnTo(g_bindingsOut, " /* ", clang_getCursorSpelling(cursor), " */ ", convertType(type, cursor), ",");
}
else {}
return CXChildVisit_Continue;
}
record FunctionDeclAttributes (asmLabel:Maybe[String]);
visitFunctionAttr(cursor:CXCursor, parent:CXCursor, data:CXClientData) : Int
{
ref attributes = Pointer[FunctionDeclAttributes](data)^;
switch (cursor.kind)
case (CXCursor_AsmLabelAttr)
attributes.asmLabel = Maybe(str(clang_getCursorSpelling(cursor)));
return CXChildVisit_Continue;
}
visitEnum(cursor:CXCursor, parent:CXCursor, data:CXClientData) : Int
{
switch (cursor.kind)
case (CXCursor_EnumConstantDecl) {
printlnTo(g_bindingsOut, "alias ", clang_getCursorSpelling(cursor), " = ",
convertType(clang_getEnumDeclIntegerType(parent), parent), "(",
clang_getEnumConstantDeclValue(cursor), ");");
}
else {
}
return CXChildVisit_Continue;
}
noDefinition?(definition:CXCursor)
= inValues?(definition.kind, CXCursor_NoDeclFound, CXCursor_InvalidFile);
opaqueDeclaration(decl:CXCursor) {
var name = nameForDeclaration(decl);
if (not symbolVisited(name))
printlnTo(g_bindingsOut, "alias ", name, " = Opaque;\n");
}
opaqueType(type:CXType) {
if (inValues?(type.kind, CXType_Record, CXType_Enum)) {
var decl = clang_getTypeDeclaration(type);
var definition = clang_getCursorDefinition(decl);
if (noDefinition?(definition))
opaqueDeclaration(decl);
}
}
withForwardDecl(cursor:CXCursor, data:CXClientData, f) {
var definition = clang_getCursorDefinition(cursor);
if (cursor == definition) {
var name = str(clang_getCursorSpelling(cursor));
if (not empty?(name))
f(cursor, nameForDeclaration(cursor), data);
else
if (null?(lookup(g_unnamedDecl, cursor)))
g_unnamedDecl[cursor] = true;
} else if (noDefinition?(definition))
opaqueDeclaration(cursor);
}
cursorMatchesPatterns(cursor:CXCursor, options:BindgenOptions) : Bool {
var file = CXFile();
clang_getSpellingLocation(clang_getCursorLocation(cursor),
@file, null(UInt), null(UInt), null(UInt));
// builtin definitions have a null file
if (null?(file)) {
return options.matchBuiltins;
}
if (empty?(options.matchPatterns))
return true;
var filename = str(clang_getFileName(file));
for (pattern in options.matchPatterns)
if (in?(filename, pattern))
return true;
return false;
}
symbolVisited(name:String) : Bool
{
if (not null?(lookup(g_visitedSymbols, name)))
return true;
g_visitedSymbols[name] = true;
return false;
}
structDefinition(cursor:CXCursor, name:String, data:CXClientData) : {
if (not symbolVisited(name)) {
var unnamedFieldIndex = 0;
printlnTo(g_bindingsOut, "record ", name, " (");
clang_visitChildren(cursor, CXCursorVisitor(visitStruct),
CXClientData(@unnamedFieldIndex));
printlnTo(g_bindingsOut, ");\n");
}
}
unionDefinition(cursor:CXCursor, name:String, data:CXClientData) : {
if (not symbolVisited(name)) {
printlnTo(g_bindingsOut, "alias ", name, " = Union[");
clang_visitChildren(cursor, CXCursorVisitor(visitUnion), data);
printlnTo(g_bindingsOut, "];\n");
}
}
enumDefinition(cursor:CXCursor, name:String, data:CXClientData) : {
if (not symbolVisited(name)) {
printlnTo(g_bindingsOut, "alias ", name, " = ",
convertType(clang_getEnumDeclIntegerType(cursor), cursor), ";");
clang_visitChildren(cursor, CXCursorVisitor(visitEnum), data);
}
}
visitToplevel(cursor:CXCursor, parent:CXCursor, data:CXClientData) : Int
{
ref options = Pointer[BindgenOptions](data)^;
if (not cursorMatchesPatterns(cursor, options))
return CXChildVisit_Continue;
var kind = clang_getCursorKind(cursor);
switch (kind)
case (CXCursor_StructDecl) {
withForwardDecl(cursor, data, structDefinition);
return CXChildVisit_Recurse;
}
case (CXCursor_UnionDecl) {
withForwardDecl(cursor, data, unionDefinition);
return CXChildVisit_Recurse;
}
case (CXCursor_EnumDecl) {
withForwardDecl(cursor, data, enumDefinition);
printlnTo(g_bindingsOut);
return CXChildVisit_Continue;
}
case (CXCursor_FunctionDecl) {
var name = str(clang_getCursorSpelling(cursor));
if (symbolVisited(name))
return CXChildVisit_Continue;
// XXX dllimport/dllexport
var attributes = FunctionDeclAttributes();
clang_visitChildren(cursor, CXCursorVisitor(visitFunctionAttr),
CXClientData(@attributes));
var type = clang_getCursorType(cursor);
printTo(g_bindingsOut, "external (");
switch (clang_getFunctionTypeCallingConv(type))
case (CXCallingConv_X86StdCall)
printTo(g_bindingsOut, "stdcall");
case (CXCallingConv_X86FastCall)
printTo(g_bindingsOut, "fastcall");
else
printTo(g_bindingsOut, "cdecl");
maybe(attributes.asmLabel,
asmLabel -> {
printTo(g_bindingsOut, ", ", stringRepr(asmLabel));
},
() -> {
if (clayKeyword?(name))
printTo(g_bindingsOut, ", ", stringRepr(name));
}
);
printTo(g_bindingsOut, ") ", clayIdentifier(name), "(");
var argCount = clang_getNumArgTypes(type);
assert(argCount >= 0);
for (arg in range(UInt(argCount))) {
if (arg > 0)
printTo(g_bindingsOut, ", ");
printTo(g_bindingsOut, "arg", arg, ":",
convertType(clang_getArgType(type, arg), cursor));
}
if (clang_isFunctionTypeVariadic(type) != 0) {
if (argCount > 0)
printTo(g_bindingsOut, ", ");
printTo(g_bindingsOut, "..");
}
printTo(g_bindingsOut, ") : ");
var returnType = clang_getCursorResultType(cursor);
if (returnType.kind != CXType_Void)
printTo(g_bindingsOut, convertType(returnType, cursor));
printlnTo(g_bindingsOut, ";\n");
return CXChildVisit_Continue;
}
case (CXCursor_VarDecl) {
var name = str(clang_getCursorSpelling(cursor));
if (symbolVisited(name))
return CXChildVisit_Continue;
if (clayKeyword?(name))
printlnTo(g_bindingsOut, "external (", stringRepr(name), ")",
clayIdentifier(name), " : ",
convertType(clang_getCursorType(cursor), cursor), ";\n");
else
printlnTo(g_bindingsOut, "external ", name, " : ",
convertType(clang_getCursorType(cursor), cursor), ";\n");
return CXChildVisit_Continue;
}
case (CXCursor_TypedefDecl) {
var name = str(clang_getCursorSpelling(cursor));
var underlyingType = clang_getTypedefDeclUnderlyingType(cursor);
if (underlyingType.kind == CXType_Unexposed)
underlyingType = clang_getCanonicalType(underlyingType);
var decl = clang_getTypeDeclaration(underlyingType);
var typeId = clayIdentifier(name);
if (clang_isCursorDefinition(decl) != 0 and
empty?(str(clang_getCursorSpelling(decl)))) {
g_unnamedDecl[decl] = false;
switch (decl.kind)
case (CXCursor_StructDecl) {
structDefinition(decl, typeId, data);
return CXChildVisit_Recurse;
}
case (CXCursor_UnionDecl) {
unionDefinition(decl, typeId, data);
return CXChildVisit_Recurse;
}
case (CXCursor_EnumDecl) {
enumDefinition(decl, typeId, data);
printlnTo(g_bindingsOut);
return CXChildVisit_Continue;
}
}
if (symbolVisited(name))
return CXChildVisit_Continue;
printlnTo(g_bindingsOut, "alias ", typeId, " = ",
convertType(underlyingType, cursor), ";\n");
opaqueType(underlyingType);
return CXChildVisit_Continue;
}
case (CXCursor_FieldDecl) {
return CXChildVisit_Continue;
}
return CXChildVisit_Recurse;
}
visitUnnamedDecl(cursor:CXCursor, data:CXClientData) : {
var name = nameForDeclaration(cursor);
switch (cursor.kind)
case (CXCursor_StructDecl) {
structDefinition(cursor, name, data);
}
case (CXCursor_UnionDecl) {
unionDefinition(cursor, name, data);
}
case (CXCursor_EnumDecl) {
enumDefinition(cursor, name, data);
printlnTo(g_bindingsOut);
}
}
record Usage ();
record MissingOutputFileName ();
record MissingImportModuleName ();
record MissingMatchPattern ();
instance Exception (
Usage,
MissingOutputFileName,
MissingImportModuleName,
MissingMatchPattern
);
overload printTo(s, _:Usage) {
printlnTo(s, "Usage: clay-bindgen [clang options...] [bindgen options...] input.h");
printlnTo(s, "Bindgen options:");
printlnTo(s, " -o <output.clay> Write bindings to <output.clay> (default stdout)");
printlnTo(s, " -import <module> Prefix \"import <module>.*;\" to generated bindings");
printlnTo(s, " -match <name> Only output bindings for definitions from files");
printlnTo(s, " whose name contains <name>");
printlnTo(s, " If multiple -match options are provided, files");
printlnTo(s, " matching any rule are bound to.");
printlnTo(s, " -builtins Output bindings for builtin definitions");
printlnTo(s, " (for example __builtin_va_list)");
printlnTo(s, "Most clang options (such as -I and -D) are also supported.");
}
overload printTo(s, _:MissingOutputFileName) {
printlnTo(s, "no output file specified after -o option");
}
overload printTo(s, _:MissingImportModuleName) {
printlnTo(s, "no module name specified after -import option");
}
overload printTo(s, _:MissingMatchPattern) {
printlnTo(s, "no filename pattern specified after -match option");
}
record BindgenOptions (
outputFileName:Maybe[String],
imports:Vector[String],
matchPatterns:Vector[String],
matchBuiltins:Bool
);
overload BindgenOptions() = BindgenOptions(
nothing(String), Vector[String](), Vector[String](), false
);
parseOptions(argc, argv) : Int, Vector[Pointer[CChar]], BindgenOptions
{
var clang_argc = 0;
var clang_argv = Vector[Pointer[CChar]]();
var options = BindgenOptions();
var arg = 1;
while (arg < argc) {
switch (CStringRef(argv[arg]))
case ("-help", "--help", "/?") {
throw Usage();
}
case ("-o") {
if (arg + 1 >= argc)
throw MissingOutputFileName();
options.outputFileName = Maybe(String(argv[arg + 1]));
arg +: 2;
}
case ("-import") {
if (arg + 1 >= argc)
throw MissingImportModuleName();
push(options.imports, String(argv[arg + 1]));
arg +: 2;
}
case ("-match") {
if (arg + 1 >= argc)
throw MissingMatchPattern();
push(options.matchPatterns, String(argv[arg + 1]));
arg +: 2;
}
case ("-builtins") {
options.matchBuiltins = true;
arg +: 1;
}
case ("--") {
clang_argc +: argc - arg;
for (i in range(arg, argc))
push(clang_argv, argv[i]);
break;
}
else {
inc(clang_argc);
push(clang_argv, argv[arg]);
arg +: 1;
}
}
return clang_argc, move(clang_argv), move(options);
}
main(argc, argv)
{
var index = clang_createIndex(0, 1);
if (null?(index)) {
println("clang failed to create index");
return 1;
}
finally clang_disposeIndex(index);
var clang_argc = 0;
var clang_argv = Vector[Pointer[CChar]]();
var options = BindgenOptions();
try {
clang_argc, clang_argv, options = parseOptions(argc, argv);
maybe(options.outputFileName,
outputFileName -> {g_bindingsOut = File(outputFileName, CREATE);}
);
} catch (ex:Usage) {
print(ex);
return 2;
} catch (ex) {
print(ex);
return 1;
}
var unit = clang_parseTranslationUnit(
index,
null(CChar),
begin(clang_argv),
clang_argc,
null(Struct_CXUnsavedFile),
0u,
0u,
);
if (null?(unit)) {
printlnTo(stderr, "no input files given");
print(Usage());
return 2;
}
finally clang_disposeTranslationUnit(unit);
var error? = false;
for (i in range(0u, clang_getNumDiagnostics(unit))) {
var diag = clang_getDiagnostic(unit, i);
printlnTo(stderr, clang_formatDiagnostic(diag,
clang_defaultDiagnosticDisplayOptions()));
if (clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error)
error? = true;
}
if (error?)
return 1;
printlnTo(g_bindingsOut, "// automatically generated by clay-bindgen");
for (imp in options.imports)
printlnTo(g_bindingsOut, "import ", imp, ".*;");
printlnTo(g_bindingsOut);
var cursor = clang_getTranslationUnitCursor(unit);
clang_visitChildren(cursor, CXCursorVisitor(visitToplevel), CXClientData(@options));
for (c, b in items(g_unnamedDecl))
if (b)
visitUnnamedDecl(c, CXClientData(@options));
flush(g_bindingsOut);
return 0;
}