-
Notifications
You must be signed in to change notification settings - Fork 37
/
Translator.d
669 lines (544 loc) · 16.4 KB
/
Translator.d
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
/**
* Copyright: Copyright (c) 2011 Jacob Carlborg. All rights reserved.
* Authors: Jacob Carlborg
* Version: Initial created: Oct 6, 2011
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0)
*/
module dstep.translator.Translator;
import std.file;
import std.array;
import clang.c.Index;
import clang.Cursor;
import clang.File;
import clang.Index;
import clang.TranslationUnit;
import clang.Type;
import clang.Util;
import dstep.core.Exceptions;
import dstep.Configuration;
import dstep.translator.Context;
import dstep.translator.Declaration;
import dstep.translator.Enum;
import dstep.translator.IncludeHandler;
import dstep.translator.objc.Category;
import dstep.translator.objc.ObjcInterface;
import dstep.translator.Options;
import dstep.translator.Output;
import dstep.translator.MacroDefinition;
import dstep.translator.Record;
import dstep.translator.Type;
import dstep.translator.TypeInference;
public import dstep.translator.Options;
class TranslationException : DStepException
{
this (string message, string file = __FILE__, size_t line = __LINE__)
{
super(message, file, line);
}
}
class Translator
{
private
{
TranslationUnit translationUnit;
string outputFile;
string inputFilename;
File inputFile;
Language language;
string[string] deferredDeclarations;
}
TypedMacroDefinition[string] typedMacroDefinitions;
Context context;
this (TranslationUnit translationUnit, Options options = Options.init)
{
this.inputFilename = translationUnit.spelling;
this.translationUnit = translationUnit;
outputFile = options.outputFile;
language = options.language;
inputFile = translationUnit.file(inputFilename);
context = new Context(translationUnit, options, this);
}
void translate ()
{
write(outputFile, translateToString());
}
Output translateCursors()
{
Output result = new Output(context.commentIndex);
typedMacroDefinitions = inferMacroSignatures(context);
bool first = true;
foreach (cursor, parent; translationUnit.cursor.allInOrder)
{
if (!skipDeclaration(cursor))
{
if (first)
{
if (result.flushHeaderComment())
result.separator();
externDeclaration(result);
first = false;
}
translateInGlobalScope(result, cursor, parent);
}
}
if (context.commentIndex)
result.flushLocation(context.commentIndex.queryLastLocation());
foreach (value; deferredDeclarations.values)
result.singleLine(value);
result.finalize();
return result;
}
string translateToString()
{
import std.algorithm.mutation : strip;
Output main = translateCursors();
Output head = new Output();
moduleDeclaration(head);
context.includeHandler.toImports(head);
return main.header ~ head.data ~ main.content;
}
void translateInGlobalScope(
Output output,
Cursor cursor,
Cursor parent = Cursor.empty)
{
translate(output, cursor, parent);
if (!context.globalScope.empty)
{
output.separator();
output.output(context.globalScope);
output.separator();
context.globalScope.reset();
}
}
void translate (
Output output,
Cursor cursor,
Cursor parent = Cursor.empty)
{
with (CXCursorKind)
{
switch (cursor.kind)
{
case objCInterfaceDecl:
output.flushLocation(cursor.extent, false);
translateObjCInterfaceDecl(output, cursor, parent);
break;
case objCProtocolDecl:
output.flushLocation(cursor.extent, false);
translateObjCProtocolDecl(output, cursor, parent);
break;
case objCCategoryDecl:
output.flushLocation(cursor.extent, false);
translateObjCCategoryDecl(output, cursor, parent);
break;
case varDecl:
output.flushLocation(cursor.extent);
translateVarDecl(output, cursor, parent);
break;
case functionDecl:
translateFunctionDecl(output, cursor, parent);
break;
case typedefDecl:
translateTypedefDecl(output, cursor);
break;
case structDecl:
translateRecord(output, context, cursor);
break;
case enumDecl:
translateEnum(output, context, cursor);
break;
case unionDecl:
translateRecord(output, context, cursor);
break;
case macroDefinition:
output.flushLocation(cursor.extent);
translateMacroDefinition(output, cursor, parent);
break;
case macroExpansion:
output.flushLocation(cursor.extent);
break;
default:
break;
}
}
}
void translateObjCInterfaceDecl(Output output, Cursor cursor, Cursor parent)
{
(new ObjcInterface!(ClassData)(cursor, parent, this)).translate(output);
}
void translateObjCProtocolDecl(Output output, Cursor cursor, Cursor parent)
{
(new ObjcInterface!(InterfaceData)(cursor, parent, this)).translate(output);
}
void translateObjCCategoryDecl(Output output, Cursor cursor, Cursor parent)
{
(new Category(cursor, parent, this)).translate(output);
}
void translateVarDecl(Output output, Cursor cursor, Cursor parent)
{
version (D1)
string storageClass = "extern ";
else
string storageClass = "extern __gshared ";
variable(output, cursor, storageClass);
}
void translateFunctionDecl(Output output, Cursor cursor, Cursor parent)
{
output.flushLocation(cursor.extent);
immutable auto name = translateIdentifier(cursor.spelling);
output.adaptiveSourceNode(translateFunction(context, cursor.func, name));
output.append(";");
}
void declareRecordForTypedef(Output output, Cursor typedef_)
{
assert(typedef_.kind == CXCursorKind.typedefDecl);
auto underlying = typedef_.underlyingCursor();
if (underlying.isEmpty)
return;
if (underlying.isEmpty ||
underlying.kind != CXCursorKind.structDecl &&
underlying.kind != CXCursorKind.unionDecl)
return;
if (context.alreadyDefined(underlying.canonical))
return;
bool skipdef = shouldSkipRecordDefinition(context, underlying);
if (underlying.definition.isEmpty || skipdef)
translateRecordDecl(output, context, underlying);
}
bool shouldSkipAlias(Cursor typedef_)
{
assert(typedef_.kind == CXCursorKind.typedefDecl);
return context.options.reduceAliases && typedef_.type.isAliasReducible;
}
void translateTypedefDecl(Output output, Cursor typedef_)
{
assert(typedef_.kind == CXCursorKind.typedefDecl);
output.flushLocation(typedef_.extent);
auto underlying = typedef_.underlyingCursor;
if (!context.shouldSkipRecord(underlying) && !shouldSkipAlias(typedef_))
{
declareRecordForTypedef(output, typedef_);
auto typedefp = context.typedefParent(underlying);
if (typedef_ != typedefp ||
underlying.isEmpty ||
(underlying.spelling != typedef_.spelling &&
underlying.spelling != ""))
{
auto canonical = typedef_.type.canonical;
auto type = translateType(context, typedef_, canonical);
auto typeSpelling = type.makeString();
// Do not alias itself
if (typedef_.spelling != typeSpelling)
{
auto spelling = translateIdentifier(typedef_.spelling);
version (D1)
{
output.adaptiveSourceNode(
type.wrapWith("alias ", " " ~ spelling ~ ";"));
}
else
{
output.adaptiveSourceNode(
type.wrapWith("alias " ~ spelling ~ " = ", ";"));
}
}
context.markAsDefined(typedef_);
}
}
}
void translateMacroDefinition(Output output, Cursor cursor, Cursor parent)
{
if (context.options.translateMacros)
{
if (auto definition = cursor.spelling in typedMacroDefinitions)
{
dstep.translator.MacroDefinition
.translateMacroDefinition(output, context, *definition);
}
}
}
void variable (Output output, Cursor cursor, string prefix = "")
{
translateVariable(output, context, cursor, prefix);
}
private:
bool skipDeclaration (Cursor cursor)
{
return (inputFilename != "" &&
inputFile != cursor.location.spelling.file)
|| context.options.skipSymbols.contains(cursor.spelling)
|| cursor.isPredefined;
}
void moduleDeclaration (Output output)
{
if (context.options.packageName != "")
{
output.singleLine("module %s;", fullModuleName(
context.options.packageName,
context.options.outputFile,
context.options.normalizeModules));
output.separator();
}
}
void externDeclaration (Output output)
{
final switch (language)
{
case Language.c:
output.singleLine("extern (C):");
break;
case Language.objC:
output.singleLine("extern (Objective-C):");
break;
}
foreach (attribute; context.options.globalAttributes)
output.singleLine("%s:", attribute);
output.separator();
}
}
SourceNode translateFunction (
Context context,
FunctionCursor func,
string name,
bool isStatic = false)
{
bool isVariadic(Context context, size_t numParams, FunctionCursor func)
{
if (func.isVariadic)
{
if (context.options.zeroParamIsVararg)
return true;
else if (numParams == 0)
return false;
else
return true;
}
return false;
}
Parameter[] params;
if (func.type.isValid) // This will be invalid for Objective-C methods
params.reserve(func.type.func.arguments.length);
foreach (param ; func.parameters)
{
auto type = translateType(context, param);
params ~= Parameter(type, param.spelling);
}
auto resultType = translateType(context, func, func.resultType);
auto multiline = func.extent.isMultiline &&
!context.options.singleLineFunctionSignatures;
auto spacer = context.options.spaceAfterFunctionName ? " " : "";
return translateFunction(
resultType,
name,
params,
isVariadic(context, params.length, func),
isStatic ? "static " : "",
spacer,
multiline);
}
package struct Parameter
{
SourceNode type;
string name;
bool isConst;
}
package SourceNode translateFunction (
SourceNode resultType,
string name,
Parameter[] parameters,
bool variadic,
string prefix = "",
string spacer = " ",
bool multiline = false)
{
import std.format : format;
string[] params;
params.reserve(parameters.length);
foreach (param ; parameters)
{
string p;
version(D1)
{
p ~= param.type;
}
else
{
if (param.isConst)
p ~= "const(";
p ~= param.type.makeString();
if (param.isConst)
p ~= ')';
}
if (param.name.length)
p ~= " " ~ translateIdentifier(param.name);
params ~= p;
}
if (variadic)
params ~= "...";
auto result = makeSourceNode(
format("%s%s %s%s(", prefix, resultType.makeString(), name, spacer),
params,
",",
")");
return multiline ? result : result.flatten();
}
void translateVariable (Output output, Context context, Cursor cursor, string prefix = "")
{
if (!context.alreadyDefined(cursor.canonical))
{
auto type = translateType(context, cursor, cursor.type);
auto identifier = translateIdentifier(cursor.spelling);
output.adaptiveSourceNode(type.wrapWith(prefix, " " ~ identifier ~ ";"));
context.markAsDefined(cursor.canonical);
}
}
void handleInclude (Context context, Type type)
{
import std.algorithm.searching;
import std.path;
if (!context.includeHandler.resolveDependency(type.declaration)) {
context.includeHandler.addInclude(type.declaration.path);
}
}
bool isDKeyword (string str)
{
switch (str)
{
case "abstract":
case "alias":
case "align":
case "asm":
case "assert":
case "auto":
case "body":
case "bool":
case "break":
case "byte":
case "case":
case "cast":
case "catch":
case "cdouble":
case "cent":
case "cfloat":
case "char":
case "class":
case "const":
case "continue":
case "creal":
case "dchar":
case "debug":
case "default":
case "delegate":
case "delete":
case "deprecated":
case "do":
case "double":
case "else":
case "enum":
case "export":
case "extern":
case "false":
case "final":
case "finally":
case "float":
case "for":
case "foreach":
case "foreach_reverse":
case "function":
case "goto":
case "idouble":
case "if":
case "ifloat":
case "import":
case "in":
case "inout":
case "int":
case "interface":
case "invariant":
case "ireal":
case "is":
case "lazy":
case "long":
case "macro":
case "mixin":
case "module":
case "new":
case "nothrow":
case "null":
case "out":
case "override":
case "package":
case "pragma":
case "private":
case "protected":
case "public":
case "pure":
case "real":
case "ref":
case "return":
case "scope":
case "shared":
case "short":
case "static":
case "struct":
case "super":
case "switch":
case "synchronized":
case "template":
case "this":
case "throw":
case "true":
case "try":
case "typedef":
case "typeid":
case "typeof":
case "ubyte":
case "ucent":
case "uint":
case "ulong":
case "union":
case "unittest":
case "ushort":
case "version":
case "void":
case "volatile":
case "wchar":
case "while":
case "with":
case "__FILE__":
case "__LINE__":
case "__DATE__":
case "__TIME__":
case "__TIMESTAMP__":
case "__VENDOR__":
case "__VERSION__":
return true;
default: break;
}
if (true /*D2*/)
{
switch (str)
{
case "immutable":
case "nothrow":
case "pure":
case "shared":
case "__gshared":
case "__thread":
case "__traits":
case "__EOF__":
return true;
default: return str.length && str[0] == '@';
}
}
return false;
}
string renameDKeyword (string str)
{
return str ~ '_';
}
string translateIdentifier (string str)
{
return isDKeyword(str) ? renameDKeyword(str) : str;
}