How it works¶
textfsm2 replaces TextFSM's template compiler and line-matching loop with compiled Rust while delegating back to Python whenever behaviour depends on user-supplied Python code.
textfsm2 (Python) textfsm2._core (Rust)
───────────────────────────────────── ─────────────────────────────────────────
TextFSM(template) ── lines ──────────▶ compile_template: port of _Parse/_ValidateFSM,
same errors and line numbers; regex validity
decided by CPython's re; cached per template
fsm.ParseText(text) ─────────────────▶ Machine.run: port of ParseText/_CheckLine/
_AppendRecord and the option hooks, GIL released
fsm.values / fsm.states / ... built lazily from the compiled program (and the
runtime state synced both ways) on first access
Exactness first¶
The complete pure-Python reference implementation remains in parser.py. TextFSM automatically falls back to Python whenever behaviour depends on Python code: a custom options_class, a subclass or instance overriding FSM hooks (_CheckLine, _CheckRule, _AppendRecord, etc.), bytes templates, or direct calls to internal methods. Everything else runs in Rust with the GIL released.
Regex engines¶
textfsm2 translates Python re syntax into Rust regex engines while preserving Python group numbering and literal quirks ({, \<, {,n}, [ inside classes, octal escapes). Each translated pattern is cross-checked against CPython's groups and groupindex and routed to one of three engines:
- Finite automata (
regex-automata) for almost every pattern (15,093 of 15,162 patterns inntc-templates). fancy-regexfor lookaround and backreferences.- CPython's own
refor constructs Rust automata cannot reproduce identically, such as possessive quantifiers, atomic groups, and repeated sub-expressions that can match the empty string when their captures are needed.
Each rule also extracts lightweight prefilter guards (leading whitespace, anchored ASCII prefix, or required literal substring) so non-matching rules skip full regex evaluation cleanly.
Unicode and line handling¶
ASCII inputs—nearly all router CLI output—run through compact byte-level automata implementing Python's semantics for \w, \d, \s, and \b. On non-ASCII lines, patterns whose semantics depend on Unicode tables are evaluated by CPython re (because CPython 3.15 and the Rust regex crates disagree on about 8,000 code points for \w), while all other patterns compile lazily to Unicode automata.
Memory and caching¶
Compiled Program instances live in a process-wide LRU cache (TEXTFSM_CACHE_SIZE, default 128), so repeated CliTable lookups or TextFSM constructions resolve in a hash lookup without recompiling. Patterns compile lazily on first match, and each cached program pools a warm search-buffer set (TEXTFSM_SCRATCH_POOL) instead of allocating buffers per regex.