From most to least fixed: const is computed by the compiler and usable anywhere, even in array sizes; override is set when a pipeline is created (override Constants); let is an immutable run-time value, the default inside functions; and var is mutable memory, needed only to assign again or take an address.
// out: 1 x f32
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
const taxRate = 0.06; // evaluated by the compiler
@compute @workgroup_size(1) fn main() {
let price = 14.99; // immutable
var total = price * (1 + taxRate); // mutable
price = 12.74;
out[0] = total;
}Output
7:3 error: cannot assign to 'let price' 7:3 info: 'let' variables are immutable 5:7 info: 'let price' declared here
Two info messages point at the declaration. Without line 7 the lab printed out: 15.889398574829102. const expressions are evaluated by the compiler, so const longest = max(312, max(428, 256)) costs nothing at run time. Prefer let to var, so the compiler and your reader know the value never changes.
<!doctype html>
<style>
body { margin: 0; background: #f7f4ee; font: 14px system-ui, sans-serif; }
.stage { position: relative; width: 100%; max-width: 600px; }
.stage canvas { display: block; width: 100%; }
.stage canvas + canvas { position: absolute; inset: 0; pointer-events: none; }
</style>
<div class="stage">
<canvas id="view" width="600" height="340"></canvas>
<canvas id="labels" width="600" height="340"></canvas>
</div>
<script>
const canvas = document.getElementById('view');
const ink = document.getElementById('labels').getContext('2d');
function showMessage(text) { // 2D fallback when WebGPU is missing
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#fbeaea'; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#8a2b2b'; ctx.font = '18px system-ui, sans-serif'; ctx.textAlign = 'center';
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}
function label(text, x, y, size = 12, color = '#2b2b2b', font = 'system-ui, sans-serif', weight = '') {
ink.font = `${weight} ${size}px ${font}`; ink.fillStyle = color; ink.fillText(text, x, y);
}
const body = (extraLine) => /* wgsl */ `
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
const taxRate = 0.06; // evaluated by the compiler
const longest = max(312, max(428, 256));
@compute @workgroup_size(1) fn main() {
let price = 14.99; // immutable
var total = price * (1 + taxRate); // mutable
${extraLine}
out[0] = price; out[1] = total; out[2] = f32(longest);
}`;
async function main() {
const adapter = await navigator.gpu?.requestAdapter();
if (!adapter) return showMessage('WebGPU is not available in this browser');
const device = await adapter.requestDevice();
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format });
// 1. The broken version: collect the compiler's messages (an error scope keeps the console clean).
device.pushErrorScope('validation');
const { messages } = await device.createShaderModule({ code: body('price = 12.74;') }).getCompilationInfo();
await device.popErrorScope();
// 2. The fixed version runs; a render pass draws the price and the tax as a stacked bar.
const B = GPUBufferUsage;
const out = device.createBuffer({ size: 12, usage: B.STORAGE | B.COPY_SRC });
const read = device.createBuffer({ size: 12, usage: B.COPY_DST | B.MAP_READ });
const compute = device.createComputePipeline({ layout: 'auto', compute: { module: device.createShaderModule({ code: body('') }) } });
const module = device.createShaderModule({ code: `
@group(0) @binding(0) var<storage> out: array<f32>;
struct Out { @builtin(position) pos: vec4f, @location(0) color: vec3f }
@vertex fn vs(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> Out {
let q = vec2f(f32(v & 1), f32(v >> 1));
let start = select(0.0, out[0], i == 1u); // bar 0: price, bar 1: the tax on top
let end = select(out[0], out[1], i == 1u);
let x = 20 + (start + q.x * (end - start)) * 30; // 30 px per dollar
return Out(vec4f(x / 300 - 1, 1 - (230 + q.y * 44) / 170, 0, 1),
select(vec3f(0.08, 0.40, 0.75), vec3f(0.88, 0.55, 0.15), i == 1u));
}
@fragment fn fs(in: Out) -> @location(0) vec4f { return vec4f(in.color, 1); }` });
const render = device.createRenderPipeline({ layout: 'auto', primitive: { topology: 'triangle-strip' },
vertex: { module }, fragment: { module, targets: [{ format }] } });
const encoder = device.createCommandEncoder();
const cp = encoder.beginComputePass();
cp.setPipeline(compute);
cp.setBindGroup(0, device.createBindGroup({ layout: compute.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: out } }] }));
cp.dispatchWorkgroups(1);
cp.end();
const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(),
clearValue: [0.97, 0.96, 0.93, 1], loadOp: 'clear', storeOp: 'store' }] });
pass.setPipeline(render);
pass.setBindGroup(0, device.createBindGroup({ layout: render.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: out } }] }));
pass.draw(4, 2);
pass.end();
encoder.copyBufferToBuffer(out, 0, read, 0, 12);
device.queue.submit([encoder.finish()]);
await read.mapAsync(GPUMapMode.READ);
const [price, total, longest] = new Float32Array(read.getMappedRange());
read.unmap();
ink.fillStyle = '#fff4f2'; ink.fillRect(8, 8, 584, 24 + messages.length * 20);
label('With "price = 12.74;" after "let price = 14.99;" the compiler reports:', 16, 26, 13, '#222', 'system-ui, sans-serif', 'bold');
messages.forEach((m, i) => label(`${m.lineNum}:${m.linePos} ${m.type}: ${m.message}`.slice(0, 84), 16, 48 + i * 20, 11.5,
m.type === 'error' ? '#8a2b2b' : '#7a5a10', 'ui-monospace, monospace'));
label('Without that line the lab prints:', 16, 172, 13, '#222', 'system-ui, sans-serif', 'bold');
label(`out[1] = total = ${total}`, 16, 194, 13, '#1f4f8a', 'ui-monospace, monospace');
label(`price $${price.toFixed(2)}`, 24, 257, 13, '#fff', 'system-ui, sans-serif', 'bold');
label(`+ tax ${(total - price).toFixed(4)}`, 20 + total * 30 + 8, 257, 13, '#8a5a00');
label(`const longest = max(312, max(428, 256)) = ${longest}: computed by the compiler, free at run time.`, 16, 310, 12, '#333');
}
main();
</script>