92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package parsekit_test
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.makaay.nl/mauricem/go-parsekit"
|
|
)
|
|
|
|
func ExampleItemType() {
|
|
// Make use of positive values. Ideally, define your ItemTypes using
|
|
// iota for easy automatic value management like this:
|
|
const (
|
|
ItemWord parsekit.ItemType = iota
|
|
ItemNumber
|
|
ItemBlob
|
|
// ...
|
|
)
|
|
}
|
|
|
|
func ExampleError() {
|
|
error := parsekit.Error{
|
|
Message: "it broke down",
|
|
Line: 10,
|
|
Column: 42}
|
|
|
|
fmt.Println(error.Error())
|
|
fmt.Println(error.ErrorFull())
|
|
// Output:
|
|
// it broke down
|
|
// it broke down after line 10, column 42
|
|
}
|
|
|
|
func ExampleMatchAnyRune() {
|
|
// Easy access to the parsekit definitions.
|
|
var a = parsekit.A
|
|
|
|
handler := func(p *parsekit.P) {
|
|
p.Expects("Any valid rune")
|
|
if p.On(a.AnyRune).Accept().End() {
|
|
p.EmitLiteral(TestItem)
|
|
p.RouteRepeat()
|
|
}
|
|
}
|
|
parser := parsekit.NewParser(handler)
|
|
run := parser.Parse("¡Any / valid / character will dö!")
|
|
|
|
for i := 0; i < 5; i++ {
|
|
match, _, _ := run.Next()
|
|
fmt.Printf("Match = %q\n", match.Value)
|
|
}
|
|
// Output:
|
|
// Match = "¡"
|
|
// Match = "A"
|
|
// Match = "n"
|
|
// Match = "y"
|
|
// Match = " "
|
|
}
|
|
|
|
func ExampleModifyToUpper() {
|
|
// Easy access to the parsekit definitions.
|
|
var c, a, m = parsekit.C, parsekit.A, parsekit.M
|
|
|
|
// A Dutch poscode consists of 4 numbers and 2 letters (1234XX).
|
|
// The numbers never start with a zero.
|
|
digitNotZero := c.Except(c.Rune('0'), a.Digit)
|
|
numbers := c.Seq(digitNotZero, c.Rep(3, a.Digit))
|
|
|
|
// It is good form to write the letters in upper case.
|
|
letter := c.Any(a.ASCIILower, a.ASCIIUpper)
|
|
letters := m.ToUpper(c.Seq(letter, letter))
|
|
|
|
// It is good form to use a single space between letters and numbers,
|
|
// but it is not mandatory.
|
|
space := m.Replace(c.Opt(a.Whitespace), " ")
|
|
|
|
// With all the building blocks, we can now build the postcode parser.
|
|
postcode := c.Seq(numbers, space, letters)
|
|
|
|
// Create a parser and let is parse some postcode inputs.
|
|
// This will print "1234 AB" for every input, because of the built-in normalization.
|
|
p := parsekit.NewMatcherWrapper(postcode)
|
|
for _, input := range []string{"1234 AB", "1234Ab", "1234 ab", "1234ab"} {
|
|
output, _, _ := p.Match("1234 AB")
|
|
fmt.Printf("Input: %q, output: %q\n", input, output)
|
|
}
|
|
// Output:
|
|
// Input: "1234 AB", output: "1234 AB"
|
|
// Input: "1234Ab", output: "1234 AB"
|
|
// Input: "1234 ab", output: "1234 AB"
|
|
// Input: "1234ab", output: "1234 AB"
|
|
}
|