gpu

source of shader::compiler

1// The shader compiler: checks a WGSL module's syntax tree and writes it2// as a SPIR-V 1.3 module for Vulkan 1.1, which the CPU rasterizer runs3// too. Every entry point (`@vertex`, `@fragment`, `@compute`) becomes a4// SPIR-V entry function that reads the stage's inputs from Input5// variables, calls the WGSL function, and writes its result to Output6// variables. Locals declared with `var` are Function variables, `let`7// values are SSA ids. The first error stops it.89import std::string;10import std::vector;11import std::option;12import std::text;1314import syntax;15import types;16import spirv;1718// A value an expression gives: an id of its type, or a pointer to one in19// a storage class.20pub type Value = struct {21    pub id: u32,22    pub ty: u32,23    pub pointer: bool = false,24    pub storage: StorageClass = ::Function, // a pointer's25    // a buffer whose type is not a struct, wrapped in one: read through26    // its one member27    pub wrapped: bool = false,28};2930type Binding = struct {31    name: String,32    value: Value,33};3435type Function = struct {36    id: u32,37    type_id: u32,38    result: u32,39    parameters: Vector<u32>,40};4142type FunctionType = struct {43    id: u32,44    result: u32,45    parameters: Vector<u32>,46};4748// What a function uses: a resource, by its index, or a function it calls.49type Use = struct {50    function: u32,51    used: Used,52};5354type Used = enum {55    Resource: u32,56    Function: u32,57};5859// An operator's or built-in's instruction for each kind of scalar.60type ByScalar<T> = struct {61    float: Option<T> = ::None,62    signed: Option<T> = ::None,63    unsigned: Option<T> = ::None,64    boolean: Option<T> = ::None,65};6667type Pointer = struct {68    storage: StorageClass,69    ty: u32,70    id: u32,71};7273type Constant = struct {74    ty: u32,75    bits: u32,76    id: u32,77};7879// What a pipeline needs to know of a resource the shader binds.80pub type ShaderResource = struct {81    pub group: u32,82    pub binding: u32,83    pub kind: ResourceKind,84    pub size: u32, // a buffer's size, its last array's elements excluded85};8687// The browser's side (webgpu.web.js) numbers them in this order.88pub type ResourceKind = enum : u32 {89    Uniform = 0,90    Storage = 1,91    StorageRead = 2, // a storage buffer only read92    Texture = 3,93    Sampler = 4,94};9596// What kind of object a resource binds.97pub type ResourceClass = enum {98    Buffer,99    Texture,100    Sampler,101};102103pub fn class(self kind: &ResourceKind) -> ResourceClass => match (kind) {104    ::Uniform, ::Storage, ::StorageRead ::Buffer;105    ::Texture ::Texture;106    ::Sampler ::Sampler;107};108109// A stage, by its SPIR-V execution model.110pub type Stage = enum : u32 {111    Vertex = 0,112    Fragment = 4,113    Compute = 5,114};115116pub type EntryPoint = struct {117    pub name: String,118    pub stage: Stage,119    pub workgroup: [u32 : 3],120    pub resources: Vector<u32>, // the resources it uses, by index121};122123pub type Compiled = struct {124    pub error: String, // empty when compiled125    pub words: Vector<u32>,126    pub entries: Vector<EntryPoint>,127    pub resources: Vector<ShaderResource>,128};129130type Loop = struct {131    merge: u32,132    continue_label: u32,133};134135type Compiler = struct {136    s: Syntax,137    t: Types = Types::create(),138    error: String = String::empty(),139    next_id: u32 = 1,140    glsl: u32 = 0, // GLSL.std.450's id141    header: Vector<u32> = Vector<u32>::empty(),142    entry_words: Vector<u32> = Vector<u32>::empty(),143    mode_words: Vector<u32> = Vector<u32>::empty(),144    decorations: Vector<u32> = Vector<u32>::empty(),145    globals: Vector<u32> = Vector<u32>::empty(),146    functions: Vector<u32> = Vector<u32>::empty(),147    // the function being written: its variables, then its body148    variables: Vector<u32> = Vector<u32>::empty(),149    body: Vector<u32> = Vector<u32>::empty(),150    terminated: bool = false, // whether the body's current block has ended151    result_type: u32 = VOID,152    loops: Vector<Loop> = Vector<Loop>::empty(),153    scopes: Vector<Binding> = Vector<Binding>::empty(),154    pointers: Vector<Pointer> = Vector<Pointer>::empty(),155    constants: Vector<Constant> = Vector<Constant>::empty(),156    function_list: Vector<Function> = Vector<Function>::empty(),157    function_types: Vector<FunctionType> = Vector<FunctionType>::empty(),158    struct_types: Vector<u32> = Vector<u32>::empty(), // the Types index of each syntax struct159    // the current entry point's Input and Output variables160    interface_ids: Vector<u32> = Vector<u32>::empty(),161    current: u32 = 0, // the function being compiled162    uses: Vector<Use> = Vector<Use>::empty(),163    entries: Vector<EntryPoint> = Vector<EntryPoint>::empty(),164    resources: Vector<ShaderResource> = Vector<ShaderResource>::empty(),165};166167pub fn compile(source: &[u8]) -> Compiled {168    var c = Compiler { .s = parse(&source) };169    if (c.s.error.length() != 0) {170        c.error = copy c.s.error;171    } else {172        c.module();173    }174    var out = Compiled {175        .error = move c.error,176        .words = Vector<u32>::empty(),177        .entries = move c.entries,178        .resources = move c.resources179    };180    if (out.error.length() == 0) {181        const words: [u32 : 5] = [MAGIC, VERSION_1_3, 0, c.next_id, 0];182        for (words) |w| {183            out.words.push(w);184        }185        const parts: [&Vector<u32> : 6] = [186            &c.header,187            &c.entry_words,188            &c.mode_words,189            &c.decorations,190            &c.globals,191            &c.functions192        ];193        for (parts) |&part| {194            for (part.view()) |w| {195                out.words.push(w);196            }197        }198    }199    return move out;200}201202/* --- Errors and ids --- */203204fn failed(self c: &Compiler) -> bool {205    return c.error.length() != 0;206}207208fn fail(self c: &var Compiler, token: u32, message: &[u8]) {209    if (c.error.length() == 0) {210        c.error = c.s.located(token, &message);211    }212}213214fn id(self c: &var Compiler) -> u32 {215    c.next_id += 1;216    return c.next_id - 1;217}218219fn text(self c: &Compiler, token: u32) -> &[u8] {220    return &c.s.text_of(token);221}222223fn expr_of(self c: &Compiler, e: u32) -> Expr => c.s.exprs.get(e to u64);224225// The run's `k`th entry in `lists`.226fn item(self c: &Compiler, run: Run, k: u64) -> u32 => c.s.lists.get(run.first to u64 + k);227228/* --- Types --- */229230// The SPIR-V id of the type, declared on first use.231fn type_id(self c: &var Compiler, ty: u32) -> u32 {232    const info = c.t.get(ty);233    if (info.id != 0) {234        return info.id;235    }236    var operands = Vector<u32>::empty();237    const opcode = match (info.kind) {238        ::Void Opcode::TypeVoid;239        ::Bool Opcode::TypeBool;240        ::I32, ::U32 {241            operands.append(&[32, if (info.kind is ::I32) 1 else 0]);242            yield Opcode::TypeInt;243        }244        ::F32 {245            operands.push(32);246            yield Opcode::TypeFloat;247        }248        ::Vector, ::Matrix {249            operands.append(&[c.type_id(info.element), info.count]);250            yield if (info.kind is ::Vector) Opcode::TypeVector else Opcode::TypeMatrix;251        }252        ::Array {253            operands.append(&[c.type_id(info.element), c.constant(U32, info.count)]);254            yield Opcode::TypeArray;255        }256        ::RuntimeArray {257            operands.push(c.type_id(info.element));258            yield Opcode::TypeRuntimeArray;259        }260        ::Struct {261            for ([..c.t.member_count(ty)]) |k| {262                const member_type = c.t.struct_member(ty, k to u32).ty;263                operands.push(c.type_id(member_type));264            }265            yield Opcode::TypeStruct;266        }267        ::Texture {268            // 2D, not depth, not arrayed, single-sampled, sampled, any format269            operands.append(&[c.type_id(F32), 1, 0, 0, 0, 1, 0]);270            yield Opcode::TypeImage;271        }272        ::Sampler Opcode::TypeSampler;273        ::SampledImage {274            operands.push(c.type_id(info.element));275            yield Opcode::TypeSampledImage;276        }277    };278    const id = c.id();279    var all = Vector<u32>::from(&[id]);280    all.append(&operands.view());281    instruction(&var c.globals, opcode, &all.view());282    c.t.list.get_var(ty to u64).id = id;283    c.decorate_layout(ty, id);284    return id;285}286287// The offsets and strides of a type buffers may hold.288fn decorate_layout(self c: &var Compiler, ty: u32, id: u32) {289    const info = c.t.get(ty);290    if (info.kind is ::Array || info.kind is ::RuntimeArray) {291        decorate(&var c.decorations, id, ::ArrayStride, &[c.t.stride(info.element)]);292    } else if (info.kind is ::Struct) {293        for ([..c.t.member_count(ty)]) |k| {294            const member = &c.t.struct_member(ty, k to u32);295            const member_type = member.ty;296            const offset = member.offset;297            decorate_member(&var c.decorations, id, k to u32, ::Offset, &[offset]);298            if (c.t.kind(member_type) == Kind::Matrix) {299                decorate_member(&var c.decorations, id, k to u32, ::ColMajor, &[]);300                const stride = c.t.stride(c.t.get(member_type).element);301                decorate_member(&var c.decorations, id, k to u32, ::MatrixStride, &[stride]);302            }303        }304    }305}306307fn pointer_type(self c: &var Compiler, storage: StorageClass, ty: u32) -> u32 {308    for (c.pointers.view()) |&p| {309        if (p.storage == storage && p.ty == ty) {310            return p.id;311        }312    }313    const pointee = c.type_id(ty);314    const id = c.id();315    instruction(&var c.globals, ::TypePointer, &[id, storage to u32, pointee]);316    c.pointers.push(Pointer { .storage = storage, .ty = ty, .id = id });317    return id;318}319320// The id of a function type, with the result and parameter types.321fn function_type(self c: &var Compiler, result: u32, parameters: &[u32]) -> u32 {322    for (c.function_types.view()) |&f| {323        if (f.result == result && f.parameters.view() == parameters) {324            return f.id;325        }326    }327    var operands = Vector<u32>::empty();328    const id = c.id();329    operands.push(id);330    operands.push(c.type_id(result));331    for (parameters) |p| {332        operands.push(c.type_id(p));333    }334    instruction(&var c.globals, ::TypeFunction, &operands.view());335    c.function_types.push(FunctionType {336        .id = id,337        .result = result,338        .parameters = Vector<u32>::from(&parameters)339    });340    return id;341}342343// The constant of a scalar type with the bits.344fn constant(self c: &var Compiler, ty: u32, bits: u32) -> u32 {345    for (c.constants.view()) |&k| {346        if (k.ty == ty && k.bits == bits) {347            return k.id;348        }349    }350    const type_id = c.type_id(ty);351    const id = c.id();352    if (ty == BOOL) {353        instruction(354            &var c.globals,355            if (bits != 0) Opcode::ConstantTrue else Opcode::ConstantFalse,356            &[type_id, id]357        );358    } else {359        instruction(&var c.globals, ::Constant, &[type_id, id, bits]);360    }361    c.constants.push(Constant { .ty = ty, .bits = bits, .id = id });362    return id;363}364365fn null_constant(self c: &var Compiler, ty: u32) -> u32 {366    const type_id = c.type_id(ty);367    const id = c.id();368    instruction(&var c.globals, ::ConstantNull, &[type_id, id]);369    return id;370}371372// The type a written type names.373fn resolve_type(self c: &var Compiler, node: u32) -> u32 {374    if (c.failed()) {375        return VOID;376    }377    const n = c.s.types.get(node to u64);378    const name = &c.text(n.token);379    if (scalar_named(&name) is ::Some |scalar|) {380        return scalar;381    }382    // vec2f, vec3i, vec4u and the like383    if (name.length() == 5 && name.starts_with(&"vec") && name[3] >= '2' && name[3] <= '4') {384        if (scalar_suffix(name[4]) is ::Some |element|) {385            return c.t.vector(element, (name[3] - '0') to u32);386        }387    }388    if (389        name.length() == 4390        && name.starts_with(&"vec")391        && name[3] >= '2'392        && name[3] <= '4'393        && n.arguments.count == 1394    ) {395        const element = c.resolve_type(c.item(n.arguments, 0));396        return c.t.vector(element, (name[3] - '0') to u32);397    }398    // mat2x2f, mat4x4<f32>399    if (name.length() >= 6 && name.starts_with(&"mat") && name[4] == 'x') {400        const columns = (name[3] - '0') to u32;401        const rows = (name[5] - '0') to u32;402        if (columns >= 2 && columns <= 4 && rows >= 2 && rows <= 4) {403            return c.t.intern(Kind::Matrix, c.t.vector(F32, rows), columns);404        }405    }406    if (name == "array" && n.arguments.count == 1) {407        const element = c.resolve_type(c.item(n.arguments, 0));408        if (n.length is ::Some |e|) {409            return c.t.intern(Kind::Array, element, c.integer_constant(e));410        }411        return c.t.intern(Kind::RuntimeArray, element, 0);412    }413    if (name == "texture_2d") {414        return c.t.intern(Kind::Texture, F32, 0);415    }416    if (name == "sampler") {417        return c.t.intern(Kind::Sampler, 0, 0);418    }419    for ([..c.s.structs.length()]) |k| {420        if (c.text(c.s.structs.get(k).token) == name) {421            return c.struct_types.get(k);422        }423    }424    c.fail(n.token, &f"unknown type '{name}'".view());425    return VOID;426}427428fn scalar_named(name: &[u8]) -> Option<u32> => match (name) {429    "bool" ::Some(BOOL);430    "i32" ::Some(I32);431    "u32" ::Some(U32);432    "f32" ::Some(F32);433    else ::None;434};435436// The type a written type names, when one is written.437fn written_type(self c: &var Compiler, node: Option<u32>) -> Option<u32> {438    return if (node is ::Some |n|) ::Some(c.resolve_type(n)) else ::None;439}440441fn scalar_suffix(suffix: u8) -> Option<u32> => match (suffix) {442    'f' ::Some(F32);443    'i' ::Some(I32);444    'u' ::Some(U32);445    else ::None;446};447448// An integer known while compiling: a literal, a module constant, or449// arithmetic over them.450fn integer_constant(self c: &var Compiler, e: u32) -> u32 {451    const x = c.expr_of(e);452    match (x.form) {453        ::Integer {454            return integer_bits(&c.text(x.token));455        }456        ::Name {457            for (c.s.constants.view()) |&k| {458                if (c.text(k.token) == c.text(x.token)) {459                    return c.integer_constant(k.value);460                }461            }462        }463        ::Binary |operands| {464            const a = c.integer_constant(operands.left);465            const b = c.integer_constant(operands.right);466            match (c.text(x.token)) {467                "+" {468                    return a + b;469                }470                "-" {471                    return a - b;472                }473                "*" {474                    return a * b;475                }476            }477        }478    }479    c.fail(x.token, &"expected an integer constant");480    return 1;481}482483// The bits of an integer literal: decimal or hexadecimal, a `u` or `i`484// suffix ignored.485fn integer_bits(text: &[u8]) -> u32 {486    var digits = &text;487    if (488        digits.length() > 0489        && (digits[digits.length() - 1] == 'u' || digits[digits.length() - 1] == 'i')490    ) {491        digits = &digits[..digits.length() - 1];492    }493    var value: u64 = 0;494    if (digits.starts_with(&"0x")) {495        for (digits[2..]) |d| {496            const digit: u64 = if (d >= 'a') (497                d - 'a' + 10498            ) to u64 else if (d >= 'A') (d - 'A' + 10) to u64 else (d - '0') to u64;499            value = (value * 16 + digit) & 0xFFFFFFFF;500        }501    } else {502        for (digits) |d| {503            value = (value * 10 + (d - '0') to u64) & 0xFFFFFFFF;504        }505    }506    return value to u32;507}508509// The bits of a float literal as an f32.510fn float_bits(text: &[u8]) -> u32 {511    var mantissa: u64 = 0;512    var exponent: i64 = 0;513    var digits: u32 = 0;514    var k: u64 = 0;515    var after_point = false;516    while (k < text.length() && text[k] != 'e' && text[k] != 'E' && text[k] != 'f') {517        if (text[k] == '.') {518            after_point = true;519        } else if (digits < 18) {520            mantissa = mantissa * 10 + (text[k] - '0') to u64;521            digits += if (mantissa == 0) 0 else 1;522            if (after_point) {523                exponent -= 1;524            }525        } else if (!after_point) {526            exponent += 1;527        }528        k += 1;529    }530    if (k < text.length() && (text[k] == 'e' || text[k] == 'E')) {531        k += 1;532        var negative = false;533        if (k < text.length() && (text[k] == '-' || text[k] == '+')) {534            negative = text[k] == '-';535            k += 1;536        }537        var written: i64 = 0;538        while (k < text.length() && text[k] >= '0' && text[k] <= '9') {539            written = written * 10 + (text[k] - '0') to i64;540            k += 1;541        }542        exponent += if (negative) -written else written;543    }544    var value = mantissa to f64;545    var power: f64 = 1.0;546    const steps = if (exponent < 0) -exponent else exponent;547    for ([..steps to u64]) {548        power *= 10.0;549    }550    value = if (exponent < 0) value / power else value * power;551    const single = value to f32;552    return single as u32;553}554555/* --- The module --- */556557fn module(self c: &var Compiler) {558    instruction(&var c.header, ::Capability, &[Capability::Shader to u32]);559    c.glsl = c.id();560    var import_words = Vector<u32>::from(&[c.glsl]);561    string_words(&"GLSL.std.450", &var import_words);562    instruction(&var c.header, ::ExtInstImport, &import_words.view());563    // logical addressing, the GLSL450 memory model564    instruction(&var c.header, ::MemoryModel, &[0, 1]);565    c.declare_structs();566    c.declare_resources();567    c.declare_functions();568    for ([..c.s.functions.length()]) |k| {569        if (!c.failed()) {570            c.function_body(k to u32);571        }572    }573    for ([..c.s.functions.length()]) |k| {574        if (!c.failed()) {575            c.entry_point(k to u32);576        }577    }578}579580fn declare_structs(self c: &var Compiler) {581    for ([..c.s.structs.length()]) |k| {582        const decl = c.s.structs.get(k);583        const index = c.t.structs.length() to u32;584        c.t.structs.push(StructInfo {585            .name = String::from(&c.text(decl.token)),586            .first = c.t.members.length() to u32,587            .count = decl.fields.count,588            .size = 0,589            .alignment = 4590        });591        const ty = c.t.intern(Kind::Struct, 0, index);592        c.struct_types.push(ty);593        var offset: u32 = 0;594        var alignment: u32 = 4;595        for ([..decl.fields.count to u64]) |m| {596            const field = c.s.fields.get(decl.fields.first to u64 + m);597            const member_type = c.resolve_type(field.ty);598            const member_alignment = c.t.alignment(member_type);599            offset = round_up(member_alignment, offset);600            if (member_alignment > alignment) {601                alignment = member_alignment;602            }603            c.t.members.push(Member {604                .name = String::from(&c.text(field.token)),605                .ty = member_type,606                .offset = offset,607                .location = c.attribute(field.attributes, &"location"),608                .builtin = c.builtin_attribute(field.attributes)609            });610            offset += c.t.size(member_type);611        }612        var info = &var c.t.structs.get_var(index to u64);613        info.alignment = alignment;614        info.size = round_up(alignment, offset);615    }616}617618// The value of the attribute of that name, when there; a bare attribute619// gives 0.620fn attribute(self c: &var Compiler, attributes: Run, name: &[u8]) -> Option<u32> {621    for ([..attributes.count to u64]) |k| {622        const a = c.s.attributes.get(attributes.first to u64 + k);623        if (c.text(a.token) == name) {624            return ::Some(if (a.value is ::Some |e|) c.integer_constant(e) else 0);625        }626    }627    return ::None;628}629630// The built-in a `@builtin` attribute names, when there.631fn builtin_attribute(self c: &var Compiler, attributes: Run) -> Option<BuiltIn> {632    for ([..attributes.count to u64]) |k| {633        const a = c.s.attributes.get(attributes.first to u64 + k);634        if (c.text(a.token) == "builtin") {635            if (a.value is ::Some |e| && c.expr_of(e).form is ::Name) {636                if (builtin_named(&c.text(c.expr_of(e).token)) is ::Some |builtin|) {637                    return ::Some(builtin);638                }639            }640            c.fail(a.token, &"unknown built-in");641            return ::None;642        }643    }644    return ::None;645}646647// A built-in, by its WGSL name.648fn builtin_named(name: &[u8]) -> Option<BuiltIn> => match (name) {649    "position" ::Some(BuiltIn::Position);650    "vertex_index" ::Some(BuiltIn::VertexIndex);651    "instance_index" ::Some(BuiltIn::InstanceIndex);652    "front_facing" ::Some(BuiltIn::FrontFacing);653    "frag_depth" ::Some(BuiltIn::FragDepth);654    "global_invocation_id" ::Some(BuiltIn::GlobalInvocationId);655    "local_invocation_id" ::Some(BuiltIn::LocalInvocationId);656    "local_invocation_index" ::Some(BuiltIn::LocalInvocationIndex);657    "workgroup_id" ::Some(BuiltIn::WorkgroupId);658    "num_workgroups" ::Some(BuiltIn::NumWorkgroups);659    "sample_index" ::Some(BuiltIn::SampleId);660    else ::None;661};662663fn declare_resources(self c: &var Compiler) {664    for ([..c.s.globals.length()]) |k| {665        if (c.failed()) {666            return;667        }668        const g = c.s.globals.get(k);669        const group = c.attribute(g.attributes, &"group");670        const binding = c.attribute(g.attributes, &"binding");671        const ty = c.resolve_type(g.ty);672        var kind: ResourceKind = ::Uniform;673        var storage = StorageClass::Uniform;674        var variable_type = ty;675        var wrapped = false;676        const space: &[u8] = if (g.space is ::Some |t|) &c.text(t) else &"";677        if (space == "uniform" || space == "storage") {678            if (space == "storage") {679                storage = StorageClass::StorageBuffer;680                const writable = if (g.access is ::Some |t|) c.text(t) == "read_write" else false;681                kind = if (writable) ::Storage else ::StorageRead;682            }683            // buffers hold a Block-decorated struct: a struct is one, other684            // types go in one of a single member685            if (c.t.kind(ty) != Kind::Struct) {686                variable_type = c.wrapper(ty);687                wrapped = true;688            }689            decorate(&var c.decorations, c.type_id(variable_type), ::Block, &[]);690        } else if (c.t.kind(ty) == Kind::Texture) {691            kind = ::Texture;692            storage = StorageClass::UniformConstant;693        } else if (c.t.kind(ty) == Kind::Sampler) {694            kind = ::Sampler;695            storage = StorageClass::UniformConstant;696        } else {697            c.fail(698                g.token,699                &"a module variable must be a uniform or storage buffer, a texture or a sampler"700            );701            return;702        }703        if (group is ::None || binding is ::None) {704            c.fail(g.token, &"a resource needs @group and @binding");705            return;706        }707        const group_number = group.unwrap_or(0);708        const binding_number = binding.unwrap_or(0);709        const pointer = c.pointer_type(storage, variable_type);710        const id = c.id();711        instruction(&var c.globals, ::Variable, &[pointer, id, storage to u32]);712        decorate(&var c.decorations, id, ::DescriptorSet, &[group_number]);713        decorate(&var c.decorations, id, ::Binding, &[binding_number]);714        c.resources.push(ShaderResource {715            .group = group_number,716            .binding = binding_number,717            .kind = kind,718            .size = c.buffer_size(ty)719        });720        c.scopes.push(Binding {721            .name = String::from(&c.text(g.token)),722            .value = Value {723                .id = id,724                .ty = if (wrapped) ty else variable_type,725                .pointer = true,726                .storage = storage,727                .wrapped = wrapped728            }729        });730    }731}732733// The size a buffer of the type needs, a runtime array's elements not734// counted.735fn buffer_size(self c: &Compiler, ty: u32) -> u32 {736    const kind = c.t.kind(ty);737    if (kind == Kind::RuntimeArray || kind == Kind::Texture || kind == Kind::Sampler) {738        return 0;739    }740    return c.t.size(ty);741}742743// A struct of one member at offset 0.744fn wrapper(self c: &var Compiler, ty: u32) -> u32 {745    const index = c.t.structs.length() to u32;746    c.t.structs.push(StructInfo {747        .name = String::from(&"Wrapper"),748        .first = c.t.members.length() to u32,749        .count = 1,750        .size = c.t.size(ty),751        .alignment = c.t.alignment(ty)752    });753    c.t.members.push(Member { .name = String::from(&"value"), .ty = ty, .offset = 0 });754    return c.t.intern(Kind::Struct, 0, index);755}756757fn declare_functions(self c: &var Compiler) {758    for ([..c.s.functions.length()]) |k| {759        const f = c.s.functions.get(k);760        var parameters = Vector<u32>::empty();761        for ([..f.parameters.count to u64]) |p| {762            parameters.push(c.resolve_type(c.s.fields.get(f.parameters.first to u64 + p).ty));763        }764        const result = if (f.result is ::Some |node|) c.resolve_type(node) else VOID;765        const type_id = c.function_type(result, &parameters.view());766        c.function_list.push(Function {767            .id = c.id(),768            .type_id = type_id,769            .result = result,770            .parameters = move parameters771        });772    }773}774775/* --- Functions --- */776777fn function_body(self c: &var Compiler, k: u32) {778    const f = c.s.functions.get(k to u64);779    const info = &c.function_list.get(k to u64);780    const function_id = info.id;781    const result = info.result;782    const type_id = info.type_id;783    const parameter_types = copy info.parameters;784    c.current = k;785    instruction(&var c.functions, ::Function, &[c.type_id(result), function_id, 0, type_id]);786    const scope = c.scopes.length();787    for ([..f.parameters.count to u64]) |p| {788        const ty = parameter_types.get(p);789        const id = c.id();790        instruction(&var c.functions, ::FunctionParameter, &[c.type_id(ty), id]);791        var name = String::from(&c.text(c.s.fields.get(f.parameters.first to u64 + p).token));792        c.scopes.push(Binding { .name = move name, .value = c.value(id, ty) });793    }794    c.variables.clear();795    c.body.clear();796    c.terminated = false;797    c.result_type = result;798    c.label(c.id());799    c.statement(f.body);800    if (!c.terminated) {801        if (result == VOID) {802            instruction(&var c.body, ::Return, &[]);803        } else {804            c.fail(f.token, &"the function can end without returning a value");805        }806    }807    c.end_function();808    c.scopes.truncate(scope);809}810811// The function's body after its declaration: the entry block's label,812// then the variables, then the rest.813fn end_function(self c: &var Compiler) {814    const label_words = 2;815    c.functions.append(&c.body.view()[..label_words]);816    c.functions.append(&c.variables.view());817    c.functions.append(&c.body.view()[label_words..]);818    instruction(&var c.functions, ::FunctionEnd, &[]);819}820821fn label(self c: &var Compiler, id: u32) {822    instruction(&var c.body, ::Label, &[id]);823    c.terminated = false;824}825826fn branch(self c: &var Compiler, target: u32) {827    if (!c.terminated) {828        instruction(&var c.body, ::Branch, &[target]);829        c.terminated = true;830    }831}832833/* --- Statements --- */834835fn statement(self c: &var Compiler, k: u32) {836    if (c.failed() || c.terminated) {837        return;838    }839    const st = c.s.stmts.get(k to u64);840    match (st.form) {841        ::Block |statements| {842            const scope = c.scopes.length();843            for ([..statements.count to u64]) |n| {844                c.statement(c.item(statements, n));845            }846            c.scopes.truncate(scope);847        }848        ::Let |&l| {849            const ty = c.written_type(l.ty);850            var value = c.load(c.expression(l.value, ty));851            if (ty is ::Some |t|) {852                value = c.convert_to(value, t, st.token);853            }854            c.scopes.push(Binding { .name = String::from(&c.text(st.token)), .value = value });855        }856        ::Var |&v| {857            c.var_statement(st.token, &v);858        }859        ::Assign |&operands| {860            c.assign(st.token, &operands);861        }862        ::Increment |e| {863            const target = c.expression(e, ::None);864            const ty = target.ty;865            const one = c.constant(ty, if (ty == F32) 0x3F800000 else 1);866            const old = c.load(target);867            const operator: &[u8] = if (c.text(st.token) == "++") &"+" else &"-";868            const updated = c.arithmetic(&operator, old, c.value(one, ty), st.token);869            c.store(target, updated, st.token);870        }871        ::Call |e| {872            c.expression(e, ::None);873        }874        ::If |&branch| {875            c.if_statement(st.token, &branch);876        }877        ::Loop |&looped| {878            c.loop_statement(st.token, &looped);879        }880        ::Break, ::Continue {881            const l = if (c.loops.try_last() is ::Some |&l|) l else {882                c.fail(st.token, &"'break' and 'continue' belong in a loop");883                return;884            };885            c.branch(if (st.form is ::Break) l.merge else l.continue_label);886        }887        ::Return |value| {888            if (value is ::Some |e|) {889                const returned = c.convert_to(890                    c.load(c.expression(e, ::Some(c.result_type))),891                    c.result_type,892                    c.expr_of(e).token893                );894                instruction(&var c.body, ::ReturnValue, &[returned.id]);895            } else {896                instruction(&var c.body, ::Return, &[]);897            }898            c.terminated = true;899        }900        ::Discard {901            instruction(&var c.body, ::Kill, &[]);902            c.terminated = true;903        }904    }905}906907fn var_statement(self c: &var Compiler, token: u32, v: &VarStatement) {908    const written = c.written_type(v.ty);909    var initial = c.value(0, VOID);910    if (v.value is ::Some |e|) {911        initial = c.load(c.expression(e, written));912    }913    const ty = if (written is ::Some |t|) t else if (v.value is ::Some) initial.ty else {914        c.fail(token, &"a 'var' needs a type or a value");915        return;916    };917    if (v.value is ::Some) {918        initial = c.convert_to(initial, ty, token);919    }920    const pointer = c.pointer_type(StorageClass::Function, ty);921    const id = c.id();922    if (v.value is ::Some) {923        instruction(924            &var c.variables,925            ::Variable,926            &[pointer, id, StorageClass::Function to u32]927        );928        instruction(&var c.body, ::Store, &[id, initial.id]);929    } else {930        // zero, as WGSL starts every variable931        const zero = c.null_constant(ty);932        instruction(933            &var c.variables,934            ::Variable,935            &[pointer, id, StorageClass::Function to u32, zero]936        );937    }938    c.scopes.push(Binding {939        .name = String::from(&c.text(token)),940        .value = Value { .id = id, .ty = ty, .pointer = true, .storage = StorageClass::Function }941    });942}943944// `token` the operator.945fn assign(self c: &var Compiler, token: u32, operands: &Operands) {946    const target = c.expression(operands.left, ::None);947    if (c.failed()) {948        return;949    }950    if (!target.pointer) {951        c.fail(token, &"the left of an assignment must be a variable or a part of one");952        return;953    }954    const operator = &c.text(token);955    var value = c.load(c.expression(operands.right, ::Some(c.t.scalar(target.ty))));956    if (operator != "=") {957        const old = c.load(target);958        value = c.arithmetic(&operator[..operator.length() - 1], old, value, token);959    }960    c.store(target, value, token);961}962963fn store(self c: &var Compiler, target: Value, value: Value, token: u32) {964    const converted = c.convert_to(value, target.ty, token);965    const pointer = c.unwrap(target);966    instruction(&var c.body, ::Store, &[pointer.id, converted.id]);967}968969fn if_statement(self c: &var Compiler, token: u32, branch: &IfStatement) {970    const condition = c.convert_to(971        c.load(c.expression(branch.condition, ::Some(BOOL))),972        BOOL,973        token974    );975    const then_label = c.id();976    const merge = c.id();977    const else_label = if (branch.otherwise is ::Some) c.id() else merge;978    instruction(&var c.body, ::SelectionMerge, &[merge, 0]);979    instruction(&var c.body, ::BranchConditional, &[condition.id, then_label, else_label]);980    c.label(then_label);981    c.statement(branch.body);982    c.branch(merge);983    if (branch.otherwise is ::Some |otherwise|) {984        c.label(else_label);985        c.statement(otherwise);986        c.branch(merge);987    }988    c.label(merge);989}990991// A loop: the header tests the condition, the body runs, the continuing992// block updates and goes back to the header.993fn loop_statement(self c: &var Compiler, token: u32, looped: &LoopStatement) {994    const header = c.id();995    const body = c.id();996    const continue_label = c.id();997    const merge = c.id();998    c.branch(header);999    c.label(header);1000    if (looped.condition is ::Some |e|) {1001        const condition = c.convert_to(c.load(c.expression(e, ::Some(BOOL))), BOOL, token);1002        instruction(&var c.body, ::LoopMerge, &[merge, continue_label, 0]);1003        instruction(&var c.body, ::BranchConditional, &[condition.id, body, merge]);1004    } else {1005        instruction(&var c.body, ::LoopMerge, &[merge, continue_label, 0]);1006        instruction(&var c.body, ::Branch, &[body]);1007    }1008    c.terminated = true;1009    c.loops.push(Loop { .merge = merge, .continue_label = continue_label });1010    c.label(body);1011    c.statement(looped.body);1012    c.branch(continue_label);1013    c.loops.pop();1014    c.label(continue_label);1015    if (looped.continuing is ::Some |continuing|) {1016        c.statement(continuing);1017    }1018    c.branch(header);1019    c.label(merge);1020}10211022/* --- Expressions --- */10231024fn value(self c: &Compiler, id: u32, ty: u32) -> Value => Value { .id = id, .ty = ty };10251026// A pointer's value read from memory; a value as it is.1027fn load(self c: &var Compiler, v: Value) -> Value {1028    if (!v.pointer || c.failed()) {1029        return v;1030    }1031    const pointer = c.unwrap(v);1032    const id = c.id();1033    instruction(&var c.body, ::Load, &[c.type_id(pointer.ty), id, pointer.id]);1034    return c.value(id, pointer.ty);1035}10361037// The pointer to a wrapped buffer's one member; any other pointer as it1038// is.1039fn unwrap(self c: &var Compiler, v: Value) -> Value {1040    if (!v.wrapped) {1041        return v;1042    }1043    const id = c.id();1044    const zero = c.constant(U32, 0);1045    instruction(1046        &var c.body,1047        ::AccessChain,1048        &[c.pointer_type(v.storage, v.ty), id, v.id, zero]1049    );1050    return Value { .id = id, .ty = v.ty, .pointer = true, .storage = v.storage };1051}10521053// Whether the expression is a literal, whose type the other operand1054// decides.1055fn is_literal(self c: &Compiler, e: u32) -> bool {1056    const x = c.expr_of(e);1057    return match (x.form) {1058        ::Integer, ::Float true;1059        ::Unary |operand| c.text(x.token) == "-" && c.is_literal(operand);1060        else false;1061    };1062}10631064// The expression's value; `hint` the scalar or type a literal takes,1065// else its own.1066fn expression(self c: &var Compiler, e: u32, hint: Option<u32>) -> Value {1067    if (c.failed()) {1068        return c.value(0, VOID);1069    }1070    const x = c.expr_of(e);1071    return match (x.form) {1072        ::Integer, ::Float c.literal(&x, hint);1073        ::Bool c.value(c.constant(BOOL, if (c.text(x.token) == "true") 1 else 0), BOOL);1074        ::Name c.name(&x, hint);1075        ::Unary |operand| c.unary(x.token, operand, hint);1076        ::Binary |&operands| c.binary(x.token, &operands, hint);1077        ::Member |base| c.member(x.token, base);1078        ::Index |&operands| c.index(x.token, &operands);1079        ::Call |&call| c.call(x.token, &call, hint);1080    };1081}10821083fn literal(self c: &var Compiler, x: &Expr, hint: Option<u32>) -> Value {1084    const text = &c.text(x.token);1085    const float = x.form is ::Float;1086    var ty = if (float) F32 else I32;1087    if (text.ends_with(&"u")) {1088        ty = U32;1089    } else if (text.ends_with(&"i")) {1090        ty = I32;1091    } else if (text.ends_with(&"f")) {1092        ty = F32;1093    } else if (hint is ::Some |h| && c.t.is_numeric_scalar(c.t.scalar(h))) {1094        const wanted = c.t.scalar(h);1095        if (!float || wanted == F32) {1096            ty = wanted;1097        }1098    }1099    var bits: u32 = 0;1100    if (ty == F32) {1101        bits = if (float) float_bits(&text) else (integer_bits(&text) to f32) as u32;1102    } else {1103        bits = integer_bits(&text);1104    }1105    return c.value(c.constant(ty, bits), ty);1106}11071108fn name(self c: &var Compiler, x: &Expr, hint: Option<u32>) -> Value {1109    const name = &c.text(x.token);1110    var k = c.scopes.length();1111    while (k > 0) {1112        k -= 1;1113        const b = &c.scopes.get(k);1114        if (b.name.view() == name) {1115            // the first scopes are the resources, in order1116            if (k < c.resources.length()) {1117                c.uses.push(Use { .function = c.current, .used = ::Resource(k to u32) });1118            }1119            return c.scopes.get(k).value;1120        }1121    }1122    for (c.s.constants.view()) |&constant| {1123        if (c.text(constant.token) == name) {1124            if (constant.ty is ::Some |node|) {1125                const ty = c.resolve_type(node);1126                return c.convert_to(c.load(c.expression(constant.value, ::Some(ty))), ty, x.token);1127            }1128            return c.load(c.expression(constant.value, hint));1129        }1130    }1131    c.fail(x.token, &f"unknown name '{name}'".view());1132    return c.value(0, VOID);1133}11341135// `token` the operator.1136fn unary(self c: &var Compiler, token: u32, e: u32, hint: Option<u32>) -> Value {1137    const operand = c.load(c.expression(e, hint));1138    const operator = &c.text(token);1139    const scalar = c.t.scalar(operand.ty);1140    var opcode = Opcode::Not;1141    if (operator == "-" && scalar == F32) {1142        opcode = ::FNegate;1143    } else if (operator == "-" && scalar == I32) {1144        opcode = ::SNegate;1145    } else if (operator == "!" && scalar == BOOL) {1146        opcode = ::LogicalNot;1147    } else if (!(operator == "~" && (scalar == I32 || scalar == U32))) {1148        c.fail(token, &f"'{operator}' does not apply to {c.t.name_of(operand.ty)}".view());1149        return operand;1150    }1151    return c.op(opcode, operand.ty, &[operand.id]);1152}11531154// Emits an instruction with a result of the type.1155fn op(self c: &var Compiler, opcode: Opcode, ty: u32, operands: &[u32]) -> Value {1156    const id = c.id();1157    var words = Vector<u32>::from(&[c.type_id(ty), id]);1158    for (operands) |o| {1159        words.push(o);1160    }1161    instruction(&var c.body, opcode, &words.view());1162    return c.value(id, ty);1163}11641165// `token` the operator.1166fn binary(self c: &var Compiler, token: u32, operands: &Operands, hint: Option<u32>) -> Value {1167    const operator = &c.text(token);1168    const comparison = operator == "=="1169        || operator == "!="1170        || operator == "<"1171        || operator == ">"1172        || operator == "<="1173        || operator == ">=";1174    const operand_hint = if (1175        comparison1176        || operator == "&&"1177        || operator == "||"1178    ) Option<u32>::None else hint;1179    var left = c.value(0, VOID);1180    var right = c.value(0, VOID);1181    if (c.is_literal(operands.left) && !c.is_literal(operands.right)) {1182        right = c.load(c.expression(operands.right, operand_hint));1183        left = c.load(c.expression(operands.left, ::Some(c.t.scalar(right.ty))));1184    } else {1185        left = c.load(c.expression(operands.left, operand_hint));1186        const shift = operator == "<<" || operator == ">>";1187        right = c.load(c.expression(1188            operands.right,1189            ::Some(if (shift) U32 else c.t.scalar(left.ty))1190        ));1191    }1192    if (c.failed()) {1193        return left;1194    }1195    if (operator == "&&" || operator == "||") {1196        const a = c.convert_to(left, BOOL, token);1197        const b = c.convert_to(right, BOOL, token);1198        return c.op(1199            if (operator == "&&") Opcode::LogicalAnd else Opcode::LogicalOr,1200            BOOL,1201            &[a.id, b.id]1202        );1203    }1204    if (comparison) {1205        return c.comparison(&operator, left, right, token);1206    }1207    return c.arithmetic(&operator, left, right, token);1208}12091210fn comparison(1211    self c: &var Compiler,1212    operator: &[u8],1213    left: Value,1214    right: Value,1215    token: u321216) -> Value {1217    if (left.ty != right.ty) {1218        c.fail(1219            token,1220            &f"'{operator}' compares {c.t.name_of(left.ty)} with {c.t.name_of(right.ty)}".view()1221        );1222        return left;1223    }1224    const scalar = c.t.scalar(left.ty);1225    const result = c.t.with_scalar(left.ty, BOOL);1226    const opcodes = match (operator) {1227        "==" ByScalar<Opcode> {1228            .float = ::Some(::FOrdEqual),1229            .signed = ::Some(::IEqual),1230            .unsigned = ::Some(::IEqual),1231            .boolean = ::Some(::LogicalEqual)1232        };1233        "!=" ByScalar<Opcode> {1234            .float = ::Some(::FOrdNotEqual),1235            .signed = ::Some(::INotEqual),1236            .unsigned = ::Some(::INotEqual),1237            .boolean = ::Some(::LogicalNotEqual)1238        };1239        "<" ByScalar<Opcode> {1240            .float = ::Some(::FOrdLessThan),1241            .signed = ::Some(::SLessThan),1242            .unsigned = ::Some(::ULessThan)1243        };1244        ">" ByScalar<Opcode> {1245            .float = ::Some(::FOrdGreaterThan),1246            .signed = ::Some(::SGreaterThan),1247            .unsigned = ::Some(::UGreaterThan)1248        };1249        "<=" ByScalar<Opcode> {1250            .float = ::Some(::FOrdLessThanEqual),1251            .signed = ::Some(::SLessThanEqual),1252            .unsigned = ::Some(::ULessThanEqual)1253        };1254        ">=" ByScalar<Opcode> {1255            .float = ::Some(::FOrdGreaterThanEqual),1256            .signed = ::Some(::SGreaterThanEqual),1257            .unsigned = ::Some(::UGreaterThanEqual)1258        };1259        else ByScalar<Opcode> {};1260    };1261    // any other scalar compares as unsigned1262    const opcode = if (scalar == F32) opcodes.float else if (scalar == I32) opcodes.signed else if (1263        scalar == BOOL1264    ) opcodes.boolean else opcodes.unsigned;1265    if (opcode is ::Some |o|) {1266        return c.op(o, result, &[left.id, right.id]);1267    }1268    c.fail(token, &f"'{operator}' does not compare {c.t.name_of(left.ty)}".view());1269    return left;1270}12711272fn arithmetic(1273    self c: &var Compiler,1274    operator: &[u8],1275    left_in: Value,1276    right_in: Value,1277    token: u321278) -> Value {1279    var left = left_in;1280    var right = right_in;1281    const left_kind = c.t.kind(left.ty);1282    const right_kind = c.t.kind(right.ty);1283    // matrices1284    if (operator == "*" && (left_kind == Kind::Matrix || right_kind == Kind::Matrix)) {1285        return c.matrix_product(left, right, token);1286    }1287    // a scalar with a vector: the scalar repeated, or for floats times,1288    // OpVectorTimesScalar1289    if (left_kind == Kind::Vector && right_kind != Kind::Vector) {1290        if (operator == "*" && right.ty == F32 && c.t.scalar(left.ty) == F32) {1291            return c.op(::VectorTimesScalar, left.ty, &[left.id, right.id]);1292        }1293        right = c.splat(right, left.ty, token);1294    } else if (right_kind == Kind::Vector && left_kind != Kind::Vector) {1295        if (operator == "*" && left.ty == F32 && c.t.scalar(right.ty) == F32) {1296            return c.op(::VectorTimesScalar, right.ty, &[right.id, left.id]);1297        }1298        left = c.splat(left, right.ty, token);1299    }1300    const shift = operator == "<<" || operator == ">>";1301    if (left.ty != right.ty && !shift) {1302        c.fail(1303            token,1304            &f"'{operator}' between {c.t.name_of(left.ty)} and {c.t.name_of(right.ty)}".view()1305        );1306        return left;1307    }1308    const scalar = c.t.scalar(left.ty);1309    const opcodes = match (operator) {1310        "+" ByScalar<Opcode> {1311            .float = ::Some(::FAdd),1312            .signed = ::Some(::IAdd),1313            .unsigned = ::Some(::IAdd)1314        };1315        "-" ByScalar<Opcode> {1316            .float = ::Some(::FSub),1317            .signed = ::Some(::ISub),1318            .unsigned = ::Some(::ISub)1319        };1320        "*" ByScalar<Opcode> {1321            .float = ::Some(::FMul),1322            .signed = ::Some(::IMul),1323            .unsigned = ::Some(::IMul)1324        };1325        "/" ByScalar<Opcode> {1326            .float = ::Some(::FDiv),1327            .signed = ::Some(::SDiv),1328            .unsigned = ::Some(::UDiv)1329        };1330        "%" ByScalar<Opcode> {1331            .float = ::Some(::FRem),1332            .signed = ::Some(::SRem),1333            .unsigned = ::Some(::UMod)1334        };1335        "&" ByScalar<Opcode> {1336            .signed = ::Some(::BitwiseAnd),1337            .unsigned = ::Some(::BitwiseAnd),1338            .boolean = ::Some(::LogicalAnd)1339        };1340        "|" ByScalar<Opcode> {1341            .signed = ::Some(::BitwiseOr),1342            .unsigned = ::Some(::BitwiseOr),1343            .boolean = ::Some(::LogicalOr)1344        };1345        "^" ByScalar<Opcode> { .signed = ::Some(::BitwiseXor), .unsigned = ::Some(::BitwiseXor) };1346        "<<" ByScalar<Opcode> {1347            .signed = ::Some(::ShiftLeftLogical),1348            .unsigned = ::Some(::ShiftLeftLogical)1349        };1350        ">>" ByScalar<Opcode> {1351            .signed = ::Some(::ShiftRightArithmetic),1352            .unsigned = ::Some(::ShiftRightLogical)1353        };1354        else ByScalar<Opcode> {};1355    };1356    const opcode = if (scalar == F32) opcodes.float else if (scalar == I32) opcodes.signed else if (1357        scalar == U321358    ) opcodes.unsigned else if (scalar == BOOL) opcodes.boolean else Option<Opcode>::None;1359    if (opcode is ::Some |o|) {1360        return c.op(o, left.ty, &[left.id, right.id]);1361    }1362    c.fail(token, &f"'{operator}' does not apply to {c.t.name_of(left.ty)}".view());1363    return left;1364}13651366fn matrix_product(self c: &var Compiler, left: Value, right: Value, token: u32) -> Value {1367    const left_kind = c.t.kind(left.ty);1368    const right_kind = c.t.kind(right.ty);1369    if (left_kind == Kind::Matrix && right_kind == Kind::Vector) {1370        return c.op(::MatrixTimesVector, c.t.get(left.ty).element, &[left.id, right.id]);1371    }1372    if (left_kind == Kind::Vector && right_kind == Kind::Matrix) {1373        const result = c.t.vector(F32, c.t.get(right.ty).count);1374        return c.op(::VectorTimesMatrix, result, &[left.id, right.id]);1375    }1376    if (left_kind == Kind::Matrix && right_kind == Kind::Matrix) {1377        const rows = c.t.get(left.ty).element;1378        const result = c.t.intern(Kind::Matrix, rows, c.t.get(right.ty).count);1379        return c.op(::MatrixTimesMatrix, result, &[left.id, right.id]);1380    }1381    if (left_kind == Kind::Matrix && right.ty == F32) {1382        return c.op(::MatrixTimesScalar, left.ty, &[left.id, right.id]);1383    }1384    if (right_kind == Kind::Matrix && left.ty == F32) {1385        return c.op(::MatrixTimesScalar, right.ty, &[right.id, left.id]);1386    }1387    c.fail(token, &"'*' between these does not apply");1388    return left;1389}13901391// The scalar repeated into a vector of the type.1392fn splat(self c: &var Compiler, scalar: Value, vector: u32, token: u32) -> Value {1393    const element = c.convert_to(scalar, c.t.scalar(vector), token);1394    var ids = Vector<u32>::empty();1395    for ([..c.t.width(vector) to u64]) |k| {1396        ids.push(element.id);1397    }1398    return c.op(::CompositeConstruct, vector, &ids.view());1399}14001401// The value as the type: only literals, which were made in the type1402// they were hinted, and identical types pass.1403fn convert_to(self c: &var Compiler, v: Value, ty: u32, token: u32) -> Value {1404    if (c.failed() || v.ty == ty) {1405        return v;1406    }1407    c.fail(token, &f"expected {c.t.name_of(ty)}, found {c.t.name_of(v.ty)}".view());1408    return v;1409}14101411// `token` the member's name.1412fn member(self c: &var Compiler, token: u32, e: u32) -> Value {1413    const base = c.expression(e, ::None);1414    if (c.failed()) {1415        return base;1416    }1417    const name = &c.text(token);1418    const kind = c.t.kind(base.ty);1419    if (kind == Kind::Struct) {1420        for ([..c.t.member_count(base.ty)]) |k| {1421            const m = &c.t.struct_member(base.ty, k to u32);1422            if (m.name.view() == name) {1423                return c.part(base, k to u32, m.ty);1424            }1425        }1426        c.fail(token, &f"{c.t.name_of(base.ty)} has no member '{name}'".view());1427        return base;1428    }1429    if (kind == Kind::Vector) {1430        return c.swizzle(base, &name, token);1431    }1432    c.fail(token, &f"{c.t.name_of(base.ty)} has no members".view());1433    return base;1434}14351436// The part at the index of a composite value or of what a pointer1437// points to, a pointer itself in that case.1438fn part(self c: &var Compiler, base: Value, index: u32, ty: u32) -> Value {1439    if (base.pointer) {1440        const pointer = c.unwrap(base);1441        const id = c.id();1442        instruction(1443            &var c.body,1444            ::AccessChain,1445            &[c.pointer_type(pointer.storage, ty), id, pointer.id, c.constant(U32, index)]1446        );1447        return Value { .id = id, .ty = ty, .pointer = true, .storage = pointer.storage };1448    }1449    return c.op(::CompositeExtract, ty, &[base.id, index]);1450}14511452fn swizzle(self c: &var Compiler, base: Value, name: &[u8], token: u32) -> Value {1453    const width = c.t.width(base.ty);1454    var indices = Vector<u32>::empty();1455    for (name) |letter| {1456        const index = component(letter);1457        if (index >= width) {1458            c.fail(token, &f"no component '{name}' in {c.t.name_of(base.ty)}".view());1459            return base;1460        }1461        indices.push(index);1462    }1463    const scalar = c.t.scalar(base.ty);1464    if (indices.length() == 1) {1465        return c.part(base, indices.get(0), scalar);1466    }1467    if (indices.length() > 4) {1468        c.fail(token, &"a swizzle has at most 4 components");1469        return base;1470    }1471    const value = c.load(base);1472    var operands = Vector<u32>::from(&[value.id, value.id]);1473    for (indices.view()) |i| {1474        operands.push(i);1475    }1476    return c.op(1477        ::VectorShuffle,1478        c.t.vector(scalar, indices.length() to u32),1479        &operands.view()1480    );1481}14821483fn component(letter: u8) -> u32 {1484    const xyzw = "xyzwrgba";1485    for ([..8]) |k| {1486        if (xyzw[k] == letter) {1487            return (k % 4) to u32;1488        }1489    }1490    return 4;1491}14921493// `token` the `[`.1494fn index(self c: &var Compiler, token: u32, operands: &Operands) -> Value {1495    const base = c.expression(operands.left, ::None);1496    const at = c.load(c.expression(operands.right, ::Some(U32)));1497    if (c.failed()) {1498        return base;1499    }1500    const scalar = c.t.scalar(at.ty);1501    if (scalar != U32 && scalar != I32) {1502        c.fail(token, &"an index must be i32 or u32");1503        return base;1504    }1505    const info = c.t.get(base.ty);1506    if (!(info.kind is ::Array || info.kind is ::RuntimeArray || info.kind is ::Matrix1507        || info.kind is ::Vector)) {1508        c.fail(token, &f"{c.t.name_of(base.ty)} cannot be indexed".view());1509        return base;1510    }1511    const element = info.element;1512    if (base.pointer) {1513        const pointer = c.unwrap(base);1514        const id = c.id();1515        instruction(1516            &var c.body,1517            ::AccessChain,1518            &[c.pointer_type(pointer.storage, element), id, pointer.id, at.id]1519        );1520        return Value { .id = id, .ty = element, .pointer = true, .storage = pointer.storage };1521    }1522    // a value indexed at run time: through a Function variable holding it1523    const pointer = c.pointer_type(StorageClass::Function, base.ty);1524    const copy_id = c.id();1525    instruction(1526        &var c.variables,1527        ::Variable,1528        &[pointer, copy_id, StorageClass::Function to u32]1529    );1530    instruction(&var c.body, ::Store, &[copy_id, base.id]);1531    const id = c.id();1532    instruction(1533        &var c.body,1534        ::AccessChain,1535        &[c.pointer_type(StorageClass::Function, element), id, copy_id, at.id]1536    );1537    return c.load(Value {1538        .id = id,1539        .ty = element,1540        .pointer = true,1541        .storage = StorageClass::Function1542    });1543}15441545/* --- Calls --- */15461547// A call's `k`th argument.1548fn argument(self c: &Compiler, x: &Call, k: u64) -> u32 => c.item(x.arguments, k);15491550fn arguments(self c: &var Compiler, x: &Call, hint: Option<u32>) -> Vector<Value> {1551    var values = Vector<Value>::empty();1552    for ([..x.arguments.count to u64]) |k| {1553        values.push(c.load(c.expression(c.argument(&x, k), hint)));1554    }1555    return move values;1556}15571558// `token` the function's or type's name.1559fn call(self c: &var Compiler, token: u32, x: &Call, hint: Option<u32>) -> Value {1560    const name = &c.text(token);1561    if (x.ty is ::Some |node|) {1562        if (name == "bitcast") {1563            // `bitcast<T>(value)`: the type is the template's argument1564            const written = c.s.types.get(node to u64).arguments;1565            if (written.count != 1 || x.arguments.count != 1) {1566                c.fail(token, &"bitcast takes one type and one value");1567                return c.value(0, VOID);1568            }1569            const ty = c.resolve_type(c.item(written, 0));1570            const operand = c.arguments(&x, ::None);1571            return c.op(::Bitcast, ty, &[operand.get(0).id]);1572        }1573        return c.construct(token, &x, c.resolve_type(node));1574    }1575    // a user function1576    for ([..c.s.functions.length()]) |k| {1577        if (c.text(c.s.functions.get(k).token) == name) {1578            return c.user_call(token, &x, k to u32);1579        }1580    }1581    // a type: a scalar conversion, a vector or struct constructor1582    if (scalar_named(&name) is ::Some |scalar|) {1583        return c.conversion(token, &x, scalar);1584    }1585    if (is_type_name(&name) || c.is_struct_name(&name)) {1586        const node = c.s.types.length() to u32;1587        c.s.types.push(TypeNode { .token = token });1588        return c.construct(token, &x, c.resolve_type(node));1589    }1590    return c.builtin(token, &x, &name, hint);1591}15921593fn is_type_name(name: &[u8]) -> bool {1594    return (name.length() == 5 && name.starts_with(&"vec"))1595        || (name.length() >= 7 && name.starts_with(&"mat"));1596}15971598fn is_struct_name(self c: &Compiler, name: &[u8]) -> bool {1599    for (c.s.structs.view()) |&decl| {1600        if (c.text(decl.token) == name) {1601            return true;1602        }1603    }1604    return false;1605}16061607fn user_call(self c: &var Compiler, token: u32, x: &Call, k: u32) -> Value {1608    c.uses.push(Use { .function = c.current, .used = ::Function(k) });1609    const function_id = c.function_list.get(k to u64).id;1610    const result = c.function_list.get(k to u64).result;1611    const parameters = copy c.function_list.get(k to u64).parameters;1612    if (parameters.length() != x.arguments.count to u64) {1613        c.fail(token, &"wrong number of arguments");1614        return c.value(0, VOID);1615    }1616    var operands = Vector<u32>::from(&[function_id]);1617    for ([..parameters.length()]) |a| {1618        const ty = parameters.get(a);1619        const argument = c.convert_to(1620            c.load(c.expression(c.argument(&x, a), ::Some(ty))),1621            ty,1622            token1623        );1624        operands.push(argument.id);1625    }1626    return c.op(::FunctionCall, result, &operands.view());1627}16281629// `f32(x)`, `u32(x)` and the like.1630fn conversion(self c: &var Compiler, token: u32, x: &Call, ty: u32) -> Value {1631    if (x.arguments.count != 1) {1632        c.fail(token, &"a conversion takes one value");1633        return c.value(0, VOID);1634    }1635    const v = c.load(c.expression(c.argument(&x, 0), ::Some(ty)));1636    return c.convert(v, ty, token);1637}16381639// Converts a scalar or vector to the scalar type, component by component.1640fn convert(self c: &var Compiler, v: Value, scalar: u32, token: u32) -> Value {1641    const from = c.t.scalar(v.ty);1642    const target = c.t.with_scalar(v.ty, scalar);1643    if (from == scalar) {1644        return v;1645    }1646    if (scalar == BOOL) {1647        const zero = c.splat_constant(v.ty, if (from == F32) 0 else 0);1648        return c.op(1649            if (from == F32) Opcode::FOrdNotEqual else Opcode::INotEqual,1650            target,1651            &[v.id, zero]1652        );1653    }1654    if (from == BOOL) {1655        const one = c.splat_constant(target, if (scalar == F32) 0x3F800000 else 1);1656        const zero = c.splat_constant(target, 0);1657        return c.op(::Select, target, &[v.id, one, zero]);1658    }1659    var opcode = Opcode::Bitcast;1660    if (from == F32) {1661        opcode = if (scalar == I32) ::ConvertFToS else ::ConvertFToU;1662    } else if (scalar == F32) {1663        opcode = if (from == I32) ::ConvertSToF else ::ConvertUToF;1664    }1665    return c.op(opcode, target, &[v.id]);1666}16671668// A constant of the scalar or vector type, each component the bits.1669fn splat_constant(self c: &var Compiler, ty: u32, bits: u32) -> u32 {1670    const scalar = c.constant(c.t.scalar(ty), bits);1671    if (c.t.kind(ty) != Kind::Vector) {1672        return scalar;1673    }1674    const id = c.id();1675    var words = Vector<u32>::from(&[c.type_id(ty), id]);1676    for ([..c.t.width(ty) to u64]) |k| {1677        words.push(scalar);1678    }1679    instruction(&var c.globals, ::ConstantComposite, &words.view());1680    return id;1681}16821683// `vec4<f32>(...)`, `array<f32, 3>(...)`, `Light(...)`, `mat2x2f(...)`.1684fn construct(self c: &var Compiler, token: u32, x: &Call, ty: u32) -> Value {1685    const info = c.t.get(ty);1686    const count = x.arguments.count;1687    if (count == 0) {1688        return c.value(c.null_constant(ty), ty);1689    }1690    if (info.kind == Kind::Vector) {1691        const scalar = info.element;1692        var ids = Vector<u32>::empty();1693        var filled: u32 = 0;1694        for ([..count to u64]) |k| {1695            var v = c.load(c.expression(c.argument(&x, k), ::Some(scalar)));1696            if (count == 1 && c.t.kind(v.ty) != Kind::Vector) {1697                v = c.convert(v, scalar, token);1698                return c.splat(v, ty, token);1699            }1700            if (count == 1 && c.t.width(v.ty) == info.count && c.t.scalar(v.ty) != scalar) {1701                return c.convert(v, scalar, token);1702            }1703            v = c.convert_to(v, c.t.with_scalar(v.ty, scalar), token);1704            ids.push(v.id);1705            filled += c.t.width(v.ty);1706        }1707        if (filled != info.count) {1708            c.fail(1709                token,1710                &f"{c.t.name_of(ty)} needs {info.count} components, given {filled}".view()1711            );1712        }1713        return c.op(::CompositeConstruct, ty, &ids.view());1714    }1715    var element_types = Vector<u32>::empty();1716    if (info.kind is ::Array || info.kind is ::Matrix) {1717        element_types = Vector<u32>::filled(info.element, info.count to u64);1718    } else if (info.kind is ::Struct) {1719        for ([..c.t.member_count(ty)]) |k| {1720            element_types.push(c.t.struct_member(ty, k to u32).ty);1721        }1722    } else {1723        c.fail(token, &f"{c.t.name_of(ty)} cannot be constructed".view());1724        return c.value(0, VOID);1725    }1726    if (element_types.length() != count to u64) {1727        c.fail(token, &f"{c.t.name_of(ty)} takes {element_types.length()} values".view());1728        return c.value(0, VOID);1729    }1730    var ids = Vector<u32>::empty();1731    for (element_types.view(), [..element_types.length()]) |element, k| {1732        const v = c.convert_to(1733            c.load(c.expression(c.argument(&x, k), ::Some(element))),1734            element,1735            token1736        );1737        ids.push(v.id);1738    }1739    return c.op(::CompositeConstruct, ty, &ids.view());1740}17411742// WGSL's built-in functions.1743fn builtin(self c: &var Compiler, token: u32, x: &Call, name: &[u8], hint: Option<u32>) -> Value {1744    if (name == "textureSample" || name == "textureSampleLevel") {1745        return c.texture_sample(token, &x, &name);1746    }1747    if (name == "select") {1748        // select(false_value, true_value, condition)1749        if (x.arguments.count != 3) {1750            c.fail(token, &"select takes 3 values");1751            return c.value(0, VOID);1752        }1753        const values = c.arguments(&x, hint);1754        const a = values.get(0);1755        const b = c.convert_to(values.get(1), a.ty, token);1756        const condition = values.get(2);1757        return c.op(::Select, a.ty, &[condition.id, b.id, a.id]);1758    }1759    const values = c.arguments(&x, hint);1760    if (c.failed()) {1761        return c.value(0, VOID);1762    }1763    if (values.length() == 0) {1764        c.fail(token, &f"unknown function '{name}'".view());1765        return c.value(0, VOID);1766    }1767    const first = values.get(0);1768    const scalar = c.t.scalar(first.ty);1769    for (values.view()) |&v| {1770        if (v.ty != first.ty && !(name == "dot" || name == "cross" || name == "distance")) {1771            if (!(1772                name == "mix"1773                || name == "clamp"1774                || name == "step"1775                || name == "smoothstep"1776                || name == "pow"1777                || name == "min"1778                || name == "max"1779            )) {1780                c.fail(token, &f"{name}'s values differ in type".view());1781                return first;1782            }1783        }1784    }1785    // the scalar operands of mix, clamp and the like repeated as vectors1786    var ids = Vector<u32>::empty();1787    for (values.view()) |&v| {1788        if (1789            v.ty != first.ty1790            && c.t.kind(first.ty) == Kind::Vector1791            && c.t.kind(v.ty) != Kind::Vector1792        ) {1793            ids.push(c.splat(v, first.ty, token).id);1794        } else {1795            ids.push(v.id);1796        }1797    }1798    if (name == "dot") {1799        return c.op(::Dot, scalar, &ids.view());1800    }1801    if (name == "dpdx" || name == "dpdy" || name == "fwidth") {1802        const opcode = if (1803            name == "dpdx"1804        ) Opcode::DPdx else if (name == "dpdy") Opcode::DPdy else Opcode::Fwidth;1805        return c.op(opcode, first.ty, &ids.view());1806    }1807    if (name == "any" || name == "all") {1808        if (c.t.kind(first.ty) != Kind::Vector) {1809            return first;1810        }1811        return c.op(if (name == "any") Opcode::Any else Opcode::All, BOOL, &ids.view());1812    }1813    const number = if (glsl_number(&name, scalar) is ::Some |n|) n else {1814        c.fail(token, &f"unknown function '{name}' for {c.t.name_of(first.ty)}".view());1815        return first;1816    };1817    var result = first.ty;1818    if (name == "length" || name == "distance") {1819        result = scalar;1820    }1821    var operands = Vector<u32>::from(&[c.glsl, number to u32]);1822    operands.append(&ids.view());1823    return c.op(::ExtInst, result, &operands.view());1824}18251826// The GLSL.std.450 instruction for a WGSL built-in on the scalar type.1827fn glsl_number(name: &[u8], scalar: u32) -> Option<Glsl> {1828    // the ones taking integers too1829    const typed = match (name) {1830        "abs" ByScalar<Glsl> { .float = ::Some(::FAbs), .signed = ::Some(::SAbs) };1831        "min" ByScalar<Glsl> {1832            .float = ::Some(::FMin),1833            .signed = ::Some(::SMin),1834            .unsigned = ::Some(::UMin)1835        };1836        "max" ByScalar<Glsl> {1837            .float = ::Some(::FMax),1838            .signed = ::Some(::SMax),1839            .unsigned = ::Some(::UMax)1840        };1841        "clamp" ByScalar<Glsl> {1842            .float = ::Some(::FClamp),1843            .signed = ::Some(::SClamp),1844            .unsigned = ::Some(::UClamp)1845        };1846        else ByScalar<Glsl> {};1847    };1848    if (typed.float is ::Some) {1849        return if (1850            scalar == F321851        ) typed.float else if (scalar == I32) typed.signed else typed.unsigned;1852    }1853    if (scalar != F32) {1854        return ::None;1855    }1856    return match (name) {1857        "round" ::Some(Glsl::RoundEven);1858        "trunc" ::Some(Glsl::Trunc);1859        "sign" ::Some(Glsl::FSign);1860        "floor" ::Some(Glsl::Floor);1861        "ceil" ::Some(Glsl::Ceil);1862        "fract" ::Some(Glsl::Fract);1863        "sin" ::Some(Glsl::Sin);1864        "cos" ::Some(Glsl::Cos);1865        "tan" ::Some(Glsl::Tan);1866        "asin" ::Some(Glsl::Asin);1867        "acos" ::Some(Glsl::Acos);1868        "atan" ::Some(Glsl::Atan);1869        "atan2" ::Some(Glsl::Atan2);1870        "pow" ::Some(Glsl::Pow);1871        "exp" ::Some(Glsl::Exp);1872        "log" ::Some(Glsl::Log);1873        "exp2" ::Some(Glsl::Exp2);1874        "log2" ::Some(Glsl::Log2);1875        "sqrt" ::Some(Glsl::Sqrt);1876        "inverseSqrt" ::Some(Glsl::InverseSqrt);1877        "mix" ::Some(Glsl::FMix);1878        "step" ::Some(Glsl::Step);1879        "smoothstep" ::Some(Glsl::SmoothStep);1880        "fma" ::Some(Glsl::Fma);1881        "length" ::Some(Glsl::Length);1882        "distance" ::Some(Glsl::Distance);1883        "cross" ::Some(Glsl::Cross);1884        "normalize" ::Some(Glsl::Normalize);1885        "reflect" ::Some(Glsl::Reflect);1886        else ::None;1887    };1888}18891890fn texture_sample(self c: &var Compiler, token: u32, x: &Call, name: &[u8]) -> Value {1891    const level = name == "textureSampleLevel";1892    if (x.arguments.count != (if (level) 4 else 3) to u32) {1893        c.fail(token, &f"{name} takes {if (level) 4 else 3} values".view());1894        return c.value(0, VOID);1895    }1896    const texture = c.load(c.expression(c.argument(&x, 0), ::None));1897    const sampler = c.load(c.expression(c.argument(&x, 1), ::None));1898    const coordinates = c.load(c.expression(c.argument(&x, 2), ::Some(F32)));1899    if (c.failed()) {1900        return texture;1901    }1902    if (c.t.kind(texture.ty) != Kind::Texture || c.t.kind(sampler.ty) != Kind::Sampler) {1903        c.fail(token, &f"{name} takes a texture_2d<f32> and a sampler".view());1904        return texture;1905    }1906    const sampled_type = c.t.intern(Kind::SampledImage, texture.ty, 0);1907    const sampled = c.op(::SampledImage, sampled_type, &[texture.id, sampler.id]);1908    const result = c.t.vector(F32, 4);1909    if (level) {1910        const lod = c.convert_to(c.load(c.expression(c.argument(&x, 3), ::Some(F32))), F32, token);1911        // the Lod image operand1912        return c.op(1913            ::ImageSampleExplicitLod,1914            result,1915            &[sampled.id, coordinates.id, 2, lod.id]1916        );1917    }1918    return c.op(::ImageSampleImplicitLod, result, &[sampled.id, coordinates.id]);1919}19201921/* --- Entry points --- */19221923// The SPIR-V entry function of a `@vertex`, `@fragment` or `@compute`1924// function: Input variables in, the call, Output variables out.1925fn entry_point(self c: &var Compiler, k: u32) {1926    const f = c.s.functions.get(k to u64);1927    const stage: Stage = if (c.attribute(f.attributes, &"vertex") is ::Some) ::Vertex else if (1928        c.attribute(f.attributes, &"fragment") is ::Some1929    ) ::Fragment else if (c.attribute(f.attributes, &"compute") is ::Some) ::Compute else {1930        return;1931    };1932    const function_id = c.function_list.get(k to u64).id;1933    const result = c.function_list.get(k to u64).result;1934    const parameters = copy c.function_list.get(k to u64).parameters;1935    c.interface_ids.clear();1936    c.variables.clear();1937    c.body.clear();1938    const entry_id = c.id();1939    c.label(c.id());1940    var arguments = Vector<u32>::from(&[function_id]);1941    for ([..parameters.length()]) |p| {1942        const field = c.s.fields.get(f.parameters.first to u64 + p);1943        const ty = parameters.get(p);1944        const location = c.attribute(field.attributes, &"location");1945        const builtin = c.builtin_attribute(field.attributes);1946        arguments.push(c.read_input(ty, location, builtin, stage, field.token));1947    }1948    const returned = c.op(::FunctionCall, result, &arguments.view());1949    if (result != VOID) {1950        const location = c.attribute(f.result_attributes, &"location");1951        const builtin = c.builtin_attribute(f.result_attributes);1952        c.write_output(returned, location, builtin, f.token);1953    }1954    instruction(&var c.body, ::Return, &[]);1955    const void_function = c.function_type(VOID, &[]);1956    instruction(&var c.functions, ::Function, &[c.type_id(VOID), entry_id, 0, void_function]);1957    c.end_function();1958    var entry_words = Vector<u32>::from(&[stage to u32, entry_id]);1959    const name = &c.text(f.token);1960    string_words(&name, &var entry_words);1961    entry_words.append(&c.interface_ids.view());1962    instruction(&var c.entry_words, ::EntryPoint, &entry_words.view());1963    var workgroup: [u32 : 3] = [1, 1, 1];1964    if (stage is ::Fragment) {1965        instruction(1966            &var c.mode_words,1967            ::ExecutionMode,1968            &[entry_id, ExecutionMode::OriginUpperLeft to u32]1969        );1970    } else if (stage is ::Compute) {1971        workgroup = c.workgroup_size(&f);1972        instruction(1973            &var c.mode_words,1974            ::ExecutionMode,1975            &[entry_id, ExecutionMode::LocalSize to u32, workgroup[0], workgroup[1], workgroup[2]]1976        );1977    }1978    c.entries.push(EntryPoint {1979        .name = String::from(&name),1980        .stage = stage,1981        .workgroup = workgroup,1982        .resources = c.resources_used(k)1983    });1984}19851986// The resources the function uses, through the functions it calls too,1987// in order.1988fn resources_used(self c: &Compiler, function: u32) -> Vector<u32> {1989    var reached = Vector<bool>::filled(false, c.function_list.length());1990    var used = Vector<bool>::filled(false, c.resources.length());1991    var pending = Vector<u32>::from(&[function]);1992    reached.get_var(function to u64) = true;1993    while (pending.pop() is ::Some |f|) {1994        for (c.uses.view()) |&u| {1995            if (u.function != f) {1996                continue;1997            }1998            match (u.used) {1999                ::Resource |r| {2000                    used.get_var(r to u64) = true;2001                }2002                ::Function |callee| {2003                    if (!reached.get(callee to u64)) {2004                        reached.get_var(callee to u64) = true;2005                        pending.push(callee);2006                    }2007                }2008            }2009        }2010    }2011    var out = Vector<u32>::empty();2012    for ([..used.length()]) |k| {2013        if (used.get(k)) {2014            out.push(k to u32);2015        }2016    }2017    return move out;2018}20192020fn workgroup_size(self c: &var Compiler, f: &FnDecl) -> [u32 : 3] {2021    var size: [u32 : 3] = [1, 1, 1];2022    for ([..f.attributes.count to u64]) |k| {2023        const a = c.s.attributes.get(f.attributes.first to u64 + k);2024        if (c.text(a.token) == "workgroup_size" && a.value is ::Some |e|) {2025            size[0] = c.integer_constant(e);2026        }2027    }2028    return size;2029}20302031// The value of an entry parameter: one Input variable, or a struct built2032// from one a member.2033fn read_input(2034    self c: &var Compiler,2035    ty: u32,2036    location: Option<u32>,2037    builtin: Option<BuiltIn>,2038    stage: Stage,2039    token: u322040) -> u32 {2041    if (c.t.kind(ty) == Kind::Struct) {2042        var ids = Vector<u32>::empty();2043        for ([..c.t.member_count(ty)]) |k| {2044            const m = &c.t.struct_member(ty, k to u32);2045            const member_type = m.ty;2046            const member_location = m.location;2047            const member_builtin = m.builtin;2048            ids.push(c.read_input(member_type, member_location, member_builtin, stage, token));2049        }2050        return c.op(::CompositeConstruct, ty, &ids.view()).id;2051    }2052    if (location is ::None && builtin is ::None) {2053        c.fail(token, &"an entry point's parameter needs @location or @builtin");2054        return 0;2055    }2056    var variable_type = ty;2057    var spirv_builtin = builtin;2058    if (builtin is ::Some |b|) {2059        match (b) {2060            ::Position {2061                if (stage is ::Fragment) {2062                    spirv_builtin = ::Some(BuiltIn::FragCoord);2063                }2064            }2065            ::GlobalInvocationId, ::LocalInvocationId, ::WorkgroupId, ::NumWorkgroups {2066                variable_type = c.t.vector(U32, 3);2067            }2068        }2069    }2070    const variable = c.interface_variable(2071        StorageClass::Input,2072        variable_type,2073        location,2074        spirv_builtin2075    );2076    if (location is ::Some && stage is ::Fragment && c.t.scalar(ty) != F32) {2077        decorate(&var c.decorations, variable, ::Flat, &[]);2078    }2079    const id = c.id();2080    instruction(&var c.body, ::Load, &[c.type_id(variable_type), id, variable]);2081    return id;2082}20832084fn write_output(2085    self c: &var Compiler,2086    value: Value,2087    location: Option<u32>,2088    builtin: Option<BuiltIn>,2089    token: u322090) {2091    if (c.t.kind(value.ty) == Kind::Struct) {2092        for ([..c.t.member_count(value.ty)]) |k| {2093            const m = &c.t.struct_member(value.ty, k to u32);2094            const member_type = m.ty;2095            const member_location = m.location;2096            const member_builtin = m.builtin;2097            const part = c.op(::CompositeExtract, member_type, &[value.id, k to u32]);2098            c.write_output(part, member_location, member_builtin, token);2099        }2100        return;2101    }2102    if (location is ::None && builtin is ::None) {2103        c.fail(token, &"an entry point's result needs @location or @builtin");2104        return;2105    }2106    const variable = c.interface_variable(StorageClass::Output, value.ty, location, builtin);2107    instruction(&var c.body, ::Store, &[variable, value.id]);2108}21092110fn interface_variable(2111    self c: &var Compiler,2112    storage: StorageClass,2113    ty: u32,2114    location: Option<u32>,2115    builtin: Option<BuiltIn>2116) -> u32 {2117    const pointer = c.pointer_type(storage, ty);2118    const id = c.id();2119    instruction(&var c.globals, ::Variable, &[pointer, id, storage to u32]);2120    if (builtin is ::Some |b|) {2121        decorate(&var c.decorations, id, ::BuiltIn, &[b to u32]);2122    } else if (location is ::Some |l|) {2123        decorate(&var c.decorations, id, ::Location, &[l]);2124    }2125    c.interface_ids.push(id);2126    return id;2127}