lookupAccess function
Parses compound variable lookups such as product.variants[0].name.
Optimized with a two-tier approach:
- Fast path: Pattern-based parsing for simple identifier chains (no array access) Uses a single pattern match + string split instead of parsing each identifier
- Slow path: Each identifier and its bracket suffixes are parsed together.
The fast path provides ~50% reduction in parser activations for simple cases.
Implementation
Parser lookupAccess() {
// Fast path: Simple identifier chain without array access
// Pattern matches: identifier(.identifier)+ where no segment is followed by '['
final identChar = pattern('a-zA-Z0-9_-');
final dot = char('.');
// First segment: identifier pattern
final firstIdent = pattern('a-zA-Z') & identChar.star();
// Additional segments: .identifier (NOT followed by '[')
final additionalSegment = dot & pattern('a-zA-Z') & identChar.star();
// Fast path parser - matches simple chains and ensures not followed by '['
// Use the same bracket parser as the slow path, including leading whitespace.
final simpleMemberAccess =
((firstIdent & additionalSegment.plus()).flatten() &
_lookupBracketStart().not())
.pick(0) // Get just the flattened string, not the lookahead result
.cast<String>()
.where((value) {
// Exclude reserved words in any segment
final parts = value.split('.');
return !parts.any(
(p) => ['and', 'or', 'not', 'contains'].contains(p),
);
})
.map((value) {
final parts = value.split('.');
final object = Identifier(parts.first);
final members = parts
.skip(1)
.map((name) => Identifier(name))
.toList();
return MemberAccess(object, members.cast<ASTNode>());
});
// Keep the established member AST shape, with indexed segments represented
// by ArrayAccess nodes. The root and each following segment are parsed once.
final indexedAccess =
seq2(ref0(_lookupSegment), (dot & ref0(_lookupSegment)).pick(1).star())
.where((parts) => parts.$1 is ArrayAccess || parts.$2.isNotEmpty)
.map((parts) {
final root = parts.$1;
final members = parts.$2.cast<ASTNode>();
return members.isEmpty ? root : MemberAccess(root, members);
});
return (simpleMemberAccess | indexedAccess).labeled('lookupAccess');
}