Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need advice: Wrong branch is picked on non-trivial match #336

Closed
gremour opened this issue Apr 22, 2023 · 1 comment
Closed

Need advice: Wrong branch is picked on non-trivial match #336

gremour opened this issue Apr 22, 2023 · 1 comment

Comments

@gremour
Copy link

gremour commented Apr 22, 2023

Hello, and thank you for the awesome library!

I'm trying to create a parser for source code. The stripped down example parsing expressions and assignments would be as following:

package main

import (
	"fmt"

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

const source = `
2;
x+y.z+1;
a=5+x;
a.b=4+y;
a.b=3+x.y+z;
a.b.c;
`

type Scope struct {
	Entry []*Entry `( @@ ";"+)*`
}

type Entry struct {
	Assignment *Value      `(@@ "=")?`
	Expression *Expression `@@`
}

type Expression struct {
	Left     *Value      `@@`
	Operator string      `( @"+"`
	Right    *Expression `@@ )?`
}

type Value struct {
	Int  int   `@Int`
	Path *Path `| @@`
}

type Path struct {
	Ident string   `@Ident`
	Path  []string `( "." @Ident )*`
}

func main() {
	parser := participle.MustBuild[Scope]()
	t, err := parser.ParseString("", source)
	if err != nil {
		fmt.Printf("Error: %v", err)
		return
	}
	repr.Println(t)
}

Parser fails on the last entry:

Error: 7:6: unexpected token ";" (expected "=")

As far as I understand, in Entry it picks Assignment path instead of Expression because it can't know how long will be the repeating Path value.

Not sure if it's the same issue as #216

Could you please suggest any workarounds to make this work? I'm still struggling with advanced regex use cases.

Also, unrelated: when I try to use positive lookahead (?="x"), I always get an error saying that branch matched the symbol in question, but it doesn't progress the lexer. Negative lookahead (?!"x") works as expected.

@gremour
Copy link
Author

gremour commented Apr 22, 2023

As usual, I came to the solution right after asking the question (I've been stuck on this issue for the 3rd day already).

Using participle.UseLookahead(n) option solves the issue. I've just used it incorrectly (called right away instead of passing to participle.MustBuild). Silly mistake.

@gremour gremour closed this as completed Apr 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant