Goal: implement a recursive matcher function match_elems(elems, text, pos) that uses a tokenized pattern (elems) which can contain quantifiers and groups, to determine if the segment of text starting at index pos matches the pattern. The function should return True if the entire pattern can be matched starting at pos; otherwise False.
Token representation:
The pattern is a list of tokens. Each token is either:
A string literal to be matched exactly (case-sensitive).
A dict with keys:
type: group
children: a list of tokens representing the sub-pattern inside the group
quantifier: an object or None:
If provided: dict with min (int), max (int or None for unbounded), greedy (bool)
A dict with type: any to match any single character.
Quantifier semantics:
The quantifier applies to the immediate preceding token (which can be a group). If greedy is true, try to match as many repetitions as allowed first; otherwise start from the minimum.
A group with quantifier means the whole inner pair of tokens repeats as a unit.
API:
The function signature is match_elems(elems, text, pos).
Returns True if the token list can be matched starting at pos; False otherwise.
The function should be pure (no I/O) and not rely on Python's re module.
Approach hints:
Implement a small recursive engine with backtracking.
Use a helper that matches a sequence of tokens starting at a given position and returns all end positions reachable after matching that sequence.
Add memoization on (idx, pos) where idx is the current position in the top-level elems list to prune repeated subcalls.
Carefully handle empty tokens and end-of-text boundaries.
Tips:
Do not use Python's re module.
Focus on correctness and backtracking efficiency rather than clever optimizations.
Include a short unit-test style snippet in the demo if you like, but keep it self-contained.