typegpu 0.11.4 → 0.11.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@ import { ResolutionError, WgslTypeError, invariant } from "../errors.js";
7
7
  import { isGPUCallable, isKnownAtComptime } from "../types.js";
8
8
  import { stitch } from "../core/resolve/stitch.js";
9
9
  import { createPtrFromOrigin, implicitFrom, ptrFn } from "../data/ptr.js";
10
- import { RefOperator } from "../data/ref.js";
10
+ import { RefOperator, _ref } from "../data/ref.js";
11
11
  import { safeStringify } from "../shared/stringify.js";
12
12
  import { convertStructValues, convertToCommonType, tryConvertSnippet } from "./conversion.js";
13
13
  import { bool, i32, u32 } from "../data/numeric.js";
@@ -23,7 +23,7 @@ import { isGenericFn } from "../core/function/tgpuFn.js";
23
23
  import { arrayOf } from "../data/array.js";
24
24
  import { pow } from "../std/numeric.js";
25
25
  import { resolveData } from "../core/resolve/resolveData.js";
26
- import { UnrollableIterable } from "../core/unroll/tgpuUnroll.js";
26
+ import { UnrollableIterable, unroll } from "../core/unroll/tgpuUnroll.js";
27
27
  import { mathToStd, supportedLogOps } from "./jsPolyfills.js";
28
28
  import { isTgpuRange } from "../std/range.js";
29
29
  import { getElementSnippet, getElementType, getLoopVarKind, getRangeSnippets } from "./forOfUtils.js";
@@ -165,8 +165,11 @@ ${this.ctx.pre}}`;
165
165
  this.ctx.popBlockScope();
166
166
  }
167
167
  }
168
+ _blockStatement(block, externalMap) {
169
+ return `${this.ctx.pre}${this._block(block, externalMap)}`;
170
+ }
168
171
  refVariable(id, dataType) {
169
- const varName = this.ctx.makeNameValid(id);
172
+ const varName = this.ctx.makeUniqueIdentifier(id, "block");
170
173
  const ptrType = ptrFn(dataType);
171
174
  const snippet = snip(new RefOperator(snip(varName, dataType, "function"), ptrType), ptrType, "function");
172
175
  this.ctx.defineVariable(id, snippet);
@@ -181,10 +184,14 @@ ${this.ctx.pre}}`;
181
184
  else if (!naturallyEphemeral) varOrigin = isEphemeralOrigin(origin) ? "this-function" : origin;
182
185
  else if (origin === "constant" && varType === "const") varOrigin = "constant";
183
186
  else varOrigin = "runtime";
184
- const snippet = snip(this.ctx.makeNameValid(id), dataType, varOrigin);
187
+ const snippet = snip(this.ctx.makeUniqueIdentifier(id, "block"), dataType, varOrigin);
185
188
  this.ctx.defineVariable(id, snippet);
186
189
  return snippet;
187
190
  }
191
+ /**
192
+ * Creates a variable declaration string.
193
+ * `keyword` may be a placeholder filled in later.
194
+ */
188
195
  emitVarDecl(pre, keyword, name, _dataType, rhsStr) {
189
196
  return `${pre}${keyword} ${name} = ${rhsStr};`;
190
197
  }
@@ -252,22 +259,14 @@ ${this.ctx.pre}}`;
252
259
  const rhsStr = this.ctx.resolve(convRhs.value, convRhs.dataType).value;
253
260
  const type = operatorToType(convLhs.dataType, op, convRhs.dataType);
254
261
  if (exprType === NODE.assignmentExpr) {
255
- if (convLhs.origin === "constant" || convLhs.origin === "constant-tgpu-const-ref" || convLhs.origin === "runtime-tgpu-const-ref") {
256
- if (isKnownAtComptime(convLhs)) throw new WgslTypeError(`'${stringifyNode(expression)}' is invalid, because the left side is defined outside of the shader, and therefore is immutable during its execution. Try using tgpu.privateVar or buffers.`);
257
- throw new WgslTypeError(`'${stringifyNode(expression)}' is invalid, because the left side is a constant.`);
258
- }
259
- if (lhsExpr.origin === "argument") throw new WgslTypeError(`'${stringifyNode(expression)}' is invalid, because non-pointer arguments cannot be mutated.`);
262
+ validateSnippetMutation(convLhs, expression);
263
+ this.tryMarkModified(lhs);
260
264
  if (op === "=" && rhsExpr.origin === "argument" && !isNaturallyEphemeral(rhsExpr.dataType)) throw new WgslTypeError(`'${stringifyNode(expression)}' is invalid, because argument references cannot be assigned.\n-----\nTry '${stringifyNode(lhs)} = ${this.ctx.resolve(rhsExpr.dataType).value}(${stringifyNode(rhs)})' to copy the value instead.\n-----`);
261
265
  if (op === "=" && !isEphemeralSnippet(rhsExpr)) throw new WgslTypeError(`'${stringifyNode(expression)}' is invalid, because references cannot be assigned.\n-----\nTry '${stringifyNode(lhs)} = ${this.ctx.resolve(rhsExpr.dataType).value}(${stringifyNode(rhs)})' to copy the value instead.\n-----`);
262
266
  }
263
267
  return snip(parenthesizedOps.includes(op) ? `(${lhsStr} ${OP_MAP[op] ?? op} ${rhsStr})` : `${lhsStr} ${OP_MAP[op] ?? op} ${rhsStr}`, type, "runtime");
264
268
  }
265
- if (expression[0] === NODE.postUpdate) {
266
- const [_, op, arg] = expression;
267
- const argExpr = this._expression(arg);
268
- const argStr = this.ctx.resolve(argExpr.value, argExpr.dataType).value;
269
- return snip(`${argStr}${op}`, argExpr.dataType, "runtime");
270
- }
269
+ if (expression[0] === NODE.postUpdate) throw new Error(`'${stringifyNode(expression)}' is invalid because update is only allowed as a statement.`);
271
270
  if (expression[0] === NODE.unaryExpr) {
272
271
  const [_, op, arg] = expression;
273
272
  const argExpr = this._expression(arg);
@@ -320,6 +319,7 @@ ${this.ctx.pre}}`;
320
319
  const rhs = this._expression(argNodes[0]);
321
320
  return callee.value.operator(this.ctx, [callee.value.lhs, rhs]);
322
321
  }
322
+ if ((callee.value === _ref || callee.value === unroll) && argNodes[0]) this.tryMarkModified(argNodes[0]);
323
323
  if (isGPUCallable(callee.value)) {
324
324
  const callable = callee.value[$gpuCallable];
325
325
  const strictSignature = callable.strictSignature;
@@ -423,7 +423,14 @@ ${this.ctx.pre}}`;
423
423
  assertExhaustive(expression);
424
424
  }
425
425
  functionDefinition(options) {
426
- const body = this._block(options.body);
426
+ let body = this._block(options.body);
427
+ const scope = this.ctx.topFunctionScope;
428
+ invariant(scope, "Expected function scope to be present");
429
+ const replacements = Object.fromEntries([...scope.placeholderForVariable.entries()].map(([variable, placeholder]) => [placeholder, scope.modifiedVariables.has(variable) ? "var" : "let"]));
430
+ if (Object.keys(replacements).length > 0) {
431
+ const regex = new RegExp(Object.keys(replacements).join("|"), "gi");
432
+ body = body.replace(regex, (match) => replacements[match] ?? "#ERR");
433
+ }
427
434
  const returnType = options.determineReturnType();
428
435
  const argList = options.args.filter((arg) => arg.used || options.functionType === "normal").map((arg) => {
429
436
  return `${getAttributesString(arg.decoratedType)}${arg.name}: ${this.ctx.resolve(arg.decoratedType).value}`;
@@ -481,7 +488,7 @@ Try 'return ${typeStr}(${str});' instead.
481
488
  if (!Array.isArray(node)) node = blockifySingleStatement(node);
482
489
  if (node[0] === NODE.block && node[1].length === 1 && node[1][0][0] === NODE.if) return this._statement(node[1][0]);
483
490
  if (node[0] === NODE.if) return this._statement(node);
484
- return `${this.ctx.pre}${this._block(blockifySingleStatement(node))}`;
491
+ return this._blockStatement(blockifySingleStatement(node));
485
492
  }
486
493
  const consequent = this._block(blockifySingleStatement(consNode));
487
494
  const alternate = !altNode ? void 0 : this._block(blockifySingleStatement(altNode));
@@ -491,7 +498,7 @@ ${this.ctx.pre}if (${condition}) ${consequent}
491
498
  ${this.ctx.pre}else ${alternate}`;
492
499
  }
493
500
  if (statement[0] === NODE.let || statement[0] === NODE.const) {
494
- let varType = "var";
501
+ let varType = "<deferred>";
495
502
  const [stmtType, rawId, rawValue] = statement;
496
503
  const eq = rawValue !== void 0 ? this._expression(rawValue) : void 0;
497
504
  if (!eq) throw new Error(`'${stringifyNode(statement)}' is invalid because all variables need initializers.`);
@@ -523,7 +530,10 @@ ${this.ctx.pre}else ${alternate}`;
523
530
  invariant(ptrType !== void 0, `Creating pointer type from origin ${eq.origin}`);
524
531
  dataType = ptrType;
525
532
  }
526
- if (!(eq.value instanceof RefOperator)) dataType = implicitFrom(dataType);
533
+ if (!(eq.value instanceof RefOperator)) {
534
+ dataType = implicitFrom(dataType);
535
+ this.tryMarkModified(rawValue);
536
+ }
527
537
  }
528
538
  } else if (stmtType === NODE.const) {
529
539
  if (eq.origin === "argument") varType = "let";
@@ -542,9 +552,16 @@ ${this.ctx.pre}else ${alternate}`;
542
552
  const snippet = this.blockVariable(varType, rawId, concretize(dataType), eq.origin);
543
553
  const rhsSnippet = tryConvertSnippet(this.ctx, eq, dataType, false);
544
554
  const rhsStr = this.ctx.resolve(rhsSnippet.value, rhsSnippet.dataType).value;
545
- return this.emitVarDecl(this.ctx.pre, varType, snippet.value, concretize(dataType), rhsStr);
555
+ let emittedVarType;
556
+ if (varType === "<deferred>") {
557
+ const scope = this.ctx.topFunctionScope;
558
+ invariant(scope, `Expected function scope to be present for ${rawId}`);
559
+ emittedVarType = `#VAR_${scope.placeholderForVariable.size}#`;
560
+ scope.placeholderForVariable.set(snippet, emittedVarType);
561
+ } else emittedVarType = varType;
562
+ return this.emitVarDecl(this.ctx.pre, emittedVarType, snippet.value, concretize(dataType), rhsStr);
546
563
  }
547
- if (statement[0] === NODE.block) return `${this.ctx.pre}${this._block(statement)}`;
564
+ if (statement[0] === NODE.block) return this._blockStatement(statement);
548
565
  if (statement[0] === NODE.for) {
549
566
  const [_, init, condition, update, body] = statement;
550
567
  const prevUnrollingFlag = this.#unrolling;
@@ -581,6 +598,7 @@ ${this.ctx.pre}else ${alternate}`;
581
598
  if (statement[0] === NODE.forOf) {
582
599
  const [_, loopVar, iterable, body] = statement;
583
600
  if (loopVar[0] !== NODE.const) throw new WgslTypeError("Only `for (const ... of ... )` loops are supported");
601
+ this.tryMarkModified(iterable);
584
602
  let ctxIndent = false;
585
603
  const prevUnrollingFlag = this.#unrolling;
586
604
  try {
@@ -599,21 +617,21 @@ ${this.ctx.pre}else ${alternate}`;
599
617
  const { value } = iterableSnippet;
600
618
  const elements = isTgpuRange(value) ? value.map((i) => coerceToSnippet(i)) : value instanceof ArrayExpression ? value.elements : Array.from({ length }, (_$1, i) => getElementSnippet(iterableSnippet, snip(i, u32, "constant")));
601
619
  if (isEphemeralSnippet(elements[0]) && !isNaturallyEphemeral(elements[0]?.dataType)) throw new WgslTypeError(`Cannot unroll '${stringifyNode(iterable)}'. The elements of iterable are constructed in place but are not value types.`);
602
- return elements.map((e, i) => `${this.ctx.pre}// unrolled iteration #${i}\n${this.ctx.pre}${this._block(blockified, { [originalLoopVarName]: e })}`).join("\n");
620
+ return elements.map((e, i) => `${this.ctx.pre}// unrolled iteration #${i}\n${this._blockStatement(blockified, { [originalLoopVarName]: e })}`).join("\n");
603
621
  }
604
622
  this.#unrolling = false;
605
- const index = this.ctx.makeNameValid("i");
623
+ const index = this.ctx.makeUniqueIdentifier("i", "block");
606
624
  const forHeaderStr = stitch`${this.ctx.pre}for (var ${index} = ${range.start}; ${index} ${range.comparison} ${range.end}; ${index} += ${range.step})`;
607
625
  let bodyStr = "";
608
626
  if (isTgpuRange(iterableSnippet.value)) bodyStr = this._block(blockified, { [originalLoopVarName]: snip(index, range.start.dataType, "runtime") });
609
627
  else {
610
628
  this.ctx.indent();
611
629
  ctxIndent = true;
612
- const loopVarName = this.ctx.makeNameValid(originalLoopVarName);
630
+ const loopVarName = this.ctx.makeUniqueIdentifier(originalLoopVarName, "block");
613
631
  const elementSnippet = getElementSnippet(iterableSnippet, snip(index, u32, "runtime"));
614
632
  const loopVarKind = getLoopVarKind(elementSnippet);
615
633
  const elementType = getElementType(elementSnippet, iterableSnippet);
616
- bodyStr = `{\n${stitch`${this.ctx.pre}${loopVarKind} ${loopVarName} = ${tryConvertSnippet(this.ctx, elementSnippet, elementType, false)};`}\n${this.ctx.pre}${this._block(blockified, { [originalLoopVarName]: snip(loopVarName, elementType, elementSnippet.origin) })}\n`;
634
+ bodyStr = `{\n${stitch`${this.ctx.pre}${loopVarKind} ${loopVarName} = ${tryConvertSnippet(this.ctx, elementSnippet, elementType, false)};`}\n${this._blockStatement(blockified, { [originalLoopVarName]: snip(loopVarName, elementType, elementSnippet.origin) })}\n`;
617
635
  this.ctx.dedent();
618
636
  bodyStr += `${this.ctx.pre}}`;
619
637
  ctxIndent = false;
@@ -625,6 +643,14 @@ ${this.ctx.pre}else ${alternate}`;
625
643
  this.ctx.popBlockScope();
626
644
  }
627
645
  }
646
+ if (statement[0] === NODE.postUpdate) {
647
+ const [_, op, arg] = statement;
648
+ const argExpr = this._expression(arg);
649
+ const argStr = this.ctx.resolve(argExpr.value, argExpr.dataType).value;
650
+ validateSnippetMutation(argExpr, statement);
651
+ this.tryMarkModified(arg);
652
+ return `${this.ctx.pre}${argStr}${op};`;
653
+ }
628
654
  if (statement[0] === NODE.continue) {
629
655
  if (this.#unrolling) throw new WgslTypeError("Cannot unroll loop containing `continue`");
630
656
  return `${this.ctx.pre}continue;`;
@@ -637,7 +663,35 @@ ${this.ctx.pre}else ${alternate}`;
637
663
  const resolved = expr.value && this.ctx.resolve(expr.value).value;
638
664
  return resolved ? `${this.ctx.pre}${resolved};` : "";
639
665
  }
666
+ /**
667
+ * Attempts a member access lookup to mark a variable as modified.
668
+ * @example
669
+ * // given `let a; a = 1;`
670
+ * tryMarkModified('a') // `a` is marked in the function scope
671
+ *
672
+ * // given `const obj; obj.prop = 1;`
673
+ * tryMarkModified('obj.prop') // `obj` is marked in the function scope
674
+ *
675
+ * // given `this.buffer.$;`
676
+ * tryMarkModified('this.buffer.$') // `this` is not marked, since there is no placeholder for it
677
+ */
678
+ tryMarkModified(expr) {
679
+ if (!expr) return;
680
+ const maybeObject = extractObject(expr);
681
+ if (maybeObject !== void 0) {
682
+ const snippet = this.ctx.getById(maybeObject);
683
+ const scope = this.ctx.topFunctionScope;
684
+ if (snippet && scope && scope.placeholderForVariable.has(snippet)) scope.modifiedVariables.add(snippet);
685
+ }
686
+ }
640
687
  };
688
+ function validateSnippetMutation(mutated, expr) {
689
+ if (mutated.origin === "constant" || mutated.origin === "constant-tgpu-const-ref" || mutated.origin === "runtime-tgpu-const-ref") {
690
+ if (isKnownAtComptime(mutated)) throw new WgslTypeError(`'${stringifyNode(expr)}' is invalid, because the left side is defined outside of the shader, and therefore is immutable during its execution. Try using tgpu.privateVar or buffers.`);
691
+ throw new WgslTypeError(`'${stringifyNode(expr)}' is invalid, because the left side is a constant.`);
692
+ }
693
+ if (mutated.origin === "argument") throw new WgslTypeError(`'${stringifyNode(expr)}' is invalid, because non-pointer arguments cannot be mutated.`);
694
+ }
641
695
  function assertExhaustive(value) {
642
696
  throw new Error(`'${safeStringify(value)}' was not handled by the WGSL generator.`);
643
697
  }
@@ -649,6 +703,11 @@ function parseNumericString(str) {
649
703
  function blockifySingleStatement(statement) {
650
704
  return typeof statement !== "object" || statement[0] !== NODE.block ? [NODE.block, [statement]] : statement;
651
705
  }
706
+ function extractObject(expr) {
707
+ let object = expr;
708
+ while (Array.isArray(object) && (object[0] === NODE.memberAccess || object[0] === NODE.indexAccess)) object = object[1];
709
+ if (typeof object === "string") return object;
710
+ }
652
711
  const wgslGenerator = new WgslGenerator();
653
712
  var wgslGenerator_default = wgslGenerator;
654
713
 
package/types.d.ts CHANGED
@@ -70,6 +70,14 @@ type FunctionScopeLayer = {
70
70
  * All types used in `return` statements.
71
71
  */
72
72
  reportedReturnTypes: Set<BaseData>;
73
+ /**
74
+ * Maps variables to their modifier placeholders
75
+ */
76
+ placeholderForVariable: Map<Snippet, string>;
77
+ /**
78
+ * Local variables that need `var` modifier.
79
+ */
80
+ modifiedVariables: Set<Snippet>;
73
81
  };
74
82
  type SlotBindingLayer = {
75
83
  type: 'slotBinding';
@@ -77,6 +85,7 @@ type SlotBindingLayer = {
77
85
  };
78
86
  type BlockScopeLayer = {
79
87
  type: 'blockScope';
88
+ takenLocalIdentifiers: Set<string>;
80
89
  declarations: Map<string, Snippet>;
81
90
  externals: Map<string, Snippet>;
82
91
  };
@@ -84,6 +93,7 @@ type StackLayer = ItemLayer | SlotBindingLayer | FunctionScopeLayer | BlockScope
84
93
  interface ItemStateStack {
85
94
  readonly itemDepth: number;
86
95
  readonly topItem: ItemLayer;
96
+ readonly topBlockScope: BlockScopeLayer | undefined;
87
97
  readonly topFunctionScope: FunctionScopeLayer | undefined;
88
98
  pushItem(): void;
89
99
  pushSlotBindings(pairs: SlotValuePair[]): void;
@@ -237,8 +247,25 @@ interface ResolutionCtx {
237
247
  * @param name the temporary name to assign to the item (if missing, just returns `callback()`)
238
248
  */
239
249
  withRenamed<T>(item: object, name: string | undefined, callback: () => T): T;
240
- getUniqueName(resource: object): string;
241
- makeNameValid(name: string): string;
250
+ /**
251
+ * @param primer The basis for the unique identifier. Depending on the strategy, or
252
+ * the names already taken, this may be modified to ensure uniqueness.
253
+ * @param scope The scope in which to generate the identifier. 'global' means
254
+ * the identifier is meant to be unique across the entire program, while
255
+ * 'block' means it cannot shadow any existing identifiers visible from
256
+ * within the current block. After the block is popped, any identifiers
257
+ * defined within it are no longer visible.
258
+ * @returns an identifier that is unique within the given scope
259
+ */
260
+ makeUniqueIdentifier(primer: string | undefined, scope: 'global' | 'block'): string;
261
+ isIdentifierTaken(name: string): boolean;
262
+ /**
263
+ * Makes sure the given identifier cannot be generated by {@link makeUniqueIdentifier}
264
+ * within the given scope.
265
+ * @param name The name to reserve
266
+ * @param scope See {@link makeUniqueIdentifier} for a description of the scope parameter.
267
+ */
268
+ reserveIdentifier(name: string, scope: 'global' | 'block'): void;
242
269
  }
243
270
  /**
244
271
  * Houses a method on the symbol '$resolve` that returns a
package/nameRegistry.d.ts DELETED
@@ -1,30 +0,0 @@
1
- //#region src/nameRegistry.d.ts
2
- interface NameRegistry {
3
- /**
4
- * Creates a valid WGSL identifier, each guaranteed to be unique
5
- * in the lifetime of a single resolution process
6
- * (excluding non-global identifiers from popped scopes).
7
- * Should append "_" to primer, followed by some id.
8
- * @param primer Used in the generation process, makes the identifier more recognizable.
9
- * @param global Whether the name should be registered in the global scope (true), or in the current function scope (false)
10
- */
11
- makeUnique(primer: string | undefined, global: boolean): string;
12
- /**
13
- * Creates a valid WGSL identifier.
14
- * Renames identifiers that are WGSL reserved words.
15
- * @param primer Used in the generation process.
16
- *
17
- * @example
18
- * makeValid("notAKeyword"); // "notAKeyword"
19
- * makeValid("struct"); // makeUnique("struct")
20
- * makeValid("struct_1"); // makeUnique("struct_1") (to avoid potential name collisions)
21
- * makeValid("_"); // ERROR (too difficult to make valid to care)
22
- */
23
- makeValid(primer: string): string;
24
- pushFunctionScope(): void;
25
- popFunctionScope(): void;
26
- pushBlockScope(): void;
27
- popBlockScope(): void;
28
- }
29
- //#endregion
30
- export { NameRegistry };