participle icon indicating copy to clipboard operation
participle copied to clipboard

Proposal: Support grammar aliases.

Open alecthomas opened this issue 7 years ago • 7 comments

In moderately complex grammars it's fairly common to see duplicate patterns emerge. For example, when matching a dot-separated identifier (eg. foo.bar) the pattern (Ident { "." Ident }) is used repeatedly. This can be handled by a Go type alias implementing the Parseable interface, but that is quite onerous.

I propose adding support for grammar aliases. Here's an example creating and using an Identifier alias:

type Assignment struct {
  Name string `@Identifier=(Ident { "." Ident })`
  Variable string `"=" @Identifier`
}

alecthomas avatar May 10 '18 04:05 alecthomas

Alternatively (or in addition to) just making it easier to go from a grammar string to something which implements Parseable would be nice. One way of factoring out the common patterns is to put them in a separate struct and using @@, but that introduces an otherwise unnecessary layer of indirection.

Having a facility parallel to Build which took a "root" instance and grammar string and returned a semi-parser would go a long way, e.g.

var identParser = participle.MustParseable(&Identifier{}, `@(Ident { "." Ident })`)

type Identifer string
type Assignment struct {
  Name Identifier `@@`
  Variable Identifier `"=" @@`
}

func (i *Identifer) Parse(l lexer.PeekingLexer) error {
  return identParser.ParseInto(i, l)
}

shahms avatar Feb 12 '19 23:02 shahms

That's not a bad idea at all. All it would take would be to add an extra method to the Parser.

alecthomas avatar Feb 14 '19 09:02 alecthomas

Though it's a bit inconvenient in that, as you say, you end up with a separate struct where you might only need a string or int or whatever.

alecthomas avatar Feb 14 '19 09:02 alecthomas

any updates?

testitm avatar Jan 22 '22 21:01 testitm

I haven't thought of a good API for this yet unfortunately.

alecthomas avatar Jan 22 '22 23:01 alecthomas

My usual pattern is to pull the field out into a struct. It's a bit uglier for the AST though.

alecthomas avatar Jan 22 '22 23:01 alecthomas

Is there any accepted approach that I could use to do what @shahms suggested in this comment?

I'm trying to understand the most appropriate way to "jump back" into the normal grammar from within an implementation of Parseable that implements precedence climbing as per the example.

jmalloc avatar Jan 24 '24 23:01 jmalloc