Skip to content

aliased-mut ​

One call that lends a value with mut(x) and also gets x, a part of it, or what holds it, through another argument or as the receiver of a method; or two loans of one object alive at once, or the owner writing it while it is lent, because an async call still holds the loan until its promise settles. On by default, as an error.

Why: a Mut parameter promises the function that, while it runs, it is the only way to that object. Rust refuses a second way in: two &mut of one value (E0499), or a &mut and a & of it (E0502). In JavaScript nothing refuses it, and the function goes wrong quietly: a transfer from an account to itself writes the second balance over the first and creates money, and a loop over items that pushes into cart.items never ends when items is cart.items. TypeScript can't see it: both arguments have the right types. Guide: State without globals.

✕ Rejectedaliased-mut
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Account = { balance: number };
type Cart = { items: string[] };

function transfer(from: Mut<Account>, to: Mut<Account>, amount: number): void {
  const next = from.balance - amount;
  to.balance += amount;
  from.balance = next;
}

function addAll(cart: Mut<Cart>, items: readonly string[]): void {
  for (const item of items) cart.items.push(`${item}!`);
}

export function rebalance(account: Mut<Account>, cart: Mut<Cart>): void {
  transfer(mut(account), mut(account), 5);
  addAll(mut(cart), cart.items);
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Account = { balance: number };
type Cart = { items: string[] };

function transfer(from: Mut<Account>, to: Mut<Account>, amount: number): void {
  const next = from.balance - amount;
  to.balance += amount;
  from.balance = next;
}

function addAll(cart: Mut<Cart>, items: readonly string[]): void {
  for (const item of items) cart.items.push(`${item}!`);
}

export function rebalance(account: Mut<Account>, cart: Mut<Cart>): void {
  transfer(account, account, 5);
  addAll(cart, cart.items);
}

✅ Accepted: one way to each object, or a copy of what is only read

✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Account = { balance: number };
type Cart = { items: string[] };

function transfer(from: Mut<Account>, to: Mut<Account>, amount: number): void {
  const next = from.balance - amount;
  to.balance += amount;
  from.balance = next;
}

function addAll(cart: Mut<Cart>, items: readonly string[]): void {
  for (const item of items) cart.items.push(`${item}!`);
}

export function rebalance(from: Mut<Account>, to: Mut<Account>, cart: Mut<Cart>): void {
  transfer(mut(from), mut(to), 5);
  transfer(mut(from), mut(to), from.balance);
  addAll(mut(cart), [...cart.items]);
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Account = { balance: number };
type Cart = { items: string[] };

function transfer(from: Mut<Account>, to: Mut<Account>, amount: number): void {
  const next = from.balance - amount;
  to.balance += amount;
  from.balance = next;
}

function addAll(cart: Mut<Cart>, items: readonly string[]): void {
  for (const item of items) cart.items.push(`${item}!`);
}

export function rebalance(from: Mut<Account>, to: Mut<Account>, cart: Mut<Cart>): void {
  transfer(from, to, 5);
  transfer(from, to, from.balance);
  addAll(cart, [...cart.items]);
}

What it reports ​

Paths are compared as written, through const names for them (const items = cart.items, const { items } = cart): a loan of x with another argument x, a part of it (x.items) or what holds it (mut(x.items) and x), two loans that overlap (mut(state) and mut(state.buckets)), and a method call whose receiver holds the loan (cart.addAll(mut(cart.items))).

A part that is a primitive isn't reported: the call gets a copy of it, read before the call runs, so nothing the function changes through the loan changes what it was given (as in transfer(mut(a), mut(b), a.balance), setPlan(mut(world), world.tick) and setDepth(mut(gl), gl.LEQUAL)). A primitive is a number, a string, a boolean, a bigint, a symbol, a literal, an enum, or a union of them. The member's declared type decides, followed across files, from a parameter, a local or this, and through const names for the path (const { LEQUAL } = gl, const ctx = this.ctx): a type alias, an interface, a class field or a parameter property, a field or an object member set to a literal without a type (retries: 3), and a getter's declared return type. A getter's value is a copy too: it is read when the argument is, before the call. .length and .size aren't reported either.

A member of a type of TypeScript's lib (WebGL2RenderingContext, Node, KeyboardEvent) written in two or more capitals (gl.LEQUAL, gl.ARRAY_BUFFER, node.ELEMENT_NODE) is one of its constants: lib declares every such property as a number or a string, which a test of the checker holds against the lib files. Other members of a lib type aren't settled (gl.canvas, an object, and gl.drawingBufferWidth, a number, alike), nor a type the program declares or augments (declare global { interface Window { ... } }), whose declaration decides.

A part whose type the declarations don't settle is reported on a path from this (this.ctx.gl.canvas), and isn't on a path from a parameter or a local.

Loans alive at once ​

A call that lends x to an async function holds the loan until its promise settles. While it waits, other code runs: if that code lends x again, or writes it, and the callee writes x after its await, one write lands on the other: an update is lost, or an older answer covers a newer one. Rust refuses both: two &mut at once (E0499), or an assignment to what is borrowed (E0506). The checker follows each loan on the function's paths (how the checker follows paths), from the call that gets it to where its promise is awaited: directly, through Promise.all or allSettled, through a list, a Set or a Map it was put into (await Promise.all(pending)), through a local or a field it was kept in. Reported, on some path:

  • x, a part of it or what holds it lent again while a loan of it is alive: in the same Promise.all([...]) (also race, any), after const p = save(mut(x)) and before await p, when p is awaited on one branch only, on the next round of a loop that keeps the promises in a list, or after a promise that is dropped (void save(mut(x))) or handed to another call;
  • the owner writing x (or a part of it) while a loan of it is alive (ledger.total = 0 between const q = add(mut(ledger)) and await q);
  • each callback of items.map(async (item) => ...) (also forEach, flatMap) that lends an object it didn't make, and one that isn't async and returns the call (ids.map(() => add(mut(ledger)))): map starts every call before any is awaited, whoever collects the list (Promise.all, a for...of that awaits each, nothing);
  • runs of the same code that overlap: a listener or an interval (on, addEventListener, setInterval, a JSX on... prop, an on... field assigned) that lends state it doesn't own (a field of this, module state, a local it captured) to a call it waits for or drops: the next event comes while the call before still holds the loan. A method or function that returns while such a loan is alive (the promise kept in a field, dropped, handed on): its next call lends the place again;
  • a loan that outlives the function: a function that returns while a call it lent its own parameter to still holds the loan (function start(ledger: Mut<Ledger>) { void add(mut(ledger)); }): its caller lends the object again, taking the loan to have ended;
  • on every way out, an exception too: the same loan (and one of a place a method or a listener outlives) still held where the function leaves by an exception between the lend and its await: a throw of its own, a call that throws (a function of the program that throws or propagates a PropagateError, by every receiver form the whole-program pass resolves, a built-in or a package's member the packs mark as throwing, a throw in a callback a call runs right away), an await that rejects (await other(); await p;), another member of the Promise.all the loan is awaited in rejecting first (await Promise.all([save(mut(doc)), upload()]): the await throws while save still runs), and a catch that returns after one of these. A call or an await counts only where the whole-program pass finds it can fail; an await of something that isn't a call (a promise a parameter holds) may always reject. A finally that awaits the loan ends it on that way out too.

Only callees that hold the loan across an await. A finding needs the callee to write the loan (or a part of it), or lend it on, after an await on some path: itself, in an async callback that captures it, or in a call it lends the loan on to. That includes a write of the call's own answer (doc.title = await fetchTitle(id)): with two calls alive at once, the older answer may land on top of the newer one. It includes updates that commute (total += 1, a push of the call's own item) too: on an adopter's code, one finding in 54 rested on one alone, too few to make an exception of. A callee that is done with the loan before its first await, never waits, or only reads the loan after waiting loses nothing to an overlap, and isn't reported (the same-block and Promise.all cases were reported before whatever the callee did). A callee the checker can't name (a parameter of function type, a package's function) is taken to hold it when the code shows its result is a promise (awaited, .then, void, in a Promise.all). When a site conflicts with several loans, the finding names the one still alive first; one finding per alive loan names the lines of the others.

❌ Rejected: two loans alive at once on some path

✕ Rejectedaliased-mut
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Ledger = { total: number };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

export async function addAll(ledger: Mut<Ledger>, ids: readonly string[]): Promise<void> {
  const pending: Promise<void>[] = [];
  for (const _ of ids) pending.push(addOne(mut(ledger)));
  await Promise.all(pending);
}

export async function maybeFirst(ledger: Mut<Ledger>, urgent: boolean): Promise<void> {
  const first = addOne(mut(ledger));
  if (urgent) await first;
  await addOne(mut(ledger));
  await first;
}

export async function reset(ledger: Mut<Ledger>): Promise<void> {
  const pending = addOne(mut(ledger));
  ledger.total = 0;
  await pending;
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Ledger = { total: number };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

export async function addAll(ledger: Mut<Ledger>, ids: readonly string[]): Promise<void> {
  const pending: Promise<void>[] = [];
  for (const _ of ids) pending.push(addOne(ledger));
  await Promise.all(pending);
}

export async function maybeFirst(ledger: Mut<Ledger>, urgent: boolean): Promise<void> {
  const first = addOne(ledger);
  if (urgent) await first;
  await addOne(ledger);
  await first;
}

export async function reset(ledger: Mut<Ledger>): Promise<void> {
  const pending = addOne(ledger);
  ledger.total = 0;
  await pending;
}

❌ Rejected: an exception leaves before the loan's await

✕ Rejectedaliased-mut
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Refused extends PropagateError {}

type Doc = { saved: boolean };

async function save(doc: Mut<Doc>): Promise<void> {
  await Promise.resolve();
  doc.saved = true;
}

function admit(n: number): void {
  if (n < 0) throw new Refused("refused");
}

async function upload(n: number): Promise<void> {
  await Promise.resolve();
  admit(n);
}

export async function store(doc: Mut<Doc>, n: number): Promise<void> {
  const pending = save(mut(doc));
  admit(n);
  await pending;
}

export async function storeBoth(doc: Mut<Doc>, n: number): Promise<void> {
  await Promise.all([save(mut(doc)), upload(n)]);
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Refused extends PropagateError {}

type Doc = { saved: boolean };

async function save(doc: Mut<Doc>): Promise<void> {
  await Promise.resolve();
  doc.saved = true;
}

function admit(n: number): void {
  if (n < 0) throw new Refused("refused");
}

async function upload(n: number): Promise<void> {
  await Promise.resolve();
  admit(n);
}

export async function store(doc: Mut<Doc>, n: number): Promise<void> {
  const pending = save(doc);
  admit(n);
  await pending;
}

export async function storeBoth(doc: Mut<Doc>, n: number): Promise<void> {
  await Promise.all([save(doc), upload(n)]);
}

✅ Accepted: what may throw first, or the loan awaited on every way out

✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Refused extends PropagateError {}

type Doc = { saved: boolean };

async function save(doc: Mut<Doc>): Promise<void> {
  await Promise.resolve();
  doc.saved = true;
}

function admit(n: number): void {
  if (n < 0) throw new Refused("refused");
}

async function upload(n: number): Promise<void> {
  await Promise.resolve();
  admit(n);
}

export async function store(doc: Mut<Doc>, n: number): Promise<void> {
  admit(n);
  await save(mut(doc));
}

export async function storeBoth(doc: Mut<Doc>, n: number): Promise<void> {
  const pending = save(mut(doc));
  try {
    await upload(n);
  } finally {
    await pending;
  }
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
import { PropagateError } from "@evobug_com/safe-ts-std/result";

class Refused extends PropagateError {}

type Doc = { saved: boolean };

async function save(doc: Mut<Doc>): Promise<void> {
  await Promise.resolve();
  doc.saved = true;
}

function admit(n: number): void {
  if (n < 0) throw new Refused("refused");
}

async function upload(n: number): Promise<void> {
  await Promise.resolve();
  admit(n);
}

export async function store(doc: Mut<Doc>, n: number): Promise<void> {
  admit(n);
  await save(doc);
}

export async function storeBoth(doc: Mut<Doc>, n: number): Promise<void> {
  const pending = save(doc);
  try {
    await upload(n);
  } finally {
    await pending;
  }
}

✅ Accepted: one loan at a time, or one object for each call

✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Ledger = { total: number };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

export async function addAll(ledger: Mut<Ledger>, ids: readonly string[]): Promise<void> {
  for (const _ of ids) await addOne(mut(ledger));
}

export async function both(a: Mut<Ledger>, b: Mut<Ledger>): Promise<void> {
  await Promise.all([addOne(mut(a)), addOne(mut(b))]);
}

export async function each(ledgers: readonly Mut<Ledger>[]): Promise<void> {
  for (const ledger of ledgers) await addOne(mut(ledger));
}

export async function reset(ledger: Mut<Ledger>): Promise<void> {
  await addOne(mut(ledger));
  ledger.total = 0;
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Ledger = { total: number };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

export async function addAll(ledger: Mut<Ledger>, ids: readonly string[]): Promise<void> {
  for (const _ of ids) await addOne(ledger);
}

export async function both(a: Mut<Ledger>, b: Mut<Ledger>): Promise<void> {
  await Promise.all([addOne(a), addOne(b)]);
}

export async function each(ledgers: readonly Mut<Ledger>[]): Promise<void> {
  for (const ledger of ledgers) await addOne(ledger);
}

export async function reset(ledger: Mut<Ledger>): Promise<void> {
  await addOne(ledger);
  ledger.total = 0;
}

The quick fix Await p first writes await p; before the second loan, where the promise is kept in a const of the same block of an async function.

❌ Rejected: each run overlaps the one before

✕ Rejectedaliased-mut
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Ledger = { total: number };
type Socket = { readonly on: (event: string, listener: () => Promise<void>) => void };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

export function listen(socket: Socket, ledger: Mut<Ledger>): void {
  socket.on("message", async () => {
    await addOne(mut(ledger));
  });
}

export class Book {
  #saving: Promise<void> = Promise.resolve();
  readonly ledger: Ledger = { total: 0 };
  save(): void {
    this.#saving = addOne(mut(this.ledger));
  }
  async settled(): Promise<void> {
    await this.#saving;
  }
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";

type Ledger = { total: number };
type Socket = { readonly on: (event: string, listener: () => Promise<void>) => void };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

export function listen(socket: Socket, ledger: Mut<Ledger>): void {
  socket.on("message", async () => {
    await addOne(ledger);
  });
}

export class Book {
  #saving: Promise<void> = Promise.resolve();
  readonly ledger: Ledger = { total: 0 };
  save(): void {
    this.#saving = addOne(this.ledger);
  }
  async settled(): Promise<void> {
    await this.#saving;
  }
}

✅ Accepted: the runs take turns, as the code shows

✓ Accepted0 diagnostics
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
import type { Option } from "@evobug_com/safe-ts-std/result";

type Ledger = { total: number };
type Socket = { readonly on: (event: string, listener: () => Promise<void>) => void };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

// Each call starts when the one before settled.
export class Queue {
  #tail: Promise<void> = Promise.resolve();
  readonly ledger: Ledger = { total: 0 };
  save(): Promise<void> {
    this.#tail = this.#tail.then(() => addOne(mut(this.ledger)));
    return this.#tail;
  }
}

// A second call finds the first one in flight.
export class InFlight {
  #saving: Option<Promise<void>> = undefined;
  readonly ledger: Ledger = { total: 0 };
  save(): void {
    if (this.#saving !== undefined) return;
    this.#saving = addOne(mut(this.ledger)).finally(() => {
      this.#saving = undefined;
    });
  }
}

// Each message waits for the one before.
export function listen(socket: Socket, ledger: Mut<Ledger>): void {
  let tail: Promise<void> = Promise.resolve();
  socket.on("message", async () => {
    tail = tail.then(() => addOne(mut(ledger)));
    await tail;
  });
}
ts
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
import type { Option } from "@evobug_com/safe-ts-std/result";

type Ledger = { total: number };
type Socket = { readonly on: (event: string, listener: () => Promise<void>) => void };

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await Promise.resolve();
  ledger.total = before + 1;
}

// Each call starts when the one before settled.
export class Queue {
  #tail: Promise<void> = Promise.resolve();
  readonly ledger: Ledger = { total: 0 };
  save(): Promise<void> {
    this.#tail = this.#tail.then(() => addOne(this.ledger));
    return this.#tail;
  }
}

// A second call finds the first one in flight.
export class InFlight {
  #saving: Option<Promise<void>> = undefined;
  readonly ledger: Ledger = { total: 0 };
  save(): void {
    if (this.#saving !== undefined) return;
    this.#saving = addOne(this.ledger).finally(() => {
      this.#saving = undefined;
    });
  }
}

// Each message waits for the one before.
export function listen(socket: Socket, ledger: Mut<Ledger>): void {
  let tail: Promise<void> = Promise.resolve();
  socket.on("message", async () => {
    tail = tail.then(() => addOne(ledger));
    await tail;
  });
}

Recognised as taking turns: a for...of (or any loop) that awaits each call; a chain kept in a field and extended by each call (this.tail = this.tail.then(() => ...)), since the loan is made in a callback that starts when the one before settled; a guard clause before the loan that tests where the promise is kept (if (this.saving) return this.saving;) or a flag the function sets before the loan (if (busy) return; busy = true;); a loan inside if (!this.saving) { ... }. A lock or a queue written as a class of the project's own isn't.

What the rule can't see ​

  • A part reached through something other than a path: an element (mut(list) and list[0]), a call's result (mut(cart) and firstItem(cart)), a value captured by a callback passed in the same call.
  • A part whose type the declarations don't settle, on a path from a parameter or a local, as above: a member of a value whose type the checker can't follow is taken to be a copy (useCanvas(mut(gl), gl.canvas) with gl a parameter). A global interface a package declares (in @types/...) isn't told apart from lib's: a member of it written in capitals is taken to be a constant.
  • Two calls: lending x to one call and keeping a part of it for later (a local read before the call that still holds the old object is stale-read's).
  • Loans in two arguments that are the same object by value: two parameters a and b that the caller passes the same object for (transfer(mut(a), mut(b)) in a function called with (x, x)), since the paths differ.
  • Over time, what the code doesn't show: who calls a function, and when (an async method that awaits a loan of this.state, called twice at once by its callers, is like stale-across-await's "who calls the function"); a callback the checker doesn't know runs again (a project's own event system, a framework's ticker); a loan held by a promise kept somewhere the checker loses it (a let reassigned, an object literal, a promise awaited only through a flag or a helper that waits for it); a loan made in a .then callback of a promise that isn't the queue's own; a synchronous callback that writes a captured Mut parameter later (it isn't a loan), nor an async function that writes state it captured and is called twice at once (const load = async (term) => { list.shown = await search(term); }: no loan is written, so this rule has nothing to follow; lent as load(mut(list), term) it is reported); a call dropped as a statement without void (f(mut(x));), which is floating-promise's when f is async and isn't followed until it is written void f(mut(x)); the owner's reads while a loan is alive (a read sees the value as it is; the write made from it is what loses an update). On a way out by an exception: std's q(...) returning the error early (it is a return the transform writes), an exception a getter or a callback the checker doesn't know runs throws, a call the whole-program pass can't resolve (taken not to throw, as for unreleased-resource), and a Promise.all built elsewhere (const all = Promise.all([...]); await all) or race / any (which may settle while a member still runs, on a normal way out too).
  • What a callee touches: the loan is the whole object. Lending game while a call holds a loan of game is reported even where the two touch different parts of it (Rust refuses it the same way); a generation counter that makes a superseded run stop isn't recognised.
  • Elements reached by index, web workers and shared memory (SharedArrayBuffer, Atomics).

A loan of the collection a for...of goes over (for (const x of items) grow(mut(items))) is no-mutation-while-iterating's.

Related: missing-mut, no-param-mutation; guide: State without globals.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra