跳转到内容

std.zig.c_translation.helpers

标准库Zig 0.17.0官方原文
源码std/zig/c_translation/helpers.zig

第 1 行

std.zig.c_translation.helpers.ArithmeticConversion

类型函数

第 4 行

C11 标准 6.3.1.8 中的“通常算术转换”。

pub fn ArithmeticConversion(comptime A: type, comptime B: type) type

参数

A: type
B: type

std.zig.c_translation.helpers.cast

函数

第 158 行

给定类型和值,按照 C 的方式将该值转换为该类型。

pub fn cast(comptime DestType: type, target: anytype) DestType

参数

DestType: type

std.zig.c_translation.helpers.CAST_OR_CALL

函数

第 356 行

二参数类函数宏 #define FOO(A, B) (A)(B) 既可能表示将 B 转换为 A,也可能表示用值 B 调用 A。

pub fn CAST_OR_CALL(a: anytype, b: anytype) switch (@typeInfo(@TypeOf(a))) { .type => a, .@"fn" => |fn_info| fn_info.return_type orelse void, else => |info| @compileError("Unexpected argument type: " ++ @tagName(info)), }

std.zig.c_translation.helpers.castInt

函数

第 215 行

fn castInt(comptime DestType: type, target: anytype) DestType

参数

DestType: type

std.zig.c_translation.helpers.castPtr

函数

第 227 行

fn castPtr(comptime DestType: type, target: anytype) DestType

参数

DestType: type

std.zig.c_translation.helpers.castToPtr

函数

第 231 行

fn castToPtr(comptime DestType: type, comptime SourceType: type, target: anytype) DestType

参数

DestType: type
SourceType: type

std.zig.c_translation.helpers.CIntLiteralBase

容器

第 109 行

字段

decimal
octal
hex

std.zig.c_translation.helpers.DISCARD

函数

第 368 行

pub inline fn DISCARD(x: anytype) void

std.zig.c_translation.helpers.div

函数

第 327 行

pub fn div(a: anytype, b: anytype) ArithmeticConversion(@TypeOf(a), @TypeOf(b))

std.zig.c_translation.helpers.F_SUFFIX

函数

第 372 行

pub fn F_SUFFIX(comptime f: comptime_float) f32

参数

f: comptime_float

std.zig.c_translation.helpers.FlexibleArrayType

类型函数

第 85 行

构造 [*c] 指针,从 SelfType 继承 const 和 volatile 注解, 用于指向 ElementType 类型的 C 柔性数组。

pub fn FlexibleArrayType(comptime SelfType: type, comptime ElementType: type) type

参数

SelfType: type
ElementType: type

std.zig.c_translation.helpers.integerRank

函数

第 62 行

C11 6.3.1.1.1

fn integerRank(comptime T: type) u8

参数

T: type

std.zig.c_translation.helpers.L_SUFFIX

函数

第 384 行

pub inline fn L_SUFFIX(comptime number: anytype) L_SUFFIX_ReturnType(number)

std.zig.c_translation.helpers.L_SUFFIX_ReturnType

类型函数

第 376 行

fn L_SUFFIX_ReturnType(comptime number: anytype) type

std.zig.c_translation.helpers.LL_SUFFIX

函数

第 392 行

pub inline fn LL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_longlong, n, .decimal))

参数

n: comptime_int

std.zig.c_translation.helpers.PromotedIntType

类型函数

第 37 行

C11 6.3.1.1.2 中描述的整数提升

fn PromotedIntType(comptime T: type) type

参数

T: type

std.zig.c_translation.helpers.promoteIntLiteral

函数

第 101 行

像 C 一样提升整数字面量的类型,直到能够容纳。

pub inline fn promoteIntLiteral( comptime SuffixType: type, comptime number: comptime_int, comptime base: CIntLiteralBase, ) PromoteIntLiteralReturnType(SuffixType, number, base)

参数

SuffixType: type
number: comptime_int
base: CIntLiteralBase

std.zig.c_translation.helpers.PromoteIntLiteralReturnType

类型函数

第 111 行

fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: comptime_int, comptime base: CIntLiteralBase) type

参数

SuffixType: type
number: comptime_int
base: CIntLiteralBase

std.zig.c_translation.helpers.rem

函数

第 338 行

pub fn rem(a: anytype, b: anytype) ArithmeticConversion(@TypeOf(a), @TypeOf(b))

std.zig.c_translation.helpers.shuffleVectorIndex

函数

第 139 行

将 clang __builtin_shufflevector 索引转换为 Zig @shuffle 索引。 clang 要求 __builtin_shufflevector 的索引参数是整数常量。 this_index 为负表示“不关心”。 clang 强制 this_index 小于向量元素总数。 参见 https://ziglang.org/documentation/master/#shuffle 参见 https://clang.llvm.org/docs/LanguageExtensions.html#langext-builtin-shufflevector

pub fn shuffleVectorIndex(comptime this_index: c_int, comptime source_vector_len: usize) i32

参数

this_index: c_int
source_vector_len: usize

std.zig.c_translation.helpers.signedRemainder

函数

第 151 行

C 的有符号整数 % 运算符。 C 标准规定:“如果商 a/b 可表示,则表达式 (a/b)*b + a%b 应等于 a”。 分母为零,或分子为该类型的最小整数且分母为 -1 时, 商不可表示。C 在这两种情况下具有未定义行为;此函数则具有 带安全检查的未定义行为。

pub fn signedRemainder(numerator: anytype, denominator: anytype) @TypeOf(numerator, denominator)

std.zig.c_translation.helpers.sizeof

函数

第 260 行

给定值,返回如同 C 的 sizeof 运算符计算的大小。

pub fn sizeof(target: anytype) usize

std.zig.c_translation.helpers.std

别名

第 1 行

别名目标 std

std.zig.c_translation.helpers.ToUnsigned

类型函数

第 74 行

fn ToUnsigned(comptime T: type) type

参数

T: type

std.zig.c_translation.helpers.U_SUFFIX

函数

第 396 行

pub inline fn U_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_uint, n, .decimal))

参数

n: comptime_int

std.zig.c_translation.helpers.UL_SUFFIX

函数

第 400 行

pub inline fn UL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_ulong, n, .decimal))

参数

n: comptime_int

std.zig.c_translation.helpers.ULL_SUFFIX

函数

第 404 行

pub inline fn ULL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_ulonglong, n, .decimal))

参数

n: comptime_int

std.zig.c_translation.helpers.WL_CONTAINER_OF

函数

第 408 行

pub fn WL_CONTAINER_OF(ptr: anytype, sample: anytype, comptime member: []const u8) @TypeOf(sample)

参数

member: []const u8
源码

std/zig/c_translation/helpers.zig

const std = @import("std");

/// C11 标准 6.3.1.8 中的“通常算术转换”。
pub fn ArithmeticConversion(comptime A: type, comptime B: type) type {
    if (A == c_longdouble or B == c_longdouble) return c_longdouble;
    if (A == f80 or B == f80) return f80;
    if (A == f64 or B == f64) return f64;
    if (A == f32 or B == f32) return f32;

    const A_Promoted = PromotedIntType(A);
    const B_Promoted = PromotedIntType(B);
    comptime {
        std.debug.assert(integerRank(A_Promoted) >= integerRank(c_int));
        std.debug.assert(integerRank(B_Promoted) >= integerRank(c_int));
    }

    if (A_Promoted == B_Promoted) return A_Promoted;

    const a_signed = @typeInfo(A_Promoted).int.signedness == .signed;
    const b_signed = @typeInfo(B_Promoted).int.signedness == .signed;

    if (a_signed == b_signed) {
        return if (integerRank(A_Promoted) > integerRank(B_Promoted)) A_Promoted else B_Promoted;
    }

    const SignedType = if (a_signed) A_Promoted else B_Promoted;
    const UnsignedType = if (!a_signed) A_Promoted else B_Promoted;

    if (integerRank(UnsignedType) >= integerRank(SignedType)) return UnsignedType;

    if (std.math.maxInt(SignedType) >= std.math.maxInt(UnsignedType)) return SignedType;

    return ToUnsigned(SignedType);
}

/// C11 6.3.1.1.2 中描述的整数提升
fn PromotedIntType(comptime T: type) type {
    return switch (T) {
        bool, c_short => c_int,
        c_ushort => if (@sizeOf(c_ushort) == @sizeOf(c_int)) c_uint else c_int,
        c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong => T,
        else => switch (@typeInfo(T)) {
            .comptime_int => @compileError("Cannot promote `" ++ @typeName(T) ++ "`; a fixed-size number type is required"),
            // 若 c_int 可表示 T 的全部值,则提升为 c_int
            .int => |int_info| if (int_info.bits < @bitSizeOf(c_int))
                c_int
                // 否则恢复原始 C 类型
            else if (int_info.bits == @bitSizeOf(c_int))
                if (int_info.signedness == .unsigned) c_uint else c_int
            else if (int_info.bits <= @bitSizeOf(c_long))
                if (int_info.signedness == .unsigned) c_ulong else c_long
            else if (int_info.bits <= @bitSizeOf(c_longlong))
                if (int_info.signedness == .unsigned) c_ulonglong else c_longlong
            else
                @compileError("Cannot promote `" ++ @typeName(T) ++ "`; a C ABI type is required"),
            else => @compileError("Attempted to promote invalid type `" ++ @typeName(T) ++ "`"),
        },
    };
}

/// C11 6.3.1.1.1
fn integerRank(comptime T: type) u8 {
    return switch (T) {
        bool => 0,
        u8, i8 => 1,
        c_short, c_ushort => 2,
        c_int, c_uint => 3,
        c_long, c_ulong => 4,
        c_longlong, c_ulonglong => 5,
        else => @compileError("integer rank not supported for `" ++ @typeName(T) ++ "`"),
    };
}

fn ToUnsigned(comptime T: type) type {
    return switch (T) {
        c_int => c_uint,
        c_long => c_ulong,
        c_longlong => c_ulonglong,
        else => @compileError("Cannot convert `" ++ @typeName(T) ++ "` to unsigned"),
    };
}

/// 构造 [*c] 指针,从 SelfType 继承 const 和 volatile 注解,
/// 用于指向 ElementType 类型的 C 柔性数组。
pub fn FlexibleArrayType(comptime SelfType: type, comptime ElementType: type) type {
    switch (@typeInfo(SelfType)) {
        .pointer => |ptr| {
            return @Pointer(.c, .{
                .@"const" = ptr.attrs.@"const",
                .@"volatile" = ptr.attrs.@"volatile",
                .@"allowzero" = true,
                .@"addrspace" = .generic,
                .@"align" = null,
            }, ElementType, null);
        },
        else => |info| @compileError("Invalid self type \"" ++ @tagName(info) ++ "\" for flexible array getter: " ++ @typeName(SelfType)),
    }
}

/// 像 C 一样提升整数字面量的类型,直到能够容纳。
pub inline fn promoteIntLiteral(
    comptime SuffixType: type,
    comptime number: comptime_int,
    comptime base: CIntLiteralBase,
) PromoteIntLiteralReturnType(SuffixType, number, base) {
    return number;
}

const CIntLiteralBase = enum { decimal, octal, hex };

fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: comptime_int, comptime base: CIntLiteralBase) type {
    const signed_decimal = [_]type{ c_int, c_long, c_longlong, c_ulonglong };
    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 (base == .decimal)
        &signed_decimal
    else
        &signed_oct_hex;

    var pos = std.mem.findScalar(type, list, SuffixType).?;
    while (pos < list.len) : (pos += 1) {
        if (number >= std.math.minInt(list[pos]) and number <= std.math.maxInt(list[pos])) {
            return list[pos];
        }
    }

    @compileError("Integer literal is too large");
}

/// 将 clang __builtin_shufflevector 索引转换为 Zig @shuffle 索引。
/// clang 要求 __builtin_shufflevector 的索引参数是整数常量。
/// `this_index` 为负表示“不关心”。
/// clang 强制 `this_index` 小于向量元素总数。
/// 参见 https://ziglang.org/documentation/master/#shuffle
/// 参见 https://clang.llvm.org/docs/LanguageExtensions.html#langext-builtin-shufflevector
pub fn shuffleVectorIndex(comptime this_index: c_int, comptime source_vector_len: usize) i32 {
    const positive_index = std.math.cast(usize, this_index) orelse return undefined;
    if (positive_index < source_vector_len) return @as(i32, @intCast(this_index));
    const b_index = positive_index - source_vector_len;
    return ~@as(i32, @intCast(b_index));
}

/// C 的有符号整数 `%` 运算符。
/// C 标准规定:“如果商 a/b 可表示,则表达式 (a/b)*b + a%b 应等于 a”。
/// 分母为零,或分子为该类型的最小整数且分母为 -1 时,
/// 商不可表示。C 在这两种情况下具有未定义行为;此函数则具有
/// 带安全检查的未定义行为。
pub fn signedRemainder(numerator: anytype, denominator: anytype) @TypeOf(numerator, denominator) {
    std.debug.assert(@typeInfo(@TypeOf(numerator, denominator)).int.signedness == .signed);
    if (denominator > 0) return @rem(numerator, denominator);
    return numerator - @divTrunc(numerator, denominator) * denominator;
}

/// 给定类型和值,按照 C 的方式将该值转换为该类型。
pub fn cast(comptime DestType: type, target: anytype) DestType {
    // 此函数的行为应类似 translate-c 中的 transCCast,但用于宏
    const SourceType = @TypeOf(target);
    switch (@typeInfo(DestType)) {
        .@"fn" => return castToPtr(*const DestType, SourceType, target),
        .pointer => return castToPtr(DestType, SourceType, target),
        .optional => |dest_opt| {
            if (@typeInfo(dest_opt.child) == .pointer) {
                return castToPtr(DestType, SourceType, target);
            } else if (@typeInfo(dest_opt.child) == .@"fn") {
                return castToPtr(?*const dest_opt.child, SourceType, target);
            }
        },
        .int => {
            switch (@typeInfo(SourceType)) {
                .pointer => {
                    return castInt(DestType, @intFromPtr(target));
                },
                .optional => |opt| {
                    if (@typeInfo(opt.child) == .pointer) {
                        return castInt(DestType, @intFromPtr(target));
                    }
                },
                .int => {
                    return castInt(DestType, target);
                },
                .@"fn" => {
                    return castInt(DestType, @intFromPtr(&target));
                },
                .bool => {
                    return @intFromBool(target);
                },
                else => {},
            }
        },
        .float => {
            switch (@typeInfo(SourceType)) {
                .int => return @as(DestType, @floatFromInt(target)),
                .float => return @as(DestType, @floatCast(target)),
                .bool => return @as(DestType, @floatFromInt(@intFromBool(target))),
                else => {},
            }
        },
        .@"union" => |info| {
            inline for (info.field_names, info.field_types) |field_name, field_type| {
                if (field_type == SourceType) return @unionInit(DestType, field_name, target);
            }

            @compileError("cast to union type '" ++ @typeName(DestType) ++ "' from type '" ++ @typeName(SourceType) ++ "' which is not present in union");
        },
        .bool => return cast(usize, target) != 0,
        else => {},
    }

    return @as(DestType, target);
}

fn castInt(comptime DestType: type, target: anytype) DestType {
    const dest = @typeInfo(DestType).int;
    const source = @typeInfo(@TypeOf(target)).int;

    const Int = @Int(source.signedness, dest.bits);

    if (dest.bits < source.bits)
        return @as(DestType, @bitCast(@as(Int, @truncate(target))))
    else
        return @as(DestType, @bitCast(@as(Int, target)));
}

fn castPtr(comptime DestType: type, target: anytype) DestType {
    return @ptrCast(@alignCast(@constCast(@volatileCast(target))));
}

fn castToPtr(comptime DestType: type, comptime SourceType: type, target: anytype) DestType {
    switch (@typeInfo(SourceType)) {
        .int => {
            return @as(DestType, @ptrFromInt(castInt(usize, target)));
        },
        .comptime_int => {
            if (target < 0)
                return @as(DestType, @ptrFromInt(@as(usize, @bitCast(@as(isize, @intCast(target))))))
            else
                return @as(DestType, @ptrFromInt(@as(usize, @intCast(target))));
        },
        .pointer => {
            return castPtr(DestType, target);
        },
        .@"fn" => {
            return castPtr(DestType, &target);
        },
        .optional => |target_opt| {
            if (@typeInfo(target_opt.child) == .pointer) {
                return castPtr(DestType, target);
            }
        },
        else => {},
    }

    return @as(DestType, target);
}

/// 给定值,返回如同 C 的 sizeof 运算符计算的大小。
pub fn sizeof(target: anytype) usize {
    const T: type = if (@TypeOf(target) == type) target else @TypeOf(target);
    switch (@typeInfo(T)) {
        .float, .int, .@"struct", .@"union", .array, .bool, .vector => return @sizeOf(T),
        .@"fn" => {
            // C 中 sizeof(main) 返回 1
            return 1;
        },
        .null => return @sizeOf(*anyopaque),
        .void => {
            // 注意:clang/gcc 中 sizeof(void) 为 1,MSVC 中为 0。
            return 1;
        },
        .@"opaque" => {
            if (T == anyopaque) {
                // 注意:clang/gcc 中 sizeof(void) 为 1,MSVC 中为 0。
                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));
            }

            // 对于字符串,sizeof("a") 返回 2。
            // 上文的 .array 情况处理了 C 中常见的指针衰变情形,但字符串仍然是字面量,
            // 因此始终为指针,所以必须在此专门处理。
            //
            //
            if (ptr.size == .one and ptr.attrs.@"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() == 0) {
                    // 字符串长度加一,用于容纳空终止符。
                    return (array_info.len + 1) * @sizeOf(array_info.child);
                }
            }

            // 移除零大小指针后,此情况将不可达,
            // 届时可将其删除。
            if (@sizeOf(T) == 0) {
                return @sizeOf(*anyopaque);
            }

            return @sizeOf(T);
        },
        .comptime_float => return @sizeOf(f64), // TODO c_double #3999
        .comptime_int => {
            // TODO: 为获得正确结果,必须将
            // `1073741824 * 4` 转换为 `int(1073741824) *% int(4)`,因为
            // sizeof(1073741824 * 4) != sizeof(4294967296)。

            // TODO: 测试 target 是否可由 int、long 或 long long 表示。
            return @sizeOf(c_int);
        },
        else => @compileError("__helpers.sizeof does not support type " ++ @typeName(T)),
    }
}

pub fn div(a: anytype, b: anytype) ArithmeticConversion(@TypeOf(a), @TypeOf(b)) {
    const ResType = ArithmeticConversion(@TypeOf(a), @TypeOf(b));
    const a_casted = cast(ResType, a);
    const b_casted = cast(ResType, b);
    switch (@typeInfo(ResType)) {
        .float => return a_casted / b_casted,
        .int => return @divTrunc(a_casted, b_casted),
        else => unreachable,
    }
}

pub fn rem(a: anytype, b: anytype) ArithmeticConversion(@TypeOf(a), @TypeOf(b)) {
    const ResType = ArithmeticConversion(@TypeOf(a), @TypeOf(b));
    const a_casted = cast(ResType, a);
    const b_casted = cast(ResType, b);
    switch (@typeInfo(ResType)) {
        .int => {
            if (@typeInfo(ResType).int.signedness == .signed) {
                return signedRemainder(a_casted, b_casted);
            } else {
                return a_casted % b_casted;
            }
        },
        else => unreachable,
    }
}

/// 二参数类函数宏 #define FOO(A, B) (A)(B) 既可能表示将 B 转换为 A,也可能表示用值 B 调用 A。
///
pub fn CAST_OR_CALL(a: anytype, b: anytype) switch (@typeInfo(@TypeOf(a))) {
    .type => a,
    .@"fn" => |fn_info| fn_info.return_type orelse void,
    else => |info| @compileError("Unexpected argument type: " ++ @tagName(info)),
} {
    switch (@typeInfo(@TypeOf(a))) {
        .type => return cast(a, b),
        .@"fn" => return a(b),
        else => unreachable, // 否则返回类型会导致编译错误
    }
}

pub inline fn DISCARD(x: anytype) void {
    _ = x;
}

pub fn F_SUFFIX(comptime f: comptime_float) f32 {
    return @as(f32, f);
}

fn L_SUFFIX_ReturnType(comptime number: anytype) type {
    switch (@typeInfo(@TypeOf(number))) {
        .int, .comptime_int => return @TypeOf(promoteIntLiteral(c_long, number, .decimal)),
        .float, .comptime_float => return c_longdouble,
        else => @compileError("Invalid value for L suffix"),
    }
}

pub inline fn L_SUFFIX(comptime number: anytype) L_SUFFIX_ReturnType(number) {
    switch (@typeInfo(@TypeOf(number))) {
        .int, .comptime_int => return promoteIntLiteral(c_long, number, .decimal),
        .float, .comptime_float => @compileError("TODO: c_longdouble initialization from comptime_float not supported"),
        else => @compileError("Invalid value for L suffix"),
    }
}

pub inline fn LL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_longlong, n, .decimal)) {
    return promoteIntLiteral(c_longlong, n, .decimal);
}

pub inline fn U_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_uint, n, .decimal)) {
    return promoteIntLiteral(c_uint, n, .decimal);
}

pub inline fn UL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_ulong, n, .decimal)) {
    return promoteIntLiteral(c_ulong, n, .decimal);
}

pub inline fn ULL_SUFFIX(comptime n: comptime_int) @TypeOf(promoteIntLiteral(c_ulonglong, n, .decimal)) {
    return promoteIntLiteral(c_ulonglong, n, .decimal);
}

pub fn WL_CONTAINER_OF(ptr: anytype, sample: anytype, comptime member: []const u8) @TypeOf(sample) {
    return @fieldParentPtr(member, ptr);
}