Skip to content

[wgsl] Support compile-time-constants (constexpr) #1272

@ben-clayton

Description

@ben-clayton

Discussed at the 2020-11-30 meeting.

#1238 has highlighted the desire compile-time-constant variables.

The textureSample() intrinsics that take an offset parameter require the offset value to be known at compile time. A const variable might be compile-time-known, but is not guaranteed.
const at module scope might suffice for offset's needs, but permitting const based on lexical scope is confusing, and specializations may break this anyway.

We may wish to consider adding constexpr as a new variable specifier, which can only be assigned a const_expr expression.

variable_statement would then look something like:

variable_statement
  : variable_decl
  | variable_decl EQUAL short_circuit_or_expression
  | CONST variable_ident_decl EQUAL short_circuit_or_expression
  | CONSTEXPR variable_ident_decl EQUAL const_expr

Exampes:

constexpr a : f32 = 1.0;
constexpr b : i32 = 2;
constexpr c : vec2<i32> = vec2<i32>(1, 2);

The current grammar of const_expr does not allow for identifiers, so constexpr d : vec2<i32> = c; would not currently be valid. const_expr could be altered to:

const_expr
  : type_decl PAREN_LEFT (const_expr COMMA)* const_expr PAREN_RIGHT
  | IDENT
  | const_literal

Where the IDENT needs to resolve to a constexpr variable, allowing for:

constexpr e : vec2<i32> = vec2<i32>(b, b);
constexpr f : vec3<i32> = vec3<i32>(e, 5);

Metadata

Metadata

Assignees

No one assigned

    Labels

    wgslWebGPU Shading Language Issues

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions