Debian Codegraph @

tests/run-pass/conditional_block.rs

raw symbols SCIP
1 extern crate peg;
2
3 peg::parser!( grammar parse() for str {
4
5 pub rule dec_byte() -> u8
6 = match_str:$(['0'..='9']*<,3>) {?
7 let val: u64 = match_str.parse().unwrap();
8
9 // only let this rule match if the value is in range 0..255
10 if val <= 255 {
11 Ok(val as u8)
12 } else {
13 // the message explains what the rule expected and is used in the parse error
14 Err("decimal byte")
15 }
16 }
17
18 rule tag() -> &'input str
19 = $(['a'..='z']+)
20
21 pub rule xml()
22 = "<" open:tag() ">" xml()* "</" close:tag() ">" {?
23 if open == close {
24 Ok(())
25 } else {
26 // TODO this has to be a `&'static str`, so we can't use a dynamic string
27 Err("matching close tag")
28 }
29 }
30
31 pub rule return_early() -> i32 = vs:$([_]+) {?
32 let v = vs.parse::<i32>().map_err(|_| "number")?;
33 if v > 100 {
34 return Err("smaller number");
35 }
36 Ok(v)
37 }
38 });
39
40 fn main() {
41 assert_eq!(parse::dec_byte("0"), Ok(0));
42 assert_eq!(parse::dec_byte("255"), Ok(255));
43 assert_eq!(parse::dec_byte("1"), Ok(1));
44 assert!(parse::dec_byte("256").is_err());
45 assert!(parse::dec_byte("1234").is_err());
46
47 assert!(parse::xml("<a></a>").is_ok());
48 assert!(parse::xml("<a><b></b><c></c></a>").is_ok());
49 assert!(parse::xml("<a><b><c></b></c></a>").is_err());
50 assert!(parse::xml("<a><b></c><c></b></a>").is_err());
51
52 assert!(parse::return_early("a").unwrap_err().expected.tokens().any(|e| e == "number"));
53 assert!(parse::return_early("123").unwrap_err().expected.tokens().any(|e| e == "smaller number"));
54 assert_eq!(parse::return_early("99").unwrap(), 99);
55 }