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

Choice with multiple parser types #54

Closed
m-decoster opened this issue Dec 20, 2015 · 2 comments
Closed

Choice with multiple parser types #54

m-decoster opened this issue Dec 20, 2015 · 2 comments

Comments

@m-decoster
Copy link

It doesn't seem possible to use choice with different types: consider an assignment of a variable:

a = b.

I would express this with (env.identifier(), env.symbol("="), choice([env.integer(), env.identifier()]), but the compiler complains that it expects an i64 instead of a String.

How can I express this without writing two separate parsers?

@Marwes
Copy link
Owner

Marwes commented Dec 20, 2015

I am guessing you have some sort of expression type which is represented as an enum like

enum Expr {
    Int(i64),
    Identifier(String),
}

If so you can just use the map parser to make them return the the Expr type

choice([env.integer().map(Expr::Int), env.identifier().map(Expr::Identifier)])

Unfortunately you will encounter another problem when you do this as each parser needs to have the same type as well as they are stored in an array which necessitates that all elements have the same type. For small number of alternations the or which allows the parsers to have distinct types as long as they all have the same return type.

For the choice parser it is however possible to cast each of the parser to a trait object which makes sure that they are all the same type.

choice::<&mut [&mut Parser<Input=InputType, Output=Expr>]>(&mut [
    &mut env.integer().map(Expr::Int),
    &mut env.identifier().map(Expr::Identifier)
])

You can see exactly how I do it in the parser I made for embed_lang here though there is some extra complexity there as well to inject location in the expression as well.

@m-decoster
Copy link
Author

Thank you for the detailed reply. As for me, this issue can now be closed.

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

2 participants