Skip to content

Commit de46a9a

Browse files
committed
fix: ArrayExpression - immediate index access
1 parent c96d9d4 commit de46a9a

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

packages/typegpu/src/tgsl/accessIndex.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
} from '../data/wgslTypes.ts';
1414
import { isKnownAtComptime } from '../types.ts';
1515
import { accessProp } from './accessProp.ts';
16-
import { coerceToSnippet } from './generationHelpers.ts';
16+
import { ArrayExpression, coerceToSnippet } from './generationHelpers.ts';
1717

1818
const indexableTypeToResult = {
1919
mat2x2f: vec2f,
@@ -54,6 +54,10 @@ export function accessIndex(target: Snippet, indexArg: Snippet | number): Snippe
5454
origin = 'runtime';
5555
}
5656

57+
if (target.value instanceof ArrayExpression && isKnownAtComptime(index)) {
58+
return target.value.elements[index.value as number];
59+
}
60+
5761
return snip(
5862
isKnownAtComptime(target) && isKnownAtComptime(index)
5963
? // oxlint-disable-next-line typescript/no-explicit-any -- it's fine, it's there

packages/typegpu/tests/array.test.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,38 @@ describe('array', () => {
443443
}"
444444
`);
445445
});
446+
447+
it('array expressions can be indexed into with a comptime-known index', () => {
448+
function foo() {
449+
'use gpu';
450+
const i = 2;
451+
const a = [i, 2][0];
452+
const b = [i, 2][1];
453+
}
454+
455+
expect(tgpu.resolve([foo])).toMatchInlineSnapshot(`
456+
"fn foo() {
457+
const i = 2;
458+
const a = i;
459+
const b = 2i;
460+
}"
461+
`);
462+
});
463+
464+
it('array expressions can be indexed into with a runtime-known index', () => {
465+
function foo() {
466+
'use gpu';
467+
const i = 0;
468+
const a = [1, 2][i];
469+
}
470+
471+
expect(tgpu.resolve([foo])).toMatchInlineSnapshot(`
472+
"fn foo() {
473+
const i = 0;
474+
let a = array<i32, 2>(1, 2)[i];
475+
}"
476+
`);
477+
});
446478
});
447479

448480
describe('array.length', () => {

0 commit comments

Comments
 (0)