You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

wgpu-rs中从W3C规范复制的WGSL着色器出现解析错误如何解决

报错原因分析
  • 核心问题是你使用的2021版wgpu对应的WGSL解析器实现的是早期语法草案,和你复制的规范文档版本存在兼容性差异,语法规则不匹配导致解析失败。
  • 直接报错触发点是早期WGSL草案强制要求loop语句必须附带continuing块,你的代码中loop结构没有定义对应的continuing块,解析器在匹配loop语法规则时预期读取到块标识,却读到了普通赋值语句的分号,就抛出了expected '(', found ';'的错误。当时的解析器行号定位存在偏差,所以错误指向了i = i + step;这一行。
  • 代码中还存在两个潜在的编译问题:
    • 所用的[[location]]、[[stage]]双括号属性是旧草案语法,后续稳定版WGSL已经替换为@location、@vertex格式的@前缀属性
    • 片元着色器的参数名in是WGSL保留关键字,不能作为自定义参数名使用
适配旧版wgpu的修复代码示例
// Vertex shader
struct VertexInput {
    [[location(0)]] pos: vec3<f32>;
};

struct VertexOutput {
    [[builtin(position)]] pos: vec4<f32>;
};

[[stage(vertex)]]
fn main(vertex_input: VertexInput) -> VertexOutput {
    var out: VertexOutput;
    out.pos = vec4<f32>(vertex_input.pos, 1.0);

    var a: i32 = 2;
    var i: i32 = 0;
    loop {
        if (i >= 4) { break; }
    
        let step: i32 = 1;
    
        i = i + step;
        if (i % 2 == 0) { continue; }
    
        a = a * 2;
        // 补充空的continuing块适配旧语法要求
        continuing {}
    }

    return out;
}

// Fragment shader
[[stage(fragment)]]
// 参数名in改为非关键字的in_data
fn main(in_data: VertexOutput) -> [[location(0)]] vec4<f32> {
    return vec4<f32>(1.0, 1.0, 1.0, 1.0);
}

内容的提问来源于stack exchange,提问作者can

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:27:04