Skip to content

Quadratic parsing of unclosed subscripts followed by a trailing ] #14

Closed

Description

@webpro

Repeated unclosed subscripts at command positions cause quadratic parsing time when the input ends with a single ]. An approximately 48 KB input takes about 1.6 seconds to parse; removing that final character reduces it to about 6 ms.

Run from the repository root with Node 24:

node --input-type=module <<'JS'
import { parse } from './src/parser.ts';

for (const closer of ['', ']']) {
  for (const n of [1000, 2000, 4000, 8000]) {
    const source = 'a[x y\n'.repeat(n) + closer;
    const start = performance.now();
    const script = parse(source);
    const ms = performance.now() - start;
    console.log({ n, closer, ms, commands: script.commands.length });
  }
}
JS

Observed at cd442665 on macOS with Node 24.19.0, rounded to milliseconds:

Lines Without trailing ] With trailing ]
2,000 2 ms 103 ms
4,000 2 ms 397 ms
8,000 6 ms 1,569 ms

Character-read counts confirm the scaling independently of timing: 64, 128 and 256 lines with the trailing ] require 14,267, 53,115 and 204,539 calls to charCodeAt on the source. Replacing a[x y with a[$x y shows the same behavior.

findClosingBracket caches the last raw ] position to skip searches when no closing bracket remains. A trailing ] defeats that guard. Each failed search traverses the remaining input, treating subsequent [ characters as nested brackets. Error recovery then retries from the next command.

Caching one failed search as proof that every later search will fail is unsafe. Recovery can change how quotes and comments are interpreted. For example, this must still preserve the valid assignment to b:

a[$x y # "
b[$x z]=1
# "

The initial subscript search sees the quotes and skips the later ]; after recovery, the first # starts a comment and b[$x z]=1 is a separate assignment.

Expected behavior is approximately linear scaling while preserving diagnostics and later commands, without a measurable slowdown on ordinary scripts. A regression test should check character-read growth rather than depend on a timing threshold.

Activity

  1. added a commit that references this issue on Nov 6, 2026
    1a97ac2
  2. added a commit that references this issue on Nov 7, 2026
    f5b87d2
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