-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathtranslate_c.zig
6677 lines (6030 loc) · 263 KB
/
translate_c.zig
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const testing = std.testing;
const assert = std.debug.assert;
const mem = std.mem;
const math = std.math;
const meta = std.meta;
const clang = @import("clang.zig");
const aro = @import("aro");
const CToken = aro.Tokenizer.Token;
const Node = ast.Node;
const Tag = Node.Tag;
const common = @import("aro_translate_c");
const ast = common.ast;
const Error = common.Error;
const MacroProcessingError = common.MacroProcessingError;
const TypeError = common.TypeError;
const TransError = common.TransError;
const SymbolTable = common.SymbolTable;
const AliasList = common.AliasList;
const ResultUsed = common.ResultUsed;
const Scope = common.ScopeExtra(Context, clang.QualType);
const PatternList = common.PatternList;
const MacroSlicer = common.MacroSlicer;
pub const Context = struct {
gpa: mem.Allocator,
arena: mem.Allocator,
source_manager: *clang.SourceManager,
decl_table: std.AutoArrayHashMapUnmanaged(usize, []const u8) = .empty,
alias_list: AliasList,
global_scope: *Scope.Root,
clang_context: *clang.ASTContext,
mangle_count: u32 = 0,
/// Table of record decls that have been demoted to opaques.
opaque_demotes: std.AutoHashMapUnmanaged(usize, void) = .empty,
/// Table of unnamed enums and records that are child types of typedefs.
unnamed_typedefs: std.AutoHashMapUnmanaged(usize, []const u8) = .empty,
/// Needed to decide if we are parsing a typename
typedefs: std.StringArrayHashMapUnmanaged(void) = .empty,
/// This one is different than the root scope's name table. This contains
/// a list of names that we found by visiting all the top level decls without
/// translating them. The other maps are updated as we translate; this one is updated
/// up front in a pre-processing step.
global_names: std.StringArrayHashMapUnmanaged(void) = .empty,
/// This is similar to `global_names`, but contains names which we would
/// *like* to use, but do not strictly *have* to if they are unavailable.
/// These are relevant to types, which ideally we would name like
/// 'struct_foo' with an alias 'foo', but if either of those names is taken,
/// may be mangled.
/// This is distinct from `global_names` so we can detect at a type
/// declaration whether or not the name is available.
weak_global_names: std.StringArrayHashMapUnmanaged(void) = .empty,
pattern_list: PatternList,
fn getMangle(c: *Context) u32 {
c.mangle_count += 1;
return c.mangle_count;
}
/// Convert a null-terminated C string to a slice allocated in the arena
fn str(c: *Context, s: [*:0]const u8) ![]u8 {
return c.arena.dupe(u8, mem.sliceTo(s, 0));
}
/// Convert a clang source location to a file:line:column string
fn locStr(c: *Context, loc: clang.SourceLocation) ![]u8 {
const spelling_loc = c.source_manager.getSpellingLoc(loc);
const filename_c = c.source_manager.getFilename(spelling_loc);
const filename = if (filename_c) |s| try c.str(s) else @as([]const u8, "(no file)");
const line = c.source_manager.getSpellingLineNumber(spelling_loc);
const column = c.source_manager.getSpellingColumnNumber(spelling_loc);
return std.fmt.allocPrint(c.arena, "{s}:{d}:{d}", .{ filename, line, column });
}
};
pub fn translate(
gpa: mem.Allocator,
args_begin: [*]?[*:0]const u8,
args_end: [*]?[*:0]const u8,
errors: *std.zig.ErrorBundle,
resources_path: [*:0]const u8,
) !std.zig.Ast {
var clang_errors: []clang.ErrorMsg = &.{};
const ast_unit = clang.LoadFromCommandLine(
args_begin,
args_end,
&clang_errors.ptr,
&clang_errors.len,
resources_path,
) orelse {
defer clang.ErrorMsg.delete(clang_errors.ptr, clang_errors.len);
var bundle: std.zig.ErrorBundle.Wip = undefined;
try bundle.init(gpa);
defer bundle.deinit();
for (clang_errors) |c_error| {
const line = line: {
const source = c_error.source orelse break :line 0;
var start = c_error.offset;
while (start > 0) : (start -= 1) {
if (source[start - 1] == '\n') break;
}
var end = c_error.offset;
while (true) : (end += 1) {
if (source[end] == 0) break;
if (source[end] == '\n') break;
}
break :line try bundle.addString(source[start..end]);
};
try bundle.addRootErrorMessage(.{
.msg = try bundle.addString(c_error.msg_ptr[0..c_error.msg_len]),
.src_loc = if (c_error.filename_ptr) |filename_ptr| try bundle.addSourceLocation(.{
.src_path = try bundle.addString(filename_ptr[0..c_error.filename_len]),
.span_start = c_error.offset,
.span_main = c_error.offset,
.span_end = c_error.offset + 1,
.line = c_error.line,
.column = c_error.column,
.source_line = line,
}) else .none,
});
}
errors.* = try bundle.toOwnedBundle("");
return error.SemanticAnalyzeFail;
};
defer ast_unit.delete();
// For memory that has the same lifetime as the Ast that we return
// from this function.
var arena_allocator = std.heap.ArenaAllocator.init(gpa);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
var context = Context{
.gpa = gpa,
.arena = arena,
.source_manager = ast_unit.getSourceManager(),
.alias_list = AliasList.init(gpa),
.global_scope = try arena.create(Scope.Root),
.clang_context = ast_unit.getASTContext(),
.pattern_list = try PatternList.init(gpa),
};
context.global_scope.* = Scope.Root.init(&context);
defer {
context.decl_table.deinit(gpa);
context.alias_list.deinit();
context.global_names.deinit(gpa);
context.opaque_demotes.deinit(gpa);
context.unnamed_typedefs.deinit(gpa);
context.typedefs.deinit(gpa);
context.global_scope.deinit();
context.pattern_list.deinit(gpa);
}
@setEvalBranchQuota(2000);
inline for (@typeInfo(std.zig.c_builtins).@"struct".decls) |decl| {
const builtin = try Tag.pub_var_simple.create(arena, .{
.name = decl.name,
.init = try Tag.import_c_builtin.create(arena, decl.name),
});
try addTopLevelDecl(&context, decl.name, builtin);
}
try prepopulateGlobalNameTable(ast_unit, &context);
if (!ast_unit.visitLocalTopLevelDecls(&context, declVisitorC)) {
return error.OutOfMemory;
}
try transPreprocessorEntities(&context, ast_unit);
for (context.alias_list.items) |alias| {
const node = try Tag.alias.create(arena, .{ .actual = alias.alias, .mangled = alias.name });
try addTopLevelDecl(&context, alias.alias, node);
}
return ast.render(gpa, context.global_scope.nodes.items);
}
/// Determines whether macro is of the form: `#define FOO FOO` (Possibly with trailing tokens)
/// Macros of this form will not be translated.
fn isSelfDefinedMacro(unit: *const clang.ASTUnit, c: *const Context, macro: *const clang.MacroDefinitionRecord) !bool {
const source = try getMacroText(unit, c, macro);
var tokenizer: aro.Tokenizer = .{
.buf = source,
.source = .unused,
.langopts = .{},
};
const name_tok = tokenizer.nextNoWS();
const name = source[name_tok.start..name_tok.end];
const first_tok = tokenizer.nextNoWS();
// We do not just check for `.Identifier` below because keyword tokens are preferentially matched first by
// the tokenizer.
// In other words we would miss `#define inline inline` (`inline` is a valid c89 identifier)
if (first_tok.id == .eof) return false;
return mem.eql(u8, name, source[first_tok.start..first_tok.end]);
}
fn prepopulateGlobalNameTable(ast_unit: *clang.ASTUnit, c: *Context) !void {
if (!ast_unit.visitLocalTopLevelDecls(c, declVisitorNamesOnlyC)) {
return error.OutOfMemory;
}
// TODO if we see #undef, delete it from the table
var it = ast_unit.getLocalPreprocessingEntities_begin();
const it_end = ast_unit.getLocalPreprocessingEntities_end();
while (it.I != it_end.I) : (it.I += 1) {
const entity = it.deref();
switch (entity.getKind()) {
.MacroDefinitionKind => {
const macro = @as(*clang.MacroDefinitionRecord, @ptrCast(entity));
const raw_name = macro.getName_getNameStart();
const name = try c.str(raw_name);
if (!try isSelfDefinedMacro(ast_unit, c, macro)) {
try c.global_names.put(c.gpa, name, {});
}
},
else => {},
}
}
}
fn declVisitorNamesOnlyC(context: ?*anyopaque, decl: *const clang.Decl) callconv(.c) bool {
const c: *Context = @ptrCast(@alignCast(context));
declVisitorNamesOnly(c, decl) catch return false;
return true;
}
fn declVisitorC(context: ?*anyopaque, decl: *const clang.Decl) callconv(.c) bool {
const c: *Context = @ptrCast(@alignCast(context));
declVisitor(c, decl) catch return false;
return true;
}
fn declVisitorNamesOnly(c: *Context, decl: *const clang.Decl) Error!void {
if (decl.castToNamedDecl()) |named_decl| {
const decl_name = try c.str(named_decl.getName_bytes_begin());
switch (decl.getKind()) {
.Record, .Enum => {
// These types are prefixed with the container kind.
const container_prefix = if (decl.getKind() == .Record) prefix: {
const record_decl: *const clang.RecordDecl = @ptrCast(decl);
if (record_decl.isUnion()) {
break :prefix "union";
} else {
break :prefix "struct";
}
} else "enum";
const prefixed_name = try std.fmt.allocPrint(c.arena, "{s}_{s}", .{ container_prefix, decl_name });
// `decl_name` and `prefixed_name` are the preferred names for this type.
// However, we can name it anything else if necessary, so these are "weak names".
try c.weak_global_names.ensureUnusedCapacity(c.gpa, 2);
c.weak_global_names.putAssumeCapacity(decl_name, {});
c.weak_global_names.putAssumeCapacity(prefixed_name, {});
},
else => {
try c.global_names.put(c.gpa, decl_name, {});
},
}
// Check for typedefs with unnamed enum/record child types.
if (decl.getKind() == .Typedef) {
const typedef_decl = @as(*const clang.TypedefNameDecl, @ptrCast(decl));
var child_ty = typedef_decl.getUnderlyingType().getTypePtr();
const addr: usize = while (true) switch (child_ty.getTypeClass()) {
.Enum => {
const enum_ty = @as(*const clang.EnumType, @ptrCast(child_ty));
const enum_decl = enum_ty.getDecl();
// check if this decl is unnamed
if (@as(*const clang.NamedDecl, @ptrCast(enum_decl)).getName_bytes_begin()[0] != 0) return;
break @intFromPtr(enum_decl.getCanonicalDecl());
},
.Record => {
const record_ty = @as(*const clang.RecordType, @ptrCast(child_ty));
const record_decl = record_ty.getDecl();
// check if this decl is unnamed
if (@as(*const clang.NamedDecl, @ptrCast(record_decl)).getName_bytes_begin()[0] != 0) return;
break @intFromPtr(record_decl.getCanonicalDecl());
},
.Elaborated => {
const elaborated_ty = @as(*const clang.ElaboratedType, @ptrCast(child_ty));
child_ty = elaborated_ty.getNamedType().getTypePtr();
},
.Decayed => {
const decayed_ty = @as(*const clang.DecayedType, @ptrCast(child_ty));
child_ty = decayed_ty.getDecayedType().getTypePtr();
},
.Attributed => {
const attributed_ty = @as(*const clang.AttributedType, @ptrCast(child_ty));
child_ty = attributed_ty.getEquivalentType().getTypePtr();
},
.MacroQualified => {
const macroqualified_ty = @as(*const clang.MacroQualifiedType, @ptrCast(child_ty));
child_ty = macroqualified_ty.getModifiedType().getTypePtr();
},
else => return,
};
const result = try c.unnamed_typedefs.getOrPut(c.gpa, addr);
if (result.found_existing) {
// One typedef can declare multiple names.
// Don't put this one in `decl_table` so it's processed later.
return;
}
result.value_ptr.* = decl_name;
// Put this typedef in the decl_table to avoid redefinitions.
try c.decl_table.putNoClobber(c.gpa, @intFromPtr(typedef_decl.getCanonicalDecl()), decl_name);
try c.typedefs.put(c.gpa, decl_name, {});
}
}
}
fn declVisitor(c: *Context, decl: *const clang.Decl) Error!void {
switch (decl.getKind()) {
.Function => {
return transFnDecl(c, &c.global_scope.base, @as(*const clang.FunctionDecl, @ptrCast(decl)));
},
.Typedef => {
try transTypeDef(c, &c.global_scope.base, @as(*const clang.TypedefNameDecl, @ptrCast(decl)));
},
.Enum => {
try transEnumDecl(c, &c.global_scope.base, @as(*const clang.EnumDecl, @ptrCast(decl)));
},
.Record => {
try transRecordDecl(c, &c.global_scope.base, @as(*const clang.RecordDecl, @ptrCast(decl)));
},
.Var => {
return visitVarDecl(c, @as(*const clang.VarDecl, @ptrCast(decl)), null);
},
.Empty => {
// Do nothing
},
.FileScopeAsm => {
try transFileScopeAsm(c, &c.global_scope.base, @as(*const clang.FileScopeAsmDecl, @ptrCast(decl)));
},
else => {
const decl_name = try c.str(decl.getDeclKindName());
try warn(c, &c.global_scope.base, decl.getLocation(), "ignoring {s} declaration", .{decl_name});
},
}
}
fn transFileScopeAsm(c: *Context, scope: *Scope, file_scope_asm: *const clang.FileScopeAsmDecl) Error!void {
const asm_string = file_scope_asm.getAsmString();
var len: usize = undefined;
const bytes_ptr = asm_string.getString_bytes_begin_size(&len);
const str = try std.fmt.allocPrint(c.arena, "\"{}\"", .{std.zig.fmtEscapes(bytes_ptr[0..len])});
const str_node = try Tag.string_literal.create(c.arena, str);
const asm_node = try Tag.asm_simple.create(c.arena, str_node);
const block = try Tag.block_single.create(c.arena, asm_node);
const comptime_node = try Tag.@"comptime".create(c.arena, block);
try scope.appendNode(comptime_node);
}
fn transFnDecl(c: *Context, scope: *Scope, fn_decl: *const clang.FunctionDecl) Error!void {
const fn_name = try c.str(@as(*const clang.NamedDecl, @ptrCast(fn_decl)).getName_bytes_begin());
if (c.global_scope.sym_table.contains(fn_name))
return; // Avoid processing this decl twice
// Skip this declaration if a proper definition exists
if (!fn_decl.isThisDeclarationADefinition()) {
if (fn_decl.getDefinition()) |def|
return transFnDecl(c, scope, def);
}
const fn_decl_loc = fn_decl.getLocation();
const has_body = fn_decl.hasBody();
const storage_class = fn_decl.getStorageClass();
const is_always_inline = has_body and fn_decl.hasAlwaysInlineAttr();
var decl_ctx = FnDeclContext{
.fn_name = fn_name,
.has_body = has_body,
.storage_class = storage_class,
.is_always_inline = is_always_inline,
.is_export = switch (storage_class) {
.None => has_body and !is_always_inline and !fn_decl.isInlineSpecified(),
.Extern, .Static => false,
.PrivateExtern => return failDecl(c, fn_decl_loc, fn_name, "unsupported storage class: private extern", .{}),
.Auto => unreachable, // Not legal on functions
.Register => unreachable, // Not legal on functions
},
};
var fn_qt = fn_decl.getType();
const fn_type = while (true) {
const fn_type = fn_qt.getTypePtr();
switch (fn_type.getTypeClass()) {
.Attributed => {
const attr_type = @as(*const clang.AttributedType, @ptrCast(fn_type));
fn_qt = attr_type.getEquivalentType();
},
.Paren => {
const paren_type = @as(*const clang.ParenType, @ptrCast(fn_type));
fn_qt = paren_type.getInnerType();
},
else => break fn_type,
}
};
const fn_ty = @as(*const clang.FunctionType, @ptrCast(fn_type));
const return_qt = fn_ty.getReturnType();
const proto_node = switch (fn_type.getTypeClass()) {
.FunctionProto => blk: {
const fn_proto_type = @as(*const clang.FunctionProtoType, @ptrCast(fn_type));
if (has_body and fn_proto_type.isVariadic()) {
decl_ctx.has_body = false;
decl_ctx.storage_class = .Extern;
decl_ctx.is_export = false;
decl_ctx.is_always_inline = false;
try warn(c, &c.global_scope.base, fn_decl_loc, "TODO unable to translate variadic function, demoted to extern", .{});
}
break :blk transFnProto(c, fn_decl, fn_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) {
error.UnsupportedType => {
return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function", .{});
},
error.OutOfMemory => |e| return e,
};
},
.FunctionNoProto => blk: {
const fn_no_proto_type = @as(*const clang.FunctionType, @ptrCast(fn_type));
break :blk transFnNoProto(c, fn_no_proto_type, fn_decl_loc, decl_ctx, true) catch |err| switch (err) {
error.UnsupportedType => {
return failDecl(c, fn_decl_loc, fn_name, "unable to resolve prototype of function", .{});
},
error.OutOfMemory => |e| return e,
};
},
else => return failDecl(c, fn_decl_loc, fn_name, "unable to resolve function type {}", .{fn_type.getTypeClass()}),
};
if (!decl_ctx.has_body) {
if (scope.id != .root) {
return addLocalExternFnDecl(c, scope, fn_name, Node.initPayload(&proto_node.base));
}
return addTopLevelDecl(c, fn_name, Node.initPayload(&proto_node.base));
}
// actual function definition with body
const body_stmt = fn_decl.getBody();
var block_scope = try Scope.Block.init(c, &c.global_scope.base, false);
block_scope.return_type = return_qt;
defer block_scope.deinit();
const top_scope = &block_scope.base;
var param_id: c_uint = 0;
for (proto_node.data.params) |*param| {
const param_name = param.name orelse {
proto_node.data.is_extern = true;
proto_node.data.is_export = false;
proto_node.data.is_inline = false;
try warn(c, &c.global_scope.base, fn_decl_loc, "function {s} parameter has no name, demoted to extern", .{fn_name});
return addTopLevelDecl(c, fn_name, Node.initPayload(&proto_node.base));
};
const c_param = fn_decl.getParamDecl(param_id);
const qual_type = c_param.getOriginalType();
const is_const = qual_type.isConstQualified();
const mangled_param_name = try block_scope.makeMangledName(c, param_name);
param.name = mangled_param_name;
if (!is_const) {
const bare_arg_name = try std.fmt.allocPrint(c.arena, "arg_{s}", .{mangled_param_name});
const arg_name = try block_scope.makeMangledName(c, bare_arg_name);
param.name = arg_name;
const redecl_node = try Tag.arg_redecl.create(c.arena, .{ .actual = mangled_param_name, .mangled = arg_name });
try block_scope.statements.append(redecl_node);
}
try block_scope.discardVariable(c, mangled_param_name);
param_id += 1;
}
const casted_body = @as(*const clang.CompoundStmt, @ptrCast(body_stmt));
transCompoundStmtInline(c, casted_body, &block_scope) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.UnsupportedTranslation,
error.UnsupportedType,
=> {
proto_node.data.is_extern = true;
proto_node.data.is_export = false;
proto_node.data.is_inline = false;
try warn(c, &c.global_scope.base, fn_decl_loc, "unable to translate function, demoted to extern", .{});
return addTopLevelDecl(c, fn_name, Node.initPayload(&proto_node.base));
},
};
// add return statement if the function didn't have one
blk: {
const maybe_body = try block_scope.complete(c);
if (fn_ty.getNoReturnAttr() or isAnyopaque(return_qt) or maybe_body.isNoreturn(false)) {
proto_node.data.body = maybe_body;
break :blk;
}
const rhs = transZeroInitExpr(c, top_scope, fn_decl_loc, return_qt.getTypePtr()) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.UnsupportedTranslation,
error.UnsupportedType,
=> {
proto_node.data.is_extern = true;
proto_node.data.is_export = false;
proto_node.data.is_inline = false;
try warn(c, &c.global_scope.base, fn_decl_loc, "unable to create a return value for function, demoted to extern", .{});
return addTopLevelDecl(c, fn_name, Node.initPayload(&proto_node.base));
},
};
const ret = try Tag.@"return".create(c.arena, rhs);
try block_scope.statements.append(ret);
proto_node.data.body = try block_scope.complete(c);
}
return addTopLevelDecl(c, fn_name, Node.initPayload(&proto_node.base));
}
fn transQualTypeMaybeInitialized(c: *Context, scope: *Scope, qt: clang.QualType, decl_init: ?*const clang.Expr, loc: clang.SourceLocation) TransError!Node {
return if (decl_init) |init_expr|
transQualTypeInitialized(c, scope, qt, init_expr, loc)
else
transQualType(c, scope, qt, loc);
}
/// This is used in global scope to convert a string literal `S` to [*c]u8:
/// &(struct {
/// var static = S.*;
/// }).static;
fn stringLiteralToCharStar(c: *Context, str: Node) Error!Node {
const var_name = Scope.Block.static_inner_name;
const variables = try c.arena.alloc(Node, 1);
variables[0] = try Tag.mut_str.create(c.arena, .{ .name = var_name, .init = str });
const anon_struct = try Tag.@"struct".create(c.arena, .{
.layout = .none,
.fields = &.{},
.functions = &.{},
.variables = variables,
});
const member_access = try Tag.field_access.create(c.arena, .{
.lhs = anon_struct,
.field_name = var_name,
});
return Tag.address_of.create(c.arena, member_access);
}
/// if mangled_name is not null, this var decl was declared in a block scope.
fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]const u8) Error!void {
const var_name = mangled_name orelse try c.str(@as(*const clang.NamedDecl, @ptrCast(var_decl)).getName_bytes_begin());
if (c.global_scope.sym_table.contains(var_name))
return; // Avoid processing this decl twice
const is_pub = mangled_name == null;
const is_threadlocal = var_decl.getTLSKind() != .None;
const scope = &c.global_scope.base;
const var_decl_loc = var_decl.getLocation();
const qual_type = var_decl.getTypeSourceInfo_getType();
const storage_class = var_decl.getStorageClass();
const has_init = var_decl.hasInit();
const decl_init = var_decl.getInit();
var is_const = qual_type.isConstQualified();
// In C extern variables with initializers behave like Zig exports.
// extern int foo = 2;
// does the same as:
// extern int foo;
// int foo = 2;
var is_extern = storage_class == .Extern and !has_init;
var is_export = !is_extern and storage_class != .Static;
if (!is_extern and qualTypeWasDemotedToOpaque(c, qual_type)) {
return failDecl(c, var_decl_loc, var_name, "non-extern variable has opaque type", .{});
}
const type_node = transQualTypeMaybeInitialized(c, scope, qual_type, decl_init, var_decl_loc) catch |err| switch (err) {
error.UnsupportedTranslation, error.UnsupportedType => {
return failDecl(c, var_decl_loc, var_name, "unable to resolve variable type", .{});
},
error.OutOfMemory => |e| return e,
};
var init_node: ?Node = null;
// If the initialization expression is not present, initialize with undefined.
// If it is an integer literal, we can skip the @as since it will be redundant
// with the variable type.
if (has_init) trans_init: {
if (decl_init) |expr| {
const node_or_error = if (expr.getStmtClass() == .StringLiteralClass)
transStringLiteralInitializer(c, @as(*const clang.StringLiteral, @ptrCast(expr)), type_node)
else
transExprCoercing(c, scope, expr, .used);
init_node = node_or_error catch |err| switch (err) {
error.UnsupportedTranslation,
error.UnsupportedType,
=> {
is_extern = true;
is_export = false;
try warn(c, scope, var_decl_loc, "unable to translate variable initializer, demoted to extern", .{});
break :trans_init;
},
error.OutOfMemory => |e| return e,
};
if (!qualTypeIsBoolean(qual_type) and isBoolRes(init_node.?)) {
init_node = try Tag.int_from_bool.create(c.arena, init_node.?);
} else if (init_node.?.tag() == .string_literal and qualTypeIsCharStar(qual_type)) {
init_node = try stringLiteralToCharStar(c, init_node.?);
}
} else {
init_node = Tag.undefined_literal.init();
}
} else if (storage_class != .Extern) {
// The C language specification states that variables with static or threadlocal
// storage without an initializer are initialized to a zero value.
// std.mem.zeroes(T)
init_node = try Tag.std_mem_zeroes.create(c.arena, type_node);
} else if (qual_type.getTypeClass() == .IncompleteArray) {
// Oh no, an extern array of unknown size! These are really fun because there's no
// direct equivalent in Zig. To translate correctly, we'll have to create a C-pointer
// to the data initialized via @extern.
const name_str = try std.fmt.allocPrint(c.arena, "\"{s}\"", .{var_name});
init_node = try Tag.builtin_extern.create(c.arena, .{
.type = type_node,
.name = try Tag.string_literal.create(c.arena, name_str),
});
// Since this is really a pointer to the underlying data, we tweak a few properties.
is_extern = false;
is_const = true;
}
const linksection_string = blk: {
var str_len: usize = undefined;
if (var_decl.getSectionAttribute(&str_len)) |str_ptr| {
break :blk str_ptr[0..str_len];
}
break :blk null;
};
const node = try Tag.var_decl.create(c.arena, .{
.is_pub = is_pub,
.is_const = is_const,
.is_extern = is_extern,
.is_export = is_export,
.is_threadlocal = is_threadlocal,
.linksection_string = linksection_string,
.alignment = ClangAlignment.forVar(c, var_decl).zigAlignment(),
.name = var_name,
.type = type_node,
.init = init_node,
});
return addTopLevelDecl(c, var_name, node);
}
const builtin_typedef_map = std.StaticStringMap([]const u8).initComptime(.{
.{ "uint8_t", "u8" },
.{ "int8_t", "i8" },
.{ "uint16_t", "u16" },
.{ "int16_t", "i16" },
.{ "uint32_t", "u32" },
.{ "int32_t", "i32" },
.{ "uint64_t", "u64" },
.{ "int64_t", "i64" },
.{ "intptr_t", "isize" },
.{ "uintptr_t", "usize" },
.{ "ssize_t", "isize" },
.{ "size_t", "usize" },
});
fn transTypeDef(c: *Context, scope: *Scope, typedef_decl: *const clang.TypedefNameDecl) Error!void {
if (c.decl_table.get(@intFromPtr(typedef_decl.getCanonicalDecl()))) |_|
return; // Avoid processing this decl twice
const toplevel = scope.id == .root;
const bs: *Scope.Block = if (!toplevel) try scope.findBlockScope(c) else undefined;
var name: []const u8 = try c.str(@as(*const clang.NamedDecl, @ptrCast(typedef_decl)).getName_bytes_begin());
try c.typedefs.put(c.gpa, name, {});
if (builtin_typedef_map.get(name)) |builtin| {
return c.decl_table.putNoClobber(c.gpa, @intFromPtr(typedef_decl.getCanonicalDecl()), builtin);
}
if (!toplevel) name = try bs.makeMangledName(c, name);
try c.decl_table.putNoClobber(c.gpa, @intFromPtr(typedef_decl.getCanonicalDecl()), name);
const child_qt = typedef_decl.getUnderlyingType();
const typedef_loc = typedef_decl.getLocation();
const init_node = transQualType(c, scope, child_qt, typedef_loc) catch |err| switch (err) {
error.UnsupportedType => {
return failDecl(c, typedef_loc, name, "unable to resolve typedef child type", .{});
},
error.OutOfMemory => |e| return e,
};
const payload = try c.arena.create(ast.Payload.SimpleVarDecl);
payload.* = .{
.base = .{ .tag = ([2]Tag{ .var_simple, .pub_var_simple })[@intFromBool(toplevel)] },
.data = .{
.name = name,
.init = init_node,
},
};
const node = Node.initPayload(&payload.base);
if (toplevel) {
try addTopLevelDecl(c, name, node);
} else {
try scope.appendNode(node);
if (node.tag() != .pub_var_simple) {
try bs.discardVariable(c, name);
}
}
}
/// Build a getter function for a flexible array member at the end of a C struct
/// e.g. `T items[]` or `T items[0]`. The generated function returns a [*c] pointer
/// to the flexible array with the correct const and volatile qualifiers
fn buildFlexibleArrayFn(
c: *Context,
scope: *Scope,
layout: *const clang.ASTRecordLayout,
field_name: []const u8,
field_decl: *const clang.FieldDecl,
) TypeError!Node {
const field_qt = field_decl.getType();
const field_qt_canon = qualTypeCanon(field_qt);
const u8_type = try Tag.type.create(c.arena, "u8");
const self_param_name = "self";
const self_param = try Tag.identifier.create(c.arena, self_param_name);
const self_type = try Tag.typeof.create(c.arena, self_param);
const fn_params = try c.arena.alloc(ast.Payload.Param, 1);
fn_params[0] = .{
.name = self_param_name,
.type = Tag.@"anytype".init(),
.is_noalias = false,
};
const array_type = @as(*const clang.ArrayType, @ptrCast(field_qt_canon));
const element_qt = array_type.getElementType();
const element_type = try transQualType(c, scope, element_qt, field_decl.getLocation());
var block_scope = try Scope.Block.init(c, scope, false);
defer block_scope.deinit();
const intermediate_type_name = try block_scope.makeMangledName(c, "Intermediate");
const intermediate_type = try Tag.helpers_flexible_array_type.create(c.arena, .{ .lhs = self_type, .rhs = u8_type });
const intermediate_type_decl = try Tag.var_simple.create(c.arena, .{
.name = intermediate_type_name,
.init = intermediate_type,
});
try block_scope.statements.append(intermediate_type_decl);
const intermediate_type_ident = try Tag.identifier.create(c.arena, intermediate_type_name);
const return_type_name = try block_scope.makeMangledName(c, "ReturnType");
const return_type = try Tag.helpers_flexible_array_type.create(c.arena, .{ .lhs = self_type, .rhs = element_type });
const return_type_decl = try Tag.var_simple.create(c.arena, .{
.name = return_type_name,
.init = return_type,
});
try block_scope.statements.append(return_type_decl);
const return_type_ident = try Tag.identifier.create(c.arena, return_type_name);
const field_index = field_decl.getFieldIndex();
const bit_offset = layout.getFieldOffset(field_index); // this is a target-specific constant based on the struct layout
const byte_offset = bit_offset / 8;
const casted_self = try Tag.as.create(c.arena, .{
.lhs = intermediate_type_ident,
.rhs = try Tag.ptr_cast.create(c.arena, self_param),
});
const field_offset = try transCreateNodeNumber(c, byte_offset, .int);
const field_ptr = try Tag.add.create(c.arena, .{ .lhs = casted_self, .rhs = field_offset });
const ptr_cast = try Tag.as.create(c.arena, .{
.lhs = return_type_ident,
.rhs = try Tag.ptr_cast.create(
c.arena,
try Tag.align_cast.create(
c.arena,
field_ptr,
),
),
});
const return_stmt = try Tag.@"return".create(c.arena, ptr_cast);
try block_scope.statements.append(return_stmt);
const payload = try c.arena.create(ast.Payload.Func);
payload.* = .{
.base = .{ .tag = .func },
.data = .{
.is_pub = true,
.is_extern = false,
.is_export = false,
.is_inline = false,
.is_var_args = false,
.name = field_name,
.linksection_string = null,
.explicit_callconv = null,
.params = fn_params,
.return_type = return_type,
.body = try block_scope.complete(c),
.alignment = null,
},
};
return Node.initPayload(&payload.base);
}
/// Return true if `field_decl` is the flexible array field for its parent record
fn isFlexibleArrayFieldDecl(c: *Context, field_decl: *const clang.FieldDecl) bool {
const record_decl = field_decl.getParent() orelse return false;
const record_flexible_field = flexibleArrayField(c, record_decl) orelse return false;
return field_decl == record_flexible_field;
}
/// Find the flexible array field for a record if any. A flexible array field is an
/// incomplete or zero-length array that occurs as the last field of a record.
/// clang's RecordDecl::hasFlexibleArrayMember is not suitable for determining
/// this because it returns false for a record that ends with a zero-length
/// array, but we consider those to be flexible arrays
fn flexibleArrayField(c: *Context, record_def: *const clang.RecordDecl) ?*const clang.FieldDecl {
var it = record_def.field_begin();
const end_it = record_def.field_end();
var flexible_field: ?*const clang.FieldDecl = null;
while (it.neq(end_it)) : (it = it.next()) {
const field_decl = it.deref();
const ty = qualTypeCanon(field_decl.getType());
const incomplete_or_zero_size = ty.isIncompleteOrZeroLengthArrayType(c.clang_context);
if (incomplete_or_zero_size) {
flexible_field = field_decl;
} else {
flexible_field = null;
}
}
return flexible_field;
}
fn mangleWeakGlobalName(c: *Context, want_name: []const u8) ![]const u8 {
var cur_name = want_name;
if (!c.weak_global_names.contains(want_name)) {
// This type wasn't noticed by the name detection pass, so nothing has been treating this as
// a weak global name. We must mangle it to avoid conflicts with locals.
cur_name = try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ want_name, c.getMangle() });
}
while (c.global_names.contains(cur_name)) {
cur_name = try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ want_name, c.getMangle() });
}
return cur_name;
}
fn transRecordDecl(c: *Context, scope: *Scope, record_decl: *const clang.RecordDecl) Error!void {
if (c.decl_table.get(@intFromPtr(record_decl.getCanonicalDecl()))) |_|
return; // Avoid processing this decl twice
const record_loc = record_decl.getLocation();
const toplevel = scope.id == .root;
const bs: *Scope.Block = if (!toplevel) try scope.findBlockScope(c) else undefined;
var is_union = false;
var container_kind_name: []const u8 = undefined;
var bare_name: []const u8 = try c.str(@as(*const clang.NamedDecl, @ptrCast(record_decl)).getName_bytes_begin());
if (record_decl.isUnion()) {
container_kind_name = "union";
is_union = true;
} else if (record_decl.isStruct()) {
container_kind_name = "struct";
} else {
try c.decl_table.putNoClobber(c.gpa, @intFromPtr(record_decl.getCanonicalDecl()), bare_name);
return failDecl(c, record_loc, bare_name, "record {s} is not a struct or union", .{bare_name});
}
var is_unnamed = false;
var name = bare_name;
if (c.unnamed_typedefs.get(@intFromPtr(record_decl.getCanonicalDecl()))) |typedef_name| {
bare_name = typedef_name;
name = typedef_name;
} else {
// Record declarations such as `struct {...} x` have no name but they're not
// anonymous hence here isAnonymousStructOrUnion is not needed
if (bare_name.len == 0) {
bare_name = try std.fmt.allocPrint(c.arena, "unnamed_{d}", .{c.getMangle()});
is_unnamed = true;
}
name = try std.fmt.allocPrint(c.arena, "{s}_{s}", .{ container_kind_name, bare_name });
if (toplevel and !is_unnamed) {
name = try mangleWeakGlobalName(c, name);
}
}
if (!toplevel) name = try bs.makeMangledName(c, name);
try c.decl_table.putNoClobber(c.gpa, @intFromPtr(record_decl.getCanonicalDecl()), name);
const is_pub = toplevel and !is_unnamed;
const init_node = blk: {
const record_def = record_decl.getDefinition() orelse {
try c.opaque_demotes.put(c.gpa, @intFromPtr(record_decl.getCanonicalDecl()), {});
break :blk Tag.opaque_literal.init();
};
var fields = std.ArrayList(ast.Payload.Record.Field).init(c.gpa);
defer fields.deinit();
var functions = std.ArrayList(Node).init(c.gpa);
defer functions.deinit();
const flexible_field = flexibleArrayField(c, record_def);
var unnamed_field_count: u32 = 0;
var it = record_def.field_begin();
const end_it = record_def.field_end();
const layout = record_def.getASTRecordLayout(c.clang_context);
const record_alignment = layout.getAlignment();
while (it.neq(end_it)) : (it = it.next()) {
const field_decl = it.deref();
const field_loc = field_decl.getLocation();
const field_qt = field_decl.getType();
if (field_decl.isBitField()) {
try c.opaque_demotes.put(c.gpa, @intFromPtr(record_decl.getCanonicalDecl()), {});
try warn(c, scope, field_loc, "{s} demoted to opaque type - has bitfield", .{container_kind_name});
break :blk Tag.opaque_literal.init();
}
var is_anon = false;
var field_name = try c.str(@as(*const clang.NamedDecl, @ptrCast(field_decl)).getName_bytes_begin());
if (field_decl.isAnonymousStructOrUnion() or field_name.len == 0) {
// Context.getMangle() is not used here because doing so causes unpredictable field names for anonymous fields.
field_name = try std.fmt.allocPrint(c.arena, "unnamed_{d}", .{unnamed_field_count});
unnamed_field_count += 1;
is_anon = true;
}
if (flexible_field == field_decl) {
const flexible_array_fn = buildFlexibleArrayFn(c, scope, layout, field_name, field_decl) catch |err| switch (err) {
error.UnsupportedType => {
try c.opaque_demotes.put(c.gpa, @intFromPtr(record_decl.getCanonicalDecl()), {});
try warn(c, scope, record_loc, "{s} demoted to opaque type - unable to translate type of flexible array field {s}", .{ container_kind_name, field_name });
break :blk Tag.opaque_literal.init();
},
else => |e| return e,
};
try functions.append(flexible_array_fn);
continue;
}
const field_type = transQualType(c, scope, field_qt, field_loc) catch |err| switch (err) {
error.UnsupportedType => {
try c.opaque_demotes.put(c.gpa, @intFromPtr(record_decl.getCanonicalDecl()), {});
try warn(c, scope, record_loc, "{s} demoted to opaque type - unable to translate type of field {s}", .{ container_kind_name, field_name });
break :blk Tag.opaque_literal.init();
},
else => |e| return e,
};
const alignment = if (flexible_field != null and field_decl.getFieldIndex() == 0)
@as(c_uint, @intCast(record_alignment))
else
ClangAlignment.forField(c, field_decl, record_def).zigAlignment();
// C99 introduced designated initializers for structs. Omitted fields are implicitly
// initialized to zero. Some C APIs are designed with this in mind. Defaulting to zero
// values for translated struct fields permits Zig code to comfortably use such an API.
const default_value = if (record_decl.isStruct())
try Tag.std_mem_zeroes.create(c.arena, field_type)
else
null;
if (is_anon) {
try c.decl_table.putNoClobber(c.gpa, @intFromPtr(field_decl.getCanonicalDecl()), field_name);
}
try fields.append(.{
.name = field_name,
.type = field_type,
.alignment = alignment,
.default_value = default_value,
});
}