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
|
package main
import (
"os"
"github.com/alecthomas/repr"
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
)
// 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.MustSimple([]lexer.SimpleRule{
{`Ident`, `[a-zA-Z][a-zA-Z_\d]*`},
{`String`, `"(?:\\.|[^"])*"`},
{`Float`, `\d+(?:\.\d+)?`},
{`Punct`, `[][=]`},
{"comment", `[#;][^\n]*`},
{"whitespace", `\s+`},
})
parser = participle.MustBuild[INI](
participle.Lexer(iniLexer),
participle.Unquote("String"),
participle.Union[Value](String{}, Number{}),
)
)
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 interface{ value() }
type String struct {
String string `@String`
}
func (String) value() {}
type Number struct {
Number float64 `@Float`
}
func (Number) value() {}
func main() {
ini, err := parser.Parse("", os.Stdin)
repr.Println(ini, repr.Indent(" "), repr.OmitEmpty(true))
if err != nil {
panic(err)
}
}
|