Import createPrattParser, binaryParselet, TokenCursor and ParseError from @neutrium/utilities/parsing. The same exports are available through the package root. This module does not depend on Math, numerical adapters, or a specific lexer or AST. It provides token lookahead, Pratt precedence handling and bounded parsing.
A Pratt parser builds an expression by choosing handlers according to token position and operator precedence. It does not tokenize source text or evaluate expressions for you. Start by defining tokens and the result each handler builds.
The consumer supplies tokens with half-open UTF-16 start/end offsets. All other token fields, lexical rules and node types belong to the consumer. Prefix lookup
selects handlers for atoms, groups and unary operators. Infix lookup selects handlers for binary, postfix or other continuations. Returning undefined means the grammar has no handler for that token in that position.
import { createPrattParser, binaryParselet, type SourceSpan,
type PrefixParselet } from '@neutrium/utilities/parsing';
interface Token extends SourceSpan { text: string }
type Node = string; // A readable tree for this example; normally an AST union.
const atom: PrefixParselet<Token, Node> = (_, token) => token.text;
const join = binaryParselet<Token, Node>(10, 'left',
(left, token, right) => `(${left}${token.text}${right})`);
const parser = createPrattParser<Token, Node>({
prefix: token => /^[a-z]+$/.test(token.text) ? atom : undefined,
infix: token => token.text === '|' ? join : undefined,
});
parser.parse([
{ text: 'red', start: 0, end: 3 },
{ text: '|', start: 4, end: 5 },
{ text: 'blue', start: 6, end: 10 },
]); // '(red|blue)'
binaryParselet(bindingPower, associativity, build) creates a frozen binary handler. Binding powers are nonnegative safe integers below Number.MAX_SAFE_INTEGER; higher values bind more tightly. parseExpression(minimumBindingPower) uses an inclusive minimum. A left-associative binary handler parses its right side at power + 1; a right-associative handler parses it at the same power. The engine consumes the operator before invoking its handler.
The previous example can parse text by supplying a generator. This lexer accepts lowercase words, |, and whitespace; it rejects every other character rather than silently skipping it. It reuses Token and parser from the example above.
import { ParseError } from '@neutrium/utilities/parsing';
function* tokenize(source: string): Generator<Token>
{
const pattern = /\s+|[a-z]+|\|/y;
let offset = 0;
while (offset < source.length)
{
pattern.lastIndex = offset;
const match = pattern.exec(source);
if (!match)
{
throw new ParseError('UNEXPECTED_TOKEN', 'Expected a word or |', {
start: offset, end: offset + 1,
});
}
const text = match[0];
const end = pattern.lastIndex;
if (!/^\s+$/.test(text))
{
yield { text, start: offset, end };
}
offset = end;
}
}
const source = 'red | blue | green';
parser.parse(tokenize(source), { end: source.length });
// '((red|blue)|green)': | is left-associative
Keep offsets in the original string, including skipped whitespace. JavaScript string indices already use the required UTF-16 units; source.slice(start, end) extracts an error's highlighted text. EOF errors have an empty span.
Catch ParseError to show a diagnostic while allowing unrelated handler errors to propagate. This example reuses the parser and lexer above:
try
{
const source = 'red | ';
parser.parse(tokenize(source), { end: source.length });
}
catch (error)
{
if (!(error instanceof ParseError)) throw error;
const message = error.reason === 'EXPECTED_EXPRESSION'
? 'Enter an expression after the operator.'
: error.message;
console.error(`${message} (offset ${error.start})`);
}
Use code and optional reason for decisions rather than matching message text. A lexer may provide its own ParseError, as above, or throw another error type; the parser passes that error through unchanged.
Handlers receive a context with peek, consume, expect(predicate, message?), unexpected(message?, reason?), span, position and parseExpression. position is a consumed-token count; span() describes lookahead or EOF. A grouping handler calls parseExpression() followed by expect for its closing delimiter. A postfix handler constructs a node from the left expression without parsing a right operand. A conditional handler can parse an operand, expect a separator, then parse another.
For implicit operations, set consumeToken: false on an infix parselet. Its token remains in lookahead so its right-operand parser can consume it. For example:
const implicitProduct = {
...binaryParselet<Token, Node>(20, 'left', (a, _, b) => `(${a}*${b})`),
consumeToken: false,
};
The grammar decides when to return this handler, including how whitespace and adjacent tokens are interpreted. An implicit handler that consumes no input throws TypeError rather than causing an infinite parsing loop. This is not backtracking: failed parses do not rewind tokens. Do not retain a context after its parse finishes.
parse and TokenCursor accept arrays, generators and other iterables, or a TokenReader<T> whose next() returns a token or undefined at EOF. Token sources are trusted synchronous producers with valid source spans. They must not yield undefined as an iterable element. Sources and tokens are not mutated, and iterators are not closed by the parser. Supply a fresh source for each parse.
Pass parser.parse(source, { end: originalText.length }) to locate EOF after trailing whitespace. Without it, EOF is located at the last emitted token's end, or zero for an empty stream. Top-level parsing always requires the entire stream to be consumed.
ParseError extends SyntaxError and has immutable code, start, end and offset (an alias for start). Codes are UNEXPECTED_TOKEN, UNEXPECTED_END and LIMIT_EXCEEDED. Consumers can translate these into domain errors. Lexer and handler exceptions propagate unchanged. Invalid configuration and handler binding powers throw TypeError or RangeError rather than a syntax error.
Since 5.1, ParseError.reason adds an immutable, optional detail independent of the message text. The broad code still distinguishes EOF, an unexpected token and resource limits. Use the code and reason for application logic; messages are for display.
| Reason | Emitted when |
|---|---|
EXPECTED_EXPRESSION |
An operand is missing at EOF, or prefix lookup has no handler |
EXPECTED_TOKEN |
expect fails or consume is called at EOF |
TRAILING_TOKEN |
assertEnd finds unconsumed input |
MAX_DEPTH_EXCEEDED |
The parser reaches its recursion limit |
MAX_TOKENS_EXCEEDED |
The cursor reads beyond its token limit |
expect and assertEnd keep their reasons even when given custom messages. Custom handlers can call context.unexpected(message, reason) or construct new ParseError(code, message, span, reason). The fourth constructor argument is optional, so existing calls continue to work. Errors constructed without it, and direct calls to unexpected without a reason, have reason === undefined. No reason is inferred from message text. The reason describes a parsing operation; it does not specify the consumer's expected token kinds or AST types.
Set limits in the second argument to createPrattParser(grammar, options), for example createPrattParser({ prefix: () => atom }, { maxDepth: 64, maxTokens: 1000 }). Factory options default to maxDepth: 128 and maxTokens: 4096. Both must be positive safe integers; depth cannot exceed 256. These settings are captured once. Each parse owns its cursor and depth counter, including reentrant calls. All nested calls through context.parseExpression share that parse's depth budget. Long left-associative chains use constant depth. A cursor keeps only one lookahead token and never shifts arrays, though an array supplied by a caller remains retained by its iterator.
Parser options, cursor options, and per-parse location options follow the same
record rules as the configuration APIs. They accept local plain objects and
null-prototype records containing only own data properties. Unknown keys
(including symbols, non-enumerable keys, and keys set to undefined), accessors,
arrays and class instances throw TypeError. Getters are never invoked; proxy
reflection traps may run. Known fields set to undefined use their defaults.
Invalid numeric values still throw RangeError.
The factory accepts only maxDepth and maxTokens; a standalone cursor accepts
only maxTokens and end; parser.parse(source, location) accepts only end.
Invalid cursor or location options are rejected before the token source is read.
This tightens the previous behaviour: misspelled or extra options now fail instead
of being silently ignored, and location options cannot override parser limits.
Pass only the relevant fields from a larger consumer configuration object.
DEFAULT_PRATT_OPTIONS is the frozen { maxDepth: 128, maxTokens: 4096 } object
used by the parser. MAX_PRATT_DEPTH exports the supported depth ceiling of 256.
Both are available from /parsing and the package root. Consumers can extend the
defaults with their own limits without repeating the shared values:
import { DEFAULT_PRATT_OPTIONS, MAX_PRATT_DEPTH } from '@neutrium/utilities/parsing';
const expressionLimits = Object.freeze({
...DEFAULT_PRATT_OPTIONS,
maxLength: 16384,
maxArguments: 64,
});
// Use MAX_PRATT_DEPTH when validating a consumer-supplied maxDepth override.
Standalone cursors accept { maxTokens, end }, default to DEFAULT_PRATT_OPTIONS.maxTokens, expose the same cursor operations, and provide assertEnd() to reject trailing tokens. The token limit counts emitted tokens, including lookahead, and excludes EOF. Detecting excess tokens requires reading one token beyond the limit. The bounds do not limit work inside a trusted producer or handler, or numerical evaluation performed by a consumer.