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

How to match and return a one char? #234

Closed
Mingun opened this issue Jul 12, 2020 · 3 comments
Closed

How to match and return a one char? #234

Mingun opened this issue Jul 12, 2020 · 3 comments

Comments

@Mingun
Copy link

Mingun commented Jul 12, 2020

I'm tries to write parser, that will return one matched char and I do not see, how I can achieve that in simple way:

rule quotedChar() -> char = ['a'|'b'|'t'|'n'|'v'|'f'|'r'|'e'|'\''|'"'|'\\'];
rule quotedChar() -> char = ch:['a'|'b'|'t'|'n'|'v'|'f'|'r'|'e'|'\''|'"'|'\\'] { ch };

Both infers return type as (). For now I found only such solution:

rule quotedChar() -> char = ch:$['a'|'b'|'t'|'n'|'v'|'f'|'r'|'e'|'\''|'"'|'\\'] { ch.chars().next().unwrap() };

Is there any better solution?

@kevinmehall
Copy link
Owner

I think that's the best that exists right now. I don't remember the reason why [] doesn't return a reference to the matched item from the input. I'll leave this open to see if that can be added or document the reason why not.

@kevinmehall
Copy link
Owner

kevinmehall commented Aug 22, 2020

This requires generic associated types to do the right way for parsers over [T] -- ParseElem::Elem should be a reference to avoid having to clone the element to both use it in the pattern and return it. This would also be a breaking change, so deferring until at least 0.7.

@wlott
Copy link

wlott commented Mar 30, 2021

ch.chars().next().unwrap()

Is there any better solution?

I personally have found:

char::from_str(s).unwrap()

to read slightly better. Granted, it will panic if the matched string isn't one character while the .chars().unwrap() will only panic if there are zero characters in the string. That may be a good thing or a bad thing depending on your views towards fault tolerance vs rigorous consistency checking.

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

3 participants