ctxexp-parser
ctxexp-parser copied to clipboard
Refactor state machine to XState-inspired declarative architecture
Refactored the lexer state machine from imperative nested functions to a declarative configuration pattern inspired by XState.
Changes
-
Declarative state configuration: Replaced 18 nested function definitions with a centralized configuration object using
on(transitions) anddef(default handlers) -
Type safety: Added explicit TypeScript interfaces for
Context,Transition,Action, andStateHandler - Pattern-based matching: Centralized character classification logic with reusable pattern matchers
- Code reduction: 453 → 243 lines (46% reduction)
Example
Before:
function K1(c: string) {
if (isProperty(c)) {
tokenString += c;
return K1;
}
if (c === ".") {
emit();
tokenString = c;
emit();
return O2;
}
// ... 6 more if statements
throw new Exception(index, `must be '.' or '(' or '[', not '${c}'`);
}
After:
K1: {
on: {
isProperty: { to: "K1", do: (c, ch) => { c.str += ch; } },
".": { to: "O2", do: (c, ch) => { c.emit(); c.str = ch; c.emit(); } },
"(": { to: "O5", do: (c, ch) => { c.emit(TokenType.ID_FN); c.str = ch; c.emit(); } },
// ... compact transition definitions
},
def: (c, ch) => { throw new Exception(c.idx, `must be '.' or '(' or '[', not '${ch}'`); }
}
All 33 existing tests pass without modification.
Original prompt
This section details on the original issue you should resolve
<issue_title>refactor stater</issue_title> <issue_description>## Description 使用类似于xstate库去重构状态机。
Target
- [ ] 增加代码可读性
- [ ] 减少代码量</issue_description>
Comments on the Issue (you are @copilot in this section)
Custom agent used: Refactor Agent You are a js code refactoring master.
- Fixes Lydanne/ctxexp-parser#1
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.