forked from alecthomas/participle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
54 lines (46 loc) · 1.12 KB
/
main.go
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
package main
import (
"os"
"github.com/alecthomas/participle"
"github.com/alecthomas/participle/lexer"
"github.com/alecthomas/repr"
)
// A custom lexer for INI files. This illustrates a relatively complex Regexp lexer, as well
// as use of the Unquote filter, which unquotes string tokens.
var iniLexer = lexer.Must(lexer.Regexp(
`(?m)` +
`(\s+)` +
`|(^[#;].*$)` +
`|(?P<Ident>[a-zA-Z][a-zA-Z_\d]*)` +
`|(?P<String>"(?:\\.|[^"])*")` +
`|(?P<Float>\d+(?:\.\d+)?)` +
`|(?P<Punct>[][=])`,
))
type INI struct {
Properties []*Property `{ @@ }`
Sections []*Section `{ @@ }`
}
type Section struct {
Identifier string `"[" @Ident "]"`
Properties []*Property `{ @@ }`
}
type Property struct {
Key string `@Ident "="`
Value *Value `@@`
}
type Value struct {
String *string ` @String`
Number *float64 `| @Float`
}
func main() {
parser, err := participle.Build(&INI{}, participle.Lexer(iniLexer), participle.Unquote(iniLexer, "String"))
if err != nil {
panic(err)
}
ini := &INI{}
err = parser.Parse(os.Stdin, ini)
if err != nil {
panic(err)
}
repr.Println(ini, repr.Indent(" "), repr.OmitEmpty(true))
}