pub trait NamedRule {
// Provided method
fn name(&self) -> Option<&'static str> { ... }
}Expand description
Defines a rule’s name separate from the Rule trait.
Most of the time, the derive macro works well enough for this purpose.
§Why a separate trait?
Since Rule is bound by its slice type,
accessing this function would require knowing that type unambiguously.
However, within crate::define, the macro can only call .name(),
as it doesn’t know the type of the underlying rule,
meaning that it can’t resolve any ambiguity caused by a rule that’s generic over multiple slice types.
However, as this trait doesn’t include the slice type anywhere, there is no ambiguity.
Provided Methods§
Sourcefn name(&self) -> Option<&'static str>
fn name(&self) -> Option<&'static str>
Defines the name printed in errors including this rule.
Examples found in repository?
examples/math.rs (lines 18-19)
18 pub LangTokens -> Vec<Token> = LangToken.consume_all()
19 .map_parsed(|v| v.into_iter().filter_map(|v| v).collect() );
20 LangToken -> Option<Token> =
21 Num : Plus : Minus : Asterisk : Slash : Percent : Carat
22 : LParen : RParen : Ans : _ Whitespace
23 : InvalidChar;
24 // Since Fail returns !, we can coerce from that to a token
25 InvalidChar -> Token from(|_, n| n) = Any, Fail::new(Unexpected::new(arg_0));
26
27 Plus -> Token = '+'.map_parsed(|_| Token::Plus);
28 Minus -> Token = '-'.map_parsed(|_| Token::Minus);
29 Asterisk -> Token = '*'.map_parsed(|_| Token::Asterisk);
30 Slash -> Token = '/'.map_parsed(|_| Token::Slash);
31 Percent -> Token = '%'.map_parsed(|_| Token::Percent);
32 Carat -> Token = '^'.map_parsed(|_| Token::Carat);
33 LParen -> Token = '('.map_parsed(|_| Token::LeftParen);
34 RParen -> Token = ')'.map_parsed(|_| Token::RightParen);
35
36 Ans -> Token = "ans".map_parsed(|_| Token::Ans);
37
38 Num -> Token from(|n| Token::Number(n)) =
39 ("nan", "NaN").map_parsed(|_| f64::NAN) :
40 ("inf", "Infinity").map_parsed(|_| f64::INFINITY) :
41 Float;
42 Float -> f64 try_from(f64::from_str) = FloatTokens.spanned().map_parsed(|span| span.source);
43
44 FloatTokens -> () = _ UInt, _ FloatFract.attempt(), _ FloatExp.attempt();
45 FloatFract -> () = _ '.', _ UInt;
46 FloatExp -> () = _ ('e', 'E'), _ ('-', '+').attempt(), _ UInt;
47
48 UInt -> &'input str = While::from(char::is_ascii_digit);
49 }
50}
51
52define! {
53 grammar TokenMath<[Token]> {
54 pub Expr -> f64 from(parse_expr) = Prod, SumSuf.consume_all();