File: multiline.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, trixie
  • size: 116 kB
  • sloc: makefile: 26
file content (89 lines) | stat: -rw-r--r-- 1,923 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package examples

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

%%{
machine multiline;

# unsigned alphabet
alphtype uint8;

action on_trailer {
    // Collect data each trailer we encounter
    m.item = append(m.item, data...)
}

action on_init {
    if len(m.item) > 0 {
        m.items = append(m.items, string(m.item[:len(m.item)-1]))
    }
    // Initialize a new item
    m.item = make([]byte, 0)
}

t = 10;

main := 
    start: (
        # Note that corpus can contain trailers - ie., can span more lines in this case.
        '$' >on_init (digit | t)+ -> trailer
    ),
    trailer: (
        t >on_trailer -> final |
        t >on_trailer -> start 
    );
}%%

%% write data nofinal;

type multilineMachine struct{
    // define here your support variables for ragel actions
    item []byte
    items []string
}

// Exec implements the ragel.Parser interface.
func (m *multilineMachine) Exec(s *parser.State) (int, int) {
    // Retrieve previously stored parsing variables
    cs, 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 *multilineMachine) OnErr(c []byte) {
    fmt.Println("OnErr")
    if len(c) > 0 {
        fmt.Println(string(c))
    }
}

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

func (m *multilineMachine) OnCompletion() {
    fmt.Println("OnCompletion")
    if len(m.item) > 0 {
        m.items = append(m.items, string(m.item))
    }
}

func (m *multilineMachine) Parse(r io.Reader) {
    m.items = []string{}
    p := parser.New(
        parser.ArbitraryReader(r, 10),          // How to read the stream
        m,                                      // How to parse it
        parser.WithStart(%%{ write start; }%%), // Options    
    )
    p.Parse()
}