typegpu 0.12.9 → 0.12.10

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.
Files changed (98) hide show
  1. package/common/attachAutoResizer.d.ts +33 -0
  2. package/common/attachAutoResizer.js +83 -0
  3. package/common/index.d.ts +1 -0
  4. package/common/index.js +1 -0
  5. package/common/writeSoA.js +4 -3
  6. package/core/commandEncoder/commandEncoder.d.ts +1 -1
  7. package/core/declare/tgpuDeclare.d.ts +10 -7
  8. package/core/declare/tgpuDeclare.js +25 -10
  9. package/core/function/comptime.d.ts +2 -0
  10. package/core/function/comptime.js +29 -24
  11. package/core/function/createCallableSchema.js +32 -37
  12. package/core/function/dualImpl.js +44 -44
  13. package/core/function/tgpuComputeFn.d.ts +0 -3
  14. package/core/function/tgpuFn.js +4 -4
  15. package/core/function/tgpuFragmentFn.d.ts +1 -1
  16. package/core/function/tgpuVertexFn.d.ts +1 -1
  17. package/core/pipeline/drawState.js +1 -1
  18. package/core/pipeline/webgpuLimitations.js +2 -1
  19. package/core/resolve/externals.js +4 -0
  20. package/core/resolve/namespace.d.ts +4 -0
  21. package/core/resolve/namespace.js +1 -2
  22. package/core/resolve/stitch.js +13 -8
  23. package/core/root/rootTypes.d.ts +40 -36
  24. package/core/slot/accessor.js +1 -1
  25. package/core/texture/texture.d.ts +1 -2
  26. package/core/texture/texture.js +37 -20
  27. package/core/texture/textureFormats.d.ts +4 -3
  28. package/core/texture/textureFormats.js +17 -6
  29. package/core/texture/textureWrite.d.ts +9 -0
  30. package/core/texture/textureWrite.js +21 -0
  31. package/core/unroll/tgpuUnroll.js +2 -4
  32. package/core/vertexLayout/vertexAttribute.d.ts +1 -4
  33. package/core/vertexLayout/vertexLayout.js +11 -30
  34. package/data/alignmentOf.d.ts +1 -1
  35. package/data/alignmentOf.js +5 -12
  36. package/data/array.js +34 -2
  37. package/data/attributes.d.ts +16 -3
  38. package/data/attributes.js +11 -2
  39. package/data/compiledIO.js +2 -2
  40. package/data/dataIO.js +61 -95
  41. package/data/dataTypes.d.ts +0 -2
  42. package/data/dataTypes.js +3 -3
  43. package/data/disarray.js +2 -0
  44. package/data/offsetUtils.js +23 -13
  45. package/data/offsets.js +1 -2
  46. package/data/partialIO.js +2 -3
  47. package/data/ref.js +35 -37
  48. package/data/schemaCallWrapper.js +2 -2
  49. package/data/schemaMemoryLayout.d.ts +6 -1
  50. package/data/schemaMemoryLayout.js +23 -14
  51. package/data/schemasEqual.js +6 -15
  52. package/data/sizeOf.d.ts +1 -1
  53. package/data/sizeOf.js +2 -3
  54. package/data/snippet.d.ts +1 -1
  55. package/data/struct.js +25 -1
  56. package/data/unstruct.js +2 -0
  57. package/data/vectorImpl.js +45 -21
  58. package/data/vertexFormatData.js +7 -9
  59. package/data/wgslTypes.d.ts +27 -12
  60. package/data/wgslTypes.js +33 -39
  61. package/extension.d.ts +0 -4
  62. package/package.json +1 -1
  63. package/resolutionCtx.d.ts +1 -1
  64. package/resolutionCtx.js +26 -7
  65. package/serial/restore.d.ts +1 -1
  66. package/shared/meta.js +1 -1
  67. package/shared/symbols.d.ts +5 -0
  68. package/shared/symbols.js +6 -1
  69. package/shared/utilityTypes.d.ts +0 -6
  70. package/std/bitcast.d.ts +1 -1
  71. package/std/comptime.js +10 -12
  72. package/std/environment.js +2 -4
  73. package/std/matrix.js +5 -5
  74. package/std/numeric.d.ts +1 -0
  75. package/std/numeric.js +35 -1
  76. package/std/typeOf.js +12 -14
  77. package/tgpu.d.ts +1 -1
  78. package/tgpu.js +1 -1
  79. package/tgpuBindGroupLayout.d.ts +6 -3
  80. package/tgpuBindGroupLayout.js +15 -2
  81. package/tgpuUnstableNamespace.d.ts +1 -0
  82. package/tgpuUnstableNamespace.js +5 -0
  83. package/tgsl/accessIndex.js +10 -7
  84. package/tgsl/accessProp.js +5 -57
  85. package/tgsl/consoleLog/types.d.ts +1 -1
  86. package/tgsl/conversion.js +21 -0
  87. package/tgsl/forOfUtils.js +1 -1
  88. package/tgsl/generationHelpers.d.ts +0 -1
  89. package/tgsl/generationHelpers.js +1 -4
  90. package/tgsl/shaderGenerator.d.ts +5 -0
  91. package/tgsl/swizzle.d.ts +24 -0
  92. package/tgsl/swizzle.js +112 -0
  93. package/tgsl/wgslGenerator.d.ts +13 -3
  94. package/tgsl/wgslGenerator.js +149 -151
  95. package/types.d.ts +10 -10
  96. package/types.js +1 -1
  97. package/taskQueue.d.ts +0 -6
  98. package/taskQueue.js +0 -30
@@ -3,6 +3,7 @@ import type { BaseData } from '../data/wgslTypes.ts';
3
3
  import type { ResolvedSnippet, Snippet } from '../data/snippet.ts';
4
4
  import type { VariableScope } from '../core/variable/tgpuVariable.ts';
5
5
  import type { BindableBufferUsage, FunctionArgument, ResolutionCtx, ShaderStage } from '../types.ts';
6
+ import type { AnyFn } from '../core/function/fnTypes.ts';
6
7
  export interface FunctionDefinitionOptions {
7
8
  readonly functionType: 'normal' | ShaderStage;
8
9
  readonly name: string;
@@ -78,6 +79,10 @@ export interface ShaderGenerator {
78
79
  functionDefinition(options: FunctionDefinitionOptions): string;
79
80
  typeInstantiation(schema: BaseData, args: readonly Snippet[]): ResolvedSnippet;
80
81
  numericLiteral(value: number, schema: BaseData): ResolvedSnippet;
82
+ /**
83
+ * Can be used to call arbitrary helper functions during shader generation, e.g. for polifylls.
84
+ */
85
+ call(callee: AnyFn, args: readonly Snippet[]): Snippet;
81
86
  emitTypeAnnotation(schema: BaseData): string;
82
87
  emitCall(name: string, templateParams: readonly Snippet[], args: readonly Snippet[]): string;
83
88
  emitBinaryOp(lhs: Snippet, op: BinaryOperator, rhs: Snippet): string;
@@ -0,0 +1,24 @@
1
+ import type { Origin, ResolvedSnippet, Snippet } from '../data/snippet.ts';
2
+ import { type BaseData } from '../data/wgslTypes.ts';
3
+ import { $comptimeValueOf, $internal, $resolve } from '../shared/symbols.ts';
4
+ import { type ComptimeValue, type ResolutionCtx, type SelfResolvable, type WithComptimeValue } from '../types.ts';
5
+ /**
6
+ * Intermediate representation for vector swizzle access.
7
+ * Vector swizzles create a new vector unless they are assigned to.
8
+ */
9
+ export declare class Swizzle implements SelfResolvable, WithComptimeValue {
10
+ readonly [$internal] = true;
11
+ readonly base: Snippet;
12
+ readonly components: string;
13
+ readonly dataType: BaseData;
14
+ /**
15
+ * This origin only applies when swizzle is NOT assigned to.
16
+ * When assigned to, {@link base}'s origin should be checked instead.
17
+ */
18
+ readonly origin: Origin;
19
+ constructor(base: Snippet, components: string | number);
20
+ toString(): string;
21
+ [$comptimeValueOf](): ComptimeValue;
22
+ [$resolve](ctx: ResolutionCtx): ResolvedSnippet;
23
+ }
24
+ export declare function isValidSwizzle(prop: string): boolean;
@@ -0,0 +1,112 @@
1
+ import { stitch } from "../core/resolve/stitch.js";
2
+ import { bool, f16, f32, i32, u32 } from "../data/numeric.js";
3
+ import { snip } from "../data/snippet.js";
4
+ import { vec2b, vec2f, vec2h, vec2i, vec2u, vec3b, vec3f, vec3h, vec3i, vec3u, vec4b, vec4f, vec4h, vec4i, vec4u, } from "../data/vector.js";
5
+ import { isVec } from "../data/wgslTypes.js";
6
+ import { invariant } from "../errors.js";
7
+ import { $comptimeValueOf, $internal, $resolve } from "../shared/symbols.js";
8
+ import { asComptime, } from "../types.js";
9
+ /**
10
+ * Intermediate representation for vector swizzle access.
11
+ * Vector swizzles create a new vector unless they are assigned to.
12
+ */
13
+ export class Swizzle {
14
+ [$internal] = true;
15
+ base;
16
+ components;
17
+ dataType;
18
+ /**
19
+ * This origin only applies when swizzle is NOT assigned to.
20
+ * When assigned to, {@link base}'s origin should be checked instead.
21
+ */
22
+ origin;
23
+ constructor(base, components) {
24
+ this.base = base;
25
+ this.components = sanitizeComponents(components);
26
+ this.dataType = getDataType(base, this.components.length);
27
+ this.origin =
28
+ this.components.length === 1 // special case, as `vec.x` can have its address taken, unlike `vec.xy`
29
+ ? base.origin
30
+ : base.origin === 'constant' || base.origin === 'constant-immutable-def'
31
+ ? 'constant'
32
+ : 'runtime';
33
+ }
34
+ toString() {
35
+ return 'swizzle';
36
+ }
37
+ [$comptimeValueOf]() {
38
+ const baseComptime = asComptime(this.base);
39
+ if (baseComptime) {
40
+ return {
41
+ comptime: true,
42
+ value: baseComptime.value[this.components],
43
+ };
44
+ }
45
+ return { comptime: false };
46
+ }
47
+ [$resolve](ctx) {
48
+ const comptime = this[$comptimeValueOf]();
49
+ if (comptime.comptime) {
50
+ return ctx.resolveSnippet(snip(comptime.value, this.dataType, this.origin, this.base.possibleSideEffects));
51
+ }
52
+ return ctx.resolveSnippet(snip(stitch `${this.base}.${this.components}`, this.dataType, this.origin, this.base.possibleSideEffects));
53
+ }
54
+ }
55
+ function sanitizeComponents(components) {
56
+ if (typeof components === 'string') {
57
+ if (!isValidSwizzle(components)) {
58
+ throw new Error(`The swizzle '${components}' is invalid.`);
59
+ }
60
+ return components;
61
+ }
62
+ else {
63
+ const component = 'xyzw'[components];
64
+ if (!component) {
65
+ throw new Error(`Cannot index vector with '${components}'.`);
66
+ }
67
+ return component;
68
+ }
69
+ }
70
+ const swizzleLenToType = {
71
+ f: {
72
+ 1: f32,
73
+ 2: vec2f,
74
+ 3: vec3f,
75
+ 4: vec4f,
76
+ },
77
+ h: {
78
+ 1: f16,
79
+ 2: vec2h,
80
+ 3: vec3h,
81
+ 4: vec4h,
82
+ },
83
+ i: {
84
+ 1: i32,
85
+ 2: vec2i,
86
+ 3: vec3i,
87
+ 4: vec4i,
88
+ },
89
+ u: {
90
+ 1: u32,
91
+ 2: vec2u,
92
+ 3: vec3u,
93
+ 4: vec4u,
94
+ },
95
+ b: {
96
+ 1: bool,
97
+ 2: vec2b,
98
+ 3: vec3b,
99
+ 4: vec4b,
100
+ },
101
+ };
102
+ function getDataType(base, length) {
103
+ const baseDataType = base.dataType;
104
+ invariant(isVec(baseDataType));
105
+ const swizzleTypeChar = baseDataType.type.includes('bool')
106
+ ? 'b'
107
+ : baseDataType.type[4];
108
+ return swizzleLenToType[swizzleTypeChar][length];
109
+ }
110
+ export function isValidSwizzle(prop) {
111
+ return prop.length >= 1 && prop.length <= 4 && /^[xyzw]+$|^[rgba]+$/.test(prop);
112
+ }
@@ -22,10 +22,19 @@ export declare class WgslGenerator implements ShaderGenerator {
22
22
  protected _emitSwitchStatement(discriminantExpr: Snippet, groupedCaseExprs: [tests: Snippet[], consequent: ResolvedStatement[]][]): string;
23
23
  protected _callShellless(callee: AnyFn, args: readonly Snippet[]): ResolvedSnippet | undefined;
24
24
  /**
25
- * A wrapper for `generateExpression` that updates `ctx.expectedType`
26
- * and tries to convert the result when it does not match the expected type.
25
+ * A wrapper for `_expression` that updates `ctx.expectedType` while generating.
26
+ * The result is NOT converted to the expected type.
27
27
  */
28
- protected _typedExpression(expression: tinyest.Expression, expectedType: wgsl.BaseData | wgsl.BaseData[]): Snippet;
28
+ protected _expressionWithTypeSuggestion(expression: tinyest.Expression, expectedType: wgsl.BaseData | wgsl.BaseData[]): Snippet;
29
+ /**
30
+ * Like `_expressionWithTypeSuggestion`, but also tries to convert the result
31
+ * when it does not match the expected type.
32
+ */
33
+ protected _expressionWithTypeConversion(expression: tinyest.Expression, expectedType: wgsl.BaseData | wgsl.BaseData[]): Snippet;
34
+ /**
35
+ * @param calleeSnippet The snippet the callee was produced from, used for more descriptive errors.
36
+ */
37
+ call(_callee: AnyFn, args: readonly Snippet[], calleeSnippet?: Snippet): Snippet;
29
38
  protected _expression(expression: tinyest.Expression): Snippet;
30
39
  private _expressionImpl;
31
40
  declareGlobalConst(options: ConstantDefinitionOptions): ResolvedSnippet;
@@ -70,4 +79,5 @@ export declare class WgslGenerator implements ShaderGenerator {
70
79
  * tryMarkModified('this.buffer.$') // `this` is not marked, since there is no placeholder for it
71
80
  */
72
81
  private tryMarkModified;
82
+ private validateSnippetMutation;
73
83
  }
@@ -8,14 +8,15 @@ import { fallthroughCopyOrigin, isMutableOrigin, isStoredInMemory, snip, } from
8
8
  import * as wgsl from "../data/wgslTypes.js";
9
9
  import { invariant, ResolutionError, WgslForbiddenStatementError, WgslTypeError, } from "../errors.js";
10
10
  import { getName } from "../shared/meta.js";
11
- import { $gpuCallable, $internal, $providing, isMarkedInternal } from "../shared/symbols.js";
11
+ import { $gpuCallable, $gpuCallableStrictSignature, $internal, $providing, isMarkedInternal, } from "../shared/symbols.js";
12
12
  import { safeStringify } from "../shared/stringify.js";
13
- import { pow } from "../std/numeric.js";
13
+ import { powOperator } from "../std/numeric.js";
14
14
  import { add, div, mul, neg, sub } from "../std/operators.js";
15
15
  import { eq, ne, lt, le, gt, ge, not } from "../std/boolean.js";
16
16
  import { asComptime, isConstant, isGPUCallable, } from "../types.js";
17
17
  import { convertStructValues, convertToCommonType, tryConvertSnippet } from "./conversion.js";
18
18
  import { ArrayExpression, coerceToSnippet, concretize, numericLiteralToSnippet, } from "./generationHelpers.js";
19
+ import { Swizzle } from "./swizzle.js";
19
20
  import { accessIndex } from "./accessIndex.js";
20
21
  import { accessProp } from "./accessProp.js";
21
22
  import { resolveData } from "../core/resolve/resolveData.js";
@@ -29,7 +30,7 @@ import { mathToStd, supportedLogOps } from "./jsPolyfills.js";
29
30
  import * as forOfUtils from "./forOfUtils.js";
30
31
  import { isTgpuRange } from "../std/range.js";
31
32
  import { stringifyNode, stringifyObjectProperty } from "../shared/tseynit.js";
32
- import { setSourceNode, stringifySnippet } from "./stringifySnippet.js";
33
+ import { getSourceNode, setSourceNode, stringifySnippet } from "./stringifySnippet.js";
33
34
  import { getAttributesString } from "../data/attributes.js";
34
35
  import { validSelectBranchTypes } from "../std/boolean.js";
35
36
  import { isInfixDispatch } from "./infixDispatch.js";
@@ -122,7 +123,7 @@ function operatorToType(lhs, op, rhs) {
122
123
  return lhs;
123
124
  }
124
125
  const unaryOpCodeToCodegen = {
125
- '-': neg[$gpuCallable].call.bind(neg),
126
+ '-': neg[$gpuCallable].bind(neg),
126
127
  void: () => snip(undefined, wgsl.Void, 'constant', false),
127
128
  '!': (ctx, [argExpr]) => {
128
129
  if (argExpr === undefined) {
@@ -142,11 +143,11 @@ const unaryOpCodeToCodegen = {
142
143
  },
143
144
  };
144
145
  const binaryOpCodeToCodegen = {
145
- '+': add[$gpuCallable].call.bind(add),
146
- '-': sub[$gpuCallable].call.bind(sub),
147
- '*': mul[$gpuCallable].call.bind(mul),
148
- '/': div[$gpuCallable].call.bind(div),
149
- '**': pow[$gpuCallable].call.bind(pow),
146
+ '+': add[$gpuCallable].bind(add),
147
+ '-': sub[$gpuCallable].bind(sub),
148
+ '*': mul[$gpuCallable].bind(mul),
149
+ '/': div[$gpuCallable].bind(div),
150
+ '**': powOperator[$gpuCallable].bind(powOperator),
150
151
  };
151
152
  const usageToVarTemplateMap = {
152
153
  private: 'private',
@@ -339,26 +340,102 @@ export class WgslGenerator {
339
340
  return shelllessCall;
340
341
  }
341
342
  /**
342
- * A wrapper for `generateExpression` that updates `ctx.expectedType`
343
- * and tries to convert the result when it does not match the expected type.
343
+ * A wrapper for `_expression` that updates `ctx.expectedType` while generating.
344
+ * The result is NOT converted to the expected type.
344
345
  */
345
- _typedExpression(expression, expectedType) {
346
+ _expressionWithTypeSuggestion(expression, expectedType) {
346
347
  const prevExpectedType = this.ctx.expectedType;
347
348
  this.ctx.expectedType = expectedType;
348
349
  try {
349
- const result = this._expression(expression);
350
- if (expectedType instanceof AutoStruct) {
351
- // We provide a certain AutoStruct object to later
352
- // investigate what props were accessed. No need to
353
- // convert the result.
354
- return result;
355
- }
356
- return setSourceNode(tryConvertSnippet(this.ctx, result, expectedType), expression);
350
+ return this._expression(expression);
357
351
  }
358
352
  finally {
359
353
  this.ctx.expectedType = prevExpectedType;
360
354
  }
361
355
  }
356
+ /**
357
+ * Like `_expressionWithTypeSuggestion`, but also tries to convert the result
358
+ * when it does not match the expected type.
359
+ */
360
+ _expressionWithTypeConversion(expression, expectedType) {
361
+ const result = this._expressionWithTypeSuggestion(expression, expectedType);
362
+ if (expectedType instanceof AutoStruct) {
363
+ // We provide a certain AutoStruct object to later
364
+ // investigate what props were accessed. No need to
365
+ // convert the result.
366
+ return result;
367
+ }
368
+ return setSourceNode(tryConvertSnippet(this.ctx, result, expectedType), expression);
369
+ }
370
+ /**
371
+ * @param calleeSnippet The snippet the callee was produced from, used for more descriptive errors.
372
+ */
373
+ call(_callee, args, calleeSnippet) {
374
+ const callee = mathToStd.get(_callee) ?? _callee;
375
+ if (supportedLogOps().includes(callee)) {
376
+ return this.ctx.generateLog(callee, args);
377
+ }
378
+ if (callee === constant) {
379
+ throw new Error('Constants cannot be defined within TypeGPU function scope. To address this, move the constant definition outside the function scope.');
380
+ }
381
+ if (isInfixDispatch(callee)) {
382
+ if (!args[0]) {
383
+ throw new WgslTypeError(`An infix operator '${getName(callee.operator)}' was called without any arguments`);
384
+ }
385
+ const lhs = coerceToSnippet(callee.lhs);
386
+ const rhs = args[0];
387
+ return callee.operator[$gpuCallable](this.ctx, [lhs, rhs]);
388
+ }
389
+ if (isGPUCallable(callee)) {
390
+ const strictSignature = callee[$gpuCallableStrictSignature];
391
+ let convertedArguments;
392
+ if (strictSignature) {
393
+ // The function's signature does not depend on the context, so it can be used to
394
+ // give a hint to the argument expressions that a specific type is expected.
395
+ convertedArguments = args.map((arg, i) => {
396
+ const argType = strictSignature.argTypes[i];
397
+ if (!argType) {
398
+ return arg;
399
+ }
400
+ const converted = tryConvertSnippet(this.ctx, arg, argType);
401
+ const sourceNode = getSourceNode(arg);
402
+ return sourceNode !== undefined ? setSourceNode(converted, sourceNode) : converted;
403
+ });
404
+ }
405
+ else {
406
+ convertedArguments = args;
407
+ }
408
+ try {
409
+ return callee[$gpuCallable](this.ctx, convertedArguments);
410
+ }
411
+ catch (err) {
412
+ if (err instanceof ResolutionError) {
413
+ throw err;
414
+ }
415
+ throw new ResolutionError(err, [
416
+ {
417
+ toString: () => `fn:${getName(callee)}`,
418
+ },
419
+ ]);
420
+ }
421
+ }
422
+ if (!isMarkedInternal(callee) || isGenericFn(callee)) {
423
+ const result = this._callShellless(callee, args);
424
+ if (result) {
425
+ return result;
426
+ }
427
+ }
428
+ // try to throw a descriptive error
429
+ const maybeMathMethod = Object.getOwnPropertyNames(Math).find((prop) => Math[prop] === callee);
430
+ if (maybeMathMethod) {
431
+ throw new Error(`Unsupported Math functionality 'Math.${maybeMathMethod}()'. Use an std alternative, or implement the function manually.`);
432
+ }
433
+ const maybeConsoleMethod = Object.getOwnPropertyNames(console).find((prop) => console[prop] === callee);
434
+ if (maybeConsoleMethod) {
435
+ throw new Error(`Unsupported console functionality 'console.${maybeConsoleMethod}()'.`);
436
+ }
437
+ throw new Error(`Function '${getName(callee) ?? (calleeSnippet ? stringifySnippet(calleeSnippet) : String(callee))}' is not marked with the 'use gpu' directive and cannot be used in a shader`);
438
+ }
362
439
  _expression(expression) {
363
440
  // Remembering which JS expression produced the snippet, for more descriptive errors
364
441
  return setSourceNode(this._expressionImpl(expression), expression);
@@ -499,7 +576,7 @@ export class WgslGenerator {
499
576
  }
500
577
  const type = operatorToType(convLhs.dataType, op, convRhs.dataType);
501
578
  if (exprType === NODE.assignmentExpr) {
502
- validateSnippetMutation(convLhs, expression);
579
+ this.validateSnippetMutation(convLhs, expression);
503
580
  this.tryMarkModified(lhs);
504
581
  // Compound assignment operators are okay, e.g. +=, -=, *=, /=, ...
505
582
  if (op === '=' &&
@@ -570,125 +647,36 @@ export class WgslGenerator {
570
647
  const type = typeof expression[1] === 'string'
571
648
  ? numericLiteralToSnippet(parseNumericString(expression[1]))
572
649
  : numericLiteralToSnippet(expression[1]);
573
- invariant(type, `Expected ${stringifyNode(expression)} to be valid numeric literal`);
650
+ invariant(type, () => `Expected ${stringifyNode(expression)} to be valid numeric literal`);
574
651
  return type;
575
652
  }
576
653
  if (expression[0] === NODE.call) {
577
654
  // Function Call
578
655
  const [_, calleeNode, argNodes] = expression;
579
656
  const _callee = this._expression(calleeNode);
580
- const callee = mathToStd.has(_callee.value)
581
- ? snip(mathToStd.get(_callee.value), UnknownData, 'runtime', _callee.possibleSideEffects)
582
- : _callee;
583
- if (supportedLogOps().includes(callee.value)) {
584
- return this.ctx.generateLog(callee.value, argNodes.map((arg) => this._expression(arg)));
585
- }
586
- if (wgsl.isWgslStruct(callee.value)) {
587
- // Struct schema call.
588
- if (argNodes.length > 1) {
589
- throw new WgslTypeError('Struct schemas should always be called with at most 1 argument');
590
- }
591
- // No arguments `Struct()`, resolve struct name and return.
592
- if (!argNodes[0]) {
593
- // The schema becomes the data type.
594
- return snip(`${this.ctx.resolve(callee.value).value}()`, callee.value,
595
- // A new struct, so not a reference.
596
- /* origin */ 'runtime', false);
597
- }
598
- const arg = this._typedExpression(argNodes[0], callee.value);
599
- // Either `Struct({ x: 1, y: 2 })`, or `Struct(otherStruct)`.
600
- // In both cases, we just let the argument resolve everything.
601
- return snip(this.ctx.resolveSnippet(arg).value, callee.value,
602
- // A new struct, so not a reference.
603
- /* origin */ 'runtime', arg.possibleSideEffects);
604
- }
605
- if (wgsl.isWgslArray(callee.value)) {
606
- // Array schema call.
607
- if (argNodes.length > 1) {
608
- throw new WgslTypeError('Array schemas should always be called with at most 1 argument');
609
- }
610
- // No arguments `array<...>()`, resolve array type and return.
611
- if (!argNodes[0]) {
612
- // The schema becomes the data type.
613
- return this.typeInstantiation(callee.value, []);
614
- }
615
- const arg = this._typedExpression(argNodes[0], callee.value);
616
- // `d.arrayOf(...)([...])`.
617
- // We don't resolve the ArrayExpression object itself to
618
- // avoid reference checks (we're copying so it's fine)
619
- if (arg.value instanceof ArrayExpression) {
620
- return this.typeInstantiation(callee.value, arg.value.elements);
621
- }
622
- // `d.arrayOf(...)(otherArr)`.
623
- // We just let the argument resolve everything.
624
- return snip(this.ctx.resolveSnippet(arg).value, callee.value,
625
- // A new array, so not a reference.
626
- /* origin */ fallthroughCopyOrigin(arg.origin), arg.possibleSideEffects);
627
- }
628
- if (callee.value === constant) {
629
- throw new Error('Constants cannot be defined within TypeGPU function scope. To address this, move the constant definition outside the function scope.');
630
- }
631
- if (isInfixDispatch(callee.value)) {
632
- if (!argNodes[0]) {
633
- throw new WgslTypeError(`An infix operator '${getName(callee.value.operator)}' was called without any arguments`);
634
- }
635
- const lhs = coerceToSnippet(callee.value.lhs);
636
- const rhs = this._expression(argNodes[0]);
637
- const callable = callee.value.operator[$gpuCallable];
638
- return callable.call(this.ctx, [lhs, rhs]);
639
- }
640
- if ((callee.value === _ref || callee.value === unroll) && argNodes[0]) {
657
+ const callee = mathToStd.get(_callee.value) ?? _callee.value;
658
+ if ((callee === _ref || callee === unroll) && argNodes[0]) {
641
659
  this.tryMarkModified(argNodes[0]);
642
660
  }
643
- if (isGPUCallable(callee.value)) {
644
- const callable = callee.value[$gpuCallable];
645
- const strictSignature = callable.strictSignature;
646
- let convertedArguments;
647
- if (strictSignature) {
648
- // The function's signature does not depend on the context, so it can be used to
649
- // give a hint to the argument expressions that a specific type is expected.
650
- convertedArguments = argNodes.map((arg, i) => {
651
- const argType = strictSignature.argTypes[i];
652
- if (!argType) {
653
- throw new WgslTypeError(`Call '${stringifyNode(expression)}' is invalid since the function expected fewer arguments`);
654
- }
655
- return this._typedExpression(arg, argType);
656
- });
657
- }
658
- else {
659
- convertedArguments = argNodes.map((arg) => this._expression(arg));
660
- }
661
- try {
662
- return callable.call(this.ctx, convertedArguments);
663
- }
664
- catch (err) {
665
- if (err instanceof ResolutionError) {
666
- throw err;
661
+ let args;
662
+ if (isGPUCallable(callee) && callee[$gpuCallableStrictSignature]) {
663
+ const strictSignature = callee[$gpuCallableStrictSignature];
664
+ // The function's signature does not depend on the context, so it can be used to
665
+ // give a hint to the argument expressions that a specific type is expected.
666
+ args = argNodes.map((arg, i) => {
667
+ const argType = strictSignature.argTypes[i];
668
+ if (!argType) {
669
+ const length = strictSignature.argTypes.length;
670
+ throw new WgslTypeError(`Call '${stringifyNode(expression)}' is invalid, the function expected at most ${length} argument${length === 1 ? '' : 's'}`);
667
671
  }
668
- throw new ResolutionError(err, [
669
- {
670
- toString: () => `fn:${getName(callee.value)}`,
671
- },
672
- ]);
673
- }
674
- }
675
- if (!isMarkedInternal(callee.value) || isGenericFn(callee.value)) {
676
- const args = argNodes.map((arg) => this._expression(arg));
677
- const result = this._callShellless(callee.value, args);
678
- if (result) {
679
- return result;
680
- }
681
- }
682
- // try to throw a descriptive error
683
- const maybeMathMethod = Object.getOwnPropertyNames(Math).find((prop) => Math[prop] === callee.value);
684
- if (maybeMathMethod) {
685
- throw new Error(`Unsupported Math functionality 'Math.${maybeMathMethod}()'. Use an std alternative, or implement the function manually.`);
672
+ // It's only a suggestion, the conversion happens later on
673
+ return this._expressionWithTypeSuggestion(arg, argType);
674
+ });
686
675
  }
687
- const maybeConsoleMethod = Object.getOwnPropertyNames(console).find((prop) => console[prop] === callee.value);
688
- if (maybeConsoleMethod) {
689
- throw new Error(`Unsupported console functionality 'console.${maybeConsoleMethod}()'.`);
676
+ else {
677
+ args = argNodes.map((arg) => this._expression(arg));
690
678
  }
691
- throw new Error(`Function '${getName(callee.value) ?? stringifySnippet(callee)}' is not marked with the 'use gpu' directive and cannot be used in a shader`);
679
+ return this.call(callee, args, _callee);
692
680
  }
693
681
  if (expression[0] === NODE.objectExpr) {
694
682
  // Normalize to `objectProperty[]`
@@ -714,7 +702,7 @@ export class WgslGenerator {
714
702
  let expr;
715
703
  if (accessed) {
716
704
  // Generating the expression expecting a specific type
717
- expr = this._typedExpression(value, accessed.type);
705
+ expr = this._expressionWithTypeConversion(value, accessed.type);
718
706
  }
719
707
  else {
720
708
  // Generating the expression and inferring the type instead
@@ -750,7 +738,7 @@ The generated shader will omit it, so its runtime side effects will not occur.`)
750
738
  }
751
739
  continue;
752
740
  }
753
- const expr = this._typedExpression(value, propType);
741
+ const expr = this._expressionWithTypeConversion(value, propType);
754
742
  entries[key] = expr;
755
743
  if (expr.possibleSideEffects) {
756
744
  keysWithSideEffectsInSourceOrder.push(key);
@@ -787,7 +775,7 @@ The generated shader will evaluate them in declaration order.`);
787
775
  if (wgsl.isWgslArray(arrType)) {
788
776
  elemType = arrType.elementType;
789
777
  // The array is typed, so its elements should be as well.
790
- values = valueNodes.map((value) => this._typedExpression(value, elemType));
778
+ values = valueNodes.map((value) => this._expressionWithTypeConversion(value, elemType));
791
779
  // Since it's an expected type, we enforce the length
792
780
  if (values.length !== arrType.elementCount) {
793
781
  throw new WgslTypeError(`Cannot create value of type '${arrType}' from an array of length: ${values.length}`);
@@ -880,13 +868,12 @@ The generated shader will evaluate them in declaration order.`);
880
868
  let body = this._block(options.body, /* allowInlining */ false);
881
869
  const scope = this.ctx.topFunctionScope;
882
870
  invariant(scope, 'Expected function scope to be present');
883
- const replacements = Object.fromEntries([...scope.placeholderForVariable.entries()].map(([variable, placeholder]) => [
884
- placeholder,
885
- scope.modifiedVariables.has(variable) ? 'var' : 'let',
886
- ]));
887
- if (Object.keys(replacements).length > 0) {
888
- const regex = new RegExp(Object.keys(replacements).join('|'), 'gi');
889
- body.code = body.code.replace(regex, (match) => replacements[match] ?? '#ERR');
871
+ if (scope.placeholderForVariable.size > 0) {
872
+ const keywordForPlaceholder = new Map();
873
+ for (const [variable, placeholder] of scope.placeholderForVariable) {
874
+ keywordForPlaceholder.set(placeholder, scope.modifiedVariables.has(variable) ? 'var' : 'let');
875
+ }
876
+ body.code = body.code.replace(/#VAR_\d+#/g, (match) => keywordForPlaceholder.get(match) ?? '#ERR');
890
877
  }
891
878
  // Only after generating the body can we determine the return type
892
879
  const returnType = options.determineReturnType();
@@ -978,7 +965,7 @@ The generated shader will evaluate them in declaration order.`);
978
965
  if (returnNode !== undefined) {
979
966
  const expectedReturnType = this.ctx.topFunctionReturnType;
980
967
  let returnSnippet = expectedReturnType
981
- ? this._typedExpression(returnNode, expectedReturnType)
968
+ ? this._expressionWithTypeConversion(returnNode, expectedReturnType)
982
969
  : this._expression(returnNode);
983
970
  if (returnSnippet.value === undefined && wgsl.isVoid(returnSnippet.dataType)) {
984
971
  this.ctx.reportReturnType(wgsl.Void);
@@ -1213,10 +1200,11 @@ Try 'return ${typeStr}(${str});' instead.
1213
1200
  }
1214
1201
  if (statement[0] === NODE.if) {
1215
1202
  const [_, condNode, consNode, altNode] = statement;
1216
- const condition = this._typedExpression(condNode, bool);
1217
- if (typeof condition.value === 'boolean') {
1203
+ const condition = this._expressionWithTypeConversion(condNode, bool);
1204
+ const comptimeCondition = asComptime(condition);
1205
+ if (typeof comptimeCondition?.value === 'boolean') {
1218
1206
  // the condition is known at comptime
1219
- let node = condition.value ? consNode : altNode;
1207
+ let node = comptimeCondition.value ? consNode : altNode;
1220
1208
  if (node === undefined) {
1221
1209
  return { code: '', definesInNearestScope: false };
1222
1210
  }
@@ -1268,7 +1256,7 @@ ${this.ctx.pre}else ${alternate}`,
1268
1256
  this.ctx.pushBlockScope();
1269
1257
  const [initStatement, conditionExpr, updateStatement] = this.ctx.withResetIndentLevel(() => [
1270
1258
  init ? this._statement(init).code : undefined,
1271
- condition ? this._typedExpression(condition, bool) : undefined,
1259
+ condition ? this._expressionWithTypeConversion(condition, bool) : undefined,
1272
1260
  update ? this._statement(update).code : undefined,
1273
1261
  ]);
1274
1262
  const initStr = initStatement ? initStatement.slice(0, -1) : '';
@@ -1289,7 +1277,7 @@ ${this.ctx.pre}else ${alternate}`,
1289
1277
  this.#unrollingChain = [];
1290
1278
  try {
1291
1279
  const [_, condition, body] = statement;
1292
- const condSnippet = this._typedExpression(condition, bool);
1280
+ const condSnippet = this._expressionWithTypeConversion(condition, bool);
1293
1281
  const conditionStr = this.ctx.resolveSnippet(condSnippet).value;
1294
1282
  const bodyStr = this._block(blockifySingleStatement(body), /* allowInlining */ false).code;
1295
1283
  return {
@@ -1504,7 +1492,7 @@ ${stringifyNode(statement)}`);
1504
1492
  const [_, op, arg] = statement;
1505
1493
  const argExpr = this._expression(arg);
1506
1494
  const argStr = this.ctx.resolveSnippet(argExpr).value;
1507
- validateSnippetMutation(argExpr, statement);
1495
+ this.validateSnippetMutation(argExpr, statement);
1508
1496
  this.tryMarkModified(arg);
1509
1497
  return { code: `${this.ctx.pre}${argStr}${op};`, definesInNearestScope: false };
1510
1498
  }
@@ -1585,6 +1573,17 @@ ${stringifyNode(statement)}`);
1585
1573
  }
1586
1574
  }
1587
1575
  }
1576
+ validateSnippetMutation(mutated, expr) {
1577
+ if (mutated.value instanceof Swizzle) {
1578
+ if (mutated.value.base.value instanceof Swizzle) {
1579
+ throw new Error(`'${stringifyNode(expr)}' is invalid. Nested swizzle mutation is disallowed for JS consistency.`);
1580
+ }
1581
+ throwIfImmutable(mutated.value.base.origin, expr, asComptime(mutated.value.base) !== undefined);
1582
+ }
1583
+ else {
1584
+ throwIfImmutable(mutated.origin, expr, asComptime(mutated) !== undefined);
1585
+ }
1586
+ }
1588
1587
  }
1589
1588
  const immutabilityReasons = {
1590
1589
  constant: 'the left side is a constant',
@@ -1596,14 +1595,13 @@ const immutabilityReasons = {
1596
1595
  argument: 'non-pointer arguments cannot be mutated',
1597
1596
  handle: 'textures and samplers cannot be mutated',
1598
1597
  };
1599
- function validateSnippetMutation(mutated, expr) {
1600
- if (isMutableOrigin(mutated.origin)) {
1598
+ function throwIfImmutable(origin, expr, knownAtComptime) {
1599
+ if (isMutableOrigin(origin)) {
1601
1600
  return;
1602
1601
  }
1603
- const reason = asComptime(mutated)
1602
+ const reason = knownAtComptime
1604
1603
  ? 'the left side is immutable during shader execution. Try using tgpu.privateVar or buffers'
1605
- : (immutabilityReasons[mutated.origin] ??
1606
- 'the left side is not a reference to an existing value');
1604
+ : (immutabilityReasons[origin] ?? 'the left side is not a reference to an existing value');
1607
1605
  throw new WgslTypeError(`'${stringifyNode(expr)}' is invalid, because ${reason}.`);
1608
1606
  }
1609
1607
  function assertExhaustive(value) {