跳转到内容

std.zig.number_literal

标准库Zig 0.17.1官方原文
源码std/zig/number_literal.zig

第 1 行

std.zig.number_literal.assert

别名

第 2 行

别名目标 std.debug.assert

std.zig.number_literal.Base

容器

第 9 行

字段

decimal = 10
hex = 16
binary = 2
octal = 8

std.zig.number_literal.checkFloat

函数

第 186 行

若 parseNumberLiteral 返回 .float 而 parseFloat 失败,则返回错误。 AstGen 依赖于调用 parseNumberLiteral 后 parseFloat 不会失败。

fn checkFloat(bytes: []const u8) !void

参数

bytes: []const u8

std.zig.number_literal.Error

容器

第 24 行

字段

leading_zero

数字含有前导零。

digit_after_base

基数前缀后必须有数字。

upper_case_base: usize

基数前缀为大写。

invalid_float_base: usize

浮点字面量的基数前缀无效。

repeated_underscore: usize

数字分隔符 '_' 重复。

invalid_underscore_after_special: usize

特殊字符(+-.)之后的 '_' 数字分隔符

invalid_digit: struct { i: usize, base: Base }

对于指定进制,此数位无效。

invalid_digit_exponent: usize

指数中存在无效数字。

duplicate_period

浮点字面量有多个小数点。

duplicate_exponent: usize

浮点字面量具有多个指数。

exponent_after_underscore: usize

指数紧接 '_' 数字分隔符之后。

special_after_underscore: usize

特殊字符(+-.)直接出现在下划线之后。

trailing_special: usize

数字以特殊字符结尾(+-.)

trailing_underscore: usize

数字以 '_' 数字分隔符结尾。

invalid_character: usize

字符不在 [0-9a-zA-Z.+-_] 内

invalid_exponent_sign: usize

[+-] 未紧跟在 [pPeE] 之后

period_after_exponent: usize

小数点出现在指数之后。

std.zig.number_literal.FloatBase

容器

第 10 行

字段

decimal = 10
hex = 16

std.zig.number_literal.ParseError

错误集合

第 4 行

错误

InvalidLiteral
OutOfMemory

std.zig.number_literal.parseNumberLiteral

函数

第 63 行

解析 fmt.parseInt、fmt.parseFloat 和 big_int.setString 接受的 Zig 数字字面量。 适用于任意 number_literal 标记字节。

pub fn parseNumberLiteral(bytes: []const u8) Result

参数

bytes: []const u8

用法示例

test parseNumberLiteral {
    try std.testing.expectEqual(Result{ .float = .decimal }, parseNumberLiteral("3E2"));
    try std.testing.expectEqual(Result{ .int = 0x3E2 }, parseNumberLiteral("0x3E2"));
    try std.testing.expectEqual(Result{ .float = .hex }, parseNumberLiteral("0x3p2"));
    try std.testing.expectEqual(Result{ .failure = .{ .period_after_exponent = 3 } }, parseNumberLiteral("3E2.5"));
    try std.testing.expectEqual(Result{ .failure = .{ .period_after_exponent = 2 } }, parseNumberLiteral("3E.5"));
    try std.testing.expectEqual(Result{ .failure = .{ .period_after_exponent = 3 } }, parseNumberLiteral("3E1."));
    try std.testing.expectEqual(Result{ .failure = .{ .invalid_float_base = 1 } }, parseNumberLiteral("0o3.1"));
    try std.testing.expectEqual(Result{ .failure = .{ .invalid_digit = .{ .i = 3, .base = .octal } } }, parseNumberLiteral("0o3e1"));
}

std.zig.number_literal.Result

容器

第 12 行

字段

int: u64

若可放入 u64,则结果可表示

big_int: Base

结果是无法用 u64 表示的整数。载荷为基数;若不是 .decimal,则切片带有两个字符的前缀。

float: FloatBase

结果为浮点数。载荷是进制;如果不是 .decimal, 则切片包含两个字符的前缀。

failure: Error

std.zig.number_literal.std

别名

第 1 行

别名目标 std

std.zig.number_literal.testOne

函数

第 200 行

fn testOne(_: @This(), smith: *std.testing.Smith) anyerror!void

参数

_: @This()
smith: *std.testing.Smith
源码

std/zig/number_literal.zig

const std = @import("../std.zig");
const assert = std.debug.assert;

pub const ParseError = error{
    OutOfMemory,
    InvalidLiteral,
};

pub const Base = enum(u8) { decimal = 10, hex = 16, binary = 2, octal = 8 };
pub const FloatBase = enum(u8) { decimal = 10, hex = 16 };

pub const Result = union(enum) {
    /// 若可放入 u64,则结果可表示
    int: u64,
    /// 结果是无法用 u64 表示的整数。载荷为基数;若不是 `.decimal`,则切片带有两个字符的前缀。
    ///
    big_int: Base,
    /// 结果为浮点数。载荷是进制;如果不是 `.decimal`,
    /// 则切片包含两个字符的前缀。
    float: FloatBase,
    failure: Error,
};

pub const Error = union(enum) {
    /// 数字含有前导零。
    leading_zero,
    /// 基数前缀后必须有数字。
    digit_after_base,
    /// 基数前缀为大写。
    upper_case_base: usize,
    /// 浮点字面量的基数前缀无效。
    invalid_float_base: usize,
    /// 数字分隔符 '_' 重复。
    repeated_underscore: usize,
    /// 特殊字符(+-.)之后的 '_' 数字分隔符
    invalid_underscore_after_special: usize,
    /// 对于指定进制,此数位无效。
    invalid_digit: struct { i: usize, base: Base },
    /// 指数中存在无效数字。
    invalid_digit_exponent: usize,
    /// 浮点字面量有多个小数点。
    duplicate_period,
    /// 浮点字面量具有多个指数。
    duplicate_exponent: usize,
    /// 指数紧接 '_' 数字分隔符之后。
    exponent_after_underscore: usize,
    /// 特殊字符(+-.)直接出现在下划线之后。
    special_after_underscore: usize,
    /// 数字以特殊字符结尾(+-.)
    trailing_special: usize,
    /// 数字以 '_' 数字分隔符结尾。
    trailing_underscore: usize,
    /// 字符不在 [0-9a-zA-Z.+-_] 内
    invalid_character: usize,
    /// [+-] 未紧跟在 [pPeE] 之后
    invalid_exponent_sign: usize,
    /// 小数点出现在指数之后。
    period_after_exponent: usize,
};

/// 解析 fmt.parseInt、fmt.parseFloat 和 big_int.setString 接受的 Zig 数字字面量。
/// 适用于任意 number_literal 标记字节。
pub fn parseNumberLiteral(bytes: []const u8) Result {
    // 由词法分析器强制执行。
    assert(bytes.len > 0 and std.ascii.isDigit(bytes[0]));
    var i: usize = 0;
    var base: u8 = 10;
    if (bytes.len >= 2 and bytes[0] == '0') switch (bytes[1]) {
        'b' => {
            base = 2;
            i = 2;
        },
        'o' => {
            base = 8;
            i = 2;
        },
        'x' => {
            base = 16;
            i = 2;
        },
        'B', 'O', 'X' => return .{ .failure = .{ .upper_case_base = 1 } },
        '.', 'e', 'E' => {},
        else => return .{ .failure = .leading_zero },
    };
    if (bytes.len == 2 and base != 10) return .{ .failure = .digit_after_base };

    var x: u64 = 0;
    var overflow = false;
    var underscore = false;
    var period = false;
    var special: u8 = 0;
    var exponent = false;
    var float = false;
    while (i < bytes.len) : (i += 1) {
        const c = bytes[i];
        switch (c) {
            '_' => {
                if (i == 2 and base != 10) return .{ .failure = .{ .invalid_underscore_after_special = i } };
                if (special != 0) return .{ .failure = .{ .invalid_underscore_after_special = i } };
                if (underscore) return .{ .failure = .{ .repeated_underscore = i } };
                underscore = true;
                continue;
            },
            'e', 'E' => if (base == 10) {
                float = true;
                if (exponent) return .{ .failure = .{ .duplicate_exponent = i } };
                if (underscore) return .{ .failure = .{ .exponent_after_underscore = i } };
                special = c;
                exponent = true;
                continue;
            },
            'p', 'P' => if (base == 16) {
                if (i == 2) {
                    return .{ .failure = .{ .digit_after_base = {} } };
                }
                float = true;
                if (exponent) return .{ .failure = .{ .duplicate_exponent = i } };
                if (underscore) return .{ .failure = .{ .exponent_after_underscore = i } };
                special = c;
                exponent = true;
                continue;
            },
            '.' => {
                if (exponent) return .{ .failure = .{ .period_after_exponent = i } };
                float = true;
                if (base != 10 and base != 16) return .{ .failure = .{ .invalid_float_base = 1 } };
                if (period) return .{ .failure = .duplicate_period };
                period = true;
                if (underscore) return .{ .failure = .{ .special_after_underscore = i } };
                special = c;
                continue;
            },
            '+', '-' => {
                switch (special) {
                    'p', 'P' => {},
                    'e', 'E' => if (base != 10) return .{ .failure = .{ .invalid_exponent_sign = i } },
                    else => return .{ .failure = .{ .invalid_exponent_sign = i } },
                }
                special = c;
                continue;
            },
            else => {},
        }
        const digit = switch (c) {
            '0'...'9' => c - '0',
            'A'...'Z' => c - 'A' + 10,
            'a'...'z' => c - 'a' + 10,
            else => return .{ .failure = .{ .invalid_character = i } },
        };
        if (digit >= base) return .{ .failure = .{ .invalid_digit = .{ .i = i, .base = @as(Base, @fromBackingInt(@intCast(base))) } } };
        if (exponent and digit >= 10) return .{ .failure = .{ .invalid_digit_exponent = i } };
        underscore = false;
        special = 0;

        if (float) continue;
        if (x != 0) {
            const res = @mulWithOverflow(x, base);
            if (res[1] != 0) overflow = true;
            x = res[0];
        }
        const res = @addWithOverflow(x, digit);
        if (res[1] != 0) overflow = true;
        x = res[0];
    }
    if (underscore) return .{ .failure = .{ .trailing_underscore = bytes.len - 1 } };
    if (special != 0) return .{ .failure = .{ .trailing_special = bytes.len - 1 } };

    if (float) return .{ .float = @as(FloatBase, @fromBackingInt(@intCast(base))) };
    if (overflow) return .{ .big_int = @as(Base, @fromBackingInt(@intCast(base))) };
    return .{ .int = x };
}

test parseNumberLiteral {
    try std.testing.expectEqual(Result{ .float = .decimal }, parseNumberLiteral("3E2"));
    try std.testing.expectEqual(Result{ .int = 0x3E2 }, parseNumberLiteral("0x3E2"));
    try std.testing.expectEqual(Result{ .float = .hex }, parseNumberLiteral("0x3p2"));
    try std.testing.expectEqual(Result{ .failure = .{ .period_after_exponent = 3 } }, parseNumberLiteral("3E2.5"));
    try std.testing.expectEqual(Result{ .failure = .{ .period_after_exponent = 2 } }, parseNumberLiteral("3E.5"));
    try std.testing.expectEqual(Result{ .failure = .{ .period_after_exponent = 3 } }, parseNumberLiteral("3E1."));
    try std.testing.expectEqual(Result{ .failure = .{ .invalid_float_base = 1 } }, parseNumberLiteral("0o3.1"));
    try std.testing.expectEqual(Result{ .failure = .{ .invalid_digit = .{ .i = 3, .base = .octal } } }, parseNumberLiteral("0o3e1"));
}

/// 若 `parseNumberLiteral` 返回 `.float` 而 `parseFloat` 失败,则返回错误。
/// AstGen 依赖于调用 `parseNumberLiteral` 后 `parseFloat` 不会失败。
fn checkFloat(bytes: []const u8) !void {
    // 数字字面量必须以数字开头
    if (bytes.len == 0 or !std.ascii.isDigit(bytes[0])) return;

    switch (parseNumberLiteral(bytes)) {
        .float => {
            _ = try std.fmt.parseFloat(f128, bytes);
        },
        else => {},
    }
}

test "parseNumberLiteral float validation" {
    const Context = struct {
        fn testOne(_: @This(), smith: *std.testing.Smith) anyerror!void {
            var buf: [256]u8 = undefined;
            const bytes = buf[0..smith.slice(&buf)];
            try checkFloat(bytes);
        }
    };
    return std.testing.fuzz(Context{}, Context.testOne, .{});
}