Documentation ¶
Index ¶
Examples ¶
Constants ¶
View Source
const Epsilon = Terminal("ε")
Epsilon is the empty string.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CFG ¶
type CFG struct { Variables V Alphabet Alphabet Rules R StartVariable Variable // contains filtered or unexported fields }
CFG is a context-free grammar (`G = (V, Σ, R, S)`).
Example ¶
package main import ( "fmt" "github.com/0x51-dev/cfg" ) func main() { g, _ := cfg.Parse(` S → aSa S → bSb S → ε `) in := "aabbaa" fmt.Println(g) p, ok := g.Evaluate(in) fmt.Println(p, ok) fmt.Println(p.Replay()) }
Output: ( { S }, { a, b }, [ S → aSa, S → bSb, S → ε ], S ) [ S → aSa, S → aSa, S → bSb, S → ε ] true S → aSa → aaSaa → aabSbaa → aabbaa
Example (Parentheses) ¶
package main import ( "fmt" "github.com/0x51-dev/cfg" ) func main() { S := cfg.Variable("S") lp := cfg.Terminal("(") rp := cfg.Terminal(")") lb := cfg.Terminal("[") rb := cfg.Terminal("]") g, _ := cfg.New( []cfg.Variable{S}, []cfg.Terminal{lp, rp, lb, rb}, []cfg.Production{ cfg.NewProduction(S, []cfg.Beta{S, S}), // SS cfg.NewProduction(S, []cfg.Beta{lp, rp}), // () cfg.NewProduction(S, []cfg.Beta{lp, S, rp}), // (S) cfg.NewProduction(S, []cfg.Beta{lb, rb}), // [] cfg.NewProduction(S, []cfg.Beta{lb, S, rb}), // [S] }, S, ) g.Depth(15) // Needed since the default depth is 10, 14 is needed for the example. in := "([[[()()[][]]]([])])" fmt.Println(g) p, ok := g.Evaluate(in) fmt.Println(p, ok) fmt.Println(p.Replay()) }
Output: ( { S }, { (, ), [, ] }, [ S → SS, S → (), S → (S), S → [], S → [S] ], S ) [ S → (S), S → [S], S → SS, S → [S], S → [S], S → SS, S → SS, S → SS, S → (), S → (), S → [], S → [], S → (S), S → [] ] true S → (S) → ([S]) → ([SS]) → ([[S]S]) → ([[[S]]S]) → ([[[SS]]S]) → ([[[SSS]]S]) → ([[[SSSS]]S]) → ([[[()SSS]]S]) → ([[[()()SS]]S]) → ([[[()()[]S]]S]) → ([[[()()[][]]]S]) → ([[[()()[][]]](S)]) → ([[[()()[][]]]([])])
func New ¶
New creates a new context-free grammar from the given variables, alphabet, rules, and start symbol. The order of the rules is important, since the first rule that matches will be used. Infinite loops can be prevented by using the repeat flag.
type Path ¶
type Path []Production
type Production ¶
Production is a production rule.
func NewProduction ¶
func NewProduction(alpha Alpha, beta []Beta) Production
func (Production) Equal ¶
func (p Production) Equal(other Production) bool
Equal checks if two production rules are equal.
func (Production) String ¶
func (p Production) String() string
type R ¶
type R []Production
R is a set of production rules. Formalized: `(α, β) ∈ R`, with `α ∈ V` and `β ∈ (V ∪ Σ)*`.
Click to show internal directories.
Click to hide internal directories.