Repository navigation
Description
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.
- An unmatched run of
{in a word, for examplen{{{{{....scanBraceExpansionfails after scanning to the end of the window, the word reader advances one character, sees the next{and scans again. - A run of
$[without a matching](or with a single trailing]), for exampleecho $[$[$[.... The legacy$[branch ofreadDollarcallsfindClosingArithmeticBracket, 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
Bound brace and legacy lookahead across lexer scopes (resolve webpro-…
Memoize failed brace and legacy arithmetic lookahead per opener (#28)