Skip to content

[complexity, checker] O(n^2 log n) — An empty match copies all variables before inspecting the first #1955

Description

@pjcavalcanti

Define Empty and Unit:

type Empty is Type:
type Unit is Data:
  U{}

Consider these terms:

def test(e: Empty) -> Unit:
  x = {\{} : Unit -> Unit};
  U{}
def test(e: Empty) -> Unit:
  x = {\{} : Unit -> Unit};
  y = {\{} : Unit -> Unit};
  U{}

Let n be the number of local empty matches: 1 and 2 above. Main copies
O(n² log n) array entries during checking.

Cause. Each \{} has no cases, although its input type Unit has a constructor.
The outer parameter e: Empty justifies this because Empty has none. To find it,
ctx_dead searches for an available variable with an empty type. First,
pmap_to_array copies the entire variable tree into an array. Repeated array joins
copy O(k log k) entries for k variables in scope. Only then does the search inspect
e, the first entry, and return. Repeating this as the scope grows copies
O(n² log n) entries.

Copying the whole scope before searching may not be necessary. Searching the
variable tree directly could stop at the first eligible empty type. Here e is at
the first node, so n matches could need O(n) search visits without the array copies.

To reproduce on main 7a7e6505a, save the setup and either term as example.bend;
run bun bend2/main.ts example.bend --check-only.

Source: tree-to-array copying, empty-type search.

Activity

  1. pjcavalcanti commented on Nov 2, 2026

    @pjcavalcanti
    CollaboratorAuthor

    Addendum — 2 November 2026

    The saving follows from what the operation needs: the first eligible empty type, rather than an array containing every variable. A direct walk can keep the original search order and return at the same first success. That order matters because inspecting a type can run a computation; erased entries must still be skipped.

    The O(n) search count applies to this family, where the same Empty variable is found first. A failed search still needs to inspect the whole context. This removes unnecessary copying without requiring the checker to recognize these particular functions.

  2. added a commit that references this issue on Nov 2, 2026
    e954dc9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions