File: main.go

package info (click to toggle)
golang-github-alecthomas-participle-v2 2.1.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 920 kB
  • sloc: javascript: 1,164; sh: 41; makefile: 7
file content (86 lines) | stat: -rw-r--r-- 1,817 bytes parent folder | download
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
// nolint: golint, dupl
package main

import (
	"os"

	"github.com/alecthomas/kong"

	"github.com/alecthomas/participle/v2"
	"github.com/alecthomas/participle/v2/lexer"
)

var (
	jsonLexer = lexer.MustSimple([]lexer.SimpleRule{
		{Name: "Comment", Pattern: `\/\/[^\n]*`},
		{Name: "String", Pattern: `"(\\"|[^"])*"`},
		{Name: "Number", Pattern: `[-+]?(\d*\.)?\d+`},
		{Name: "Punct", Pattern: `[-[!@#$%^&*()+_={}\|:;"'<,>.?/]|]`},
		{Name: "Null", Pattern: "null"},
		{Name: "True", Pattern: "true"},
		{Name: "False", Pattern: "false"},
		{Name: "EOL", Pattern: `[\n\r]+`},
		{Name: "Whitespace", Pattern: `[ \t]+`},
	})

	jsonParser = participle.MustBuild[Json](
		participle.Lexer(jsonLexer),
		participle.Unquote("String"),
		participle.Elide("Whitespace", "EOL"),
		participle.UseLookahead(2),
	)

	cli struct {
		File string `arg:"" type:"existingfile" help:"File to parse."`
	}
)

// Parse a Json string.
func Parse(data []byte) (*Json, error) {
	json, err := jsonParser.ParseBytes("", data)
	if err != nil {
		return nil, err
	}
	return json, nil
}

type Json struct {
	Pos lexer.Position

	Object *Object `parser:"@@ |"`
	Array  *Array  `parser:"@@ |"`
	Number *string `parser:"@Number |"`
	String *string `parser:"@String |"`
	False  *string `parser:"@False |"`
	True   *string `parser:"@True |"`
	Null   *string `parser:"@Null"`
}

type Object struct {
	Pos lexer.Position

	Pairs []*Pair `parser:"'{' @@ (',' @@)* '}'"`
}

type Pair struct {
	Pos lexer.Position

	Key   string `parser:"@String ':'"`
	Value *Json  `parser:"@@"`
}

type Array struct {
	Pos lexer.Position

	Items []*Json `parser:"'[' @@ (',' @@)* ']'"`
}

func main() {
	ctx := kong.Parse(&cli)
	data, err := os.ReadFile(cli.File)
	ctx.FatalIfErrorf(err)

	res, err := Parse(data)
	ctx.FatalIfErrorf(err)
	ctx.Printf("res is: %v", res)
}