TParser - Dynamic Parser Machine
Fonte: source/classes/tparser.prg
TParser is a generic grammar-rule engine skeleton. It maintains a list of production rules and a state stack. Rules consist of a non-terminal symbol, a token array, and an action code block. This class provides the framework for building expression parsers, command interpreters, or domain-specific language processors.
Key DATA Members
| DATA | Type | Description |
|---|---|---|
aRules | Array | Array of grammar rules, each { cNonTerminal, aTokens, bAction } |
aStates | Array | State stack for parsing; state 0 is empty by default |
Methods
| Method | Description |
|---|---|
New() | Create a new parser with empty rules and initial state |
Add( cNonTerminal, aTokens, bAction ) | Add a production rule: non-terminal -> sequence of tokens with action |
Example: Add Grammar Rules
#include "FiveWin.ch"
function Main()
local oParser := TParser():New()
// expr -> number
oParser:Add( "expr", { "number" }, {|n| n } )
// expr -> expr + expr
oParser:Add( "expr", { "expr", "+", "expr" }, {|a,b| a + b } )
// expr -> expr * expr
oParser:Add( "expr", { "expr", "*", "expr" }, {|a,b| a * b } )
// Access the rules
? Len( oParser:aRules ) // 3 rules added
return nil
Notes
- TParser is a skeleton class. The core
Add()method builds the rule table; you must implement the tokenizer and the parsing algorithm (shift-reduce, recursive descent, etc.) yourself using theaRulesandaStatesdata. - Each rule's
aTokensarray defines the expected token sequence; thebActionblock is the semantic action fired when the rule matches. aStatesstarts with a single empty state (index 0). States can be pushed/popped during parsing to handle nested constructs.