authorgravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2021-08-29 15:09:22+03:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2021-08-29 15:11:38+03:00
logbe9b490f844277237bd0b60ba6120689723243b3
tree508690c564f01966500de51eb3fb4f84f81ecc20
parent49c9975484aeb4c1534626d0f975a938a795ebe2

translate-c: remove now unnecessary mangling of primitive type shadowing

Closes #6382

3 files changed, 55 insertions(+), 57 deletions(-)

src/translate_c.zig+24-49
......@@ -203,9 +203,7 @@ const Scope = struct {
203203 /// Check if the global scope contains this name, without looking into the "future", e.g.
204204 /// ignore the preprocessed decl and macro names.
205205 fn containsNow(scope: *Root, name: []const u8) bool {
206 return isZigPrimitiveType(name) or
207 scope.sym_table.contains(name) or
208 scope.macro_table.contains(name);
206 return scope.sym_table.contains(name) or scope.macro_table.contains(name);
209207 }
210208
211209 /// Check if the global scope contains the name, includes all decls that haven't been translated yet.
......@@ -495,19 +493,17 @@ fn declVisitorNamesOnly(c: *Context, decl: *const clang.Decl) Error!void {
495493 },
496494 else => return,
497495 } else unreachable;
498 // TODO https://github.com/ziglang/zig/issues/3756
499 // TODO https://github.com/ziglang/zig/issues/1802
500 const name = if (isZigPrimitiveType(decl_name)) try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ decl_name, c.getMangle() }) else decl_name;
496
501497 const result = try c.unnamed_typedefs.getOrPut(c.gpa, addr);
502498 if (result.found_existing) {
503499 // One typedef can declare multiple names.
504500 // Don't put this one in `decl_table` so it's processed later.
505501 return;
506502 }
507 result.value_ptr.* = name;
503 result.value_ptr.* = decl_name;
508504 // Put this typedef in the decl_table to avoid redefinitions.
509 try c.decl_table.putNoClobber(c.gpa, @ptrToInt(typedef_decl.getCanonicalDecl()), name);
510 try c.typedefs.put(c.gpa, name, {});
505 try c.decl_table.putNoClobber(c.gpa, @ptrToInt(typedef_decl.getCanonicalDecl()), decl_name);
506 try c.typedefs.put(c.gpa, decl_name, {});
511507 }
512508 }
513509}
......@@ -752,10 +748,6 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co
752748 const is_pub = mangled_name == null;
753749 const is_threadlocal = var_decl.getTLSKind() != .None;
754750 const scope = &c.global_scope.base;
755
756 // TODO https://github.com/ziglang/zig/issues/3756
757 // TODO https://github.com/ziglang/zig/issues/1802
758 const checked_name = if (isZigPrimitiveType(var_name)) try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ var_name, c.getMangle() }) else var_name;
759751 const var_decl_loc = var_decl.getLocation();
760752
761753 const qual_type = var_decl.getTypeSourceInfo_getType();
......@@ -774,7 +766,7 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co
774766
775767 const type_node = transQualTypeMaybeInitialized(c, scope, qual_type, decl_init, var_decl_loc) catch |err| switch (err) {
776768 error.UnsupportedTranslation, error.UnsupportedType => {
777 return failDecl(c, var_decl_loc, checked_name, "unable to resolve variable type", .{});
769 return failDecl(c, var_decl_loc, var_name, "unable to resolve variable type", .{});
778770 },
779771 error.OutOfMemory => |e| return e,
780772 };
......@@ -833,11 +825,11 @@ fn visitVarDecl(c: *Context, var_decl: *const clang.VarDecl, mangled_name: ?[]co
833825 .is_threadlocal = is_threadlocal,
834826 .linksection_string = linksection_string,
835827 .alignment = zigAlignment(var_decl.getAlignedAttribute(c.clang_context)),
836 .name = checked_name,
828 .name = var_name,
837829 .type = type_node,
838830 .init = init_node,
839831 });
840 return addTopLevelDecl(c, checked_name, node);
832 return addTopLevelDecl(c, var_name, node);
841833}
842834
843835const builtin_typedef_map = std.ComptimeStringMap([]const u8, .{
......@@ -861,11 +853,7 @@ fn transTypeDef(c: *Context, scope: *Scope, typedef_decl: *const clang.TypedefNa
861853 const toplevel = scope.id == .root;
862854 const bs: *Scope.Block = if (!toplevel) try scope.findBlockScope(c) else undefined;
863855
864 const bare_name = try c.str(@ptrCast(*const clang.NamedDecl, typedef_decl).getName_bytes_begin());
865
866 // TODO https://github.com/ziglang/zig/issues/3756
867 // TODO https://github.com/ziglang/zig/issues/1802
868 var name: []const u8 = if (isZigPrimitiveType(bare_name)) try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ bare_name, c.getMangle() }) else bare_name;
856 var name: []const u8 = try c.str(@ptrCast(*const clang.NamedDecl, typedef_decl).getName_bytes_begin());
869857 try c.typedefs.put(c.gpa, name, {});
870858
871859 if (builtin_typedef_map.get(name)) |builtin| {
......@@ -1535,12 +1523,12 @@ fn transOffsetOfExpr(
15351523/// node -> @bitCast(usize, @intCast(isize, node))
15361524fn usizeCastForWrappingPtrArithmetic(gpa: *mem.Allocator, node: Node) TransError!Node {
15371525 const intcast_node = try Tag.int_cast.create(gpa, .{
1538 .lhs = try Tag.identifier.create(gpa, "isize"),
1526 .lhs = try Tag.type.create(gpa, "isize"),
15391527 .rhs = node,
15401528 });
15411529
15421530 return Tag.bit_cast.create(gpa, .{
1543 .lhs = try Tag.identifier.create(gpa, "usize"),
1531 .lhs = try Tag.type.create(gpa, "usize"),
15441532 .rhs = intcast_node,
15451533 });
15461534}
......@@ -3345,7 +3333,7 @@ fn transSignedArrayAccess(
33453333 const then_value = try Tag.add.create(c.arena, .{
33463334 .lhs = container_node,
33473335 .rhs = try Tag.int_cast.create(c.arena, .{
3348 .lhs = try Tag.identifier.create(c.arena, "usize"),
3336 .lhs = try Tag.type.create(c.arena, "usize"),
33493337 .rhs = tmp_ref,
33503338 }),
33513339 });
......@@ -3357,7 +3345,7 @@ fn transSignedArrayAccess(
33573345
33583346 const minuend = container_node;
33593347 const signed_size = try Tag.int_cast.create(c.arena, .{
3360 .lhs = try Tag.identifier.create(c.arena, "isize"),
3348 .lhs = try Tag.type.create(c.arena, "isize"),
33613349 .rhs = tmp_ref,
33623350 });
33633351 const to_cast = try Tag.add_wrap.create(c.arena, .{
......@@ -3365,7 +3353,7 @@ fn transSignedArrayAccess(
33653353 .rhs = try Tag.negate.create(c.arena, Tag.one_literal.init()),
33663354 });
33673355 const bitcast_node = try Tag.bit_cast.create(c.arena, .{
3368 .lhs = try Tag.identifier.create(c.arena, "usize"),
3356 .lhs = try Tag.type.create(c.arena, "usize"),
33693357 .rhs = to_cast,
33703358 });
33713359 const subtrahend = try Tag.bit_not.create(c.arena, bitcast_node);
......@@ -3421,7 +3409,7 @@ fn transArrayAccess(c: *Context, scope: *Scope, stmt: *const clang.ArraySubscrip
34213409 const container_node = try transExpr(c, scope, unwrapped_base, .used);
34223410 const rhs = if (is_longlong or is_signed) blk: {
34233411 // check if long long first so that signed long long doesn't just become unsigned long long
3424 const typeid_node = if (is_longlong) try Tag.identifier.create(c.arena, "usize") else try transQualTypeIntWidthOf(c, subscr_qt, false);
3412 const typeid_node = if (is_longlong) try Tag.type.create(c.arena, "usize") else try transQualTypeIntWidthOf(c, subscr_qt, false);
34253413 break :blk try Tag.int_cast.create(c.arena, .{ .lhs = typeid_node, .rhs = try transExpr(c, scope, subscr_expr, .used) });
34263414 } else try transExpr(c, scope, subscr_expr, .used);
34273415
......@@ -3953,7 +3941,7 @@ fn transFloatingLiteral(c: *Context, scope: *Scope, expr: *const clang.FloatingL
39533941
39543942fn transBinaryConditionalOperator(c: *Context, scope: *Scope, stmt: *const clang.BinaryConditionalOperator, used: ResultUsed) TransError!Node {
39553943 // GNU extension of the ternary operator where the middle expression is
3956 // omitted, the conditition itself is returned if it evaluates to true
3944 // omitted, the condition itself is returned if it evaluates to true
39573945 const qt = @ptrCast(*const clang.Expr, stmt).getType();
39583946 const res_is_bool = qualTypeIsBoolean(qt);
39593947 const casted_stmt = @ptrCast(*const clang.AbstractConditionalOperator, stmt);
......@@ -4040,7 +4028,7 @@ fn transConditionalOperator(c: *Context, scope: *Scope, stmt: *const clang.Condi
40404028 .then = then_body,
40414029 .@"else" = else_body,
40424030 });
4043 // Clang inserts ImplicitCast(ToVoid)'s to both rhs and lhs so we don't need to supress the result here.
4031 // Clang inserts ImplicitCast(ToVoid)'s to both rhs and lhs so we don't need to suppress the result here.
40444032 return if_node;
40454033}
40464034
......@@ -4671,6 +4659,7 @@ fn transType(c: *Context, scope: *Scope, ty: *const clang.Type, source_loc: clan
46714659 if (@ptrCast(*const clang.Decl, typedef_decl).castToNamedDecl()) |named_decl| {
46724660 const decl_name = try c.str(named_decl.getName_bytes_begin());
46734661 if (c.global_names.get(decl_name)) |_| trans_scope = &c.global_scope.base;
4662 if (builtin_typedef_map.get(decl_name)) |builtin| return Tag.type.create(c.arena, builtin);
46744663 }
46754664 try transTypeDef(c, trans_scope, typedef_decl);
46764665 const name = c.decl_table.get(@ptrToInt(typedef_decl.getCanonicalDecl())).?;
......@@ -4994,19 +4983,6 @@ pub fn freeErrors(errors: []ClangErrMsg) void {
49944983 errors.ptr.delete(errors.len);
49954984}
49964985
4997fn isZigPrimitiveType(name: []const u8) bool {
4998 if (name.len > 1 and (name[0] == 'u' or name[0] == 'i')) {
4999 for (name[1..]) |c| {
5000 switch (c) {
5001 '0'...'9' => {},
5002 else => return false,
5003 }
5004 }
5005 return true;
5006 }
5007 return @import("AstGen.zig").simple_types.has(name);
5008}
5009
50104986const PatternList = struct {
50114987 patterns: []Pattern,
50124988
......@@ -5311,10 +5287,7 @@ fn transPreprocessorEntities(c: *Context, unit: *clang.ASTUnit) Error!void {
53115287 const end_loc = clang.Lexer.getLocForEndOfToken(macro.getSourceRange_getEnd(), c.source_manager, unit);
53125288
53135289 const name = try c.str(raw_name);
5314 // TODO https://github.com/ziglang/zig/issues/3756
5315 // TODO https://github.com/ziglang/zig/issues/1802
5316 const mangled_name = if (isZigPrimitiveType(name)) try std.fmt.allocPrint(c.arena, "{s}_{d}", .{ name, c.getMangle() }) else name;
5317 if (scope.containsNow(mangled_name)) {
5290 if (scope.containsNow(name)) {
53185291 continue;
53195292 }
53205293
......@@ -5328,7 +5301,7 @@ fn transPreprocessorEntities(c: *Context, unit: *clang.ASTUnit) Error!void {
53285301 var macro_ctx = MacroCtx{
53295302 .source = slice,
53305303 .list = tok_list.items,
5331 .name = mangled_name,
5304 .name = name,
53325305 .loc = begin_loc,
53335306 };
53345307 assert(mem.eql(u8, macro_ctx.slice(), name));
......@@ -5766,7 +5739,8 @@ fn parseCPrimaryExprInner(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!N
57665739 try m.fail(c, "TODO implement function '{s}' in std.zig.c_builtins", .{mangled_name});
57675740 return error.ParseError;
57685741 }
5769 const identifier = try Tag.identifier.create(c.arena, builtin_typedef_map.get(mangled_name) orelse mangled_name);
5742 if (builtin_typedef_map.get(mangled_name)) |ty| return Tag.type.create(c.arena, ty);
5743 const identifier = try Tag.identifier.create(c.arena, mangled_name);
57705744 scope.skipVariableDiscard(identifier.castTag(.identifier).?.data);
57715745 return identifier;
57725746 },
......@@ -6055,7 +6029,8 @@ fn parseCSpecifierQualifierList(c: *Context, m: *MacroCtx, scope: *Scope, allow_
60556029 .Identifier => {
60566030 const mangled_name = scope.getAlias(m.slice());
60576031 if (!allow_fail or c.typedefs.contains(mangled_name)) {
6058 return try Tag.identifier.create(c.arena, builtin_typedef_map.get(mangled_name) orelse mangled_name);
6032 if (builtin_typedef_map.get(mangled_name)) |ty| return try Tag.type.create(c.arena, ty);
6033 return try Tag.identifier.create(c.arena, mangled_name);
60596034 }
60606035 },
60616036 .Keyword_void => return try Tag.type.create(c.arena, "c_void"),
src/translate_c/ast.zig+19-4
......@@ -801,11 +801,26 @@ const Context = struct {
801801 }
802802
803803 fn addToken(c: *Context, tag: TokenTag, bytes: []const u8) Allocator.Error!TokenIndex {
804 return addTokenFmt(c, tag, "{s}", .{bytes});
804 return c.addTokenFmt(tag, "{s}", .{bytes});
805 }
806
807 fn isZigPrimitiveType(name: []const u8) bool {
808 if (name.len > 1 and (name[0] == 'u' or name[0] == 'i')) {
809 for (name[1..]) |c| {
810 switch (c) {
811 '0'...'9' => {},
812 else => return false,
813 }
814 }
815 return true;
816 }
817 return @import("../AstGen.zig").simple_types.has(name);
805818 }
806819
807820 fn addIdentifier(c: *Context, bytes: []const u8) Allocator.Error!TokenIndex {
808 return addTokenFmt(c, .identifier, "{s}", .{std.zig.fmtId(bytes)});
821 if (isZigPrimitiveType(bytes))
822 return c.addTokenFmt(.identifier, "@\"{s}\"", .{bytes});
823 return c.addTokenFmt(.identifier, "{s}", .{std.zig.fmtId(bytes)});
809824 }
810825
811826 fn listToSpan(c: *Context, list: []const NodeIndex) Allocator.Error!NodeSubRange {
......@@ -1999,7 +2014,7 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {
19992014 members[1] = 0;
20002015
20012016 for (payload.fields) |field, i| {
2002 const name_tok = try c.addIdentifier(field.name);
2017 const name_tok = try c.addTokenFmt(.identifier, "{s}", .{std.zig.fmtId(field.name)});
20032018 _ = try c.addToken(.colon, ":");
20042019 const type_expr = try renderNode(c, field.type);
20052020
......@@ -2079,7 +2094,7 @@ fn renderFieldAccess(c: *Context, lhs: NodeIndex, field_name: []const u8) !NodeI
20792094 .main_token = try c.addToken(.period, "."),
20802095 .data = .{
20812096 .lhs = lhs,
2082 .rhs = try c.addIdentifier(field_name),
2097 .rhs = try c.addTokenFmt(.identifier, "{s}", .{std.zig.fmtId(field_name)}),
20832098 },
20842099 });
20852100}
test/translate_c.zig+12-4
......@@ -318,8 +318,8 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
318318 \\};
319319 \\pub const Color = struct_Color;
320320 ,
321 \\pub inline fn CLITERAL(type_1: anytype) @TypeOf(type_1) {
322 \\ return type_1;
321 \\pub inline fn CLITERAL(@"type": anytype) @TypeOf(@"type") {
322 \\ return @"type";
323323 \\}
324324 ,
325325 \\pub const LIGHTGRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 200), @as(c_int, 200), @as(c_int, 200), @as(c_int, 255) });
......@@ -2031,10 +2031,18 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
20312031 cases.add("shadowing primitive types",
20322032 \\unsigned anyerror = 2;
20332033 \\#define noreturn _Noreturn
2034 \\typedef enum {
2035 \\ f32,
2036 \\ u32,
2037 \\} BadEnum;
20342038 , &[_][]const u8{
2035 \\pub export var anyerror_1: c_uint = 2;
2039 \\pub export var @"anyerror": c_uint = 2;
2040 ,
2041 \\pub const @"noreturn" = @compileError("unable to translate C expr: unexpected token .Keyword_noreturn");
20362042 ,
2037 \\pub const noreturn_2 = @compileError("unable to translate C expr: unexpected token .Keyword_noreturn");
2043 \\pub const @"f32": c_int = 0;
2044 \\pub const @"u32": c_int = 1;
2045 \\pub const BadEnum = c_uint;
20382046 });
20392047
20402048 cases.add("floats",