translate-c: move utility functions to a separate namespace

This commit is contained in:
Veikka Tuominen 2021-06-12 21:30:36 +03:00
parent ec36b82d05
commit 699b6cdf01
8 changed files with 501 additions and 476 deletions

View File

@ -10,7 +10,6 @@ const page_size = std.mem.page_size;
pub const tokenizer = @import("c/tokenizer.zig"); pub const tokenizer = @import("c/tokenizer.zig");
pub const Token = tokenizer.Token; pub const Token = tokenizer.Token;
pub const Tokenizer = tokenizer.Tokenizer; pub const Tokenizer = tokenizer.Tokenizer;
pub const builtins = @import("c/builtins.zig");
test { test {
_ = tokenizer; _ = tokenizer;

View File

@ -884,319 +884,6 @@ pub fn Vector(comptime len: u32, comptime child: type) type {
}); });
} }
/// Given a type and value, cast the value to the type as c would.
/// This is for translate-c and is not intended for general use.
pub fn cast(comptime DestType: type, target: anytype) DestType {
// this function should behave like transCCast in translate-c, except it's for macros and enums
const SourceType = @TypeOf(target);
switch (@typeInfo(DestType)) {
.Pointer => return castToPtr(DestType, SourceType, target),
.Optional => |dest_opt| {
if (@typeInfo(dest_opt.child) == .Pointer) {
return castToPtr(DestType, SourceType, target);
}
},
.Enum => |enum_type| {
if (@typeInfo(SourceType) == .Int or @typeInfo(SourceType) == .ComptimeInt) {
const intermediate = cast(enum_type.tag_type, target);
return @intToEnum(DestType, intermediate);
}
},
.Int => {
switch (@typeInfo(SourceType)) {
.Pointer => {
return castInt(DestType, @ptrToInt(target));
},
.Optional => |opt| {
if (@typeInfo(opt.child) == .Pointer) {
return castInt(DestType, @ptrToInt(target));
}
},
.Enum => {
return castInt(DestType, @enumToInt(target));
},
.Int => {
return castInt(DestType, target);
},
else => {},
}
},
else => {},
}
return @as(DestType, target);
}
fn castInt(comptime DestType: type, target: anytype) DestType {
const dest = @typeInfo(DestType).Int;
const source = @typeInfo(@TypeOf(target)).Int;
if (dest.bits < source.bits)
return @bitCast(DestType, @truncate(Int(source.signedness, dest.bits), target))
else
return @bitCast(DestType, @as(Int(source.signedness, dest.bits), target));
}
fn castPtr(comptime DestType: type, target: anytype) DestType {
const dest = ptrInfo(DestType);
const source = ptrInfo(@TypeOf(target));
if (source.is_const and !dest.is_const or source.is_volatile and !dest.is_volatile)
return @intToPtr(DestType, @ptrToInt(target))
else if (@typeInfo(dest.child) == .Opaque)
// dest.alignment would error out
return @ptrCast(DestType, target)
else
return @ptrCast(DestType, @alignCast(dest.alignment, target));
}
fn castToPtr(comptime DestType: type, comptime SourceType: type, target: anytype) DestType {
switch (@typeInfo(SourceType)) {
.Int => {
return @intToPtr(DestType, castInt(usize, target));
},
.ComptimeInt => {
if (target < 0)
return @intToPtr(DestType, @bitCast(usize, @intCast(isize, target)))
else
return @intToPtr(DestType, @intCast(usize, target));
},
.Pointer => {
return castPtr(DestType, target);
},
.Optional => |target_opt| {
if (@typeInfo(target_opt.child) == .Pointer) {
return castPtr(DestType, target);
}
},
else => {},
}
return @as(DestType, target);
}
fn ptrInfo(comptime PtrType: type) TypeInfo.Pointer {
return switch (@typeInfo(PtrType)) {
.Optional => |opt_info| @typeInfo(opt_info.child).Pointer,
.Pointer => |ptr_info| ptr_info,
else => unreachable,
};
}
test "std.meta.cast" {
const E = enum(u2) {
Zero,
One,
Two,
};
var i = @as(i64, 10);
try testing.expect(cast(*u8, 16) == @intToPtr(*u8, 16));
try testing.expect(cast(*u64, &i).* == @as(u64, 10));
try testing.expect(cast(*i64, @as(?*align(1) i64, &i)) == &i);
try testing.expect(cast(?*u8, 2) == @intToPtr(*u8, 2));
try testing.expect(cast(?*i64, @as(*align(1) i64, &i)) == &i);
try testing.expect(cast(?*i64, @as(?*align(1) i64, &i)) == &i);
try testing.expect(cast(E, 1) == .One);
try testing.expectEqual(@as(u32, 4), cast(u32, @intToPtr(*u32, 4)));
try testing.expectEqual(@as(u32, 4), cast(u32, @intToPtr(?*u32, 4)));
try testing.expectEqual(@as(u32, 10), cast(u32, @as(u64, 10)));
try testing.expectEqual(@as(u8, 2), cast(u8, E.Two));
try testing.expectEqual(@bitCast(i32, @as(u32, 0x8000_0000)), cast(i32, @as(u32, 0x8000_0000)));
try testing.expectEqual(@intToPtr(*u8, 2), cast(*u8, @intToPtr(*const u8, 2)));
try testing.expectEqual(@intToPtr(*u8, 2), cast(*u8, @intToPtr(*volatile u8, 2)));
try testing.expectEqual(@intToPtr(?*c_void, 2), cast(?*c_void, @intToPtr(*u8, 2)));
const C_ENUM = enum(c_int) {
A = 0,
B,
C,
_,
};
try testing.expectEqual(cast(C_ENUM, @as(i64, -1)), @intToEnum(C_ENUM, -1));
try testing.expectEqual(cast(C_ENUM, @as(i8, 1)), .B);
try testing.expectEqual(cast(C_ENUM, @as(u64, 1)), .B);
try testing.expectEqual(cast(C_ENUM, @as(u64, 42)), @intToEnum(C_ENUM, 42));
var foo: c_int = -1;
try testing.expect(cast(*c_void, -1) == @intToPtr(*c_void, @bitCast(usize, @as(isize, -1))));
try testing.expect(cast(*c_void, foo) == @intToPtr(*c_void, @bitCast(usize, @as(isize, -1))));
try testing.expect(cast(?*c_void, -1) == @intToPtr(?*c_void, @bitCast(usize, @as(isize, -1))));
try testing.expect(cast(?*c_void, foo) == @intToPtr(?*c_void, @bitCast(usize, @as(isize, -1))));
}
/// Given a value returns its size as C's sizeof operator would.
/// This is for translate-c and is not intended for general use.
pub fn sizeof(target: anytype) usize {
const T: type = if (@TypeOf(target) == type) target else @TypeOf(target);
switch (@typeInfo(T)) {
.Float, .Int, .Struct, .Union, .Enum, .Array, .Bool, .Vector => return @sizeOf(T),
.Fn => {
// sizeof(main) returns 1, sizeof(&main) returns pointer size.
// We cannot distinguish those types in Zig, so use pointer size.
return @sizeOf(T);
},
.Null => return @sizeOf(*c_void),
.Void => {
// Note: sizeof(void) is 1 on clang/gcc and 0 on MSVC.
return 1;
},
.Opaque => {
if (T == c_void) {
// Note: sizeof(void) is 1 on clang/gcc and 0 on MSVC.
return 1;
} else {
@compileError("Cannot use C sizeof on opaque type " ++ @typeName(T));
}
},
.Optional => |opt| {
if (@typeInfo(opt.child) == .Pointer) {
return sizeof(opt.child);
} else {
@compileError("Cannot use C sizeof on non-pointer optional " ++ @typeName(T));
}
},
.Pointer => |ptr| {
if (ptr.size == .Slice) {
@compileError("Cannot use C sizeof on slice type " ++ @typeName(T));
}
// for strings, sizeof("a") returns 2.
// normal pointer decay scenarios from C are handled
// in the .Array case above, but strings remain literals
// and are therefore always pointers, so they need to be
// specially handled here.
if (ptr.size == .One and ptr.is_const and @typeInfo(ptr.child) == .Array) {
const array_info = @typeInfo(ptr.child).Array;
if ((array_info.child == u8 or array_info.child == u16) and
array_info.sentinel != null and
array_info.sentinel.? == 0)
{
// length of the string plus one for the null terminator.
return (array_info.len + 1) * @sizeOf(array_info.child);
}
}
// When zero sized pointers are removed, this case will no
// longer be reachable and can be deleted.
if (@sizeOf(T) == 0) {
return @sizeOf(*c_void);
}
return @sizeOf(T);
},
.ComptimeFloat => return @sizeOf(f64), // TODO c_double #3999
.ComptimeInt => {
// TODO to get the correct result we have to translate
// `1073741824 * 4` as `int(1073741824) *% int(4)` since
// sizeof(1073741824 * 4) != sizeof(4294967296).
// TODO test if target fits in int, long or long long
return @sizeOf(c_int);
},
else => @compileError("std.meta.sizeof does not support type " ++ @typeName(T)),
}
}
test "sizeof" {
const E = enum(c_int) { One, _ };
const S = extern struct { a: u32 };
const ptr_size = @sizeOf(*c_void);
try testing.expect(sizeof(u32) == 4);
try testing.expect(sizeof(@as(u32, 2)) == 4);
try testing.expect(sizeof(2) == @sizeOf(c_int));
try testing.expect(sizeof(2.0) == @sizeOf(f64));
try testing.expect(sizeof(E) == @sizeOf(c_int));
try testing.expect(sizeof(E.One) == @sizeOf(c_int));
try testing.expect(sizeof(S) == 4);
try testing.expect(sizeof([_]u32{ 4, 5, 6 }) == 12);
try testing.expect(sizeof([3]u32) == 12);
try testing.expect(sizeof([3:0]u32) == 16);
try testing.expect(sizeof(&[_]u32{ 4, 5, 6 }) == ptr_size);
try testing.expect(sizeof(*u32) == ptr_size);
try testing.expect(sizeof([*]u32) == ptr_size);
try testing.expect(sizeof([*c]u32) == ptr_size);
try testing.expect(sizeof(?*u32) == ptr_size);
try testing.expect(sizeof(?[*]u32) == ptr_size);
try testing.expect(sizeof(*c_void) == ptr_size);
try testing.expect(sizeof(*void) == ptr_size);
try testing.expect(sizeof(null) == ptr_size);
try testing.expect(sizeof("foobar") == 7);
try testing.expect(sizeof(&[_:0]u16{ 'f', 'o', 'o', 'b', 'a', 'r' }) == 14);
try testing.expect(sizeof(*const [4:0]u8) == 5);
try testing.expect(sizeof(*[4:0]u8) == ptr_size);
try testing.expect(sizeof([*]const [4:0]u8) == ptr_size);
try testing.expect(sizeof(*const *const [4:0]u8) == ptr_size);
try testing.expect(sizeof(*const [4]u8) == ptr_size);
try testing.expect(sizeof(sizeof) == @sizeOf(@TypeOf(sizeof)));
try testing.expect(sizeof(void) == 1);
try testing.expect(sizeof(c_void) == 1);
}
pub const CIntLiteralRadix = enum { decimal, octal, hexadecimal };
fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: comptime_int, comptime radix: CIntLiteralRadix) type {
const signed_decimal = [_]type{ c_int, c_long, c_longlong };
const signed_oct_hex = [_]type{ c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong };
const unsigned = [_]type{ c_uint, c_ulong, c_ulonglong };
const list: []const type = if (@typeInfo(SuffixType).Int.signedness == .unsigned)
&unsigned
else if (radix == .decimal)
&signed_decimal
else
&signed_oct_hex;
var pos = mem.indexOfScalar(type, list, SuffixType).?;
while (pos < list.len) : (pos += 1) {
if (number >= math.minInt(list[pos]) and number <= math.maxInt(list[pos])) {
return list[pos];
}
}
@compileError("Integer literal is too large");
}
/// Promote the type of an integer literal until it fits as C would.
/// This is for translate-c and is not intended for general use.
pub fn promoteIntLiteral(
comptime SuffixType: type,
comptime number: comptime_int,
comptime radix: CIntLiteralRadix,
) PromoteIntLiteralReturnType(SuffixType, number, radix) {
return number;
}
test "promoteIntLiteral" {
const signed_hex = promoteIntLiteral(c_int, math.maxInt(c_int) + 1, .hexadecimal);
try testing.expectEqual(c_uint, @TypeOf(signed_hex));
if (math.maxInt(c_longlong) == math.maxInt(c_int)) return;
const signed_decimal = promoteIntLiteral(c_int, math.maxInt(c_int) + 1, .decimal);
const unsigned = promoteIntLiteral(c_uint, math.maxInt(c_uint) + 1, .hexadecimal);
if (math.maxInt(c_long) > math.maxInt(c_int)) {
try testing.expectEqual(c_long, @TypeOf(signed_decimal));
try testing.expectEqual(c_ulong, @TypeOf(unsigned));
} else {
try testing.expectEqual(c_longlong, @TypeOf(signed_decimal));
try testing.expectEqual(c_ulonglong, @TypeOf(unsigned));
}
}
/// For a given function type, returns a tuple type which fields will /// For a given function type, returns a tuple type which fields will
/// correspond to the argument types. /// correspond to the argument types.
/// ///
@ -1316,38 +1003,6 @@ pub fn globalOption(comptime name: []const u8, comptime T: type) ?T {
return @as(T, @field(root, name)); return @as(T, @field(root, name));
} }
/// This function is for translate-c and is not intended for general use.
/// Convert from clang __builtin_shufflevector index to Zig @shuffle index
/// clang requires __builtin_shufflevector index arguments to be integer constants.
/// negative values for `this_index` indicate "don't care" so we arbitrarily choose 0
/// clang enforces that `this_index` is less than the total number of vector elements
/// See https://ziglang.org/documentation/master/#shuffle
/// See https://clang.llvm.org/docs/LanguageExtensions.html#langext-builtin-shufflevector
pub fn shuffleVectorIndex(comptime this_index: c_int, comptime source_vector_len: usize) i32 {
if (this_index <= 0) return 0;
const positive_index = @intCast(usize, this_index);
if (positive_index < source_vector_len) return @intCast(i32, this_index);
const b_index = positive_index - source_vector_len;
return ~@intCast(i32, b_index);
}
test "shuffleVectorIndex" {
const vector_len: usize = 4;
try testing.expect(shuffleVectorIndex(-1, vector_len) == 0);
try testing.expect(shuffleVectorIndex(0, vector_len) == 0);
try testing.expect(shuffleVectorIndex(1, vector_len) == 1);
try testing.expect(shuffleVectorIndex(2, vector_len) == 2);
try testing.expect(shuffleVectorIndex(3, vector_len) == 3);
try testing.expect(shuffleVectorIndex(4, vector_len) == -1);
try testing.expect(shuffleVectorIndex(5, vector_len) == -2);
try testing.expect(shuffleVectorIndex(6, vector_len) == -3);
try testing.expect(shuffleVectorIndex(7, vector_len) == -4);
}
/// Returns whether `error_union` contains an error. /// Returns whether `error_union` contains an error.
pub fn isError(error_union: anytype) bool { pub fn isError(error_union: anytype) bool {
return if (error_union) |_| false else |_| true; return if (error_union) |_| false else |_| true;
@ -1357,34 +1012,3 @@ test "isError" {
try std.testing.expect(isError(math.absInt(@as(i8, -128)))); try std.testing.expect(isError(math.absInt(@as(i8, -128))));
try std.testing.expect(!isError(math.absInt(@as(i8, -127)))); try std.testing.expect(!isError(math.absInt(@as(i8, -127))));
} }
/// This function is for translate-c and is not intended for general use.
/// Constructs a [*c] pointer with the const and volatile annotations
/// from SelfType for pointing to a C flexible array of ElementType.
pub fn FlexibleArrayType(comptime SelfType: type, ElementType: type) type {
switch (@typeInfo(SelfType)) {
.Pointer => |ptr| {
return @Type(TypeInfo{ .Pointer = .{
.size = .C,
.is_const = ptr.is_const,
.is_volatile = ptr.is_volatile,
.alignment = @alignOf(ElementType),
.child = ElementType,
.is_allowzero = true,
.sentinel = null,
} });
},
else => |info| @compileError("Invalid self type \"" ++ @tagName(info) ++ "\" for flexible array getter: " ++ @typeName(SelfType)),
}
}
test "Flexible Array Type" {
const Container = extern struct {
size: usize,
};
try testing.expectEqual(FlexibleArrayType(*Container, c_int), [*c]c_int);
try testing.expectEqual(FlexibleArrayType(*const Container, c_int), [*c]const c_int);
try testing.expectEqual(FlexibleArrayType(*volatile Container, c_int), [*c]volatile c_int);
try testing.expectEqual(FlexibleArrayType(*const volatile Container, c_int), [*c]const volatile c_int);
}

View File

@ -16,6 +16,10 @@ pub const ast = @import("zig/ast.zig");
pub const system = @import("zig/system.zig"); pub const system = @import("zig/system.zig");
pub const CrossTarget = @import("zig/cross_target.zig").CrossTarget; pub const CrossTarget = @import("zig/cross_target.zig").CrossTarget;
// Files needed by translate-c.
pub const c_builtins = @import("zig/c_builtins.zig");
pub const c_translation = @import("zig/c_translation.zig");
pub const SrcHash = [16]u8; pub const SrcHash = [16]u8;
pub fn hashSrc(src: []const u8) SrcHash { pub fn hashSrc(src: []const u8) SrcHash {

View File

@ -0,0 +1,385 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2015-2021 Zig Contributors
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
// The MIT license requires this copyright notice to be included in all copies
// and substantial portions of the software.
const std = @import("std");
const testing = std.testing;
const math = std.math;
const mem = std.mem;
/// Given a type and value, cast the value to the type as c would.
pub fn cast(comptime DestType: type, target: anytype) DestType {
// this function should behave like transCCast in translate-c, except it's for macros and enums
const SourceType = @TypeOf(target);
switch (@typeInfo(DestType)) {
.Fn, .Pointer => return castToPtr(DestType, SourceType, target),
.Optional => |dest_opt| {
if (@typeInfo(dest_opt.child) == .Pointer or @typeInfo(dest_opt.child) == .Fn) {
return castToPtr(DestType, SourceType, target);
}
},
.Enum => |enum_type| {
if (@typeInfo(SourceType) == .Int or @typeInfo(SourceType) == .ComptimeInt) {
const intermediate = cast(enum_type.tag_type, target);
return @intToEnum(DestType, intermediate);
}
},
.Int => {
switch (@typeInfo(SourceType)) {
.Pointer => {
return castInt(DestType, @ptrToInt(target));
},
.Optional => |opt| {
if (@typeInfo(opt.child) == .Pointer) {
return castInt(DestType, @ptrToInt(target));
}
},
.Enum => {
return castInt(DestType, @enumToInt(target));
},
.Int => {
return castInt(DestType, target);
},
else => {},
}
},
else => {},
}
return @as(DestType, target);
}
fn castInt(comptime DestType: type, target: anytype) DestType {
const dest = @typeInfo(DestType).Int;
const source = @typeInfo(@TypeOf(target)).Int;
if (dest.bits < source.bits)
return @bitCast(DestType, @truncate(std.meta.Int(source.signedness, dest.bits), target))
else
return @bitCast(DestType, @as(std.meta.Int(source.signedness, dest.bits), target));
}
fn castPtr(comptime DestType: type, target: anytype) DestType {
const dest = ptrInfo(DestType);
const source = ptrInfo(@TypeOf(target));
if (source.is_const and !dest.is_const or source.is_volatile and !dest.is_volatile)
return @intToPtr(DestType, @ptrToInt(target))
else if (@typeInfo(dest.child) == .Opaque)
// dest.alignment would error out
return @ptrCast(DestType, target)
else
return @ptrCast(DestType, @alignCast(dest.alignment, target));
}
fn castToPtr(comptime DestType: type, comptime SourceType: type, target: anytype) DestType {
switch (@typeInfo(SourceType)) {
.Int => {
return @intToPtr(DestType, castInt(usize, target));
},
.ComptimeInt => {
if (target < 0)
return @intToPtr(DestType, @bitCast(usize, @intCast(isize, target)))
else
return @intToPtr(DestType, @intCast(usize, target));
},
.Pointer => {
return castPtr(DestType, target);
},
.Optional => |target_opt| {
if (@typeInfo(target_opt.child) == .Pointer) {
return castPtr(DestType, target);
}
},
else => {},
}
return @as(DestType, target);
}
fn ptrInfo(comptime PtrType: type) std.builtin.TypeInfo.Pointer {
return switch (@typeInfo(PtrType)) {
.Optional => |opt_info| @typeInfo(opt_info.child).Pointer,
.Pointer => |ptr_info| ptr_info,
else => unreachable,
};
}
test "cast" {
const E = enum(u2) {
Zero,
One,
Two,
};
var i = @as(i64, 10);
try testing.expect(cast(*u8, 16) == @intToPtr(*u8, 16));
try testing.expect(cast(*u64, &i).* == @as(u64, 10));
try testing.expect(cast(*i64, @as(?*align(1) i64, &i)) == &i);
try testing.expect(cast(?*u8, 2) == @intToPtr(*u8, 2));
try testing.expect(cast(?*i64, @as(*align(1) i64, &i)) == &i);
try testing.expect(cast(?*i64, @as(?*align(1) i64, &i)) == &i);
try testing.expect(cast(E, 1) == .One);
try testing.expectEqual(@as(u32, 4), cast(u32, @intToPtr(*u32, 4)));
try testing.expectEqual(@as(u32, 4), cast(u32, @intToPtr(?*u32, 4)));
try testing.expectEqual(@as(u32, 10), cast(u32, @as(u64, 10)));
try testing.expectEqual(@as(u8, 2), cast(u8, E.Two));
try testing.expectEqual(@bitCast(i32, @as(u32, 0x8000_0000)), cast(i32, @as(u32, 0x8000_0000)));
try testing.expectEqual(@intToPtr(*u8, 2), cast(*u8, @intToPtr(*const u8, 2)));
try testing.expectEqual(@intToPtr(*u8, 2), cast(*u8, @intToPtr(*volatile u8, 2)));
try testing.expectEqual(@intToPtr(?*c_void, 2), cast(?*c_void, @intToPtr(*u8, 2)));
const C_ENUM = enum(c_int) {
A = 0,
B,
C,
_,
};
try testing.expectEqual(cast(C_ENUM, @as(i64, -1)), @intToEnum(C_ENUM, -1));
try testing.expectEqual(cast(C_ENUM, @as(i8, 1)), .B);
try testing.expectEqual(cast(C_ENUM, @as(u64, 1)), .B);
try testing.expectEqual(cast(C_ENUM, @as(u64, 42)), @intToEnum(C_ENUM, 42));
var foo: c_int = -1;
try testing.expect(cast(*c_void, -1) == @intToPtr(*c_void, @bitCast(usize, @as(isize, -1))));
try testing.expect(cast(*c_void, foo) == @intToPtr(*c_void, @bitCast(usize, @as(isize, -1))));
try testing.expect(cast(?*c_void, -1) == @intToPtr(?*c_void, @bitCast(usize, @as(isize, -1))));
try testing.expect(cast(?*c_void, foo) == @intToPtr(?*c_void, @bitCast(usize, @as(isize, -1))));
const FnPtr = ?fn (*c_void) void;
try testing.expect(cast(FnPtr, 0) == @intToPtr(FnPtr, @as(usize, 0)));
try testing.expect(cast(FnPtr, foo) == @intToPtr(FnPtr, @bitCast(usize, @as(isize, -1))));
}
/// Given a value returns its size as C's sizeof operator would.
pub fn sizeof(target: anytype) usize {
const T: type = if (@TypeOf(target) == type) target else @TypeOf(target);
switch (@typeInfo(T)) {
.Float, .Int, .Struct, .Union, .Enum, .Array, .Bool, .Vector => return @sizeOf(T),
.Fn => {
// sizeof(main) returns 1, sizeof(&main) returns pointer size.
// We cannot distinguish those types in Zig, so use pointer size.
return @sizeOf(T);
},
.Null => return @sizeOf(*c_void),
.Void => {
// Note: sizeof(void) is 1 on clang/gcc and 0 on MSVC.
return 1;
},
.Opaque => {
if (T == c_void) {
// Note: sizeof(void) is 1 on clang/gcc and 0 on MSVC.
return 1;
} else {
@compileError("Cannot use C sizeof on opaque type " ++ @typeName(T));
}
},
.Optional => |opt| {
if (@typeInfo(opt.child) == .Pointer) {
return sizeof(opt.child);
} else {
@compileError("Cannot use C sizeof on non-pointer optional " ++ @typeName(T));
}
},
.Pointer => |ptr| {
if (ptr.size == .Slice) {
@compileError("Cannot use C sizeof on slice type " ++ @typeName(T));
}
// for strings, sizeof("a") returns 2.
// normal pointer decay scenarios from C are handled
// in the .Array case above, but strings remain literals
// and are therefore always pointers, so they need to be
// specially handled here.
if (ptr.size == .One and ptr.is_const and @typeInfo(ptr.child) == .Array) {
const array_info = @typeInfo(ptr.child).Array;
if ((array_info.child == u8 or array_info.child == u16) and
array_info.sentinel != null and
array_info.sentinel.? == 0)
{
// length of the string plus one for the null terminator.
return (array_info.len + 1) * @sizeOf(array_info.child);
}
}
// When zero sized pointers are removed, this case will no
// longer be reachable and can be deleted.
if (@sizeOf(T) == 0) {
return @sizeOf(*c_void);
}
return @sizeOf(T);
},
.ComptimeFloat => return @sizeOf(f64), // TODO c_double #3999
.ComptimeInt => {
// TODO to get the correct result we have to translate
// `1073741824 * 4` as `int(1073741824) *% int(4)` since
// sizeof(1073741824 * 4) != sizeof(4294967296).
// TODO test if target fits in int, long or long long
return @sizeOf(c_int);
},
else => @compileError("std.meta.sizeof does not support type " ++ @typeName(T)),
}
}
test "sizeof" {
const E = enum(c_int) { One, _ };
const S = extern struct { a: u32 };
const ptr_size = @sizeOf(*c_void);
try testing.expect(sizeof(u32) == 4);
try testing.expect(sizeof(@as(u32, 2)) == 4);
try testing.expect(sizeof(2) == @sizeOf(c_int));
try testing.expect(sizeof(2.0) == @sizeOf(f64));
try testing.expect(sizeof(E) == @sizeOf(c_int));
try testing.expect(sizeof(E.One) == @sizeOf(c_int));
try testing.expect(sizeof(S) == 4);
try testing.expect(sizeof([_]u32{ 4, 5, 6 }) == 12);
try testing.expect(sizeof([3]u32) == 12);
try testing.expect(sizeof([3:0]u32) == 16);
try testing.expect(sizeof(&[_]u32{ 4, 5, 6 }) == ptr_size);
try testing.expect(sizeof(*u32) == ptr_size);
try testing.expect(sizeof([*]u32) == ptr_size);
try testing.expect(sizeof([*c]u32) == ptr_size);
try testing.expect(sizeof(?*u32) == ptr_size);
try testing.expect(sizeof(?[*]u32) == ptr_size);
try testing.expect(sizeof(*c_void) == ptr_size);
try testing.expect(sizeof(*void) == ptr_size);
try testing.expect(sizeof(null) == ptr_size);
try testing.expect(sizeof("foobar") == 7);
try testing.expect(sizeof(&[_:0]u16{ 'f', 'o', 'o', 'b', 'a', 'r' }) == 14);
try testing.expect(sizeof(*const [4:0]u8) == 5);
try testing.expect(sizeof(*[4:0]u8) == ptr_size);
try testing.expect(sizeof([*]const [4:0]u8) == ptr_size);
try testing.expect(sizeof(*const *const [4:0]u8) == ptr_size);
try testing.expect(sizeof(*const [4]u8) == ptr_size);
try testing.expect(sizeof(sizeof) == @sizeOf(@TypeOf(sizeof)));
try testing.expect(sizeof(void) == 1);
try testing.expect(sizeof(c_void) == 1);
}
pub const CIntLiteralRadix = enum { decimal, octal, hexadecimal };
fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: comptime_int, comptime radix: CIntLiteralRadix) type {
const signed_decimal = [_]type{ c_int, c_long, c_longlong };
const signed_oct_hex = [_]type{ c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong };
const unsigned = [_]type{ c_uint, c_ulong, c_ulonglong };
const list: []const type = if (@typeInfo(SuffixType).Int.signedness == .unsigned)
&unsigned
else if (radix == .decimal)
&signed_decimal
else
&signed_oct_hex;
var pos = mem.indexOfScalar(type, list, SuffixType).?;
while (pos < list.len) : (pos += 1) {
if (number >= math.minInt(list[pos]) and number <= math.maxInt(list[pos])) {
return list[pos];
}
}
@compileError("Integer literal is too large");
}
/// Promote the type of an integer literal until it fits as C would.
pub fn promoteIntLiteral(
comptime SuffixType: type,
comptime number: comptime_int,
comptime radix: CIntLiteralRadix,
) PromoteIntLiteralReturnType(SuffixType, number, radix) {
return number;
}
test "promoteIntLiteral" {
const signed_hex = promoteIntLiteral(c_int, math.maxInt(c_int) + 1, .hexadecimal);
try testing.expectEqual(c_uint, @TypeOf(signed_hex));
if (math.maxInt(c_longlong) == math.maxInt(c_int)) return;
const signed_decimal = promoteIntLiteral(c_int, math.maxInt(c_int) + 1, .decimal);
const unsigned = promoteIntLiteral(c_uint, math.maxInt(c_uint) + 1, .hexadecimal);
if (math.maxInt(c_long) > math.maxInt(c_int)) {
try testing.expectEqual(c_long, @TypeOf(signed_decimal));
try testing.expectEqual(c_ulong, @TypeOf(unsigned));
} else {
try testing.expectEqual(c_longlong, @TypeOf(signed_decimal));
try testing.expectEqual(c_ulonglong, @TypeOf(unsigned));
}
}
/// Convert from clang __builtin_shufflevector index to Zig @shuffle index
/// clang requires __builtin_shufflevector index arguments to be integer constants.
/// negative values for `this_index` indicate "don't care" so we arbitrarily choose 0
/// clang enforces that `this_index` is less than the total number of vector elements
/// See https://ziglang.org/documentation/master/#shuffle
/// See https://clang.llvm.org/docs/LanguageExtensions.html#langext-builtin-shufflevector
pub fn shuffleVectorIndex(comptime this_index: c_int, comptime source_vector_len: usize) i32 {
if (this_index <= 0) return 0;
const positive_index = @intCast(usize, this_index);
if (positive_index < source_vector_len) return @intCast(i32, this_index);
const b_index = positive_index - source_vector_len;
return ~@intCast(i32, b_index);
}
test "shuffleVectorIndex" {
const vector_len: usize = 4;
try testing.expect(shuffleVectorIndex(-1, vector_len) == 0);
try testing.expect(shuffleVectorIndex(0, vector_len) == 0);
try testing.expect(shuffleVectorIndex(1, vector_len) == 1);
try testing.expect(shuffleVectorIndex(2, vector_len) == 2);
try testing.expect(shuffleVectorIndex(3, vector_len) == 3);
try testing.expect(shuffleVectorIndex(4, vector_len) == -1);
try testing.expect(shuffleVectorIndex(5, vector_len) == -2);
try testing.expect(shuffleVectorIndex(6, vector_len) == -3);
try testing.expect(shuffleVectorIndex(7, vector_len) == -4);
}
/// Constructs a [*c] pointer with the const and volatile annotations
/// from SelfType for pointing to a C flexible array of ElementType.
pub fn FlexibleArrayType(comptime SelfType: type, ElementType: type) type {
switch (@typeInfo(SelfType)) {
.Pointer => |ptr| {
return @Type(.{ .Pointer = .{
.size = .C,
.is_const = ptr.is_const,
.is_volatile = ptr.is_volatile,
.alignment = @alignOf(ElementType),
.child = ElementType,
.is_allowzero = true,
.sentinel = null,
} });
},
else => |info| @compileError("Invalid self type \"" ++ @tagName(info) ++ "\" for flexible array getter: " ++ @typeName(SelfType)),
}
}
test "Flexible Array Type" {
const Container = extern struct {
size: usize,
};
try testing.expectEqual(FlexibleArrayType(*Container, c_int), [*c]c_int);
try testing.expectEqual(FlexibleArrayType(*const Container, c_int), [*c]const c_int);
try testing.expectEqual(FlexibleArrayType(*volatile Container, c_int), [*c]volatile c_int);
try testing.expectEqual(FlexibleArrayType(*const volatile Container, c_int), [*c]const volatile c_int);
}

View File

@ -12,7 +12,6 @@ const meta = std.meta;
const ast = @import("translate_c/ast.zig"); const ast = @import("translate_c/ast.zig");
const Node = ast.Node; const Node = ast.Node;
const Tag = Node.Tag; const Tag = Node.Tag;
const c_builtins = std.c.builtins;
const CallingConvention = std.builtin.CallingConvention; const CallingConvention = std.builtin.CallingConvention;
@ -863,7 +862,7 @@ fn buildFlexibleArrayFn(
defer block_scope.deinit(); defer block_scope.deinit();
const intermediate_type_name = try block_scope.makeMangledName(c, "Intermediate"); const intermediate_type_name = try block_scope.makeMangledName(c, "Intermediate");
const intermediate_type = try Tag.std_meta_flexible_array_type.create(c.arena, .{ .lhs = self_type, .rhs = u8_type }); 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, .{ const intermediate_type_decl = try Tag.var_simple.create(c.arena, .{
.name = intermediate_type_name, .name = intermediate_type_name,
.init = intermediate_type, .init = intermediate_type,
@ -872,7 +871,7 @@ fn buildFlexibleArrayFn(
const intermediate_type_ident = try Tag.identifier.create(c.arena, intermediate_type_name); 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_name = try block_scope.makeMangledName(c, "ReturnType");
const return_type = try Tag.std_meta_flexible_array_type.create(c.arena, .{ .lhs = self_type, .rhs = element_type }); 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, .{ const return_type_decl = try Tag.var_simple.create(c.arena, .{
.name = return_type_name, .name = return_type_name,
.init = return_type, .init = return_type,
@ -1290,9 +1289,19 @@ fn transStmt(
return maybeSuppressResult(c, scope, result_used, shuffle_vec_node); return maybeSuppressResult(c, scope, result_used, shuffle_vec_node);
}, },
// When adding new cases here, see comment for maybeBlockify() // When adding new cases here, see comment for maybeBlockify()
else => { .GCCAsmStmtClass,
return fail(c, error.UnsupportedTranslation, stmt.getBeginLoc(), "TODO implement translation of stmt class {s}", .{@tagName(sc)}); .GotoStmtClass,
}, .IndirectGotoStmtClass,
.AttributedStmtClass,
.AddrLabelExprClass,
.AtomicExprClass,
.BlockExprClass,
.UserDefinedLiteralClass,
.BuiltinBitCastExprClass,
.DesignatedInitExprClass,
.LabelStmtClass,
=> return fail(c, error.UnsupportedTranslation, stmt.getBeginLoc(), "TODO implement translation of stmt class {s}", .{@tagName(sc)}),
else => return fail(c, error.UnsupportedTranslation, stmt.getBeginLoc(), "unsupported stmt class {s}", .{@tagName(sc)}),
} }
} }
@ -1374,7 +1383,7 @@ fn makeShuffleMask(c: *Context, scope: *Scope, expr: *const clang.ShuffleVectorE
for (init_list) |*init, i| { for (init_list) |*init, i| {
const index_expr = try transExprCoercing(c, scope, expr.getExpr(@intCast(c_uint, i + 2)), .used); const index_expr = try transExprCoercing(c, scope, expr.getExpr(@intCast(c_uint, i + 2)), .used);
const converted_index = try Tag.std_meta_shuffle_vector_index.create(c.arena, .{ .lhs = index_expr, .rhs = vector_len }); const converted_index = try Tag.helpers_shuffle_vector_index.create(c.arena, .{ .lhs = index_expr, .rhs = vector_len });
init.* = converted_index; init.* = converted_index;
} }
@ -1820,13 +1829,10 @@ fn transDeclStmtOne(
.Function => { .Function => {
try visitFnDecl(c, @ptrCast(*const clang.FunctionDecl, decl)); try visitFnDecl(c, @ptrCast(*const clang.FunctionDecl, decl));
}, },
else => |kind| return fail( else => {
c, const decl_name = try c.str(decl.getDeclKindName());
error.UnsupportedTranslation, try warn(c, &c.global_scope.base, decl.getLocation(), "ignoring {s} declaration", .{decl_name});
decl.getLocation(), },
"TODO implement translation of DeclStmt kind {s}",
.{@tagName(kind)},
),
} }
} }
@ -1902,7 +1908,7 @@ fn transImplicitCastExpr(
const ne = try Tag.not_equal.create(c.arena, .{ .lhs = ptr_to_int, .rhs = Tag.zero_literal.init() }); const ne = try Tag.not_equal.create(c.arena, .{ .lhs = ptr_to_int, .rhs = Tag.zero_literal.init() });
return maybeSuppressResult(c, scope, result_used, ne); return maybeSuppressResult(c, scope, result_used, ne);
}, },
.IntegralToBoolean => { .IntegralToBoolean, .FloatingToBoolean => {
const sub_expr_node = try transExpr(c, scope, sub_expr, .used); const sub_expr_node = try transExpr(c, scope, sub_expr, .used);
// The expression is already a boolean one, return it as-is // The expression is already a boolean one, return it as-is
@ -1924,14 +1930,14 @@ fn transImplicitCastExpr(
c, c,
error.UnsupportedTranslation, error.UnsupportedTranslation,
@ptrCast(*const clang.Stmt, expr).getBeginLoc(), @ptrCast(*const clang.Stmt, expr).getBeginLoc(),
"TODO implement translation of CastKind {s}", "unsupported CastKind {s}",
.{@tagName(kind)}, .{@tagName(kind)},
), ),
} }
} }
fn isBuiltinDefined(name: []const u8) bool { fn isBuiltinDefined(name: []const u8) bool {
inline for (meta.declarations(c_builtins)) |decl| { inline for (meta.declarations(std.zig.c_builtins)) |decl| {
if (std.mem.eql(u8, name, decl.name)) return true; if (std.mem.eql(u8, name, decl.name)) return true;
} }
return false; return false;
@ -2358,8 +2364,10 @@ fn transCCast(
return Tag.float_to_int.create(c.arena, .{ .lhs = dst_node, .rhs = expr }); return Tag.float_to_int.create(c.arena, .{ .lhs = dst_node, .rhs = expr });
} }
if (!cIsFloating(src_type) and cIsFloating(dst_type)) { if (!cIsFloating(src_type) and cIsFloating(dst_type)) {
var rhs = expr;
if (qualTypeIsBoolean(src_type)) rhs = try Tag.bool_to_int.create(c.arena, expr);
// @intToFloat(dest_type, val) // @intToFloat(dest_type, val)
return Tag.int_to_float.create(c.arena, .{ .lhs = dst_node, .rhs = expr }); return Tag.int_to_float.create(c.arena, .{ .lhs = dst_node, .rhs = rhs });
} }
if (qualTypeIsBoolean(src_type) and !qualTypeIsBoolean(dst_type)) { if (qualTypeIsBoolean(src_type) and !qualTypeIsBoolean(dst_type)) {
// @boolToInt returns either a comptime_int or a u1 // @boolToInt returns either a comptime_int or a u1
@ -2370,7 +2378,7 @@ fn transCCast(
} }
if (cIsEnum(dst_type)) { if (cIsEnum(dst_type)) {
// import("std").meta.cast(dest_type, val) // import("std").meta.cast(dest_type, val)
return Tag.std_meta_cast.create(c.arena, .{ .lhs = dst_node, .rhs = expr }); return Tag.helpers_cast.create(c.arena, .{ .lhs = dst_node, .rhs = expr });
} }
if (cIsEnum(src_type) and !cIsEnum(dst_type)) { if (cIsEnum(src_type) and !cIsEnum(dst_type)) {
// @enumToInt(val) // @enumToInt(val)
@ -4547,6 +4555,10 @@ fn transType(c: *Context, scope: *Scope, ty: *const clang.Type, source_loc: clan
.rhs = try transQualType(c, scope, element_qt, source_loc), .rhs = try transQualType(c, scope, element_qt, source_loc),
}); });
}, },
.ExtInt, .ExtVector => {
const type_name = c.str(ty.getTypeClassName());
return fail(c, error.UnsupportedType, source_loc, "TODO implement translation of type: '{s}'", .{type_name});
},
else => { else => {
const type_name = c.str(ty.getTypeClassName()); const type_name = c.str(ty.getTypeClassName());
return fail(c, error.UnsupportedType, source_loc, "unsupported type: '{s}'", .{type_name}); return fail(c, error.UnsupportedType, source_loc, "unsupported type: '{s}'", .{type_name});
@ -4982,7 +4994,7 @@ fn transMacroFnDefine(c: *Context, m: *MacroCtx) ParseError!void {
break :blk br.data.val; break :blk br.data.val;
} else expr; } else expr;
const return_type = if (typeof_arg.castTag(.std_meta_cast) orelse typeof_arg.castTag(.std_mem_zeroinit)) |some| const return_type = if (typeof_arg.castTag(.helpers_cast) orelse typeof_arg.castTag(.std_mem_zeroinit)) |some|
some.data.lhs some.data.lhs
else if (typeof_arg.castTag(.std_mem_zeroes)) |some| else if (typeof_arg.castTag(.std_mem_zeroes)) |some|
some.data some.data
@ -5095,7 +5107,7 @@ fn parseCNumLit(c: *Context, m: *MacroCtx) ParseError!Node {
if (guaranteed_to_fit) { if (guaranteed_to_fit) {
return Tag.as.create(c.arena, .{ .lhs = type_node, .rhs = literal_node }); return Tag.as.create(c.arena, .{ .lhs = type_node, .rhs = literal_node });
} else { } else {
return Tag.std_meta_promoteIntLiteral.create(c.arena, .{ return Tag.helpers_promoteIntLiteral.create(c.arena, .{
.type = type_node, .type = type_node,
.value = literal_node, .value = literal_node,
.radix = try Tag.enum_literal.create(c.arena, radix), .radix = try Tag.enum_literal.create(c.arena, radix),
@ -5578,7 +5590,7 @@ fn parseCCastExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node {
return parseCPostfixExpr(c, m, scope, type_name); return parseCPostfixExpr(c, m, scope, type_name);
} }
const node_to_cast = try parseCCastExpr(c, m, scope); const node_to_cast = try parseCCastExpr(c, m, scope);
return Tag.std_meta_cast.create(c.arena, .{ .lhs = type_name, .rhs = node_to_cast }); return Tag.helpers_cast.create(c.arena, .{ .lhs = type_name, .rhs = node_to_cast });
} }
}, },
else => {}, else => {},
@ -5925,7 +5937,7 @@ fn parseCUnaryExpr(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node {
break :blk inner; break :blk inner;
} else try parseCUnaryExpr(c, m, scope); } else try parseCUnaryExpr(c, m, scope);
return Tag.std_meta_sizeof.create(c.arena, operand); return Tag.helpers_sizeof.create(c.arena, operand);
}, },
.Keyword_alignof => { .Keyword_alignof => {
// TODO this won't work if using <stdalign.h>'s // TODO this won't work if using <stdalign.h>'s

View File

@ -74,7 +74,7 @@ pub const Node = extern union {
tuple, tuple,
container_init, container_init,
container_init_dot, container_init_dot,
std_meta_cast, helpers_cast,
/// _ = operand; /// _ = operand;
discard, discard,
@ -124,8 +124,8 @@ pub const Node = extern union {
std_math_Log2Int, std_math_Log2Int,
/// @intCast(lhs, rhs) /// @intCast(lhs, rhs)
int_cast, int_cast,
/// @import("std").meta.promoteIntLiteral(value, type, radix) /// @import("std").zig.c_translation.promoteIntLiteral(value, type, radix)
std_meta_promoteIntLiteral, helpers_promoteIntLiteral,
/// @import("std").meta.alignment(value) /// @import("std").meta.alignment(value)
std_meta_alignment, std_meta_alignment,
/// @rem(lhs, rhs) /// @rem(lhs, rhs)
@ -193,12 +193,12 @@ pub const Node = extern union {
array_type, array_type,
null_sentinel_array_type, null_sentinel_array_type,
/// @import("std").meta.sizeof(operand) /// @import("std").zig.c_translation.sizeof(operand)
std_meta_sizeof, helpers_sizeof,
/// @import("std").meta.FlexibleArrayType(lhs, rhs) /// @import("std").zig.c_translation.FlexibleArrayType(lhs, rhs)
std_meta_flexible_array_type, helpers_flexible_array_type,
/// @import("std").meta.shuffleVectorIndex(lhs, rhs) /// @import("std").zig.c_translation.shuffleVectorIndex(lhs, rhs)
std_meta_shuffle_vector_index, helpers_shuffle_vector_index,
/// @import("std").meta.Vector(lhs, rhs) /// @import("std").meta.Vector(lhs, rhs)
std_meta_vector, std_meta_vector,
/// @import("std").mem.zeroes(operand) /// @import("std").mem.zeroes(operand)
@ -272,7 +272,7 @@ pub const Node = extern union {
.if_not_break, .if_not_break,
.switch_else, .switch_else,
.block_single, .block_single,
.std_meta_sizeof, .helpers_sizeof,
.std_meta_alignment, .std_meta_alignment,
.bool_to_int, .bool_to_int,
.sizeof, .sizeof,
@ -332,13 +332,13 @@ pub const Node = extern union {
.align_cast, .align_cast,
.array_access, .array_access,
.std_mem_zeroinit, .std_mem_zeroinit,
.std_meta_flexible_array_type, .helpers_flexible_array_type,
.std_meta_shuffle_vector_index, .helpers_shuffle_vector_index,
.std_meta_vector, .std_meta_vector,
.ptr_cast, .ptr_cast,
.div_exact, .div_exact,
.offset_of, .offset_of,
.std_meta_cast, .helpers_cast,
=> Payload.BinOp, => Payload.BinOp,
.integer_literal, .integer_literal,
@ -362,7 +362,7 @@ pub const Node = extern union {
.tuple => Payload.TupleInit, .tuple => Payload.TupleInit,
.container_init => Payload.ContainerInit, .container_init => Payload.ContainerInit,
.container_init_dot => Payload.ContainerInitDot, .container_init_dot => Payload.ContainerInitDot,
.std_meta_promoteIntLiteral => Payload.PromoteIntLiteral, .helpers_promoteIntLiteral => Payload.PromoteIntLiteral,
.block => Payload.Block, .block => Payload.Block,
.c_pointer, .single_pointer => Payload.Pointer, .c_pointer, .single_pointer => Payload.Pointer,
.array_type, .null_sentinel_array_type => Payload.Array, .array_type, .null_sentinel_array_type => Payload.Array,
@ -868,7 +868,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
// pub usingnamespace @import("std").c.builtins; // pub usingnamespace @import("std").c.builtins;
_ = try c.addToken(.keyword_pub, "pub"); _ = try c.addToken(.keyword_pub, "pub");
const usingnamespace_token = try c.addToken(.keyword_usingnamespace, "usingnamespace"); const usingnamespace_token = try c.addToken(.keyword_usingnamespace, "usingnamespace");
const import_node = try renderStdImport(c, "c", "builtins"); const import_node = try renderStdImport(c, &.{ "zig", "c_builtins" });
_ = try c.addToken(.semicolon, ";"); _ = try c.addToken(.semicolon, ";");
return c.addNode(.{ return c.addNode(.{
@ -882,52 +882,52 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
}, },
.std_math_Log2Int => { .std_math_Log2Int => {
const payload = node.castTag(.std_math_Log2Int).?.data; const payload = node.castTag(.std_math_Log2Int).?.data;
const import_node = try renderStdImport(c, "math", "Log2Int"); const import_node = try renderStdImport(c, &.{ "math", "Log2Int" });
return renderCall(c, import_node, &.{payload}); return renderCall(c, import_node, &.{payload});
}, },
.std_meta_cast => { .helpers_cast => {
const payload = node.castTag(.std_meta_cast).?.data; const payload = node.castTag(.helpers_cast).?.data;
const import_node = try renderStdImport(c, "meta", "cast"); const import_node = try renderStdImport(c, &.{ "zig", "c_translation", "cast" });
return renderCall(c, import_node, &.{ payload.lhs, payload.rhs }); return renderCall(c, import_node, &.{ payload.lhs, payload.rhs });
}, },
.std_meta_promoteIntLiteral => { .helpers_promoteIntLiteral => {
const payload = node.castTag(.std_meta_promoteIntLiteral).?.data; const payload = node.castTag(.helpers_promoteIntLiteral).?.data;
const import_node = try renderStdImport(c, "meta", "promoteIntLiteral"); const import_node = try renderStdImport(c, &.{ "zig", "c_translation", "promoteIntLiteral" });
return renderCall(c, import_node, &.{ payload.type, payload.value, payload.radix }); return renderCall(c, import_node, &.{ payload.type, payload.value, payload.radix });
}, },
.std_meta_alignment => { .std_meta_alignment => {
const payload = node.castTag(.std_meta_alignment).?.data; const payload = node.castTag(.std_meta_alignment).?.data;
const import_node = try renderStdImport(c, "meta", "alignment"); const import_node = try renderStdImport(c, &.{ "meta", "alignment" });
return renderCall(c, import_node, &.{payload}); return renderCall(c, import_node, &.{payload});
}, },
.std_meta_sizeof => { .helpers_sizeof => {
const payload = node.castTag(.std_meta_sizeof).?.data; const payload = node.castTag(.helpers_sizeof).?.data;
const import_node = try renderStdImport(c, "meta", "sizeof"); const import_node = try renderStdImport(c, &.{ "zig", "c_translation", "sizeof" });
return renderCall(c, import_node, &.{payload}); return renderCall(c, import_node, &.{payload});
}, },
.std_mem_zeroes => { .std_mem_zeroes => {
const payload = node.castTag(.std_mem_zeroes).?.data; const payload = node.castTag(.std_mem_zeroes).?.data;
const import_node = try renderStdImport(c, "mem", "zeroes"); const import_node = try renderStdImport(c, &.{ "mem", "zeroes" });
return renderCall(c, import_node, &.{payload}); return renderCall(c, import_node, &.{payload});
}, },
.std_mem_zeroinit => { .std_mem_zeroinit => {
const payload = node.castTag(.std_mem_zeroinit).?.data; const payload = node.castTag(.std_mem_zeroinit).?.data;
const import_node = try renderStdImport(c, "mem", "zeroInit"); const import_node = try renderStdImport(c, &.{ "mem", "zeroInit" });
return renderCall(c, import_node, &.{ payload.lhs, payload.rhs }); return renderCall(c, import_node, &.{ payload.lhs, payload.rhs });
}, },
.std_meta_flexible_array_type => { .helpers_flexible_array_type => {
const payload = node.castTag(.std_meta_flexible_array_type).?.data; const payload = node.castTag(.helpers_flexible_array_type).?.data;
const import_node = try renderStdImport(c, "meta", "FlexibleArrayType"); const import_node = try renderStdImport(c, &.{ "zig", "c_translation", "FlexibleArrayType" });
return renderCall(c, import_node, &.{ payload.lhs, payload.rhs }); return renderCall(c, import_node, &.{ payload.lhs, payload.rhs });
}, },
.std_meta_shuffle_vector_index => { .helpers_shuffle_vector_index => {
const payload = node.castTag(.std_meta_shuffle_vector_index).?.data; const payload = node.castTag(.helpers_shuffle_vector_index).?.data;
const import_node = try renderStdImport(c, "meta", "shuffleVectorIndex"); const import_node = try renderStdImport(c, &.{ "zig", "c_translation", "shuffleVectorIndex" });
return renderCall(c, import_node, &.{ payload.lhs, payload.rhs }); return renderCall(c, import_node, &.{ payload.lhs, payload.rhs });
}, },
.std_meta_vector => { .std_meta_vector => {
const payload = node.castTag(.std_meta_vector).?.data; const payload = node.castTag(.std_meta_vector).?.data;
const import_node = try renderStdImport(c, "meta", "Vector"); const import_node = try renderStdImport(c, &.{ "meta", "Vector" });
return renderCall(c, import_node, &.{ payload.lhs, payload.rhs }); return renderCall(c, import_node, &.{ payload.lhs, payload.rhs });
}, },
.call => { .call => {
@ -2269,13 +2269,13 @@ fn renderNodeGrouped(c: *Context, node: Node) !NodeIndex {
.alignof, .alignof,
.typeof, .typeof,
.typeinfo, .typeinfo,
.std_meta_sizeof,
.std_meta_alignment, .std_meta_alignment,
.std_meta_cast,
.std_meta_promoteIntLiteral,
.std_meta_vector, .std_meta_vector,
.std_meta_shuffle_vector_index, .helpers_sizeof,
.std_meta_flexible_array_type, .helpers_cast,
.helpers_promoteIntLiteral,
.helpers_shuffle_vector_index,
.helpers_flexible_array_type,
.std_mem_zeroinit, .std_mem_zeroinit,
.integer_literal, .integer_literal,
.float_literal, .float_literal,
@ -2442,7 +2442,7 @@ fn renderBinOp(c: *Context, node: Node, tag: std.zig.ast.Node.Tag, tok_tag: Toke
}); });
} }
fn renderStdImport(c: *Context, first: []const u8, second: []const u8) !NodeIndex { fn renderStdImport(c: *Context, parts: []const []const u8) !NodeIndex {
const import_tok = try c.addToken(.builtin, "@import"); const import_tok = try c.addToken(.builtin, "@import");
_ = try c.addToken(.l_paren, "("); _ = try c.addToken(.l_paren, "(");
const std_tok = try c.addToken(.string_literal, "\"std\""); const std_tok = try c.addToken(.string_literal, "\"std\"");
@ -2463,8 +2463,9 @@ fn renderStdImport(c: *Context, first: []const u8, second: []const u8) !NodeInde
}); });
var access_chain = import_node; var access_chain = import_node;
access_chain = try renderFieldAccess(c, access_chain, first); for (parts) |part| {
access_chain = try renderFieldAccess(c, access_chain, second); access_chain = try renderFieldAccess(c, access_chain, part);
}
return access_chain; return access_chain;
} }

View File

@ -133,7 +133,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\ const A = @enumToInt(enum_Foo.A); \\ const A = @enumToInt(enum_Foo.A);
\\ const B = @enumToInt(enum_Foo.B); \\ const B = @enumToInt(enum_Foo.B);
\\ const C = @enumToInt(enum_Foo.C); \\ const C = @enumToInt(enum_Foo.C);
\\ var a: enum_Foo = @import("std").meta.cast(enum_Foo, B); \\ var a: enum_Foo = @import("std").zig.c_translation.cast(enum_Foo, B);
\\ { \\ {
\\ const enum_Foo = extern enum( \\ const enum_Foo = extern enum(
++ default_enum_type ++ ++ default_enum_type ++
@ -146,7 +146,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\ const A_2 = @enumToInt(enum_Foo.A); \\ const A_2 = @enumToInt(enum_Foo.A);
\\ const B_3 = @enumToInt(enum_Foo.B); \\ const B_3 = @enumToInt(enum_Foo.B);
\\ const C_4 = @enumToInt(enum_Foo.C); \\ const C_4 = @enumToInt(enum_Foo.C);
\\ var a_5: enum_Foo = @import("std").meta.cast(enum_Foo, B_3); \\ var a_5: enum_Foo = @import("std").zig.c_translation.cast(enum_Foo, B_3);
\\ } \\ }
\\} \\}
}); });
@ -242,7 +242,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\#define MEM_PHYSICAL_TO_K0(x) (void*)((uint32_t)(x) + SYS_BASE_CACHED) \\#define MEM_PHYSICAL_TO_K0(x) (void*)((uint32_t)(x) + SYS_BASE_CACHED)
, &[_][]const u8{ , &[_][]const u8{
\\pub inline fn MEM_PHYSICAL_TO_K0(x: anytype) ?*c_void { \\pub inline fn MEM_PHYSICAL_TO_K0(x: anytype) ?*c_void {
\\ return @import("std").meta.cast(?*c_void, @import("std").meta.cast(u32, x) + SYS_BASE_CACHED); \\ return @import("std").zig.c_translation.cast(?*c_void, @import("std").zig.c_translation.cast(u32, x) + SYS_BASE_CACHED);
\\} \\}
}); });
@ -282,8 +282,8 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
, ,
\\pub const VALUE = ((((@as(c_int, 1) + (@as(c_int, 2) * @as(c_int, 3))) + (@as(c_int, 4) * @as(c_int, 5))) + @as(c_int, 6)) << @as(c_int, 7)) | @boolToInt(@as(c_int, 8) == @as(c_int, 9)); \\pub const VALUE = ((((@as(c_int, 1) + (@as(c_int, 2) * @as(c_int, 3))) + (@as(c_int, 4) * @as(c_int, 5))) + @as(c_int, 6)) << @as(c_int, 7)) | @boolToInt(@as(c_int, 8) == @as(c_int, 9));
, ,
\\pub inline fn _AL_READ3BYTES(p: anytype) @TypeOf((@import("std").meta.cast([*c]u8, p).* | ((@import("std").meta.cast([*c]u8, p) + @as(c_int, 1)).* << @as(c_int, 8))) | ((@import("std").meta.cast([*c]u8, p) + @as(c_int, 2)).* << @as(c_int, 16))) { \\pub inline fn _AL_READ3BYTES(p: anytype) @TypeOf((@import("std").zig.c_translation.cast([*c]u8, p).* | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 1)).* << @as(c_int, 8))) | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 2)).* << @as(c_int, 16))) {
\\ return (@import("std").meta.cast([*c]u8, p).* | ((@import("std").meta.cast([*c]u8, p) + @as(c_int, 1)).* << @as(c_int, 8))) | ((@import("std").meta.cast([*c]u8, p) + @as(c_int, 2)).* << @as(c_int, 16)); \\ return (@import("std").zig.c_translation.cast([*c]u8, p).* | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 1)).* << @as(c_int, 8))) | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 2)).* << @as(c_int, 16));
\\} \\}
}); });
@ -438,17 +438,17 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
, &[_][]const u8{ , &[_][]const u8{
\\pub const struct_foo = extern struct { \\pub const struct_foo = extern struct {
\\ x: c_int align(4), \\ x: c_int align(4),
\\ pub fn y(self: anytype) @import("std").meta.FlexibleArrayType(@TypeOf(self), c_int) { \\ pub fn y(self: anytype) @import("std").zig.c_translation.FlexibleArrayType(@TypeOf(self), c_int) {
\\ const Intermediate = @import("std").meta.FlexibleArrayType(@TypeOf(self), u8); \\ const Intermediate = @import("std").zig.c_translation.FlexibleArrayType(@TypeOf(self), u8);
\\ const ReturnType = @import("std").meta.FlexibleArrayType(@TypeOf(self), c_int); \\ const ReturnType = @import("std").zig.c_translation.FlexibleArrayType(@TypeOf(self), c_int);
\\ return @ptrCast(ReturnType, @alignCast(@alignOf(c_int), @ptrCast(Intermediate, self) + 4)); \\ return @ptrCast(ReturnType, @alignCast(@alignOf(c_int), @ptrCast(Intermediate, self) + 4));
\\ } \\ }
\\}; \\};
\\pub const struct_bar = extern struct { \\pub const struct_bar = extern struct {
\\ x: c_int align(4), \\ x: c_int align(4),
\\ pub fn y(self: anytype) @import("std").meta.FlexibleArrayType(@TypeOf(self), c_int) { \\ pub fn y(self: anytype) @import("std").zig.c_translation.FlexibleArrayType(@TypeOf(self), c_int) {
\\ const Intermediate = @import("std").meta.FlexibleArrayType(@TypeOf(self), u8); \\ const Intermediate = @import("std").zig.c_translation.FlexibleArrayType(@TypeOf(self), u8);
\\ const ReturnType = @import("std").meta.FlexibleArrayType(@TypeOf(self), c_int); \\ const ReturnType = @import("std").zig.c_translation.FlexibleArrayType(@TypeOf(self), c_int);
\\ return @ptrCast(ReturnType, @alignCast(@alignOf(c_int), @ptrCast(Intermediate, self) + 4)); \\ return @ptrCast(ReturnType, @alignCast(@alignOf(c_int), @ptrCast(Intermediate, self) + 4));
\\ } \\ }
\\}; \\};
@ -583,7 +583,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
cases.add("#define hex literal with capital X", cases.add("#define hex literal with capital X",
\\#define VAL 0XF00D \\#define VAL 0XF00D
, &[_][]const u8{ , &[_][]const u8{
\\pub const VAL = @import("std").meta.promoteIntLiteral(c_int, 0xF00D, .hexadecimal); \\pub const VAL = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xF00D, .hexadecimal);
}); });
cases.add("anonymous struct & unions", cases.add("anonymous struct & unions",
@ -1738,7 +1738,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\pub const e = @enumToInt(enum_unnamed_1.e); \\pub const e = @enumToInt(enum_unnamed_1.e);
\\pub const f = @enumToInt(enum_unnamed_1.f); \\pub const f = @enumToInt(enum_unnamed_1.f);
\\pub const g = @enumToInt(enum_unnamed_1.g); \\pub const g = @enumToInt(enum_unnamed_1.g);
\\pub export var h: enum_unnamed_1 = @import("std").meta.cast(enum_unnamed_1, e); \\pub export var h: enum_unnamed_1 = @import("std").zig.c_translation.cast(enum_unnamed_1, e);
\\const enum_unnamed_2 = extern enum( \\const enum_unnamed_2 = extern enum(
++ default_enum_type ++ ++ default_enum_type ++
\\) { \\) {
@ -1882,7 +1882,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\typedef struct { int dummy; } NRF_GPIO_Type; \\typedef struct { int dummy; } NRF_GPIO_Type;
\\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE) \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)
, &[_][]const u8{ , &[_][]const u8{
\\pub const NRF_GPIO = @import("std").meta.cast([*c]NRF_GPIO_Type, NRF_GPIO_BASE); \\pub const NRF_GPIO = @import("std").zig.c_translation.cast([*c]NRF_GPIO_Type, NRF_GPIO_BASE);
}); });
cases.add("basic macro function", cases.add("basic macro function",
@ -2379,7 +2379,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\ var a = arg_a; \\ var a = arg_a;
\\ var b = arg_b; \\ var b = arg_b;
\\ var c = arg_c; \\ var c = arg_c;
\\ var d: enum_Foo = @import("std").meta.cast(enum_Foo, FooA); \\ var d: enum_Foo = @import("std").zig.c_translation.cast(enum_Foo, FooA);
\\ var e: c_int = @boolToInt((a != 0) and (b != 0)); \\ var e: c_int = @boolToInt((a != 0) and (b != 0));
\\ var f: c_int = @boolToInt((b != 0) and (c != null)); \\ var f: c_int = @boolToInt((b != 0) and (c != null));
\\ var g: c_int = @boolToInt((a != 0) and (c != null)); \\ var g: c_int = @boolToInt((a != 0) and (c != null));
@ -3182,13 +3182,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\#define BAR (void*) a \\#define BAR (void*) a
\\#define BAZ (uint32_t)(2) \\#define BAZ (uint32_t)(2)
, &[_][]const u8{ , &[_][]const u8{
\\pub inline fn FOO(bar: anytype) @TypeOf(baz(@import("std").meta.cast(?*c_void, baz))) { \\pub inline fn FOO(bar: anytype) @TypeOf(baz(@import("std").zig.c_translation.cast(?*c_void, baz))) {
\\ return baz(@import("std").meta.cast(?*c_void, baz)); \\ return baz(@import("std").zig.c_translation.cast(?*c_void, baz));
\\} \\}
, ,
\\pub const BAR = @import("std").meta.cast(?*c_void, a); \\pub const BAR = @import("std").zig.c_translation.cast(?*c_void, a);
, ,
\\pub const BAZ = @import("std").meta.cast(u32, @as(c_int, 2)); \\pub const BAZ = @import("std").zig.c_translation.cast(u32, @as(c_int, 2));
}); });
cases.add("macro with cast to unsigned short, long, and long long", cases.add("macro with cast to unsigned short, long, and long long",
@ -3196,9 +3196,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\#define CURLAUTH_BASIC ((unsigned long) 1) \\#define CURLAUTH_BASIC ((unsigned long) 1)
\\#define CURLAUTH_BASIC_BUT_ULONGLONG ((unsigned long long) 1) \\#define CURLAUTH_BASIC_BUT_ULONGLONG ((unsigned long long) 1)
, &[_][]const u8{ , &[_][]const u8{
\\pub const CURLAUTH_BASIC_BUT_USHORT = @import("std").meta.cast(c_ushort, @as(c_int, 1)); \\pub const CURLAUTH_BASIC_BUT_USHORT = @import("std").zig.c_translation.cast(c_ushort, @as(c_int, 1));
\\pub const CURLAUTH_BASIC = @import("std").meta.cast(c_ulong, @as(c_int, 1)); \\pub const CURLAUTH_BASIC = @import("std").zig.c_translation.cast(c_ulong, @as(c_int, 1));
\\pub const CURLAUTH_BASIC_BUT_ULONGLONG = @import("std").meta.cast(c_ulonglong, @as(c_int, 1)); \\pub const CURLAUTH_BASIC_BUT_ULONGLONG = @import("std").zig.c_translation.cast(c_ulonglong, @as(c_int, 1));
}); });
cases.add("macro conditional operator", cases.add("macro conditional operator",
@ -3413,8 +3413,8 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\#define DefaultScreen(dpy) (((_XPrivDisplay)(dpy))->default_screen) \\#define DefaultScreen(dpy) (((_XPrivDisplay)(dpy))->default_screen)
\\ \\
, &[_][]const u8{ , &[_][]const u8{
\\pub inline fn DefaultScreen(dpy: anytype) @TypeOf(@import("std").meta.cast(_XPrivDisplay, dpy).*.default_screen) { \\pub inline fn DefaultScreen(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.default_screen) {
\\ return @import("std").meta.cast(_XPrivDisplay, dpy).*.default_screen; \\ return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.default_screen;
\\} \\}
}); });
@ -3422,9 +3422,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\#define NULL ((void*)0) \\#define NULL ((void*)0)
\\#define FOO ((int)0x8000) \\#define FOO ((int)0x8000)
, &[_][]const u8{ , &[_][]const u8{
\\pub const NULL = @import("std").meta.cast(?*c_void, @as(c_int, 0)); \\pub const NULL = @import("std").zig.c_translation.cast(?*c_void, @as(c_int, 0));
, ,
\\pub const FOO = @import("std").meta.cast(c_int, @import("std").meta.promoteIntLiteral(c_int, 0x8000, .hexadecimal)); \\pub const FOO = @import("std").zig.c_translation.cast(c_int, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8000, .hexadecimal));
}); });
if (std.Target.current.abi == .msvc) { if (std.Target.current.abi == .msvc) {
@ -3503,11 +3503,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\pub const GUARANTEED_TO_FIT_1 = @as(c_int, 1024); \\pub const GUARANTEED_TO_FIT_1 = @as(c_int, 1024);
\\pub const GUARANTEED_TO_FIT_2 = @as(c_long, 10241024); \\pub const GUARANTEED_TO_FIT_2 = @as(c_long, 10241024);
\\pub const GUARANTEED_TO_FIT_3 = @as(c_ulong, 20482048); \\pub const GUARANTEED_TO_FIT_3 = @as(c_ulong, 20482048);
\\pub const MAY_NEED_PROMOTION_1 = @import("std").meta.promoteIntLiteral(c_int, 10241024, .decimal); \\pub const MAY_NEED_PROMOTION_1 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 10241024, .decimal);
\\pub const MAY_NEED_PROMOTION_2 = @import("std").meta.promoteIntLiteral(c_long, 307230723072, .decimal); \\pub const MAY_NEED_PROMOTION_2 = @import("std").zig.c_translation.promoteIntLiteral(c_long, 307230723072, .decimal);
\\pub const MAY_NEED_PROMOTION_3 = @import("std").meta.promoteIntLiteral(c_ulong, 819281928192, .decimal); \\pub const MAY_NEED_PROMOTION_3 = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 819281928192, .decimal);
\\pub const MAY_NEED_PROMOTION_HEX = @import("std").meta.promoteIntLiteral(c_int, 0x80000000, .hexadecimal); \\pub const MAY_NEED_PROMOTION_HEX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80000000, .hexadecimal);
\\pub const MAY_NEED_PROMOTION_OCT = @import("std").meta.promoteIntLiteral(c_int, 0o20000000000, .octal); \\pub const MAY_NEED_PROMOTION_OCT = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0o20000000000, .octal);
}); });
// See __builtin_alloca_with_align comment in std.c.builtins // See __builtin_alloca_with_align comment in std.c.builtins
@ -3642,7 +3642,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
\\typedef long long LONG_PTR; \\typedef long long LONG_PTR;
\\#define INVALID_HANDLE_VALUE ((void *)(LONG_PTR)-1) \\#define INVALID_HANDLE_VALUE ((void *)(LONG_PTR)-1)
, &[_][]const u8{ , &[_][]const u8{
\\pub const MAP_FAILED = @import("std").meta.cast(?*c_void, -@as(c_int, 1)); \\pub const MAP_FAILED = @import("std").zig.c_translation.cast(?*c_void, -@as(c_int, 1));
\\pub const INVALID_HANDLE_VALUE = @import("std").meta.cast(?*c_void, @import("std").meta.cast(LONG_PTR, -@as(c_int, 1))); \\pub const INVALID_HANDLE_VALUE = @import("std").zig.c_translation.cast(?*c_void, @import("std").zig.c_translation.cast(LONG_PTR, -@as(c_int, 1)));
}); });
} }