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 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
pub LangTokens -> Vec<Token> = LangToken.consume_all()
.map_parsed(|v| v.into_iter().filter_map(|v| v).collect() );
LangToken -> Option<Token> =
Num : Plus : Minus : Asterisk : Slash : Percent : Carat
: LParen : RParen : Ans : _ Whitespace
: InvalidChar;
// Since Fail returns !, we can coerce from that to a token
InvalidChar -> Token from(|_, n| n) = Any, Fail::new(Unexpected::new(arg_0));
Plus -> Token = '+'.map_parsed(|_| Token::Plus);
Minus -> Token = '-'.map_parsed(|_| Token::Minus);
Asterisk -> Token = '*'.map_parsed(|_| Token::Asterisk);
Slash -> Token = '/'.map_parsed(|_| Token::Slash);
Percent -> Token = '%'.map_parsed(|_| Token::Percent);
Carat -> Token = '^'.map_parsed(|_| Token::Carat);
LParen -> Token = '('.map_parsed(|_| Token::LeftParen);
RParen -> Token = ')'.map_parsed(|_| Token::RightParen);
Ans -> Token = "ans".map_parsed(|_| Token::Ans);
Num -> Token from(|n| Token::Number(n)) =
("nan", "NaN").map_parsed(|_| f64::NAN) :
("inf", "Infinity").map_parsed(|_| f64::INFINITY) :
Float;
Float -> f64 try_from(f64::from_str) = FloatTokens.spanned().map_parsed(|span| span.source);
FloatTokens -> () = _ UInt, _ FloatFract.attempt(), _ FloatExp.attempt();
FloatFract -> () = _ '.', _ UInt;
FloatExp -> () = _ ('e', 'E'), _ ('-', '+').attempt(), _ UInt;
UInt -> &'input str = While::from(char::is_ascii_digit);
}
}
define! {
grammar TokenMath<[Token]> {
pub Expr -> f64 from(parse_expr) = Prod, SumSuf.consume_all();