Usage

This page will explain how to go from a Katydid grammar to validating a parsed tree. This is done in two steps. Each of these steps have several alternatives.  

1.  Construct the Grammar
2.  Validation

This assumes you have already constructed a parser, if not see the page on parser usage.

Constructing a Relapse Grammar

First we need to parse our relapse string into a grammar. This is perfect for when we are receiving a string from the user or a configuration file.

import "github.com/katydid/katydid/relapse"

func main() {
    katydidString := "a:*"
    katydidGrammar, err := relapse.Parse(katydidString)
    if err != nil {
        panic(err)
    }
}

If you don’t understand the katydidString’s value it might be good idea to first take the Katydid Tour.
We could also have programmatically constructed our ast (abstract syntax tree).

import "github.com/katydid/katydid/relapse/ast"

func main() {
    katydidPattern := ast.NewTreeNode(ast.NewStringName("a"),ast.NewZAny())
    katydidRefs := map[string]*ast.Pattern{"main": katydidPattern}
    katydidGrammar := ast.NewGrammar(katydidRefs)
}

This can become quite verbose, so we can rather use the combinator library, with which we can more concisely, but still programmatically, construct the grammar.

import . "github.com/katydid/katydid/relapse/combinator"

func main() {
    katydidPattern := In("a", Any())
    g := G{"main": katydidPattern}
    katydidGrammar := g.Grammar()
}

We can also use combinator functions on the leaves.

import . "github.com/katydid/katydid/relapse/combinator"

func main() {
    fun := Eq(StringVar(), StringConst("abc"))
    katydidPattern := In("a", Value(fun))
    g := G{"main": katydidPattern}
    katydidGrammar := g.Grammar()
}

Validation

Now that we have an initialized parser and a katydid grammar we can validate the parsed tree against the schema.

import "github.com/katydid/katydid/relapse"
import "github.com/katydid/katydid/relapse/ast"
import "fmt"

func validate(grammar *ast.Grammar, p parser.Interface) {
    mem := relapse.Prepare(grammar)
    match, err := relapse.Validate(mem, p)
    if err != nil {
        panic(err)
    }
    if !match {
        fmt.Printf("Expected match given %s\n", grammar.String())
    }
}

Here we created a memoized grammar for faster repeated execution, which is the default way to use Katydid, but there are others way too that we won't cover here.