美文网首页
算子编译期参数检查

算子编译期参数检查

作者: Joe_WQ | 来源:发表于2025-01-22 10:55 被阅读0次

说明

pytorch的底层实现是用的c++,导致检查type极其麻烦,需要jit、template之类的技术,但是zig是支持type类型的,comptime如虎添翼。

简单的函数名和参数检查

注:以下代码是deepseek r1 生成的,然后改了下bug,在 0.14-dev下能跑起来。

const std = @import("std");

const Tensor = struct {};
// 定义 Tensor 结构体示例
const Dpu = struct {
    // 示例方法,符合要求的签名
    pub fn add(self: *Tensor, dim: i32, index: *Tensor, src: *Tensor) Tensor {
        std.debug.print("add {}, {}, {}, {}\n", .{ self, dim, index, src });
        return Tensor{};
    }
};

// 编译时检查方法签名的函数
fn checkMethodSignature(
    comptime Struct: type,
    comptime methodName: []const u8,
    comptime expectedParamTypes: []const type,
    comptime expectedReturnType: type,
) void {
    // 检查方法是否存在于结构体中
    if (!@hasDecl(Struct, methodName)) {
        @compileError("方法 '" ++ methodName ++ "' 不存在于 " ++ @typeName(Struct));
    }

    // 获取方法实例及其类型信息
    const method = @field(Struct, methodName);
    const FuncType = @TypeOf(method);
    const funcInfo = @typeInfo(FuncType).@"fn";

    // 检查参数数量(包含 self)
    const expectedParamCount = expectedParamTypes.len;
    if (funcInfo.params.len != expectedParamCount) {
        @compileError("参数数量错误,期望 " ++ std.fmt.comptimePrint("{}", .{expectedParamCount}) ++ " 个,实际 " ++ std.fmt.comptimePrint("{}", .{funcInfo.params.len}));
    }

    // 检查参数类型
    for (funcInfo.params[0..], 0..) |param, i| {
        const expectedType = expectedParamTypes[i];
        if (param.type != expectedType) {
            @compileError("参数 " ++ std.fmt.comptimePrint("{}", .{i}) ++ " 类型应为 " ++ @typeName(expectedType) ++ ",实际为 " ++ @typeName(param.type.?));
        }
    }

    // 检查返回类型
    if (funcInfo.return_type != expectedReturnType) {
        @compileError("返回类型应为 " ++ @typeName(expectedReturnType) ++ ",实际为 " ++ @typeName(funcInfo.return_type.?));
    }
}

// 编译时执行检查
comptime {
    checkMethodSignature(Dpu, "add", &[_]type{ *Tensor, i32, *Tensor, *Tensor }, Tensor);
}

pub fn main() void {
    std.debug.print("函数签名检查通过!\n", .{});
}

相关文章

  • iOS编译警告

    iOS编译警告-消除方法参数检查相关的警告 iOS编译警告-消除注释中的警告

  • 震惊!Android官方竟不推荐使用enum类型!

    枚举是一种规范,它规范了参数的形式,这样就可以不用考虑类型的不匹配(编译期检查)并且显式的替代了int型参数可能带...

  • instancetype和id的区别

    1、instancetype在编译期确定实例的类型,id在编译期不检查类型,运行时检查类型。2、id可以作为方法的...

  • JVM常用参数

    内存设置 GC设置 调试参数 其他 -Xverify:none 跳过编译检查服务器推荐GC参数:-Xloggc:g...

  • 简析java泛型

    1.Java如果没有泛型会有什么灾难? -泛型实现类型参数化,将类型检查从运行期提前到编译期,限定元素类型,避免强...

  • javaSE_day13_泛型

    泛型:参数化数据类型;类,方法 ,构造器,接口 好处:编译器 进行类型检查; 泛型类:类名 <类型参数> 类型参数...

  • Effective Java(3rd)-Item27 消除未经检

      当你使用泛型编程时,你将看到许多编译警告:未检查的强制转换警告,未检查的方法调用,未检查的参数化vararg类...

  • [Note] 2021-06-10 Gradle flavors

    CMake 参数传递 打包编译指令参数 -> gradle 参数 -> CMakeList 参数 -> 编译C++...

  • Linux Note 7 20160717

    软件管理 源代码形式 基本流程 ./configure 检查编译环境,相关库文件配置参数,生成makefile m...

  • 9. Spring

    IOC 由于java 编译后才能运行,由于编译期进行的检查可能导致我们缺组件不能编译通过。所以要想个办法绕过编译器...

网友评论

      本文标题:算子编译期参数检查

      本文链接:https://www.haomeiwen.com/subject/wihcujtx.html