Skip to content

Commit a5d25fa

Browse files
authored
translate_c: fix typedeffed pointer subtraction
Closes #14560.
1 parent d24ebf1 commit a5d25fa

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/translate_c.zig

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1748,7 +1748,8 @@ fn transBinaryOperator(
17481748
const lhs_expr = stmt.getLHS();
17491749
const lhs_qt = getExprQualType(c, lhs_expr);
17501750
const lhs_qt_translated = try transQualType(c, scope, lhs_qt, lhs_expr.getBeginLoc());
1751-
const elem_type = lhs_qt_translated.castTag(.c_pointer).?.data.elem_type;
1751+
const c_pointer = getContainer(c, lhs_qt_translated).?;
1752+
const elem_type = c_pointer.castTag(.c_pointer).?.data.elem_type;
17521753
const sizeof = try Tag.sizeof.create(c.arena, elem_type);
17531754

17541755
const bitcast = try Tag.bit_cast.create(c.arena, .{ .lhs = ptrdiff_type, .rhs = infixOpNode });

test/translate_c.zig

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3916,4 +3916,36 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
39163916
\\ }) != 0) {}
39173917
\\}
39183918
});
3919+
3920+
if (builtin.os.tag == .windows) {
3921+
cases.add("Pointer subtraction with typedef",
3922+
\\typedef char* S;
3923+
\\void foo() {
3924+
\\ S a, b;
3925+
\\ long long c = a - b;
3926+
\\}
3927+
, &[_][]const u8{
3928+
\\pub export fn foo() void {
3929+
\\ var a: S = undefined;
3930+
\\ var b: S = undefined;
3931+
\\ var c: c_longlong = @divExact(@bitCast(c_longlong, @ptrToInt(a) -% @ptrToInt(b)), @sizeOf(u8));
3932+
\\ _ = @TypeOf(c);
3933+
\\}
3934+
});
3935+
} else {
3936+
cases.add("Pointer subtraction with typedef",
3937+
\\typedef char* S;
3938+
\\void foo() {
3939+
\\ S a, b;
3940+
\\ long c = a - b;
3941+
\\}
3942+
, &[_][]const u8{
3943+
\\pub export fn foo() void {
3944+
\\ var a: S = undefined;
3945+
\\ var b: S = undefined;
3946+
\\ var c: c_long = @divExact(@bitCast(c_long, @ptrToInt(a) -% @ptrToInt(b)), @sizeOf(u8));
3947+
\\ _ = @TypeOf(c);
3948+
\\}
3949+
});
3950+
}
39193951
}

0 commit comments

Comments
 (0)