-
Hello 👋 My question: Is it possible to parse the following grammar without implementing a custom lexer? I'm trying to write a parser for a grammar similar to the tree-sitter test file format. File:
The grammar would be:
where filePath is a line of text and content is any string except for I got this far: type TestFile struct {
Path string `FileStart@Content`
Content string `ContentStart@Content`
}
type Example struct {
Input []TestFile `@@*`
}
var (
exampleLexer = lexer.MustSimple([]lexer.SimpleRule{
{`FileStart`, `===`},
{`ContentStart`, `---`},
{"whitespace", `\s+`},
{"Content", `[^\n]+`},
})
exampleParser = participle.MustBuild[Example](
participle.Lexer(exampleLexer),
)
) But because I defined content as I was excited about defining the grammar in struct field tags, but for this particular case, it might be simpler/easier to write custom code that reads the input line-by-line. WDYT? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I'd probably do something like: type TestFile struct {
Path string `FileStart @(Content '\n'?)+`
Content string `ContentStart @(Content \n'?)+`
} |
Beta Was this translation helpful? Give feedback.
Thanks @alecthomas you helped me heaps! That was almost the solution 🙇. Since I care about the new lines in the
Content
field, I had to make the new line an explicit symbol like thisExplanation for other people who might look at this:
Since the lexer tries the rules in order, each line will try the
FileStart
…