Skip to content

Quadratic parsing of unmatched { runs and unmatched legacy $[ runs #27

Closed

Description

@jecruz

Two inputs make the lexer repeat a failed lookahead scan once per opener, so the work grows quadratically with the length of the word. Both are related to, but distinct from, #14 (unclosed subscripts followed by a trailing ], findClosingBracket); this report does not touch subscript recovery.

  1. An unmatched run of { in a word, for example n{{{{{.... scanBraceExpansion fails after scanning to the end of the window, the word reader advances one character, sees the next { and scans again.
  2. A run of $[ without a matching ] (or with a single trailing ]), for example echo $[$[$[.... The legacy $[ branch of readDollar calls findClosingArithmeticBracket, falls back to a literal $ on failure, and the next $[ repeats the scan.

Reproduction, counting charCodeAt reads instead of timing:

import { parse } from "unbash";

const charCodeAt = String.prototype.charCodeAt;
for (const size of [1024, 4096, 16384]) {
  for (const source of [
    "n" + "{".repeat(size - 1),
    "echo " + "$[".repeat(Math.floor((size - 5) / 2)),
    "echo " + "$[".repeat(Math.floor((size - 6) / 2)) + "]",
  ]) {
    let reads = 0;
    String.prototype.charCodeAt = function (index) {
      reads++;
      return charCodeAt.call(this, index);
    };
    try {
      parse(source);
    } finally {
      String.prototype.charCodeAt = charCodeAt;
    }
    console.log(source.length, reads);
  }
}

Observed on main (61b82c2), reads per input of length N:

N n{{{... echo $[$[... echo $[$[...]
1024 1,046,537 521,232 521,740
4096 16,769,033 8,376,336 8,378,380
16384 268,402,697 134,168,592 134,176,780
65536 4,294,836,233 2,147,287,056 2,147,319,820

(The $[ rows are for lengths N-1, N, N-1 and N as generated above: 1023/1024, 4095/4096, 16383/16384, 65535/65536.) Reads quadruple when the length doubles.

Root cause: both scans fail only after reaching the end of the window, and neither records the failure, so the caller's retry at the next opener repeats the same work. The result for a given opener in a given source window cannot change between retries, so it can be remembered.

I am happy to send a PR (following the maintainer's invitation to send a PR) with a failures-only memoisation that keeps the grammar and AST unchanged.

Activity

  1. added a commit that references this issue on Nov 6, 2026
    139346f
  2. added a commit that references this issue on Nov 7, 2026
    41aeadf
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