A function is fn name(param: Type, ...) -> ReturnType { ... }, without -> ReturnType if it returns nothing. Parameters are immutable values (Pointers passes pointers), and functions live at module scope in any order:
// out: 2 x f32
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(1) fn main() {
out[0] = salePrice(39.50, 15);
out[1] = salePrice(14.99, 0);
}
fn salePrice(price: f32, percentOff: f32) -> f32 {
return round(price * (100 - percentOff)) / 100;
}Output
out: 33.58000183105469, 14.989999771118164
The compiler enforced four rules here. No recursion: a self-call failed with "cyclic dependency found: 'pagesLeft' -> 'pagesLeft'". No overloading your own functions: a second fn price(x: u32) gave "redeclaration of 'price'". Results of built-ins must be used: sqrt(2.0); gave "ignoring return value of builtin 'sqrt'" (write _ = f(); to discard deliberately). And every path must return: "missing return at end of function".
<!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', align = 'left') {
ink.font = `${size}px ${font}`; ink.fillStyle = color; ink.textAlign = align; ink.fillText(text, x, y);
}
const books = [['The Quiet Harbor', 14.99, 15], ['Small Steps to Big Summits', 39.50, 25], ['Salt and Saffron', 24.00, 10],
["The Clockmaker's Paradox", 18.75, 0], ['Night Trains', 16.20, 40], ['Paper Gardens', 21.30, 20]];
// main() calls salePrice() before its declaration: module-scope order does not matter.
const lab = /* wgsl */ `
@group(0) @binding(0) var<storage> input: array<vec2f>; // price, percent off
@group(0) @binding(1) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(6) fn main(@builtin(local_invocation_index) i: u32) {
out[i] = salePrice(input[i].x, input[i].y);
}
fn salePrice(price: f32, percentOff: f32) -> f32 {
return round(price * (100 - percentOff)) / 100;
}`;
const recursive = `fn pagesLeft(n: u32) -> u32 { if (n == 0) { return 0; } return pagesLeft(n - 1); }`;
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 });
device.pushErrorScope('validation'); // an expected error, kept out of the console
const { messages } = await device.createShaderModule({ code: recursive }).getCompilationInfo();
await device.popErrorScope();
const B = GPUBufferUsage;
const input = device.createBuffer({ size: 48, usage: B.STORAGE | B.COPY_DST });
device.queue.writeBuffer(input, 0, new Float32Array(books.flatMap(([, p, off]) => [p, off])));
const out = device.createBuffer({ size: 24, usage: B.STORAGE | B.COPY_SRC });
const read = device.createBuffer({ size: 24, usage: B.COPY_DST | B.MAP_READ });
const compute = device.createComputePipeline({ layout: 'auto', compute: { module: device.createShaderModule({ code: lab }) } });
const module = device.createShaderModule({ code: `
@group(0) @binding(0) var<storage> input: array<vec2f>;
@group(0) @binding(1) var<storage> sale: 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 book = i / 2;
let isSale = i % 2 == 1;
let w = select(input[book].x, sale[book], isSale) * 8; // 8 px per dollar
let px = vec2f(200 + q.x * w, 30 + f32(book) * 42 + select(0.0, 14.0, isSale) + q.y * 12);
return Out(vec4f(px.x / 300 - 1, 1 - px.y / 170, 0, 1),
select(vec3f(0.75, 0.73, 0.69), vec3f(0.16, 0.56, 0.30), isSale));
}
@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: input } }, { binding: 1, 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: input } }, { binding: 1, resource: { buffer: out } }] }));
pass.draw(4, 12);
pass.end();
encoder.copyBufferToBuffer(out, 0, read, 0, 24);
device.queue.submit([encoder.finish()]);
await read.mapAsync(GPUMapMode.READ);
const sale = new Float32Array(read.getMappedRange().slice(0));
read.unmap();
label('salePrice(price, percentOff): grey list price, green sale price', 12, 18, 12.5, '#222');
books.forEach(([title, price, off], i) => {
label(title, 190, 42 + i * 42, 11.5, '#222', undefined, 'right');
label(`${off}% off`, 190, 56 + i * 42, 10.5, '#777', undefined, 'right');
label(`$${price.toFixed(2)}`, 206 + price * 8, 41 + i * 42, 10.5, '#555');
label(`$${sale[i].toFixed(2)}`, 206 + sale[i] * 8, 55 + i * 42, 10.5, '#1e6b3a');
});
const m = messages.find((x) => x.type === 'error');
label('A function that calls itself:', 12, 300, 12, '#222');
label(m ? m.message.slice(0, 80) : 'compiled?', 12, 318, 11.5, '#8a2b2b', 'ui-monospace, monospace');
}
main();
</script>