Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/typegpu/src/tgsl/wgslGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
numericLiteralToSnippet,
} from './generationHelpers.ts';
import type { ShaderGenerator } from './shaderGenerator.ts';
import { constant } from '../core/constant/tgpuConstant.ts';

const { NodeTypeCatalog: NODE } = tinyest;

Expand Down Expand Up @@ -367,7 +368,7 @@ ${this.ctx.pre}}`;
}

throw new Error(
`Cannot index value ${targetStr} of unknown type with index ${propertyStr}`,
`Unable to index a value of unknown type with index ${propertyStr}. If the value is an array, to address this, consider one of the following approaches: (1) declare the array using 'tgpu.const', (2) store the array in a buffer, or (3) define the array within the GPU function scope.`,
);
}

Expand Down Expand Up @@ -438,6 +439,12 @@ ${this.ctx.pre}}`;
);
}

if (callee.value === constant) {
throw new Error(
'Constants cannot be defined within TypeGPU function scope. To address this, move the constant definition outside the function scope.',
);
}

if (callee.value instanceof InfixDispatch) {
// Infix operator dispatch.
if (!argNodes[0]) {
Expand Down
27 changes: 27 additions & 0 deletions packages/typegpu/tests/tgsl/wgslGenerator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1147,4 +1147,31 @@ describe('wgslGenerator', () => {
}"
`);
});

it('throws a descriptive error when accessing an external array with a runtime known index', () => {
const myArray = [9, 8, 7, 6];

const testFn = tgpu.fn([d.u32], d.u32)((i) => {
return myArray[i] as number;
});

expect(() => asWgsl(testFn)).toThrowErrorMatchingInlineSnapshot(`
[Error: Resolution of the following tree failed:
- <root>
- fn:testFn: Unable to index a value of unknown type with index i. If the value is an array, to address this, consider one of the following approaches: (1) declare the array using 'tgpu.const', (2) store the array in a buffer, or (3) define the array within the GPU function scope.]
`);
});

it('throws a descriptive error when declaring a const inside TGSL', () => {
const testFn = tgpu.fn([d.u32], d.u32)((i) => {
const myArray = tgpu.const(d.arrayOf(d.u32, 4), [9, 8, 7, 6]);
return myArray.$[i] as number;
});

expect(() => asWgsl(testFn)).toThrowErrorMatchingInlineSnapshot(`
[Error: Resolution of the following tree failed:
- <root>
- fn:testFn: Constants cannot be defined within TypeGPU function scope. To address this, move the constant definition outside the function scope.]
`);
});
});