Skip to content

Commit c23c36b

Browse files
authored
fix: Better std.range internal variables type inference (#2384)
1 parent c593bfb commit c23c36b

4 files changed

Lines changed: 33 additions & 6 deletions

File tree

packages/typegpu/src/tgsl/forOfUtils.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,14 @@ export function getRangeSnippets(
6363
const { value, dataType } = iterableSnippet;
6464

6565
if (isTgpuRange(value)) {
66+
const { start, end, step } = value;
67+
const dataType = [start, end, step].every((v) => v >= 0) ? u32 : i32;
68+
6669
return {
67-
start: snip(value.start, i32, 'constant'),
68-
end: snip(value.end, i32, 'constant'),
69-
step: snip(value.step, i32, 'constant'),
70-
comparison: value.step < 0 ? '>' : '<',
70+
start: snip(start, dataType, 'constant'),
71+
end: snip(end, dataType, 'constant'),
72+
step: snip(step, dataType, 'constant'),
73+
comparison: step < 0 ? '>' : '<',
7174
};
7275
}
7376

packages/typegpu/src/tgsl/wgslGenerator.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1263,7 +1263,7 @@ ${this.ctx.pre}else ${alternate}`;
12631263

12641264
if (isTgpuRange(iterableSnippet.value)) {
12651265
bodyStr = this._block(blockified, {
1266-
[originalLoopVarName]: snip(index, u32, 'runtime'),
1266+
[originalLoopVarName]: snip(index, range.start.dataType, 'runtime'), // range.start, .end , .step have the same dataType
12671267
});
12681268
} else {
12691269
this.ctx.indent();

packages/typegpu/tests/std/range.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ describe('on the GPU', () => {
107107
expect(tgpu.resolve([main])).toMatchInlineSnapshot(`
108108
"fn main() -> f32 {
109109
var result = 0f;
110-
for (var i = 0i; i < 8i; i += 2i) {
110+
for (var i = 0u; i < 8u; i += 2u) {
111111
result += f32(i);
112112
}
113113
for (var i = 10i; i > -10i; i += -1i) {

packages/typegpu/tests/tgsl/wgslGenerator.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -979,6 +979,30 @@ describe('wgslGenerator', () => {
979979
`);
980980
});
981981

982+
it('handles "for ... of ..." over `std.range`', ({ root }) => {
983+
const testFn = tgpu.fn(
984+
[],
985+
d.f32,
986+
)(() => {
987+
'use gpu';
988+
for (const bounce of std.range(12)) {
989+
const test = d.u32(2) + bounce;
990+
return d.f32(test);
991+
}
992+
return 0;
993+
});
994+
995+
expect(tgpu.resolve([testFn])).toMatchInlineSnapshot(`
996+
"fn testFn() -> f32 {
997+
for (var i = 0u; i < 12u; i += 1u) {
998+
let test = (2u + i);
999+
return f32(test);
1000+
}
1001+
return 0f;
1002+
}"
1003+
`);
1004+
});
1005+
9821006
it('creates correct resources for lazy values and slots', () => {
9831007
const testFn = tgpu.fn([], d.vec4u)(() => lazyV4u.$);
9841008

0 commit comments

Comments
 (0)