File: ebnf_test.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 (77 lines) | stat: -rw-r--r-- 1,850 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
package participle_test

import (
	"strings"
	"testing"

	require "github.com/alecthomas/assert/v2"
	"github.com/alecthomas/participle/v2"
)

func TestEBNF(t *testing.T) {
	parser := mustTestParser[EBNF](t)
	expected := `
EBNF = Production* .
Production = <ident> "=" Expression+ "." .
Expression = Sequence ("|" Sequence)* .
Sequence = Term+ .
Term = <ident> | Literal | Range | Group | LookaheadGroup | EBNFOption | Repetition | Negation .
Literal = <string> .
Range = <string> "…" <string> .
Group = "(" Expression ")" .
LookaheadGroup = "(" "?" ("=" | "!") Expression ")" .
EBNFOption = "[" Expression "]" .
Repetition = "{" Expression "}" .
Negation = "!" Expression .
`
	require.Equal(t, strings.TrimSpace(expected), parser.String())
}

func TestEBNF_Other(t *testing.T) {
	type Grammar struct {
		PositiveLookahead string `  (?= 'good') @Ident`
		NegativeLookahead string `| (?! 'bad' | "worse") @Ident`
		Negation          string `| !("anything" | 'but')`
	}

	parser := mustTestParser[Grammar](t)
	expected := `Grammar = ((?= "good") <ident>) | ((?! "bad" | "worse") <ident>) | ~("anything" | "but") .`
	require.Equal(t, expected, parser.String())
}

type (
	EBNFUnion interface{ ebnfUnion() }

	EBNFUnionA struct {
		A string `@Ident`
	}

	EBNFUnionB struct {
		B string `@String`
	}

	EBNFUnionC struct {
		C string `@Float`
	}
)

func (EBNFUnionA) ebnfUnion() {}
func (EBNFUnionB) ebnfUnion() {}
func (EBNFUnionC) ebnfUnion() {}

func TestEBNF_Union(t *testing.T) {
	type Grammar struct {
		TheUnion EBNFUnion `@@`
	}

	parser := mustTestParser[Grammar](t, participle.Union[EBNFUnion](EBNFUnionA{}, EBNFUnionB{}, EBNFUnionC{}))
	require.Equal(t,
		strings.TrimSpace(`
Grammar = EBNFUnion .
EBNFUnion = EBNFUnionA | EBNFUnionB | EBNFUnionC .
EBNFUnionA = <ident> .
EBNFUnionB = <string> .
EBNFUnionC = <float> .
`),
		parser.String())
}