software-mansion / software-mansion/TypeGPU

[RFC] impr: Weak type checking on binary expression operands

Open
#2,645 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
3.2k
Forks
123
Avg merge
3d 5h
Merged PRs (30d)
34

Description

It all comes down to this list:

const parenthesizedOps = [
  '==',
  '!=',
  '===',
  '!==',
  '<',
  '<=',
  '>',
  '>=',
  '<<',
  '>>',
  '+',
  '-',
  '*',
  '/',
  '%',
  '|',
  '^',
  '&',
  '&&',
  '||',
];

Currently, we don't really check the types of the operands. For example:

 const eq = tgpu.fn([Boid, BoidOnSteroids])((x, y) => {
  'use gpu';
  const r = x === y;
});

will happily compile.

Right now, we rely on the fact that wgsl compiler will throw a descriptive error.
I was fine with this approach for a long time, but...

No 1.
const x = d.vec3f();
const y = x;

const eq = () => {
  'use gpu';
  const _r = x === y;
};

The above function will inline true in place of the equality comparison.
However, if x and y were runtime known values, the return type of the function would have been d.vec3b (since that't how wgsl treats == between vectors).

No 2.

Delegating error handling to the wgsl compiler quickly makes things difficult to debug.
For instance, out ternary operator polyfill uses select underneath. It does not check if the condition operand can be converted to a boolean, it assumes that typescript will prevent users from doing so.

While typescript sometimes catches this, an equality comparison between runtime known vectors results in boolean vector. This completely changes the behavior of select. Furthermore, users end up with no idea why there is a type mismatch in a select expression they didn't even use.

No 3.

Conceptually, the wgsl generator should always produce valid code.


Proposition:

Strictly check operand types to closely match the wgsl specification.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing how binary expressions are type-checked and generated, then inspect the ternary operator polyfill's use of select. Compare operand rules with the WGSL specification and the examples in the issue. Done means invalid operand combinations are rejected before generation and diagnostics no longer surface misleading select errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.