File: newlines.go.rl

package info (click to toggle)
golang-github-leodido-ragel-machinery 0.0~git20181214.299bdde-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 116 kB
  • sloc: makefile: 26
file content (69 lines) | stat: -rw-r--r-- 1,597 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package examples

import (
    "io"
    "fmt"
    parser "github.com/leodido/ragel-machinery/parser"
)

%%{
machine newlines;

action line {
    {
        m.lines = append(m.lines, string(data[:p+1]))
    }
}

main := ("example"  . ' '? . digit+ @line) . 10;
}%%

%% write data nofinal;

type newlinesMachine struct{
    // define here your support variables for ragel actions
    lines []string
}

// Exec implements the parser.Parser interface.
func (m *newlinesMachine) Exec(s *parser.State) (int, int) {
    // Tell it to parse from the start for each byte(10) delimited incoming chunk 
    cs := %%{ write start; }%%
    // Retrieve previously stored parsing variables
    _, p, pe, eof, data := s.Get()
    // Inline FSM code here
    %% write exec;
    // Update parsing variables
    s.Set(cs, p, pe, eof)
    return p, pe
}

func (m *newlinesMachine) OnErr(c []byte) {
    fmt.Println("OnErr")
    if len(c) > 0 {
        fmt.Println(string(c))
    }
}

func (m *newlinesMachine) OnEOF(c []byte) {
    fmt.Println("OnEOF")
    if len(c) > 0 {
        fmt.Println(string(c))
    }
}

func (m *newlinesMachine) OnCompletion() {
    fmt.Println("OnCompletion")
}

// Parse composes a new ragel parser for the incoming stream using the current FSM.
func (m *newlinesMachine) Parse(r io.Reader) []string {
    m.lines = []string{}
    p := parser.New(
        parser.ArbitraryReader(r, '\n'),        // How to read the stream
        m,                                      // How to parse it
        parser.WithStart(%%{ write start; }%%), // Options
    )
    p.Parse()
    return m.lines
}