Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions ebnf/ebnf.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,19 @@ type Term struct {
func (t *Term) sealed() {}

func (t *Term) String() string {
negation := ""
if t.Negation {
negation = "~"
}
switch {
case t.Name != "":
return t.Name + t.Repetition
return negation + t.Name + t.Repetition
case t.Literal != "":
return t.Literal + t.Repetition
return negation + t.Literal + t.Repetition
case t.Token != "":
return "<" + t.Token + ">" + t.Repetition
return negation + "<" + t.Token + ">" + t.Repetition
case t.Group != nil:
return t.Group.String() + t.Repetition
return negation + t.Group.String() + t.Repetition
default:
panic("??")
}
Expand Down Expand Up @@ -92,7 +96,7 @@ func (s *SubExpression) sealed() {}
func (s *SubExpression) String() string {
out := "("
if s.Lookahead != LookaheadAssertionNone {
out += "?" + string(s.Lookahead)
out += "?" + string(s.Lookahead) + " "
}
out += s.Expr.String() + ")"
return out
Expand Down
25 changes: 25 additions & 0 deletions ebnf/ebnf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,28 @@ func TestEBNF(t *testing.T) {
require.NoError(t, err, input)
require.Equal(t, input, ast.String())
}

func TestEBNFRoundTrip(t *testing.T) {
tests := []struct {
name string
input string
}{
{"NegatedLiteral", `Term = ~"a" .`},
{"NegatedToken", `Term = ~<ident> .`},
{"NegatedProduction", `Term = ~Production .`},
{"NegatedGroup", `Term = ~("a" | "b") .`},
{"NegatedRepetition", `Term = ~"a"+ .`},
{"PositiveLookahead", `Term = (?= "a") "b" .`},
{"NegativeLookahead", `Term = (?! "a") "b" .`},
// Verbatim output of Parser.String() for the grammar in
// TestEBNF_Other in the root package.
{"ParserOutput", `Grammar = ((?= "good") <ident>) | ((?! "bad" | "worse") <ident>) | ~("anything" | "but") .`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ast, err := ParseString(test.input)
require.NoError(t, err, test.input)
require.Equal(t, test.input, ast.String())
})
}
}