├── .gitignore ├── doc_images ├── basic.png ├── simple_parser.png └── automatic_diagram.png ├── Cargo.toml ├── src ├── parser │ ├── test.rs │ ├── atom │ │ ├── test.rs │ │ └── mod.rs │ ├── mod.rs │ └── expression │ │ ├── test.rs │ │ └── mod.rs ├── peg │ ├── peg2code.rs │ ├── gcode.rs │ ├── test.rs │ ├── rules.rs │ └── mod.rs ├── main.rs ├── ast │ ├── flat.rs │ └── mod.rs └── lib.rs ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .* 4 | -------------------------------------------------------------------------------- /doc_images/basic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jleahred/dynparser/HEAD/doc_images/basic.png -------------------------------------------------------------------------------- /doc_images/simple_parser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jleahred/dynparser/HEAD/doc_images/simple_parser.png -------------------------------------------------------------------------------- /doc_images/automatic_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jleahred/dynparser/HEAD/doc_images/automatic_diagram.png -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dynparser" 3 | version = "0.4.3" 4 | edition = "2018" 5 | authors = ["jleahred "] 6 | license = "GPL-3.0" 7 | description = "Dynamic parser. You can define rules at run time. It's possible to use peg format" 8 | readme = "README.md" 9 | repository = "https://github.com/jleahred/dynparser" 10 | keywords = ["parsing", "parser", "dynamic", "peg"] 11 | 12 | [dependencies] 13 | idata = "0.1.0" 14 | -------------------------------------------------------------------------------- /src/parser/test.rs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // mod parser TEST 4 | // 5 | //----------------------------------------------------------------------- 6 | 7 | use crate::parser::{expression::parse, Status}; 8 | 9 | #[test] 10 | fn test_parse_expr_lit() { 11 | let rules = rules! {"main" => lit!("aaa")}; 12 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 13 | 14 | let (status, _) = parse(status_init).ok().unwrap(); 15 | assert!(status.pos.col == 3); 16 | assert!(status.pos.n == 3); 17 | assert!(status.pos.row == 0); 18 | } 19 | 20 | #[test] 21 | fn test_parse_expr_and_ok() { 22 | let rules = rules! {"main" => and![lit!("aa"), and![lit!("bb"), lit!("cc")]]}; 23 | let status_init = Status::init("aabbcc", &rules); 24 | 25 | let (status, _) = parse(status_init).ok().unwrap(); 26 | assert_eq!(status.pos.col, 6); 27 | assert_eq!(status.pos.n, 6); 28 | assert_eq!(status.pos.row, 0); 29 | } 30 | 31 | #[test] 32 | fn test_parse_expr_or_ok() { 33 | let rules = rules! {"main" => or![lit!("bb"), and![lit!("aa"), lit!("bb")]]}; 34 | let status_init = Status::init("aabb", &rules); 35 | 36 | let (status, _) = parse(status_init).ok().unwrap(); 37 | assert_eq!(status.pos.col, 4); 38 | assert_eq!(status.pos.n, 4); 39 | assert_eq!(status.pos.row, 0); 40 | } 41 | 42 | #[test] 43 | fn test_parse_expr_not_ok() { 44 | let rules = rules! {"main" => not!(lit!("bb"))}; 45 | let status_init = Status::init("aa", &rules); 46 | 47 | let (status, _) = parse(status_init).ok().unwrap(); 48 | assert_eq!(status.pos.col, 0); 49 | assert_eq!(status.pos.n, 0); 50 | assert_eq!(status.pos.row, 0); 51 | } 52 | 53 | #[test] 54 | fn test_parse_expr_repeat_ok() { 55 | let rules = rules! {"main" => rep![lit!("aa"), 3]}; 56 | { 57 | let status_init = Status::init("aaaaaa", &rules); 58 | 59 | let (status, _) = parse(status_init).ok().unwrap(); 60 | assert_eq!(status.pos.col, 6); 61 | assert_eq!(status.pos.n, 6); 62 | assert_eq!(status.pos.row, 0); 63 | } 64 | 65 | // { 66 | // let status_init = Status::init("aaaaaa", rep![lit!("aa"), 0, 3]); 67 | 68 | // let result = parse(status_init).ok().unwrap(); 69 | // assert_eq!(result.status.pos.col, 6); 70 | // assert_eq!(result.status.pos.n, 6); 71 | // assert_eq!(result.status.pos.row, 0); 72 | // } 73 | } 74 | -------------------------------------------------------------------------------- /src/peg/peg2code.rs: -------------------------------------------------------------------------------- 1 | //! Here it's the peg grammar to parse the peg input ;-P 2 | //! 3 | //! There is also a function to print the rust source code 4 | //! 5 | //! It's used in order to develop myself 6 | //! 7 | //! A parser for the parser (you know) 8 | //! 9 | //! To generate the code to parse the peg, you just have to run... 10 | //! 11 | //! ``` 12 | //! extern crate dynparser; 13 | //! use dynparser::peg::peg2code; 14 | //! 15 | //! fn main() { 16 | //! peg2code::print_rules2parse_peg(); 17 | //! } 18 | //! ``` 19 | //! 20 | //! And the result, has to be pasted in peg::rules.rs 21 | //! 22 | 23 | use {crate::peg, crate::rules_from_peg}; 24 | 25 | fn text_peg2code() -> &'static str { 26 | r#" 27 | /* A peg grammar to parse peg grammars 28 | * 29 | */ 30 | 31 | main = grammar 32 | 33 | grammar = (rule / module)+ 34 | 35 | module = _ mod_name _ '{' _ grammar _ '}' _eol _ 36 | mod_name = symbol 37 | symbol = [_a-zA-Z0-9] [_'"a-zA-Z0-9]* 38 | 39 | rule = _ rule_name _ '=' _ expr _eol _ 40 | rule_name = '.'? symbol ('.' symbol)* 41 | 42 | expr = or 43 | 44 | or = and ( _ '/' _ or )? 45 | error = 'error' _ '(' _ literal _ ')' 46 | 47 | and = error 48 | / rep_or_neg ( _1 _ !(rule_name _ ('=' / '{')) and )* 49 | _1 = (' ' / eol) // this is the and separator 50 | 51 | rep_or_neg = atom_or_par ('*' / '+' / '?')? 52 | / '!' atom_or_par 53 | 54 | atom_or_par = (atom / parenth) 55 | 56 | parenth = '(' _ expr _ ( ')' 57 | / error("unbalanced parethesis: missing ')'") 58 | ) 59 | 60 | atom = literal 61 | / match 62 | / rule_name 63 | / dot // as rule_name can start with a '.', dot has to be after rule_name 64 | 65 | literal = lit_noesc / lit_esc 66 | 67 | lit_noesc = _' ( !_' . )* _' 68 | _' = "'" 69 | 70 | lit_esc = _" 71 | ( esc_char 72 | / hex_char 73 | / !_" . 74 | )* 75 | _" 76 | _" = '"' 77 | 78 | esc_char = '\r' 79 | / '\n' 80 | / '\t' 81 | / '\\' 82 | / '\"' 83 | 84 | hex_char = '\0x' [0-9A-F] [0-9A-F] 85 | 86 | eol = ("\r\n" / "\n" / "\r") 87 | _eol = (' ' / comment)* eol 88 | 89 | match = '[' 90 | ( 91 | (mchars mbetween*) 92 | / mbetween+ 93 | ) 94 | ']' 95 | 96 | mchars = (!']' !(. '-') .)+ 97 | mbetween = (. '-' .) 98 | 99 | dot = '.' 100 | 101 | _ = ( ' ' 102 | / eol 103 | / comment 104 | )* 105 | 106 | comment = line_comment 107 | / mline_comment 108 | 109 | line_comment = '//' (!eol .)* eol 110 | mline_comment = '/*' (!'*/' .)* '*/' 111 | "# 112 | } 113 | 114 | /// A parser for the parser. 115 | /// 116 | /// It will take the peg grammar to parse peg grammars 117 | /// 118 | pub fn print_rules2parse_peg() { 119 | let rules = rules_from_peg(text_peg2code()) 120 | .map_err(|e| { 121 | println!("{}", e); 122 | panic!("FAIL"); 123 | }) 124 | .unwrap(); 125 | 126 | println!("{}", peg::gcode::rust_from_rules(&rules)) 127 | } 128 | -------------------------------------------------------------------------------- /src/peg/gcode.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | //! Generate source code from a set of rules 3 | //! 4 | //! example 5 | //! ```rust 6 | //! extern crate dynparser; 7 | //! use dynparser::{peg, rules_from_peg}; 8 | //! 9 | //! fn main() { 10 | //! let rules = rules_from_peg( 11 | //! r#" 12 | //! 13 | //! main = as / a bs 14 | //! 15 | //! as = a+ 16 | //! 17 | //! a = 'a' 18 | //! 19 | //! bs = 'b'+ 20 | //! 21 | //! "#, 22 | //! ).map_err(|e| { 23 | //! println!("{}", e); 24 | //! panic!("FAIL"); 25 | //! }) 26 | //! .unwrap(); 27 | //! 28 | //! println!("{}", peg::gcode::rust_from_rules(&rules)) 29 | //! } 30 | //! ``` 31 | //! The parser itself uses a peg grammar and generate the rules with this 32 | //! function 33 | //! 34 | //! The rules code generated by this program will be 35 | //! ```ignore 36 | //! "as" => rep!(ref_rule!("a"), 1) 37 | //! , "a" => lit!("a") 38 | //! , "main" => or!(ref_rule!("as"), and!(ref_rule!("a"), ref_rule!("bs"))) 39 | //! , "bs" => rep!(lit!("b"), 1) 40 | //! ``` 41 | 42 | use crate::parser::{ 43 | atom, 44 | atom::Atom, 45 | expression::{self, Expression}, 46 | }; 47 | 48 | /// Generate a string with rust code from a ```expression::SetOfRules``` 49 | pub fn rust_from_rules(rules: &expression::SetOfRules) -> String { 50 | let add_rule = |crules: String, rule: &str| -> String { 51 | let begin = if crules == "" { " " } else { ", " }; 52 | crules + "\n " + begin + rule 53 | }; 54 | 55 | rules.0.iter().fold("".to_string(), |acc, (name, expr)| { 56 | add_rule(acc, &rule2code(name, expr)) 57 | }) 58 | } 59 | 60 | fn rule2code(name: &str, expr: &Expression) -> String { 61 | format!(r##"r#"{}"# => {}"##, name, expr2code(expr)) 62 | } 63 | 64 | fn expr2code(expr: &Expression) -> String { 65 | match expr { 66 | Expression::Simple(atom) => atom2code(atom), 67 | Expression::And(mexpr) => format!("and!({})", mexpr2code(mexpr)), 68 | Expression::Or(mexpr) => format!("or!({})", mexpr2code(mexpr)), 69 | Expression::Not(e) => format!("not!({})", expr2code(e)), 70 | Expression::Repeat(rep) => repeat2code(rep), 71 | Expression::RuleName(rname) => format!(r##"ref_rule!(r#"{}"#)"##, rname), 72 | } 73 | } 74 | 75 | fn mexpr2code(mexpr: &expression::MultiExpr) -> String { 76 | mexpr 77 | .0 78 | .iter() 79 | .fold(String::new(), |acc, expr| match acc.len() { 80 | 0 => expr2code(expr).to_string(), 81 | _ => format!("{}, {}", acc, expr2code(expr)), 82 | }) 83 | } 84 | 85 | fn atom2code(atom: &Atom) -> String { 86 | let replace_esc = |s: String| { 87 | s.replace("\n", r#"\n"#) 88 | .replace("\r", r#"\r"#) 89 | .replace("\t", r#"\t"#) 90 | .replace(r#"""#, r#"\""#) 91 | }; 92 | 93 | match atom { 94 | Atom::Literal(s) => format!(r#"lit!("{}")"#, replace_esc(s.to_string())), 95 | Atom::Error(s) => format!(r#"error!("{}")"#, replace_esc(s.to_string())), 96 | Atom::Match(mrules) => match_rules2code(mrules), 97 | Atom::Dot => "dot!()".to_string(), 98 | Atom::EOF => "eof!()".to_string(), 99 | } 100 | } 101 | 102 | fn match_rules2code(mrules: &atom::MatchRules) -> String { 103 | fn bounds2code(acc: String, bounds: &[(char, char)]) -> String { 104 | match bounds.split_first() { 105 | Some(((f, t), rest)) => { 106 | format!(", from '{}', to '{}' {}", f, t, bounds2code(acc, rest)) 107 | } 108 | None => acc, 109 | } 110 | } 111 | 112 | format!( 113 | r##"ematch!(chlist r#"{}"# {})"##, 114 | &mrules.0, 115 | bounds2code(String::new(), &mrules.1) 116 | ) 117 | } 118 | 119 | fn repeat2code(rep: &expression::RepInfo) -> String { 120 | "rep!(".to_owned() 121 | + &expr2code(&rep.expression) 122 | + ", " 123 | + &rep.min.0.to_string() 124 | + &match rep.max { 125 | Some(ref m) => format!(", {}", m.0), 126 | None => "".to_owned(), 127 | } 128 | + ")" 129 | } 130 | -------------------------------------------------------------------------------- /src/parser/atom/test.rs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // mod parser::atom TEST 4 | // 5 | //----------------------------------------------------------------------- 6 | use super::Status; 7 | use super::{parse_dot, parse_eof, parse_literal, parse_match, MatchRules}; 8 | 9 | #[test] 10 | fn test_parse_literal_ok() { 11 | let rules = rules!{}; 12 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 13 | let (status_end, _) = parse_literal(status_init, "aaa").ok().unwrap(); 14 | 15 | assert!(status_end.pos.col == 3); 16 | assert!(status_end.pos.n == 3); 17 | assert!(status_end.pos.row == 0); 18 | } 19 | 20 | #[test] 21 | fn test_parse_literal_ok2() { 22 | let rules = rules!{}; 23 | let status_init = Status::init("abcdefghij", &rules); 24 | let (status_end, _) = parse_literal(status_init, "abc").ok().unwrap(); 25 | 26 | assert_eq!(status_end.pos.col, 3); 27 | assert_eq!(status_end.pos.n, 3); 28 | assert_eq!(status_end.pos.row, 0); 29 | } 30 | 31 | #[test] 32 | fn test_parse_literal_fail() { 33 | let rules = rules!{}; 34 | let status_init = Status::init("abcdefghij", &rules); 35 | assert!(parse_literal(status_init, "bbb").is_err()); 36 | } 37 | 38 | #[test] 39 | fn test_parse_literal_fail2() { 40 | let rules = rules!{}; 41 | let status_init = Status::init("abcdefghij", &rules); 42 | assert!(parse_literal(status_init, "abd").is_err()); 43 | } 44 | 45 | #[test] 46 | fn test_parse_literal_fail_short_text2parse() { 47 | let rules = rules!{}; 48 | let status_init = Status::init("abcd", &rules); 49 | assert!(parse_literal(status_init, "abcdefghij").is_err()); 50 | } 51 | 52 | #[test] 53 | fn test_parse_literal_with_new_line() { 54 | let rules = rules!{}; 55 | let status_init = Status::init( 56 | "aa 57 | aaaaaaaaaaaaaa", 58 | &rules, 59 | ); 60 | let (status_end, _) = parse_literal( 61 | status_init, 62 | "aa 63 | a", 64 | ).ok() 65 | .unwrap(); 66 | 67 | assert!(status_end.pos.col == 1); 68 | assert!(status_end.pos.row == 1); 69 | } 70 | 71 | #[test] 72 | fn test_parse_dot() { 73 | let rules = rules!{}; 74 | let status = Status::init("ab", &rules); 75 | 76 | let (status, _) = parse_dot(status).ok().unwrap(); 77 | assert!(status.pos.col == 1); 78 | assert!(status.pos.n == 1); 79 | assert!(status.pos.row == 0); 80 | 81 | let (status, _) = parse_dot(status).ok().unwrap(); 82 | assert!(status.pos.col == 2); 83 | assert!(status.pos.n == 2); 84 | assert!(status.pos.row == 0); 85 | 86 | assert!(parse_dot(status).is_err()); 87 | } 88 | 89 | #[test] 90 | fn test_parse_match_ok() { 91 | let rules = rules!{}; 92 | let status = Status::init("a f0ghi", &rules); 93 | 94 | let match_rules = MatchRules::new().with_chars("54321ed_cba"); 95 | let (status, _) = parse_match(status, &match_rules).ok().unwrap(); 96 | assert_eq!(status.pos.col, 1); 97 | assert_eq!(status.pos.n, 1); 98 | assert_eq!(status.pos.row, 0); 99 | 100 | let (status, _) = parse_dot(status).ok().unwrap(); 101 | 102 | let match_rules = MatchRules::new().with_bound_chars(vec![('f', 'g'), ('h', 'j')]); 103 | let (status, _) = parse_match(status, &match_rules).ok().unwrap(); 104 | assert_eq!(status.pos.col, 3); 105 | assert_eq!(status.pos.n, 3); 106 | assert_eq!(status.pos.row, 0); 107 | 108 | assert!(parse_match(status, &match_rules).is_err()); 109 | } 110 | 111 | #[test] 112 | fn test_parse_match_err() { 113 | let rules = rules!{}; 114 | let status = Status::init("a9", &rules); 115 | 116 | let match_rules = MatchRules::new().with_chars("ed_cba"); 117 | let (status, _) = parse_match(status, &match_rules).ok().unwrap(); 118 | assert_eq!(status.pos.col, 1); 119 | assert_eq!(status.pos.n, 1); 120 | assert_eq!(status.pos.row, 0); 121 | 122 | let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '8')]); 123 | assert!(parse_match(status, &match_rules).is_err()); 124 | } 125 | 126 | #[test] 127 | fn test_parse_match_eof_ok() { 128 | let rules = rules!{}; 129 | let status = Status::init("a", &rules); 130 | 131 | let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '9')]); 132 | let (status, _) = parse_match(status, &match_rules).ok().unwrap(); 133 | 134 | assert!(parse_eof(status).is_ok()); 135 | } 136 | 137 | #[test] 138 | fn test_parse_match_eof_error() { 139 | let rules = rules!{}; 140 | let status = Status::init("ab", &rules); 141 | 142 | let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '9')]); 143 | let (status, _) = parse_match(status, &match_rules).ok().unwrap(); 144 | 145 | assert!(parse_eof(status).is_err()); 146 | } 147 | -------------------------------------------------------------------------------- /src/parser/atom/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::ast; 2 | /// Support for minimum expressions elements 3 | /// Here we have the parser and types for non dependencies kind 4 | use crate::parser::{ErrPriority, Error, Result, Status}; 5 | use std::result; 6 | 7 | #[cfg(test)] 8 | mod test; 9 | 10 | //----------------------------------------------------------------------- 11 | //----------------------------------------------------------------------- 12 | // 13 | // T Y P E S 14 | // 15 | //----------------------------------------------------------------------- 16 | //----------------------------------------------------------------------- 17 | 18 | /// This is a minimum expression element 19 | #[derive(Debug)] 20 | pub enum Atom { 21 | /// Literal string 22 | Literal(String), 23 | /// Character matches a list of chars or a list of ranges 24 | Match(MatchRules), 25 | /// Indicates an error. 26 | /// It will propagate an error while processing 27 | Error(String), 28 | /// Any char 29 | Dot, 30 | /// End Of File 31 | EOF, 32 | } 33 | 34 | /// contains a char slice and a (char,char) slice 35 | /// if char matches one in char slice -> OK 36 | /// if char matches between tuple in elems slice -> OK 37 | #[derive(Debug)] 38 | pub struct MatchRules(pub(crate) String, pub(crate) Vec<(char, char)>); 39 | 40 | impl MatchRules { 41 | /// get a reference to set of chars of match rule 42 | pub fn chars(&self) -> &str { 43 | &self.0 44 | } 45 | 46 | /// get a reference to vector of ranges (from, to )of match rule 47 | pub fn ranges(&self) -> &Vec<(char, char)> { 48 | &self.1 49 | } 50 | } 51 | 52 | //----------------------------------------------------------------------- 53 | //----------------------------------------------------------------------- 54 | // 55 | // A P I 56 | // 57 | //----------------------------------------------------------------------- 58 | //----------------------------------------------------------------------- 59 | 60 | pub(crate) fn parse<'a>(status: Status<'a>, atom: &'a Atom) -> Result<'a> { 61 | match atom { 62 | Atom::Literal(literal) => parse_literal(status, &literal), 63 | Atom::Error(error) => parse_error(&status, &error), 64 | Atom::Match(ref match_rules) => parse_match(status, &match_rules), 65 | Atom::Dot => parse_dot(status), 66 | Atom::EOF => parse_eof(status), 67 | } 68 | } 69 | 70 | impl MatchRules { 71 | /// Create a MatchRules instance based on string and bounds 72 | pub fn init(s: &str, bounds: Vec<(char, char)>) -> Self { 73 | MatchRules(s.to_string(), bounds) 74 | } 75 | #[allow(dead_code)] // used in tests 76 | pub(crate) fn new() -> Self { 77 | MatchRules("".to_string(), vec![]) 78 | } 79 | #[allow(dead_code)] // used in tests 80 | pub(crate) fn with_chars(mut self, chrs: &str) -> Self { 81 | self.0 = chrs.to_string(); 82 | self 83 | } 84 | #[allow(dead_code)] // used in tests 85 | pub(crate) fn with_bound_chars(mut self, bounds: Vec<(char, char)>) -> Self { 86 | self.1 = bounds; 87 | self 88 | } 89 | } 90 | 91 | //----------------------------------------------------------------------- 92 | // 93 | // SUPPORT 94 | // 95 | //----------------------------------------------------------------------- 96 | 97 | macro_rules! ok { 98 | ($st:expr, $val:expr) => { 99 | Ok(($st, ast::Node::Val($val.to_owned()))) 100 | }; 101 | } 102 | 103 | fn parse_literal<'a>(mut status: Status<'a>, literal: &'a str) -> Result<'a> { 104 | for ch in literal.chars() { 105 | status = parse_char(status, ch).map_err(|st| { 106 | Error::from_status_normal(&st, &format!("expected literal: <{}>", literal)) 107 | })?; 108 | } 109 | ok!(status, literal) 110 | } 111 | 112 | fn parse_error<'a>(status: &Status<'a>, error: &'a str) -> Result<'a> { 113 | Err(Error::from_status(&status, &error, ErrPriority::Critical)) 114 | } 115 | 116 | fn parse_dot(status: Status) -> Result { 117 | let (status, ch) = status 118 | .get_char() 119 | .map_err(|st| Error::from_status_normal(&st, "dot"))?; 120 | 121 | ok!(status, ch.to_string()) 122 | } 123 | 124 | fn parse_match<'a>(status: Status<'a>, match_rules: &MatchRules) -> Result<'a> { 125 | let match_char = |ch: char| -> bool { 126 | if match_rules.0.find(ch).is_some() { 127 | true 128 | } else { 129 | for &(b, t) in &match_rules.1 { 130 | if b <= ch && ch <= t { 131 | return true; 132 | } 133 | } 134 | false 135 | } 136 | }; 137 | 138 | status 139 | .get_char() 140 | .and_then(|(st, ch)| { 141 | if match_char(ch) { 142 | ok!(st, ch.to_string()) 143 | } else { 144 | Err(st) 145 | } 146 | }) 147 | .map_err(|st| { 148 | Error::from_status_normal( 149 | &st, 150 | &format!("match. expected {} {:?}", match_rules.0, match_rules.1), 151 | ) 152 | }) 153 | } 154 | 155 | fn parse_eof(status: Status) -> Result { 156 | match status.get_char() { 157 | Ok((st, _ch)) => Err(Error::from_status_normal(&st, "expected EOF")), 158 | Err(st) => ok!(st, "EOF"), 159 | } 160 | } 161 | 162 | fn parse_char(status: Status, ch: char) -> result::Result { 163 | let (st, got_ch) = status.get_char()?; 164 | if ch == got_ch { 165 | Ok(st) 166 | } else { 167 | Err(st) 168 | } 169 | } 170 | 171 | impl<'a> Status<'a> { 172 | fn get_char(mut self) -> result::Result<(Self, char), Self> { 173 | match self.it_parsing.next() { 174 | None => Err(self), 175 | Some(ch) => { 176 | self.pos.n += 1; 177 | match ch { 178 | '\n' => { 179 | self.pos.col = 0; 180 | self.pos.row += 1; 181 | self.pos.start_line = self.pos.n; 182 | } 183 | '\r' => { 184 | self.pos.col = 0; 185 | } 186 | _ => { 187 | self.pos.col += 1; 188 | } 189 | } 190 | Ok((self, ch)) 191 | } 192 | } 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /src/parser/mod.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | //! Tools to execute parser of a expression 3 | 4 | use crate::ast; 5 | use std::result; 6 | 7 | //----------------------------------------------------------------------- 8 | //----------------------------------------------------------------------- 9 | // 10 | // 11 | // mod parser 12 | // 13 | // 14 | //----------------------------------------------------------------------- 15 | //----------------------------------------------------------------------- 16 | 17 | /// Support for minimum expressions elements 18 | pub mod atom; 19 | pub mod expression; 20 | 21 | use std::str::Chars; 22 | 23 | //----------------------------------------------------------------------- 24 | //----------------------------------------------------------------------- 25 | // 26 | // T Y P E S 27 | // 28 | //----------------------------------------------------------------------- 29 | //----------------------------------------------------------------------- 30 | 31 | /// Information about the possition on parsing 32 | #[derive(PartialEq, Clone, Debug)] 33 | pub struct Possition { 34 | /// char position parsing 35 | pub n: usize, 36 | /// row parsing row 37 | pub row: usize, 38 | /// parsing col 39 | pub col: usize, 40 | /// possition were line started for current pos *m* 41 | pub start_line: usize, 42 | } 43 | 44 | impl Possition { 45 | fn init() -> Self { 46 | Self { 47 | n: 0, 48 | row: 0, 49 | col: 0, 50 | start_line: 0, 51 | } 52 | } 53 | } 54 | 55 | /// Error priority 56 | #[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord)] 57 | pub enum ErrPriority { 58 | /// normal error 59 | Normal, 60 | /// Very important error 61 | Critical, 62 | } 63 | 64 | /// Context error information 65 | #[derive(Debug, Clone)] 66 | pub struct Error { 67 | /// Possition achive parsing 68 | pub pos: Possition, 69 | /// Error description parsing 70 | pub descr: String, 71 | /// Line content before where error was produced 72 | pub line_before: String, 73 | /// Line content after where error was produced 74 | pub line_after: String, 75 | // Suberrors when parsing an *or* (it could be removed!) 76 | // pub errors: Vec, 77 | /// Rules path followed till got the error 78 | /// Only available if trace_rules is on 79 | pub parsing_rules: Vec, 80 | /// error priority 81 | pub priority: ErrPriority, 82 | } 83 | 84 | //----------------------------------------------------------------------- 85 | #[derive(Debug, Clone)] 86 | pub(crate) struct Status<'a> { 87 | pub(crate) text2parse: &'a str, 88 | pub(crate) it_parsing: Chars<'a>, 89 | pub(crate) pos: Possition, 90 | pub(crate) rules: &'a expression::SetOfRules, 91 | // main = ("a")* 92 | // if you try to parse "abb" i.e. 93 | // the error will not be processed full input 94 | // It's true, but it could be more useful to know where 95 | // it fail trying to repeat 96 | pub(crate) potential_error: Option, 97 | 98 | /// If true, it will fill walking rules 99 | /// too expensive. For use just to debug errors 100 | pub(crate) trace_rules: bool, 101 | pub(crate) walking_rules: Vec, 102 | } 103 | 104 | impl<'a> Status<'a> { 105 | pub(crate) fn init(t2p: &'a str, rules: &'a expression::SetOfRules) -> Self { 106 | Status { 107 | text2parse: t2p, 108 | it_parsing: t2p.chars(), 109 | pos: Possition::init(), 110 | trace_rules: false, 111 | walking_rules: vec![], 112 | rules, 113 | potential_error: None, 114 | } 115 | } 116 | 117 | pub(crate) fn init_debug( 118 | t2p: &'a str, 119 | rules: &'a expression::SetOfRules, 120 | trace_rules: bool, 121 | ) -> Self { 122 | Status { 123 | text2parse: t2p, 124 | it_parsing: t2p.chars(), 125 | pos: Possition::init(), 126 | trace_rules, 127 | walking_rules: vec![], 128 | rules, 129 | potential_error: None, 130 | } 131 | } 132 | pub(crate) fn push_rule(mut self, on_node: &str) -> Self { 133 | self.walking_rules.push(on_node.to_string()); 134 | self 135 | } 136 | pub(crate) fn set_potential_error(mut self, err: Error) -> Self { 137 | self.potential_error = Some(err); 138 | self 139 | } 140 | } 141 | 142 | pub(crate) type Result<'a> = result::Result<(Status<'a>, ast::Node), Error>; 143 | 144 | //----------------------------------------------------------------------- 145 | //----------------------------------------------------------------------- 146 | // 147 | // A P I 148 | // 149 | //----------------------------------------------------------------------- 150 | //----------------------------------------------------------------------- 151 | 152 | //----------------------------------------------------------------------- 153 | // T E S T 154 | //----------------------------------------------------------------------- 155 | #[cfg(test)] 156 | mod test; 157 | 158 | //----------------------------------------------------------------------- 159 | // I N T E R N A L 160 | //----------------------------------------------------------------------- 161 | impl Error { 162 | pub(crate) fn from_status(status: &Status, descr: &str, prior: ErrPriority) -> Self { 163 | Error { 164 | pos: status.pos.clone(), 165 | descr: descr.to_owned(), 166 | line_before: status.text2parse[status.pos.start_line..status.pos.n].to_string(), 167 | line_after: status 168 | .it_parsing 169 | .clone() 170 | .take_while(|&ch| ch != '\n' && ch != '\r') 171 | .collect(), 172 | // errors: vec![], 173 | parsing_rules: status.walking_rules.clone(), 174 | priority: prior, 175 | } 176 | } 177 | 178 | pub(crate) fn from_status_normal(status: &Status, descr: &str) -> Self { 179 | Self::from_status(status, descr, ErrPriority::Normal) 180 | } 181 | 182 | // pub(crate) fn from_st_errs(status: &Status, descr: &str, errors: Vec) -> Self { 183 | // let max_pr = |verrors: &Vec| { 184 | // use std::cmp::max; 185 | // verrors 186 | // .iter() 187 | // .fold(ErrPriority::Normal, |acc, err| max(acc, err.priority)) 188 | // }; 189 | 190 | // let mp = max_pr(&errors); 191 | // Error { 192 | // pos: status.pos.clone(), 193 | // descr: descr.to_owned(), 194 | // line: status.text2parse[status.pos.start_line..status.pos.n].to_string(), 195 | // // errors, 196 | // parsing_rules: status.walking_rules.clone(), 197 | // priority: mp, 198 | // } 199 | // } 200 | } 201 | -------------------------------------------------------------------------------- /src/parser/expression/test.rs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // mod parser::expression TEST 4 | // 5 | //----------------------------------------------------------------------- 6 | 7 | use super::{parse_expr, Expression, MultiExpr, NRep, RepInfo, Status}; 8 | use crate::parser::atom::Atom; 9 | 10 | #[test] 11 | fn test_parse_literal_ok() { 12 | let rules = rules! {}; 13 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 14 | let expr = Expression::Simple(Atom::Literal("aaa".to_string())); 15 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 16 | 17 | assert!(status.pos.col == 3); 18 | assert!(status.pos.n == 3); 19 | assert!(status.pos.row == 0); 20 | } 21 | 22 | #[test] 23 | fn test_parse_literal_error() { 24 | let rules = rules! {}; 25 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 26 | let expr = Expression::Simple(Atom::Literal("bb".to_string())); 27 | assert!(parse_expr(status_init, &expr).is_err()); 28 | } 29 | 30 | #[test] 31 | fn test_parse_and_ok() { 32 | let rules = rules! {}; 33 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 34 | let and_rules = vec![ 35 | Expression::Simple(Atom::Literal("aa".to_string())), 36 | Expression::Simple(Atom::Literal("aa".to_string())), 37 | ]; 38 | let expr = Expression::And(MultiExpr(and_rules)); 39 | 40 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 41 | 42 | assert_eq!(status.pos.col, 4); 43 | assert_eq!(status.pos.n, 4); 44 | assert_eq!(status.pos.row, 0); 45 | } 46 | 47 | #[test] 48 | fn test_parse_and_fail() { 49 | let rules = rules! {}; 50 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 51 | let and_rules = vec![ 52 | Expression::Simple(Atom::Literal("aa".to_string())), 53 | Expression::Simple(Atom::Literal("bb".to_string())), 54 | ]; 55 | let expr = Expression::And(MultiExpr(and_rules)); 56 | 57 | assert!(parse_expr(status_init, &expr).is_err()); 58 | } 59 | 60 | #[test] 61 | fn test_parse_not_ok() { 62 | let rules = rules! {}; 63 | let status_init = Status::init("aa", &rules); 64 | 65 | let expr_not = Expression::Not(Box::new(Expression::Simple(Atom::Literal( 66 | "bb".to_string(), 67 | )))); 68 | let (status, _) = parse_expr(status_init, &expr_not).ok().unwrap(); 69 | 70 | assert_eq!(status.pos.col, 0); 71 | assert_eq!(status.pos.n, 0); 72 | assert_eq!(status.pos.row, 0); 73 | } 74 | 75 | #[test] 76 | fn test_parse_not_fail() { 77 | let rules = rules! {}; 78 | let status_init = Status::init("aa", &rules); 79 | 80 | let expr_not = Expression::Not(Box::new(Expression::Simple(Atom::Literal( 81 | "aa".to_string(), 82 | )))); 83 | assert!(parse_expr(status_init, &expr_not).is_err()); 84 | } 85 | 86 | #[test] 87 | fn test_parse_or_ok() { 88 | let rules = rules! {}; 89 | { 90 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 91 | let rules = vec![ 92 | Expression::Simple(Atom::Literal("aa".to_string())), 93 | Expression::Simple(Atom::Literal("aa".to_string())), 94 | ]; 95 | let expr = Expression::Or(MultiExpr(rules)); 96 | 97 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 98 | 99 | assert_eq!(status.pos.col, 2); 100 | assert_eq!(status.pos.n, 2); 101 | assert_eq!(status.pos.row, 0); 102 | } 103 | { 104 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 105 | let rules = vec![ 106 | Expression::Simple(Atom::Literal("aa".to_string())), 107 | Expression::Simple(Atom::Literal("bb".to_string())), 108 | ]; 109 | let expr = Expression::Or(MultiExpr(rules)); 110 | 111 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 112 | 113 | assert_eq!(status.pos.col, 2); 114 | assert_eq!(status.pos.n, 2); 115 | assert_eq!(status.pos.row, 0); 116 | } 117 | { 118 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 119 | let rules = vec![ 120 | Expression::Simple(Atom::Literal("bb".to_string())), 121 | Expression::Simple(Atom::Literal("aa".to_string())), 122 | ]; 123 | let expr = Expression::Or(MultiExpr(rules)); 124 | 125 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 126 | 127 | assert_eq!(status.pos.col, 2); 128 | assert_eq!(status.pos.n, 2); 129 | assert_eq!(status.pos.row, 0); 130 | } 131 | } 132 | 133 | #[test] 134 | fn test_parse_or_fail() { 135 | let rules = rules! {}; 136 | let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules); 137 | let and_rules = vec![ 138 | Expression::Simple(Atom::Literal("cc".to_string())), 139 | Expression::Simple(Atom::Literal("bb".to_string())), 140 | ]; 141 | let expr = Expression::And(MultiExpr(and_rules)); 142 | 143 | assert!(parse_expr(status_init, &expr).is_err()); 144 | } 145 | 146 | #[test] 147 | fn test_parse_repeat_ok() { 148 | let rules = rules! {}; 149 | let repeat_literal = |literal, min, max: Option| { 150 | Expression::Repeat(RepInfo { 151 | expression: Box::new(Expression::Simple(Atom::Literal(literal))), 152 | min, 153 | max, 154 | }) 155 | }; 156 | 157 | { 158 | let status_init = Status::init("aaaaaa", &rules); 159 | let expr = repeat_literal("aa".to_string(), NRep(0), None); 160 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 161 | 162 | assert_eq!(status.pos.col, 6); 163 | assert_eq!(status.pos.n, 6); 164 | assert_eq!(status.pos.row, 0); 165 | } 166 | { 167 | let status_init = Status::init("aaaaaa", &rules); 168 | let expr = repeat_literal("aa".to_string(), NRep(3), None); 169 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 170 | 171 | assert_eq!(status.pos.col, 6); 172 | assert_eq!(status.pos.n, 6); 173 | assert_eq!(status.pos.row, 0); 174 | } 175 | { 176 | let status_init = Status::init("aaaaaa", &rules); 177 | let expr = repeat_literal("aa".to_string(), NRep(0), Some(NRep(3))); 178 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 179 | 180 | assert_eq!(status.pos.col, 6); 181 | assert_eq!(status.pos.n, 6); 182 | assert_eq!(status.pos.row, 0); 183 | } 184 | { 185 | let status_init = Status::init("aaaaaa", &rules); 186 | let expr = repeat_literal("aa".to_string(), NRep(0), Some(NRep(1))); 187 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 188 | 189 | assert_eq!(status.pos.col, 2); 190 | assert_eq!(status.pos.n, 2); 191 | assert_eq!(status.pos.row, 0); 192 | } 193 | { 194 | let status_init = Status::init("aaaaaa", &rules); 195 | let expr = repeat_literal("bb".to_string(), NRep(0), None); 196 | let (status, _) = parse_expr(status_init, &expr).ok().unwrap(); 197 | 198 | assert_eq!(status.pos.col, 0); 199 | assert_eq!(status.pos.n, 0); 200 | assert_eq!(status.pos.row, 0); 201 | } 202 | } 203 | 204 | #[test] 205 | fn test_parse_repeat_fail() { 206 | let rules = rules! {}; 207 | let repeat_literal = |literal, min, max: Option| { 208 | Expression::Repeat(RepInfo { 209 | expression: Box::new(Expression::Simple(Atom::Literal(literal))), 210 | min, 211 | max, 212 | }) 213 | }; 214 | 215 | { 216 | let status_init = Status::init("aaaaaa", &rules); 217 | let expr = repeat_literal("aa".to_string(), NRep(4), None); 218 | assert!(parse_expr(status_init, &expr).is_err()); 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /src/peg/test.rs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // mod peg TEST 4 | // 5 | //----------------------------------------------------------------------- 6 | use crate::parse; 7 | use crate::peg; 8 | 9 | #[test] 10 | fn validate_peg1() { 11 | let peg = r#" 12 | 13 | main = "aaa" "bb" c* / ((d f)+ / es) 14 | c = c' 15 | c' = c'' 16 | c'' = "c" 17 | d = "d" 18 | f = "f" 19 | es = "e"+ 20 | 21 | "#; 22 | 23 | assert!(parse(peg, &peg::rules::parse_peg()).is_ok()); 24 | } 25 | 26 | #[test] 27 | fn validate_peg2() { 28 | let peg = r#" 29 | 30 | main = "aaa" 31 | / "bb" c* 32 | / ((d f)+ / es) 33 | 34 | c = c' 35 | c' = c'' 36 | c'' = "c" 37 | d = "d" 38 | f = "f" 39 | es = "e"+ 40 | 41 | "#; 42 | 43 | assert!(parse(peg, &peg::rules::parse_peg()).is_ok()); 44 | } 45 | 46 | #[test] 47 | fn invalid_peg1() { 48 | let peg = r#" 49 | 50 | main = "aaa" "bb" c * / ((d f)+ / es) 51 | c = c' 52 | c' = c'' 53 | c'' = "c" 54 | d = "d" 55 | f = "f" 56 | es = "e"+ 57 | 58 | "#; 59 | 60 | assert!(parse(peg, &peg::rules::parse_peg()).is_err()); 61 | } 62 | 63 | #[test] 64 | fn invalid_peg2() { 65 | let peg = r#" 66 | 67 | main = "aaa" 68 | / "bb" c* 69 | / ((d f)+ / es 70 | 71 | c = c' 72 | c' = c'' 73 | c'' = "c" 74 | d = "d" 75 | f = "f" 76 | es = "e"+ 77 | 78 | "#; 79 | 80 | assert!(parse(peg, &peg::rules::parse_peg()).is_err()); 81 | } 82 | 83 | #[test] 84 | fn validate_peg3() { 85 | let peg = r#" 86 | 87 | main = "aaa "bb" c* / ((d f)+ / es) 88 | c = c' 89 | c' = c'' 90 | c'' = "c" 91 | d = "d" 92 | f = "f" 93 | es = "e"+ 94 | 95 | "#; 96 | 97 | assert!(parse(peg, &peg::rules::parse_peg()).is_err()); 98 | } 99 | 100 | #[test] 101 | fn validate_peg4() { 102 | let peg = r#" 103 | 104 | ma in = "aaa" "bb" c* / ((d f)+ / es) 105 | c = c' 106 | c' = c'' 107 | c'' = "c" 108 | d = "d" 109 | f = "f" 110 | es = "e"+ 111 | 112 | "#; 113 | 114 | assert!(parse(peg, &peg::rules::parse_peg()).is_err()); 115 | } 116 | 117 | #[test] 118 | fn validate_peg5() { 119 | let peg = r#" 120 | 121 | main = "aaa" "bb" c* / ((d f)+* / es) 122 | c = c' 123 | c' = c'' 124 | c'' = "c" 125 | d = "d" 126 | f = "f" 127 | es = "e"+ 128 | 129 | "#; 130 | 131 | assert!(parse(peg, &peg::rules::parse_peg()).is_err()); 132 | } 133 | 134 | #[test] 135 | fn parse_literal() { 136 | let peg = r#" 137 | 138 | main = "hello" 139 | 140 | "#; 141 | 142 | let rules = peg::rules_from_peg(peg).unwrap(); 143 | 144 | assert!(parse("hello", &rules).is_ok()); 145 | } 146 | 147 | #[test] 148 | fn parse_and_literal() { 149 | let peg = r#" 150 | 151 | main = "hello" " " "world" 152 | 153 | "#; 154 | 155 | let rules = peg::rules_from_peg(peg).unwrap(); 156 | 157 | assert!(parse("hello world", &rules).is_ok()); 158 | } 159 | 160 | #[test] 161 | fn parse_or_literal() { 162 | let peg = r#" 163 | 164 | main = "hello" " " "world" 165 | / "hola" " " "mundo" 166 | / "hola" 167 | 168 | "#; 169 | 170 | let rules = peg::rules_from_peg(peg).unwrap(); 171 | 172 | assert!(parse("hello world", &rules).is_ok()); 173 | assert!(parse("hola", &rules).is_ok()); 174 | assert!(parse("hola mundo", &rules).is_ok()); 175 | assert!(parse("bye", &rules).is_err()); 176 | } 177 | 178 | #[test] 179 | fn parse_ref_rule() { 180 | let peg = r#" 181 | 182 | main = "hello" " " world 183 | 184 | world = "world" 185 | 186 | "#; 187 | 188 | let rules = peg::rules_from_peg(peg).unwrap(); 189 | 190 | assert!(parse("hello world", &rules).is_ok()); 191 | assert!(parse("bye", &rules).is_err()); 192 | } 193 | 194 | #[test] 195 | fn parse_parenth() { 196 | let peg = r#" 197 | 198 | main = "hello" " " (world / "mars") 199 | 200 | world = "world" 201 | 202 | "#; 203 | 204 | let rules = peg::rules_from_peg(peg).unwrap(); 205 | 206 | assert!(parse("hello world", &rules).is_ok()); 207 | assert!(parse("hello mars", &rules).is_ok()); 208 | assert!(parse("hello pluto", &rules).is_err()); 209 | assert!(parse("hello", &rules).is_err()); 210 | } 211 | 212 | #[test] 213 | fn parse_klean() { 214 | let peg = r#" 215 | 216 | main = "a"* 217 | 218 | "#; 219 | 220 | let rules = peg::rules_from_peg(peg).unwrap(); 221 | 222 | assert!(parse("aaaaaa", &rules).is_ok()); 223 | assert!(parse("a", &rules).is_ok()); 224 | assert!(parse("", &rules).is_ok()); 225 | assert!(parse("bbb", &rules).is_err()); 226 | assert!(parse("b", &rules).is_err()); 227 | assert!(parse("aab", &rules).is_err()); 228 | } 229 | 230 | #[test] 231 | fn parse_one_or_more() { 232 | let peg = r#" 233 | 234 | main = "a"+ 235 | 236 | "#; 237 | 238 | let rules = peg::rules_from_peg(peg).unwrap(); 239 | 240 | assert!(parse("aaaaaa", &rules).is_ok()); 241 | assert!(parse("a", &rules).is_ok()); 242 | assert!(parse("", &rules).is_err()); 243 | assert!(parse("bbb", &rules).is_err()); 244 | assert!(parse("b", &rules).is_err()); 245 | assert!(parse("aab", &rules).is_err()); 246 | } 247 | 248 | #[test] 249 | fn parse_one_or_zero() { 250 | let peg = r#" 251 | 252 | main = "a"? 253 | 254 | "#; 255 | 256 | let rules = peg::rules_from_peg(peg).unwrap(); 257 | 258 | assert!(parse("aaaaaa", &rules).is_err()); 259 | assert!(parse("a", &rules).is_ok()); 260 | assert!(parse("", &rules).is_ok()); 261 | assert!(parse("bbb", &rules).is_err()); 262 | assert!(parse("b", &rules).is_err()); 263 | assert!(parse("ab", &rules).is_err()); 264 | } 265 | 266 | #[test] 267 | fn parse_negation() { 268 | let peg = r#" 269 | 270 | main = !"bye" "hello" 271 | 272 | "#; 273 | 274 | let rules = peg::rules_from_peg(peg).unwrap(); 275 | 276 | assert!(parse("hello", &rules).is_ok()); 277 | assert!(parse("bye", &rules).is_err()); 278 | assert!(parse("hi", &rules).is_err()); 279 | assert!(parse("bye hello", &rules).is_err()); 280 | } 281 | 282 | #[test] 283 | fn parse_dot() { 284 | let peg = r#" 285 | 286 | main = . . . . . 287 | 288 | "#; 289 | 290 | let rules = peg::rules_from_peg(peg).unwrap(); 291 | 292 | assert!(parse("hello", &rules).is_ok()); 293 | assert!(parse("hola.", &rules).is_ok()); 294 | assert!(parse("hi", &rules).is_err()); 295 | assert!(parse("bye hello", &rules).is_err()); 296 | } 297 | 298 | #[test] 299 | fn parse_dot_with_rep() { 300 | let peg = r#" 301 | 302 | main = (!"h" .)* "hello" 303 | 304 | "#; 305 | 306 | let rules = peg::rules_from_peg(peg).unwrap(); 307 | 308 | assert!(parse("-----hello", &rules).is_ok()); 309 | assert!(parse("_hello", &rules).is_ok()); 310 | assert!(parse("hello", &rules).is_ok()); 311 | assert!(parse("Hola hello", &rules).is_ok()); 312 | assert!(parse("hola hello", &rules).is_err()); 313 | assert!(parse("hola_hello", &rules).is_err()); 314 | assert!(parse("Hello", &rules).is_err()); 315 | assert!(parse("bye", &rules).is_err()); 316 | assert!(parse("hola", &rules).is_err()); 317 | assert!(parse("hello hola", &rules).is_err()); 318 | } 319 | 320 | #[test] 321 | fn peg_incorrect_match() { 322 | let peg = r#" 323 | 324 | main = [A-Zab] 325 | 326 | "#; 327 | 328 | assert!(peg::rules_from_peg(peg).is_err()); 329 | } 330 | 331 | #[test] 332 | fn test_match() { 333 | let peg = r#" 334 | 335 | main = [123A-X]+ 336 | 337 | "#; 338 | 339 | let rules = peg::rules_from_peg(peg).unwrap(); 340 | 341 | assert!(parse("1111", &rules).is_ok()); 342 | assert!(parse("222311", &rules).is_ok()); 343 | assert!(parse("ABCDEF", &rules).is_ok()); 344 | assert!(parse("ABCDEF4", &rules).is_err()); 345 | assert!(parse("", &rules).is_err()); 346 | assert!(parse("1234", &rules).is_err()); 347 | assert!(parse("Z", &rules).is_err()); 348 | assert!(parse("ABZ", &rules).is_err()); 349 | } 350 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate dynparser; 2 | use dynparser::peg::peg2code; 3 | 4 | fn main() { 5 | peg2code::print_rules2parse_peg(); 6 | } 7 | 8 | // -------------------------- 9 | // modules 10 | 11 | // extern crate dynparser; 12 | // use dynparser::{parse, rules_from_peg}; 13 | 14 | // fn main() { 15 | // let rules = rules_from_peg( 16 | // r#" 17 | 18 | // main = as / b.bs / abc.abs / abc.c.cs 19 | 20 | // as = 'a'+ 21 | 22 | // b { 23 | // bs = 'b'+ 24 | // } 25 | 26 | // abc { 27 | // abs = .as / .b.bs 28 | 29 | // c { 30 | // cs = 'c'+ 31 | // } 32 | // } 33 | 34 | // "#, 35 | // ).unwrap(); 36 | 37 | // assert!(parse("abcz", &rules).is_ok()); 38 | // } 39 | 40 | // // -------------------------------------------------------------------------- 41 | 42 | // extern crate dynparser; 43 | // use dynparser::{peg, rules_from_peg}; 44 | 45 | // fn main() { 46 | // let rules = rules_from_peg( 47 | // r#" 48 | 49 | // main = grammar 50 | 51 | // grammar = rule+ 52 | 53 | // rule = _ symbol _ "=" _ expr _eol _ 54 | 55 | // expr = or 56 | 57 | // or = and ( _ "/" _ or )* 58 | 59 | // and = rep_or_neg ( _1 _ !(symbol _ "=") and )* 60 | 61 | // rep_or_neg = atom_or_par ("*" / "+" / "?")? 62 | // / "!" atom_or_par 63 | 64 | // atom_or_par = (atom / parenth) 65 | 66 | // parenth = "(" _ expr _ ")" 67 | 68 | // atom = literal 69 | // / match 70 | // / dot 71 | // / symbol 72 | 73 | // literal = _" ( "\\" . 74 | // / !_" . 75 | // )* _" 76 | // _" = "\"" 77 | 78 | // symbol = [_'a-zA-Z0-9] [_'"a-zA-Z0-9]* 79 | 80 | // eol = ("\r\n" / "\n" / "\r") 81 | // _eol = " "* eol 82 | 83 | // match = "[" 84 | // ( 85 | // (mchars mbetween*) 86 | // / mbetween+ 87 | // ) 88 | // "]" 89 | 90 | // mchars = (!"]" !(. "-") .)+ 91 | // mbetween = (. "-" .) 92 | 93 | // dot = "." 94 | 95 | // _ = ( " " 96 | // / eol 97 | // )* 98 | 99 | // _1 = (" " / eol) 100 | 101 | // "#, 102 | // ).map_err(|e| { 103 | // println!("{}", e); 104 | // panic!("FAIL"); 105 | // }).unwrap(); 106 | 107 | // println!("{}", peg::gcode::rust_from_rules(&rules)) 108 | // } 109 | 110 | // -------------------------------------------------------------------------- 111 | 112 | // extern crate dynparser; 113 | // use dynparser::{parse, rules_from_peg}; 114 | 115 | // fn main() { 116 | // let rules = rules_from_peg( 117 | // r#" 118 | // main = '(' main ( ')' / error("unbalanced parenthesys") ) 119 | // / 'hello' 120 | // "#, 121 | // ).map_err(|e| { 122 | // println!("{}", e); 123 | // panic!("FAIL"); 124 | // }).unwrap(); 125 | 126 | // println!("{:#?}", rules); 127 | 128 | // let result = parse("a2AA456bzJ88", &rules); 129 | // match result { 130 | // Ok(ast) => println!("{:#?}", ast), 131 | // Err(e) => println!("Error: {:?}", e), 132 | // }; 133 | // } 134 | 135 | // -------------------------- 136 | // extern crate dynparser; 137 | // use dynparser::{parse, rules_from_peg}; 138 | 139 | // fn main() { 140 | // let rules = rules_from_peg( 141 | // r#" 142 | 143 | // main = "a" ( "bc" "c" 144 | // / "bcdd" 145 | // / b_and_c d_or_z 146 | // ) 147 | 148 | // b_and_c = "b" "c" 149 | // d_or_z = "d" / "z" 150 | 151 | // "#, 152 | // ).unwrap(); 153 | 154 | // assert!(parse("abcz", &rules).is_ok()); 155 | // // assert!(parse("abcdd", &rules).is_ok()); 156 | // // assert!(parse("abcc", &rules).is_ok()); 157 | // // assert!(parse("bczd", &rules).is_err()); 158 | // } 159 | 160 | // -------------------- 161 | 162 | // extern crate dynparser; 163 | // use dynparser::peg; 164 | // use dynparser::{parse, rules_from_peg}; 165 | 166 | // fn main() { 167 | // let peg_rules = r#" 168 | 169 | // main = (aaa / "bbb")* zzz 170 | // aaa = "aaa" 171 | // zzz = "zzz" 172 | 173 | // "#; 174 | // let rules = rules_from_peg(peg_rules) 175 | // .map_err(|e| { 176 | // println!("{}", e); 177 | // panic!("FAIL"); 178 | // }).unwrap(); 179 | 180 | // // println!("{:#?}", rules); 181 | 182 | // // let result = parse("a2Z", &rules); 183 | // // match result { 184 | // // Ok(ast) => { 185 | // // println!("{:#?}", ast.compact().flatten()); 186 | // // } 187 | // // Err(e) => println!("Error: {:?}", e), 188 | // // }; 189 | // // println!("{:#?}", rules_from_peg(&peg_rules)) 190 | // println!("{}", peg::gcode::rust_from_rules(&rules)); 191 | 192 | // let rules2 = peg::rules_from_peg2(peg_rules) 193 | // .map_err(|e| { 194 | // println!("{}", e); 195 | // panic!("FAIL"); 196 | // }).unwrap(); 197 | // println!("{}", peg::gcode::rust_from_rules(&rules2)); 198 | // } 199 | 200 | // // -------------------------------------------------------------------------- 201 | 202 | // #[macro_use] 203 | // extern crate dynparser; 204 | // use dynparser::{ast, idata, parse}; 205 | 206 | // fn main() { 207 | // let rules = rules!( 208 | // "rep_or_neg" => or!(and!(ref_rule!("atom_or_par"), rep!(or!(lit!("*"), lit!("+"), lit!("?")), 0, 1)), and!(lit!("!"), ref_rule!("atom_or_par"))) 209 | // , "literal" => and!(ref_rule!("_\""), rep!(or!(and!(lit!("\\"), dot!()), and!(not!(ref_rule!("_\"")), dot!())), 0), ref_rule!("_\"")) 210 | // , "eol" => or!(lit!("\r\n"), lit!("\n"), lit!("\r")) 211 | // , "mchars" => rep!(and!(not!(lit!("]")), not!(and!(dot!(), lit!("-"))), dot!()), 1) 212 | // , "mbetween" => and!(dot!(), lit!("-"), dot!()) 213 | // , "atom_or_par" => or!(ref_rule!("atom"), ref_rule!("parenth")) 214 | // , "dot" => lit!(".") 215 | // , "or" => and!(ref_rule!("and"), rep!(and!(ref_rule!("_"), lit!("/"), ref_rule!("_"), ref_rule!("or")), 0)) 216 | // , "_eol" => and!(rep!(lit!(" "), 0), ref_rule!("eol")) 217 | // , "rule" => and!(ref_rule!("_"), ref_rule!("symbol"), ref_rule!("_"), lit!("="), ref_rule!("_"), ref_rule!("expr"), ref_rule!("_eol"), ref_rule!("_")) 218 | // , "symbol" => and!(ematch!(chlist "_'" , from 'a', to 'z' , from 'A', to 'Z' , from '0', to '9' ), rep!(ematch!(chlist "_'\"" , from 'a', to 'z' , from 'A', to 'Z' , from '0', to '9' ), 0)) 219 | // , "main" => ref_rule!("grammar") 220 | // , "match" => and!(lit!("["), or!(and!(rep!(ref_rule!("mchars"), 1), rep!(ref_rule!("mbetween"), 0)), rep!(ref_rule!("mbetween"), 1)), lit!("]")) 221 | // , "grammar" => rep!(ref_rule!("rule"), 1) 222 | // , "and" => and!(ref_rule!("rep_or_neg"), rep!(and!(ref_rule!("_1"), ref_rule!("_"), not!(and!(ref_rule!("symbol"), ref_rule!("_"), lit!("="))), ref_rule!("and")), 0)) 223 | // , "_" => rep!(or!(lit!(" "), ref_rule!("eol")), 0) 224 | // , "parenth" => and!(lit!("("), ref_rule!("_"), ref_rule!("expr"), ref_rule!("_"), lit!(")")) 225 | // , "expr" => ref_rule!("or") 226 | // , "_\"" => lit!("\"") 227 | // , "atom" => or!(ref_rule!("literal"), ref_rule!("match"), ref_rule!("dot"), ref_rule!("symbol")) 228 | // , "_1" => or!(lit!(" "), ref_rule!("eol")) 229 | // ); 230 | 231 | // let parsed = parse( 232 | // r#" 233 | 234 | // main = "Hello world" 235 | 236 | // "#, 237 | // &rules, 238 | // ).map_err(|e| { 239 | // println!("{:?}", e); 240 | // panic!("FAIL"); 241 | // }).unwrap(); 242 | 243 | // println!( 244 | // "{:#?}", 245 | // parsed 246 | // .prune(&["_", "_eol"]) 247 | // .compact() 248 | // .flatten() 249 | // .iter() 250 | // .filter(|n| { 251 | // let remove = [ 252 | // "main", 253 | // "grammar", 254 | // "atom_or_par", 255 | // "atom_or_par", 256 | // "rep_or_neg", 257 | // ]; 258 | // use idata::IVec; 259 | // let remove = remove.iter().fold(vec![], |acc, item| { 260 | // acc.ipush(format!("begin.{}", item)) 261 | // .ipush(format!("end.{}", item)) 262 | // }); 263 | // match n { 264 | // ast::Node::Rule((name, _)) => !remove.contains(name), 265 | // _ => true, 266 | // } 267 | // }).collect::>() 268 | // ); 269 | // } 270 | -------------------------------------------------------------------------------- /src/ast/flat.rs: -------------------------------------------------------------------------------- 1 | //! Data information to build the Flat AST 2 | //! And some functions to work with it 3 | //! 4 | //! The AST is a tree, because... it has to be during the parsing 5 | //! and building. 6 | //! 7 | //! But once the input has been processed, we will want to follow 8 | //! the tree in a specific order. 9 | //! 10 | //! It's not complicated visit the elements in a tree, but could 11 | //! be easier if the AST has been "flattened" 12 | //! 13 | //! In order to flatten the tree, is necessary to add a new kind 14 | //! of node. The end 'Rule' 15 | //! 16 | 17 | use crate::ast::{self, error, Error}; 18 | use idata::cont::IVec; 19 | use std::result::Result; 20 | 21 | // ------------------------------------------------------------------------------------- 22 | // T Y P E S 23 | 24 | /// Information of a node when ast has been flattened 25 | #[derive(Debug, PartialEq)] 26 | pub enum Node { 27 | /// The node is terminal (atom) with a name 28 | Val(String), 29 | /// Starts a rule 30 | BeginRule(String), 31 | /// Ends a rule 32 | EndRule(String), 33 | /// Reached end of file 34 | EOF, 35 | } 36 | 37 | impl ast::Node { 38 | /// Flattening tree 39 | /// 40 | /// It's very commont to visit nodes in order 41 | /// The grammar checked the consistency of input 42 | /// Flattening the AST, could be interesting in order to process the tree 43 | /// 44 | /// ``` 45 | /// use dynparser::ast::{self, flat}; 46 | /// 47 | /// let ast_before_flatten = ast::Node::Rule(( 48 | /// "first".to_string(), 49 | /// vec![ 50 | /// ast::Node::Rule(( 51 | /// "node1".to_string(), 52 | /// vec![ 53 | /// ast::Node::Val("hello".to_string()), 54 | /// ast::Node::Rule(("node1.1".to_string(), vec![ast::Node::Val(" ".to_string())])), 55 | /// ], 56 | /// )), 57 | /// ast::Node::Rule(( 58 | /// "node2".to_string(), 59 | /// vec![ast::Node::Val("world".to_string())], 60 | /// )), 61 | /// ], 62 | /// )); 63 | /// 64 | /// let vec_after_flatten = 65 | /// vec![ 66 | /// flat::Node::BeginRule("first".to_string()), 67 | /// flat::Node::BeginRule("node1".to_string()), 68 | /// flat::Node::Val("hello".to_string()), 69 | /// flat::Node::BeginRule("node1.1".to_string()), 70 | /// flat::Node::Val(" ".to_string()), 71 | /// flat::Node::EndRule("node1.1".to_string()), 72 | /// flat::Node::EndRule("node1".to_string()), 73 | /// flat::Node::BeginRule("node2".to_string()), 74 | /// flat::Node::Val("world".to_string()), 75 | /// flat::Node::EndRule("node2".to_string()), 76 | /// flat::Node::EndRule("first".to_string()), 77 | /// ]; 78 | /// 79 | /// assert!(ast_before_flatten.flatten() == vec_after_flatten) 80 | ///``` 81 | pub fn flatten(&self) -> Vec { 82 | fn flatten_acc(acc: Vec, next: &ast::Node) -> Vec { 83 | match next { 84 | ast::Node::EOF => acc, 85 | ast::Node::Val(v) => acc.ipush(Node::Val(v.clone())), 86 | ast::Node::Rule((n, vn)) => { 87 | let acc = acc.ipush(Node::BeginRule(n.to_string())); 88 | let acc = vn.iter().fold(acc, |facc, n| flatten_acc(facc, n)); 89 | acc.ipush(Node::EndRule(n.to_string())) 90 | } 91 | } 92 | } 93 | 94 | flatten_acc(vec![], self) 95 | } 96 | } 97 | 98 | /// Consume a ast::flat::Node if it's a Rule kind with a specific value 99 | /// and return the rest of nodes 100 | /// 101 | ///``` 102 | /// use dynparser::ast::flat; 103 | /// let nodes = vec![ 104 | /// flat::Node::BeginRule("hello".to_string()), 105 | /// flat::Node::Val("world".to_string()), 106 | /// ]; 107 | /// 108 | /// let nodes = flat::consume_node_start_rule_name("hello", &nodes).unwrap(); 109 | /// 110 | /// let (node, nodes) = flat::consume_val(nodes).unwrap(); 111 | /// assert!(node == "world"); 112 | /// assert!(nodes.len() == 0); 113 | ///``` 114 | /// 115 | pub fn consume_node_start_rule_name<'a>( 116 | name: &str, 117 | nodes: &'a [Node], 118 | ) -> Result<&'a [Node], Error> { 119 | let (node, nodes) = split_first_nodes(nodes)?; 120 | let node_name = match node { 121 | Node::BeginRule(n) => Ok(n), 122 | _ => Err(error(&format!("expected begin rule for {}", name), None)), 123 | }?; 124 | if node_name == name { 125 | Ok(nodes) 126 | } else { 127 | Err(error( 128 | &format!("expected {} node, received {}", name, node_name), 129 | None, 130 | )) 131 | } 132 | } 133 | 134 | /// Consume a Node indicating the end of a rule, 135 | /// if it's a Rule kind with a specific name 136 | /// and return the rest of nodes 137 | /// 138 | ///``` 139 | /// use dynparser::ast::flat; 140 | /// let nodes = vec![ 141 | /// flat::Node::EndRule("hello".to_string()), 142 | /// flat::Node::EndRule("hi".to_string()), 143 | /// ]; 144 | /// 145 | /// let nodes = flat::consume_node_end_rule_name("hello", &nodes).unwrap(); 146 | /// let nodes = flat::consume_node_end_rule_name("hi", &nodes).unwrap(); 147 | /// assert!(nodes.len() == 0); 148 | ///``` 149 | /// 150 | pub fn consume_node_end_rule_name<'a>(name: &str, nodes: &'a [Node]) -> Result<&'a [Node], Error> { 151 | let (node, nodes) = split_first_nodes(nodes)?; 152 | let node_name = match node { 153 | Node::EndRule(n) => Ok(n), 154 | _ => Err(error(&format!("expected end rule for {}", name), None)), 155 | }?; 156 | if node_name == name { 157 | Ok(nodes) 158 | } else { 159 | Err(error( 160 | &format!("expected {} node, received {}", name, node_name), 161 | None, 162 | )) 163 | } 164 | } 165 | 166 | /// Given a list of nodes, return the first and the rest on a tuple 167 | /// 168 | ///``` 169 | /// use dynparser::ast::flat; 170 | /// let nodes = vec![ 171 | /// flat::Node::Val("hello".to_string()), 172 | /// flat::Node::Val("world".to_string()), 173 | /// flat::Node::Val(".".to_string()), 174 | /// ]; 175 | /// 176 | /// let (node, nodes) = flat::split_first_nodes(&nodes).unwrap(); 177 | /// assert!(flat::get_node_val(node).unwrap() == "hello"); 178 | /// assert!(nodes.len() == 2); 179 | /// 180 | /// let (node, nodes) = flat::split_first_nodes(&nodes).unwrap(); 181 | /// assert!(flat::get_node_val(node).unwrap() == "world"); 182 | /// assert!(nodes.len() == 1); 183 | /// 184 | /// let (node, nodes) = flat::split_first_nodes(&nodes).unwrap(); 185 | /// assert!(flat::get_node_val(node).unwrap() == "."); 186 | /// assert!(nodes.len() == 0); 187 | ///``` 188 | /// 189 | pub fn split_first_nodes(nodes: &[Node]) -> Result<(&Node, &[Node]), Error> { 190 | nodes 191 | .split_first() 192 | .ok_or_else(|| error("trying get first element from nodes on empty slice", None)) 193 | } 194 | 195 | /// Return a reference to first node 196 | /// 197 | ///``` 198 | /// use dynparser::ast::flat; 199 | /// let nodes = vec![ 200 | /// flat::Node::BeginRule("hello".to_string()), 201 | /// flat::Node::Val("world".to_string()), 202 | /// ]; 203 | /// 204 | /// let first = flat::peek_first_node(&nodes).unwrap(); 205 | /// assert!(first == &flat::Node::BeginRule("hello".to_string())); 206 | ///``` 207 | /// 208 | pub fn peek_first_node(nodes: &[Node]) -> Result<&Node, Error> { 209 | if nodes.is_empty() { 210 | Err(error("exptected node on peek_first_node", None)) 211 | } else { 212 | Ok(&nodes[0]) 213 | } 214 | } 215 | 216 | /// Get the value of the Node 217 | /// If node is not a Node::Val, it will return an error 218 | ///``` 219 | /// use dynparser::ast::flat; 220 | /// let node = flat::Node::Val("hello".to_string()); 221 | /// 222 | /// let val = flat::get_node_val(&node).unwrap(); 223 | /// 224 | /// assert!(val == "hello"); 225 | ///``` 226 | pub fn get_node_val(node: &Node) -> Result<&str, Error> { 227 | match node { 228 | Node::Val(v) => Ok(v), 229 | _ => Err(error("expected node::Val", None)), 230 | } 231 | } 232 | 233 | /// Consume a node if it's a Val kind and the vaule is 234 | /// equal to the provider one 235 | /// 236 | ///``` 237 | /// use dynparser::ast::flat; 238 | /// let nodes = vec![ 239 | /// flat::Node::Val("hello".to_string()), 240 | /// flat::Node::Val("world".to_string()), 241 | /// flat::Node::Val(".".to_string()), 242 | /// ]; 243 | /// 244 | /// let nodes = flat::consume_this_value("hello", &nodes).unwrap(); 245 | /// let nodes = flat::consume_this_value("world", &nodes).unwrap(); 246 | ///``` 247 | /// 248 | pub fn consume_this_value<'a>(v: &str, nodes: &'a [Node]) -> Result<&'a [Node], Error> { 249 | let (node, nodes) = split_first_nodes(nodes)?; 250 | 251 | let nv = get_node_val(node)?; 252 | if nv == v { 253 | Ok(nodes) 254 | } else { 255 | Err(error( 256 | "trying get first element from nodes on empty slice", 257 | None, 258 | )) 259 | } 260 | } 261 | 262 | /// It will get the node name of a node if it's a rule one (begin or end). 263 | /// In other case, it will return an error 264 | /// 265 | /// ``` 266 | /// use dynparser::ast::flat; 267 | /// 268 | /// let node = flat::Node::BeginRule("aaa".to_string()); 269 | /// 270 | /// let node_name = flat::get_nodename(&node).unwrap(); 271 | /// 272 | /// assert!(node_name == "aaa"); 273 | /// ``` 274 | pub fn get_nodename(node: &Node) -> Result<&str, Error> { 275 | match node { 276 | Node::BeginRule(nname) => Ok(nname), 277 | Node::EndRule(nname) => Ok(nname), 278 | _ => Err(error("expected node::Rule", None)), 279 | } 280 | } 281 | 282 | /// Given a slice of nodes, return the value (&str) of first 283 | /// node if it is a Node::Val and return the rest of nodes 284 | /// 285 | /// If it's not possible, it returns an error 286 | /// 287 | ///``` 288 | /// use dynparser::ast::flat; 289 | /// let nodes = vec![ 290 | /// flat::Node::Val("hello".to_string()), 291 | /// flat::Node::Val("world".to_string()), 292 | /// ]; 293 | /// 294 | /// let (val, nodes) = flat::consume_val(&nodes).unwrap(); 295 | /// assert!(val == "hello"); 296 | /// assert!(nodes.len() == 1); 297 | /// 298 | /// let (val, nodes) = flat::consume_val(&nodes).unwrap(); 299 | /// assert!(val == "world"); 300 | /// assert!(nodes.len() == 0); 301 | ///``` 302 | /// 303 | pub fn consume_val(nodes: &[Node]) -> Result<(&str, &[Node]), Error> { 304 | let (node, nodes) = split_first_nodes(nodes)?; 305 | match node { 306 | Node::Val(v) => Ok((&v, nodes)), 307 | _ => Err(error("expected Val node", None)), 308 | } 309 | } 310 | -------------------------------------------------------------------------------- /src/parser/expression/mod.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | //! Here we have the parser for non atomic things 3 | 4 | use super::super::idata::{ 5 | cont::IVec, 6 | tc::{tail_call, TailCall}, 7 | }; 8 | use crate::ast; 9 | use crate::parser::{atom, atom::Atom, ErrPriority, Error, Result, Status}; 10 | use std::collections::HashMap; 11 | use std::result; 12 | 13 | #[cfg(test)] 14 | mod test; 15 | 16 | //----------------------------------------------------------------------- 17 | //----------------------------------------------------------------------- 18 | // 19 | // T Y P E S 20 | // 21 | //----------------------------------------------------------------------- 22 | //----------------------------------------------------------------------- 23 | 24 | #[derive(Clone, Copy, Debug)] 25 | pub(crate) struct Started(usize); 26 | 27 | pub(crate) type ResultExpr<'a> = result::Result<(Status<'a>, Vec), Error>; 28 | 29 | /// The set of rules to be parsed 30 | /// Any rule has a name 31 | /// A rule can be registered just once 32 | /// The starting rule is main 33 | #[derive(Debug)] 34 | pub struct SetOfRules(pub HashMap); 35 | 36 | impl SetOfRules { 37 | /// Initialize a set of rules with a hashmap of 38 | /// In general, is better to use the ```rules!``` macro 39 | pub fn new(mrules: HashMap) -> Self { 40 | SetOfRules(mrules) 41 | } 42 | 43 | /// As this is a dynamic parser, it is necessary to add rules on 44 | /// runtime. 45 | /// 46 | /// This method, will take the owner ship, and will return itself 47 | /// 48 | /// In this way, you don't need to declare mutable vars. 49 | /// You could need recursion in some cases 50 | /// 51 | /// To add several rules at once, look for merge 52 | /// 53 | /// ``` 54 | /// #[macro_use] extern crate dynparser; 55 | /// use dynparser::parse; 56 | /// 57 | /// fn main() { 58 | /// let rules = rules!{ 59 | /// "main" => and!{ 60 | /// rep!(lit!("a"), 1, 5), 61 | /// ref_rule!("rule2") 62 | /// } 63 | /// }; 64 | /// 65 | /// let rules = rules.add("rule2", lit!("bcd")); 66 | /// 67 | /// assert!(parse("aabcd", &rules).is_ok()) 68 | /// } 69 | /// ``` 70 | pub fn add(mut self, name: &str, expr: Expression) -> Self { 71 | self.0.insert(name.to_owned(), expr); 72 | self 73 | } 74 | 75 | /// As this is a dynamic parser, it is necessary to add rules on 76 | /// runtime. 77 | /// 78 | /// This method, will take the owner ship, and will return itself 79 | /// 80 | /// In this way, you don't need to declare mutable vars. 81 | /// You could need recursion in some cases 82 | /// 83 | /// It will add the rules from the parameter 84 | /// 85 | /// ``` 86 | /// #[macro_use] extern crate dynparser; 87 | /// use dynparser::parse; 88 | /// 89 | /// fn main() { 90 | /// let rules = rules!{ 91 | /// "main" => and!{ 92 | /// rep!(lit!("a"), 1, 5), 93 | /// ref_rule!("rule2") 94 | /// } 95 | /// }; 96 | /// 97 | /// let rules = rules.merge(rules!{"rule2" => lit!("bcd")}); 98 | /// 99 | /// assert!(parse("aabcd", &rules).is_ok()) 100 | /// } 101 | /// ``` 102 | pub fn merge(self, rules2merge: Self) -> Self { 103 | SetOfRules(rules2merge.0.into_iter().chain(self.0).collect()) 104 | } 105 | } 106 | 107 | #[allow(missing_docs)] 108 | #[derive(Debug)] 109 | pub enum Expression { 110 | Simple(Atom), 111 | And(MultiExpr), 112 | Or(MultiExpr), 113 | Not(Box), 114 | Repeat(RepInfo), 115 | RuleName(String), 116 | } 117 | 118 | /// Opaque type to manage multiple expressions 119 | #[derive(Debug)] 120 | pub struct MultiExpr(pub Vec); 121 | 122 | impl MultiExpr { 123 | /// Creates a new instance of ```MultiExpr``` from a vector 124 | pub fn new(v: Vec) -> Self { 125 | MultiExpr(v) 126 | } 127 | } 128 | 129 | /// Opaque type to manage repetition subexpression 130 | #[derive(Debug)] 131 | pub struct RepInfo { 132 | /// expresion 133 | pub expression: Box, 134 | /// min repetions 135 | pub min: NRep, 136 | /// max repetions 137 | pub max: Option, 138 | } 139 | 140 | impl RepInfo { 141 | /// Creates a Repeticion Info for an expression with min and 142 | /// optionally max values to repeat 143 | pub fn new(expression: Box, min: usize, max: Option) -> Self { 144 | RepInfo { 145 | expression, 146 | min: NRep(min), 147 | max: max.map(NRep), 148 | } 149 | } 150 | } 151 | 152 | /// Number of repetitions of rule 153 | #[derive(Debug)] 154 | pub struct NRep(pub(crate) usize); 155 | 156 | impl std::fmt::Display for NRep { 157 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 158 | write!(f, "{}", self.0) 159 | } 160 | } 161 | 162 | //----------------------------------------------------------------------- 163 | //----------------------------------------------------------------------- 164 | // 165 | // A P I 166 | // 167 | //----------------------------------------------------------------------- 168 | //----------------------------------------------------------------------- 169 | 170 | //----------------------------------------------------------------------- 171 | pub(crate) fn parse(status: Status) -> Result { 172 | parse_rule_name(status, "main") 173 | } 174 | 175 | //----------------------------------------------------------------------- 176 | // SUPPORT 177 | 178 | //----------------------------------------------------------------------- 179 | fn parse_rule_name<'a>(status: Status<'a>, rule_name: &str) -> Result<'a> { 180 | // use std::time::{Duration, Instant}; 181 | // let start = Instant::now(); 182 | 183 | let status = if status.trace_rules { 184 | status.push_rule(&format!("r:{}", rule_name)) 185 | } else { 186 | status 187 | }; 188 | 189 | let rules = &status.rules.0; 190 | let expression = rules.get(rule_name).ok_or_else(|| { 191 | Error::from_status( 192 | &status, 193 | &format!("Missing rule: {}", rule_name), 194 | ErrPriority::Critical, 195 | ) 196 | })?; 197 | let (st, nodes) = parse_expr(status, &expression)?; 198 | 199 | // let elapsed = start.elapsed(); 200 | // println!( 201 | // "____ elapsed time parsing {} {}.{}", 202 | // rule_name, 203 | // elapsed.as_secs(), 204 | // elapsed.subsec_millis() 205 | // ); 206 | Ok((st, ast::Node::Rule((rule_name.to_owned(), nodes)))) 207 | } 208 | 209 | fn parse_atom_as_expr<'a>(status: Status<'a>, a: &'a Atom) -> ResultExpr<'a> { 210 | let (st, node) = atom::parse(status, a)?; 211 | Ok((st, vec![node])) 212 | } 213 | 214 | fn parse_rule_name_as_expr<'a>(status: Status<'a>, rule_name: &str) -> ResultExpr<'a> { 215 | let (st, ast) = parse_rule_name(status, rule_name)?; 216 | Ok((st, vec![ast])) 217 | } 218 | 219 | fn parse_expr<'a>(status: Status<'a>, expression: &'a Expression) -> ResultExpr<'a> { 220 | match *expression { 221 | Expression::Simple(ref val) => parse_atom_as_expr(status, &val), 222 | Expression::And(ref val) => parse_and(status, &val), 223 | Expression::Or(ref val) => parse_or(&status, &val), 224 | Expression::Not(ref val) => parse_not(status, &val), 225 | Expression::Repeat(ref val) => parse_repeat(status, &val), 226 | Expression::RuleName(ref val) => parse_rule_name_as_expr(status, &val), 227 | } 228 | } 229 | 230 | //----------------------------------------------------------------------- 231 | fn parse_and<'a>(status: Status<'a>, multi_expr: &'a MultiExpr) -> ResultExpr<'a> { 232 | let init_tc: (_, &[Expression], Vec) = (status, &(multi_expr.0), vec![]); 233 | 234 | tail_call(init_tc, |acc| { 235 | if acc.1.is_empty() { 236 | TailCall::Return(Ok((acc.0, acc.2))) 237 | } else { 238 | let result_parse = parse_expr(acc.0, &acc.1[0]); 239 | match result_parse { 240 | Ok((status, vnodes)) => { 241 | TailCall::Call((status, &acc.1[1..], acc.2.iappend(vnodes))) 242 | } 243 | Err(err) => TailCall::Return(Err(err)), 244 | } 245 | } 246 | }) 247 | } 248 | 249 | //----------------------------------------------------------------------- 250 | fn parse_or<'a>(status: &Status<'a>, multi_expr: &'a MultiExpr) -> ResultExpr<'a> { 251 | let deep_err = |oe1: Option, e2: Error| match oe1 { 252 | Some(e1) => match (e1.priority > e2.priority, e1.pos.n > e2.pos.n) { 253 | (true, _) => Some(e1), 254 | (false, true) => Some(e1), 255 | (false, false) => Some(e2), 256 | }, 257 | None => Some(e2), 258 | }; 259 | 260 | let init_tc: (_, &[Expression], Option) = (status.clone(), &(multi_expr.0), None); 261 | 262 | tail_call(init_tc, |acc| { 263 | if acc.1.is_empty() { 264 | TailCall::Return(Err(match acc.2 { 265 | Some(err) => err, 266 | _ => Error::from_status_normal( 267 | &status, 268 | "LOGIC ERROR!!! checked all options in or with ¿NO? errors", 269 | ), 270 | })) 271 | } else { 272 | let try_parse = parse_expr(acc.0.clone(), &acc.1[0]); 273 | match try_parse { 274 | Ok(result) => TailCall::Return(Ok(result)), 275 | Err(e) => { 276 | if e.priority == ErrPriority::Critical { 277 | TailCall::Return(Err(e)) 278 | } else { 279 | TailCall::Call((acc.0, &acc.1[1..], deep_err(acc.2, e))) 280 | } 281 | } 282 | } 283 | } 284 | }) 285 | } 286 | 287 | //----------------------------------------------------------------------- 288 | fn parse_not<'a>(status: Status<'a>, expression: &'a Expression) -> ResultExpr<'a> { 289 | match parse_expr(status.clone(), expression) { 290 | Ok(_) => Err(Error::from_status_normal(&status, "not")), 291 | Err(_) => Ok((status, vec![])), 292 | } 293 | } 294 | 295 | //----------------------------------------------------------------------- 296 | fn parse_repeat<'a>(status: Status<'a>, rep_info: &'a RepInfo) -> ResultExpr<'a> { 297 | let big_min_bound = |counter| counter >= rep_info.min.0; 298 | let touch_max_bound = |counter: usize| match rep_info.max { 299 | Some(ref m) => counter + 1 == m.0, 300 | None => false, 301 | }; 302 | 303 | let init_tc: (_, _, Vec) = (status, 0, vec![]); 304 | Ok(tail_call(init_tc, |acc| { 305 | let try_parse = parse_expr(acc.0.clone(), &rep_info.expression); 306 | match (try_parse, big_min_bound(acc.1), touch_max_bound(acc.1)) { 307 | (Err(e), true, _) => { 308 | if e.priority == ErrPriority::Critical { 309 | TailCall::Return(Err(e)) 310 | } else { 311 | TailCall::Return(Ok((acc.0.set_potential_error(e), acc.2))) 312 | } 313 | } 314 | (Err(e), false, _) => TailCall::Return(Err(e)), 315 | // Err(Error::from_status( 316 | // &acc.0, 317 | // &format!("inside repeat {:#?}", e), 318 | // ))), 319 | (Ok((status, vnodes)), _, false) => { 320 | TailCall::Call((status, acc.1 + 1, acc.2.iappend(vnodes))) 321 | } 322 | (Ok((status, vnodes)), _, true) => { 323 | TailCall::Return(Ok((status, acc.2.iappend(vnodes)))) 324 | } 325 | } 326 | })?) 327 | } 328 | // SUPPORT 329 | //----------------------------------------------------------------------- 330 | -------------------------------------------------------------------------------- /src/peg/rules.rs: -------------------------------------------------------------------------------- 1 | use crate::parser; 2 | 3 | pub(crate) fn parse_peg() -> parser::expression::SetOfRules { 4 | rules!( 5 | r#"dot"# => lit!(".") 6 | , r#"module"# => and!(ref_rule!(r#"_"#), ref_rule!(r#"mod_name"#), ref_rule!(r#"_"#), lit!("{"), ref_rule!(r#"_"#), ref_rule!(r#"grammar"#), ref_rule!(r#"_"#), lit!("}"), ref_rule!(r#"_eol"#), ref_rule!(r#"_"#)) 7 | , r#"mline_comment"# => and!(lit!("/*"), rep!(and!(not!(lit!("*/")), dot!()), 0), lit!("*/")) 8 | , r#"_1"# => or!(lit!(" "), ref_rule!(r#"eol"#)) 9 | , r#"comment"# => or!(ref_rule!(r#"line_comment"#), ref_rule!(r#"mline_comment"#)) 10 | , r#"or"# => and!(ref_rule!(r#"and"#), rep!(and!(ref_rule!(r#"_"#), lit!("/"), ref_rule!(r#"_"#), ref_rule!(r#"or"#)), 0, 1)) 11 | , r#"literal"# => or!(ref_rule!(r#"lit_noesc"#), ref_rule!(r#"lit_esc"#)) 12 | , r#"mod_name"# => ref_rule!(r#"symbol"#) 13 | , r#"esc_char"# => or!(lit!("\\r"), lit!("\\n"), lit!("\\t"), lit!("\\\\"), lit!("\\\"")) 14 | , r#"atom"# => or!(ref_rule!(r#"literal"#), ref_rule!(r#"match"#), ref_rule!(r#"rule_name"#), ref_rule!(r#"dot"#)) 15 | , r#"hex_char"# => and!(lit!("\\0x"), ematch!(chlist r#""# , from '0', to '9' , from 'A', to 'F' ), ematch!(chlist r#""# , from '0', to '9' , from 'A', to 'F' )) 16 | , r#"parenth"# => and!(lit!("("), ref_rule!(r#"_"#), ref_rule!(r#"expr"#), ref_rule!(r#"_"#), or!(lit!(")"), error!("unbalanced parethesis: missing ')'"))) 17 | , r#"and"# => or!(ref_rule!(r#"error"#), and!(ref_rule!(r#"rep_or_neg"#), rep!(and!(ref_rule!(r#"_1"#), ref_rule!(r#"_"#), not!(and!(ref_rule!(r#"rule_name"#), ref_rule!(r#"_"#), or!(lit!("="), lit!("{")))), ref_rule!(r#"and"#)), 0))) 18 | , r#"rule"# => and!(ref_rule!(r#"_"#), ref_rule!(r#"rule_name"#), ref_rule!(r#"_"#), lit!("="), ref_rule!(r#"_"#), ref_rule!(r#"expr"#), ref_rule!(r#"_eol"#), ref_rule!(r#"_"#)) 19 | , r#"grammar"# => rep!(or!(ref_rule!(r#"rule"#), ref_rule!(r#"module"#)), 1) 20 | , r#"match"# => and!(lit!("["), or!(and!(ref_rule!(r#"mchars"#), rep!(ref_rule!(r#"mbetween"#), 0)), rep!(ref_rule!(r#"mbetween"#), 1)), lit!("]")) 21 | , r#"rep_or_neg"# => or!(and!(ref_rule!(r#"atom_or_par"#), rep!(or!(lit!("*"), lit!("+"), lit!("?")), 0, 1)), and!(lit!("!"), ref_rule!(r#"atom_or_par"#))) 22 | , r#"_eol"# => and!(rep!(or!(lit!(" "), ref_rule!(r#"comment"#)), 0), ref_rule!(r#"eol"#)) 23 | , r#"line_comment"# => and!(lit!("//"), rep!(and!(not!(ref_rule!(r#"eol"#)), dot!()), 0), ref_rule!(r#"eol"#)) 24 | , r#"lit_noesc"# => and!(ref_rule!(r#"_'"#), rep!(and!(not!(ref_rule!(r#"_'"#)), dot!()), 0), ref_rule!(r#"_'"#)) 25 | , r#"rule_name"# => and!(rep!(lit!("."), 0, 1), ref_rule!(r#"symbol"#), rep!(and!(lit!("."), ref_rule!(r#"symbol"#)), 0)) 26 | , r#"_""# => lit!("\"") 27 | , r#"mchars"# => rep!(and!(not!(lit!("]")), not!(and!(dot!(), lit!("-"))), dot!()), 1) 28 | , r#"expr"# => ref_rule!(r#"or"#) 29 | , r#"symbol"# => and!(ematch!(chlist r#"_"# , from 'a', to 'z' , from 'A', to 'Z' , from '0', to '9' ), rep!(ematch!(chlist r#"_'""# , from 'a', to 'z' , from 'A', to 'Z' , from '0', to '9' ), 0)) 30 | , r#"error"# => and!(lit!("error"), ref_rule!(r#"_"#), lit!("("), ref_rule!(r#"_"#), ref_rule!(r#"literal"#), ref_rule!(r#"_"#), lit!(")")) 31 | , r#"_'"# => lit!("'") 32 | , r#"eol"# => or!(lit!("\r\n"), lit!("\n"), lit!("\r")) 33 | , r#"lit_esc"# => and!(ref_rule!(r#"_""#), rep!(or!(ref_rule!(r#"esc_char"#), ref_rule!(r#"hex_char"#), and!(not!(ref_rule!(r#"_""#)), dot!())), 0), ref_rule!(r#"_""#)) 34 | , r#"mbetween"# => and!(dot!(), lit!("-"), dot!()) 35 | , r#"_"# => rep!(or!(lit!(" "), ref_rule!(r#"eol"#), ref_rule!(r#"comment"#)), 0) 36 | , r#"main"# => ref_rule!(r#"grammar"#) 37 | , r#"atom_or_par"# => or!(ref_rule!(r#"atom"#), ref_rule!(r#"parenth"#)) 38 | 39 | ) 40 | } 41 | 42 | // ------------------------------------------------------------------------ 43 | // ------------------------------------------------------------------------ 44 | // 45 | // this is the first version of code to parse the peg grammar 46 | // it was, obviously written by hand 47 | // pub(crate) fn parse_peg_first() -> parser::expression::SetOfRules { 48 | // rules!( 49 | 50 | // "main" => ref_rule!("grammar"), 51 | 52 | // "grammar" => rep!(ref_rule!("rule"), 1), 53 | 54 | // "rule" => and!( 55 | // ref_rule!("_"), ref_rule!("symbol"), 56 | // ref_rule!("_"), lit! ("="), 57 | // ref_rule!("_"), ref_rule!("expr"), 58 | // ref_rule!("_eol"), 59 | // ref_rule!("_") 60 | // ), 61 | 62 | // "expr" => ref_rule!("or"), 63 | 64 | // "or" => and!( 65 | // ref_rule!("and"), 66 | // rep!( 67 | // and!( 68 | // ref_rule!("_"), lit!("/"), 69 | // ref_rule!("_"), ref_rule!("or") 70 | // ), 71 | // 0 72 | // ) 73 | // ), 74 | 75 | // "and" => and!( 76 | // ref_rule!("rep_or_neg"), 77 | // rep!( 78 | // and!( 79 | // ref_rule!("_1"), ref_rule!("_"), 80 | // not!(and!( 81 | // ref_rule!("symbol"), 82 | // ref_rule!("_"), lit! ("=") 83 | // )), 84 | // ref_rule!("and") 85 | // ), 86 | // 0 87 | // ) 88 | // ), 89 | 90 | // "rep_or_neg" => or!( 91 | // and!( 92 | // ref_rule!("atom_or_par"), 93 | // rep!( 94 | // or!( 95 | // lit!("*"), 96 | // lit!("+"), 97 | // lit!("?") 98 | // ) 99 | // , 0, 1 100 | // ) 101 | // ), 102 | // and!( 103 | // lit!("!"), 104 | // ref_rule!("atom_or_par") 105 | // ) 106 | // ), 107 | 108 | // "atom_or_par" => or!( 109 | // ref_rule!("atom"), 110 | // ref_rule!("parenth") 111 | // ), 112 | 113 | // "parenth" => and!( 114 | // lit!("("), 115 | // ref_rule!("_"), 116 | // ref_rule!("expr"), 117 | // ref_rule!("_"), 118 | // lit!(")") 119 | // ), 120 | 121 | // "atom" => or!( 122 | // ref_rule!("literal"), 123 | // ref_rule!("match"), 124 | // ref_rule!("dot"), 125 | // ref_rule!("symbol") 126 | // ), 127 | 128 | // "literal" => and!( 129 | // ref_rule!(r#"_""#), 130 | // rep!( 131 | // and!( 132 | // not!( 133 | // ref_rule!(r#"_""#) 134 | // ), 135 | // dot!() 136 | // ) 137 | // , 0 138 | // ), 139 | // ref_rule!(r#"_""#) 140 | // ), 141 | 142 | // r#"_""# => lit!(r#"""#), 143 | 144 | // "match" => and!( 145 | // lit!("["), 146 | // or!( 147 | // and!( 148 | // rep!(ref_rule!("mchars"), 1), 149 | // rep!(ref_rule!("mbetween"), 0) 150 | // ), 151 | // rep!(ref_rule!("mbetween"), 1) 152 | // ), 153 | // lit!("]") 154 | // ), 155 | 156 | // "mchars" => rep!( 157 | // and!( 158 | // not!(lit!("]")), 159 | // not!(and!(dot!(), lit!("-"))), 160 | // dot!()) 161 | // ,1 162 | // ), 163 | 164 | // "mbetween" => and!(dot!(), lit!("-"), dot!()), 165 | 166 | // "dot" => lit!("."), 167 | 168 | // "symbol" => and!( 169 | // ematch!( chlist "_'", 170 | // from 'a', to 'z', 171 | // from 'A', to 'Z', 172 | // from '0', to '9' 173 | // ), 174 | // rep!( 175 | // ematch!( chlist "_'\"", 176 | // from 'a', to 'z', 177 | // from 'A', to 'Z', 178 | // from '0', to '9' 179 | // ), 180 | // 0 181 | // ) 182 | // ), 183 | 184 | // "_" => rep!( or!( 185 | // lit!(" "), 186 | // ref_rule!("eol") 187 | // // ref_rule!("comment") 188 | // ) 189 | // , 0 190 | // ), 191 | 192 | // "_eol" => and!( 193 | // rep!( or!( 194 | // lit!(" ") 195 | // ) 196 | // , 0 197 | // ), 198 | // ref_rule!("eol") 199 | // ), 200 | 201 | // "_1" => or!( 202 | // lit!(" "), 203 | // ref_rule!("eol") 204 | // // ref_rule!("comment") 205 | // ), 206 | 207 | // "spaces" => rep!(lit!(" "), 0), 208 | 209 | // "eol" => or!( 210 | // lit!("\r\n"), 211 | // lit!("\n"), 212 | // lit!("\r") 213 | // ) 214 | 215 | // // "comment" => or!( 216 | // // and!( 217 | // // lit!("//"), 218 | // // rep!( 219 | // // and!( 220 | // // not!(ref_rule!("eol")), 221 | // // dot!() 222 | // // ) 223 | // // , 0 224 | // // ), 225 | // // ref_rule!("eol") 226 | // // ), 227 | // // and!( 228 | // // lit!("/*"), 229 | // // rep!( 230 | // // and!( 231 | // // not!(lit!("*/")), 232 | // // dot!() 233 | // // ) 234 | // // , 0 235 | // // ), 236 | // // lit!("*/") 237 | // // ) 238 | // // ) 239 | // ) 240 | // } 241 | 242 | // And this is the first autogenerated code :-) working 243 | // "rep_or_neg" => or!(and!(ref_rule!("atom_or_par"), rep!(or!(lit!("*"), lit!("+"), lit!("?")), 0, 1)), and!(lit!("!"), ref_rule!("atom_or_par"))) 244 | // , "literal" => and!(ref_rule!("_\""), rep!(or!(and!(lit!("\\"), dot!()), and!(not!(ref_rule!("_\"")), dot!())), 0), ref_rule!("_\"")) 245 | // , "eol" => or!(lit!("\r\n"), lit!("\n"), lit!("\r")) 246 | // , "mchars" => rep!(and!(not!(lit!("]")), not!(and!(dot!(), lit!("-"))), dot!()), 1) 247 | // , "mbetween" => and!(dot!(), lit!("-"), dot!()) 248 | // , "atom_or_par" => or!(ref_rule!("atom"), ref_rule!("parenth")) 249 | // , "dot" => lit!(".") 250 | // , "or" => and!(ref_rule!("and"), rep!(and!(ref_rule!("_"), lit!("/"), ref_rule!("_"), ref_rule!("or")), 0)) 251 | // , "_eol" => and!(rep!(lit!(" "), 0), ref_rule!("eol")) 252 | // , "rule" => and!(ref_rule!("_"), ref_rule!("symbol"), ref_rule!("_"), lit!("="), ref_rule!("_"), ref_rule!("expr"), ref_rule!("_eol"), ref_rule!("_")) 253 | // , "symbol" => and!(ematch!(chlist "_'" , from 'a', to 'z' , from 'A', to 'Z' , from '0', to '9' ), rep!(ematch!(chlist "_'\"" , from 'a', to 'z' , from 'A', to 'Z' , from '0', to '9' ), 0)) 254 | // , "main" => ref_rule!("grammar") 255 | // , "match" => and!(lit!("["), or!(and!(rep!(ref_rule!("mchars"), 1), rep!(ref_rule!("mbetween"), 0)), rep!(ref_rule!("mbetween"), 1)), lit!("]")) 256 | // , "grammar" => rep!(ref_rule!("rule"), 1) 257 | // , "and" => and!(ref_rule!("rep_or_neg"), rep!(and!(ref_rule!("_1"), ref_rule!("_"), not!(and!(ref_rule!("symbol"), ref_rule!("_"), lit!("="))), ref_rule!("and")), 0)) 258 | // , "_" => rep!(or!(lit!(" "), ref_rule!("eol")), 0) 259 | // , "parenth" => and!(lit!("("), ref_rule!("_"), ref_rule!("expr"), ref_rule!("_"), lit!(")")) 260 | // , "expr" => ref_rule!("or") 261 | // , "_\"" => lit!("\"") 262 | // , "atom" => or!(ref_rule!("literal"), ref_rule!("match"), ref_rule!("dot"), ref_rule!("symbol")) 263 | // , "_1" => or!(lit!(" "), ref_rule!("eol")) 264 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | // #![feature(external_doc)] 3 | // #![doc(include = "../README.md")] 4 | 5 | //! For an introduction and context view, read... 6 | //! 7 | //! [README.md](https://github.com/jleahred/dynparser) 8 | //! 9 | //! A very basic example... 10 | //! ```rust 11 | //! extern crate dynparser; 12 | //! use dynparser::{parse, rules_from_peg}; 13 | //! 14 | //! fn main() { 15 | //! let rules = rules_from_peg( 16 | //! r#" 17 | //! 18 | //! main = letter letter_or_num+ 19 | //! 20 | //! letter = [a-zA-Z] 21 | //! 22 | //! letter_or_num = letter 23 | //! / number 24 | //! 25 | //! number = [0-9] 26 | //! 27 | //! "#, 28 | //! ).unwrap(); 29 | //! 30 | //! assert!(parse("a2AA456bzJ88", &rules).is_ok()); 31 | //! } 32 | //!``` 33 | //! 34 | //! 35 | //! The classical calculator example 36 | //! 37 | //! ```rust 38 | //! extern crate dynparser; 39 | //! use dynparser::{parse, rules_from_peg}; 40 | //! 41 | //! 42 | //! fn main() { 43 | //! let rules = rules_from_peg( 44 | //! r#" 45 | //! 46 | //! main = _ expr _ 47 | //! 48 | //! expr = add_t (_ add_op _ add_t)* 49 | //! / portion_expr 50 | //! 51 | //! add_t = fact_t (_ fact_op _ fact_t)* 52 | //! 53 | //! fact_t = portion_expr 54 | //! 55 | //! portion_expr = '(' expr ')' 56 | //! / item 57 | //! 58 | //! item = num 59 | //! 60 | //! num = [0-9]+ ('.' [0-9]+)? 61 | //! add_op = '+' / '-' 62 | //! fact_op = '*' / '/' 63 | //! 64 | //! _ = ' '* 65 | //! 66 | //! "#, 67 | //! ).map_err(|e| { 68 | //! println!("{}", e); 69 | //! panic!("FAIL"); 70 | //! }) 71 | //! .unwrap(); 72 | //! 73 | //! let result = parse(" 1 + 2* 3 +(5/5 - (8-7))", &rules); 74 | //! match result { 75 | //! Ok(ast) => println!( 76 | //! "{:#?}", 77 | //! ast.compact() 78 | //! .prune(&vec!["_"]) 79 | //! .pass_through_except(&vec!["main", "add_t", "fact_t"]) 80 | //! ), 81 | //! Err(e) => println!("Error: {:?}", e), 82 | //! }; 83 | //! } 84 | //! ``` 85 | //! 86 | //! Please, read [README.md](https://github.com/jleahred/dynparser) for 87 | //! more context information 88 | //! 89 | //! ```rust 90 | //! extern crate dynparser; 91 | //! use dynparser::{parse, rules_from_peg}; 92 | //! fn main() { 93 | //! let rules = rules_from_peg( 94 | //! r#" 95 | //! 96 | //! main = '(' main ( ')' / error("unbalanced parenthesis") ) 97 | //! / 'hello' 98 | //! 99 | //! "#, 100 | //! ).unwrap(); 101 | //! 102 | //! match parse("((hello)", &rules) { 103 | //! Ok(_) => panic!("It should fail"), 104 | //! Err(e) => assert!(e.descr == "unbalanced parenthesis"), 105 | //! } 106 | //! } 107 | //! ``` 108 | 109 | extern crate idata; 110 | 111 | // ------------------------------------------------------------------------------------- 112 | // M A C R O S 113 | 114 | /// Create a map of rules 115 | /// 116 | /// example 117 | /// ``` 118 | /// #[macro_use] extern crate dynparser; 119 | /// use dynparser::parse; 120 | /// 121 | /// fn main() { 122 | /// let rules = rules!{ 123 | /// "main" => and!{ 124 | /// lit!("aa"), 125 | /// ref_rule!("rule2") 126 | /// }, 127 | /// "rule2" => and!{ 128 | /// lit!("b"), 129 | /// lit!("c") 130 | /// } 131 | /// }; 132 | /// 133 | /// assert!(parse("aabc", &rules).is_ok()) 134 | /// } 135 | /// ``` 136 | #[macro_export] 137 | #[cfg_attr(feature = "cargo-clippy", allow(clippy::let_and_return))] 138 | macro_rules! rules { 139 | ($($n:expr => $e:expr),*) => {{ 140 | use $crate::parser::expression; 141 | use std::collections::HashMap; 142 | 143 | let rules = expression::SetOfRules::new(HashMap::::new()); 144 | $(let rules = rules.add($n, $e);)* 145 | rules 146 | }}; 147 | } 148 | 149 | /// Create a literal 150 | /// 151 | /// example 152 | /// ``` 153 | /// #[macro_use] extern crate dynparser; 154 | /// use dynparser::parse; 155 | /// 156 | /// fn main() { 157 | /// let rules = rules!{ 158 | /// "main" => lit!("aa") 159 | /// }; 160 | /// 161 | /// assert!(parse("aa", &rules).is_ok()) 162 | /// } 163 | /// ``` 164 | #[macro_export] 165 | macro_rules! lit { 166 | ($e:expr) => {{ 167 | $crate::parser::expression::Expression::Simple($crate::parser::atom::Atom::Literal( 168 | $e.to_string(), 169 | )) 170 | }}; 171 | } 172 | 173 | /// Generate an error 174 | /// 175 | /// example 176 | /// ``` 177 | /// #[macro_use] extern crate dynparser; 178 | /// use dynparser::parse; 179 | /// 180 | /// fn main() { 181 | /// let rules = rules!{ 182 | /// "main" => error!("aa") 183 | /// }; 184 | /// 185 | /// assert!(parse("aa", &rules).is_err()) 186 | /// } 187 | /// ``` 188 | /// 189 | /// ```rust 190 | /// extern crate dynparser; 191 | /// use dynparser::{parse, rules_from_peg}; 192 | /// fn main() { 193 | /// let rules = rules_from_peg( 194 | /// r#" 195 | /// 196 | /// main = '(' main ( ')' / error("unbalanced parenthesis") ) 197 | /// / 'hello' 198 | /// 199 | /// "#, 200 | /// ).unwrap(); 201 | /// 202 | /// match parse("((hello)", &rules) { 203 | /// Ok(_) => panic!("It should fail"), 204 | /// Err(e) => assert!(e.descr == "unbalanced parenthesis"), 205 | /// } 206 | /// } 207 | /// ``` 208 | 209 | #[macro_export] 210 | macro_rules! error { 211 | ($e:expr) => {{ 212 | $crate::parser::expression::Expression::Simple($crate::parser::atom::Atom::Error( 213 | $e.to_string(), 214 | )) 215 | }}; 216 | } 217 | 218 | /// Atom::Dot (any character) 219 | /// 220 | /// example 221 | /// ``` 222 | /// #[macro_use] extern crate dynparser; 223 | /// use dynparser::parse; 224 | /// 225 | /// fn main() { 226 | /// let rules = rules!{ 227 | /// "main" => and!(dot!(), dot!()) 228 | /// }; 229 | /// 230 | /// assert!(parse("aa", &rules).is_ok()) 231 | /// } 232 | /// ``` 233 | #[macro_export] 234 | macro_rules! dot { 235 | () => {{ 236 | $crate::parser::expression::Expression::Simple($crate::parser::atom::Atom::Dot) 237 | }}; 238 | } 239 | 240 | /// Generate a match expression with optional characters and a list 241 | /// of bounds 242 | /// 243 | /// "String", from 'a', to 'b', from 'c', to 'd' 244 | /// The first string, is a set of chars. 245 | /// Later you can write a list of tuples with ranges to validate 246 | /// 247 | /// example 248 | /// ``` 249 | /// #[macro_use] extern crate dynparser; 250 | /// use dynparser::parse; 251 | /// 252 | /// fn main() { 253 | /// let rules = rules!{ 254 | /// "main" => rep!(ematch!( chlist "cd", 255 | /// from 'a', to 'b', 256 | /// from 'j', to 'p' 257 | /// ), 0) 258 | /// }; 259 | /// 260 | /// assert!(parse("aabcdj", &rules).is_ok()) 261 | /// } 262 | /// ``` 263 | /// 264 | /// 265 | /// You can also pass a list of chars and a vector of char bounds as next 266 | /// example 267 | /// 268 | /// ``` 269 | /// #[macro_use] extern crate dynparser; 270 | /// use dynparser::parse; 271 | /// 272 | /// fn main() { 273 | /// let rules = rules!{ 274 | /// "main" => rep!(ematch!( chlist "cd", 275 | /// from2 vec![ 276 | /// ('a', 'b'), 277 | /// ('j', 'p') 278 | /// ] 279 | /// ), 0) 280 | /// }; 281 | /// 282 | /// assert!(parse("aabcdj", &rules).is_ok()) 283 | /// } 284 | /// ``` 285 | 286 | #[macro_export] 287 | macro_rules! ematch { 288 | (chlist $chars:expr, $(from $from:expr, to $to:expr),*) => {{ 289 | //use idata::cont::IVec; // pending macros by example 2.0 290 | use $crate::parser; 291 | let mut v = Vec::<(char, char)>::new(); 292 | 293 | //$(let v = v.ipush(($from, $to));)+ // pending macros by example 2.0 294 | $(v.push(($from, $to));)+ 295 | let amatch = parser::atom::Atom::Match(parser::atom::MatchRules::init($chars, v)); 296 | parser::expression::Expression::Simple(amatch) 297 | }}; 298 | 299 | (chlist $chars:expr, from2 $vfrom2:expr) => {{ 300 | use $crate::parser; 301 | 302 | let amatch = parser::atom::Atom::Match(parser::atom::MatchRules::init($chars, $vfrom2)); 303 | parser::expression::Expression::Simple(amatch) 304 | }}; 305 | } 306 | 307 | /// Concat expressions (and) 308 | /// 309 | /// example 310 | /// ``` 311 | /// #[macro_use] extern crate dynparser; 312 | /// use dynparser::parse; 313 | /// 314 | /// fn main() { 315 | /// let rules = rules!{ 316 | /// "main" => and!(dot!(), dot!()) 317 | /// }; 318 | /// 319 | /// assert!(parse("aa", &rules).is_ok()) 320 | /// } 321 | /// ``` 322 | #[macro_export] 323 | macro_rules! and { 324 | ($($e:expr),*) => {{ 325 | use $crate::parser::expression::{Expression, MultiExpr}; 326 | 327 | Expression::And(MultiExpr::new(vec![$($e ,)*])) 328 | }}; 329 | } 330 | 331 | /// Choose expressions (or) 332 | /// 333 | /// example 334 | /// ``` 335 | /// #[macro_use] extern crate dynparser; 336 | /// use dynparser::parse; 337 | /// 338 | /// fn main() { 339 | /// let rules = rules!{ 340 | /// "main" => or!(lit!("z"), lit!("a")) 341 | /// }; 342 | /// 343 | /// assert!(parse("a", &rules).is_ok()) 344 | /// } 345 | /// ``` 346 | #[macro_export] 347 | macro_rules! or { 348 | ($($e:expr),*) => {{ 349 | use $crate::parser::expression::{Expression, MultiExpr}; 350 | 351 | Expression::Or(MultiExpr::new(vec![$($e ,)*])) 352 | }}; 353 | } 354 | 355 | /// negate expression 356 | /// 357 | /// example 358 | /// ``` 359 | /// #[macro_use] extern crate dynparser; 360 | /// use dynparser::parse; 361 | /// 362 | /// fn main() { 363 | /// let rules = rules!{ 364 | /// "main" => and!(not!(lit!("b")), dot!()) 365 | /// }; 366 | /// 367 | /// assert!(parse("a", &rules).is_ok()) 368 | /// } 369 | /// ``` 370 | /// 371 | /// not! will not move the parsing position 372 | #[macro_export] 373 | macro_rules! not { 374 | ($e:expr) => {{ 375 | $crate::parser::expression::Expression::Not(Box::new($e)) 376 | }}; 377 | } 378 | 379 | /// repeat expression. 380 | /// You have to define minimum repetitions and optionally 381 | /// maximum repetitions (if missing, infinite) 382 | /// 383 | /// example 384 | /// ``` 385 | /// #[macro_use] extern crate dynparser; 386 | /// use dynparser::parse; 387 | /// 388 | /// fn main() { 389 | /// let rules = rules!{ 390 | /// "main" => rep!(lit!("a"), 0) 391 | /// }; 392 | /// 393 | /// assert!(parse("aaaaaaaa", &rules).is_ok()) 394 | /// } 395 | /// ``` 396 | /// repeating from 0 to infinite 397 | /// 398 | /// ``` 399 | /// #[macro_use] extern crate dynparser; 400 | /// use dynparser::parse; 401 | /// 402 | /// fn main() { 403 | /// let rules = rules!{ 404 | /// "main" => rep!(lit!("a"), 0, 3) 405 | /// }; 406 | /// 407 | /// assert!(parse("aaa", &rules).is_ok()) 408 | /// } 409 | /// ``` 410 | #[macro_export] 411 | macro_rules! rep { 412 | ($e:expr, $min:expr) => {{ 413 | use $crate::parser::expression; 414 | 415 | expression::Expression::Repeat(expression::RepInfo::new(Box::new($e), $min, None)) 416 | }}; 417 | 418 | ($e:expr, $min:expr, $max:expr) => {{ 419 | use $crate::parser::expression; 420 | 421 | expression::Expression::Repeat(expression::RepInfo::new(Box::new($e), $min, Some($max))) 422 | }}; 423 | } 424 | 425 | /// This will create a subexpression referring to a "rule name" 426 | /// 427 | /// ``` 428 | /// #[macro_use] extern crate dynparser; 429 | /// 430 | /// fn main() { 431 | /// let rules = rules!{ 432 | /// "main" => ref_rule!("3a"), 433 | /// "3a" => lit!("aaa") 434 | /// }; 435 | /// 436 | /// assert!(dynparser::parse("aaa", &rules).is_ok()) 437 | /// } 438 | /// ``` 439 | #[macro_export] 440 | macro_rules! ref_rule { 441 | ($e:expr) => {{ 442 | $crate::parser::expression::Expression::RuleName($e.to_owned()) 443 | }}; 444 | } 445 | 446 | // M A C R O S 447 | // ------------------------------------------------------------------------------------- 448 | 449 | pub mod ast; 450 | pub mod parser; 451 | pub mod peg; 452 | 453 | // ------------------------------------------------------------------------------------- 454 | // T Y P E S 455 | 456 | // T Y P E S 457 | // ------------------------------------------------------------------------------------- 458 | 459 | // ------------------------------------------------------------------------------------- 460 | // A P I 461 | 462 | /// Parse a string with a set of rules 463 | /// 464 | /// the `main` rule is the starting point to parse 465 | /// 466 | /// # Examples 467 | /// 468 | /// Parse a simple literal 469 | /// 470 | /// ``` 471 | /// #[macro_use] extern crate dynparser; 472 | /// 473 | /// fn main() { 474 | /// let rules = rules!{ 475 | /// "main" => ref_rule!("3a"), 476 | /// "3a" => lit!("aaa") 477 | /// }; 478 | /// 479 | /// assert!(dynparser::parse("aaa", &rules).is_ok()) 480 | /// } 481 | /// 482 | /// ``` 483 | /// More examples in macros 484 | /// 485 | 486 | pub fn parse(s: &str, rules: &parser::expression::SetOfRules) -> Result { 487 | parse_with_debug(s, rules, false) 488 | } 489 | 490 | /// Same as parser, but with debug info 491 | /// 492 | /// It will trace the rules called 493 | /// 494 | /// It's expensive, use it just to develop and locate errors 495 | /// 496 | pub fn parse_debug( 497 | s: &str, 498 | rules: &parser::expression::SetOfRules, 499 | ) -> Result { 500 | parse_with_debug(s, rules, true) 501 | } 502 | 503 | fn parse_with_debug( 504 | s: &str, 505 | rules: &parser::expression::SetOfRules, 506 | debug: bool, 507 | ) -> Result { 508 | let (st, ast) = if debug { 509 | parser::expression::parse(parser::Status::init_debug(s, &rules, debug))? 510 | } else { 511 | parser::expression::parse(parser::Status::init(s, &rules))? 512 | }; 513 | match (st.pos.n == s.len(), st.potential_error.clone()) { 514 | (true, _) => Ok(ast), 515 | (false, Some(e)) => Err(e), 516 | (false, None) => Err(parser::Error::from_status_normal( 517 | &st, 518 | "not consumed full input", 519 | )), 520 | } 521 | } 522 | 523 | pub use peg::rules_from_peg; 524 | 525 | // A P I 526 | // ------------------------------------------------------------------------------------- 527 | 528 | //----------------------------------------------------------------------- 529 | // I N T E R N A L 530 | -------------------------------------------------------------------------------- /src/ast/mod.rs: -------------------------------------------------------------------------------- 1 | //! Data information to build the AST 2 | //! And some functions to work with AST 3 | //! 4 | 5 | use idata::cont::IVec; 6 | use std::result::Result; 7 | 8 | pub mod flat; 9 | 10 | // ------------------------------------------------------------------------------------- 11 | // T Y P E S 12 | 13 | /// Context information about an error manipulanting the ast 14 | /// You will have an String with the description, and the node 15 | /// wich produced the error 16 | /// It will have the error description and the string of node 17 | /// info 18 | #[derive(Debug, PartialEq)] 19 | pub struct Error(pub String, pub Option); 20 | 21 | /// Helper to create an ast::Error 22 | /// ``` 23 | /// use dynparser::ast; 24 | /// 25 | /// let error_a = ast::error("testing", None); 26 | /// let error_b = ast::Error("testing".to_string(), None); 27 | /// 28 | /// assert!(error_a == error_b) 29 | /// ``` 30 | 31 | pub fn error(desc: &str, ast_context: Option<&str>) -> Error { 32 | Error(desc.to_string(), ast_context.map(|a| a.to_string())) 33 | } 34 | 35 | /// Information of a node 36 | #[derive(Debug, PartialEq)] 37 | pub enum Node { 38 | /// The node is terminal (atom) with a name 39 | Val(String), 40 | /// The node is not terminal (rule) 41 | /// with a name and a vec of nodes 42 | Rule((String, Vec)), 43 | /// Reached end of file 44 | EOF, 45 | } 46 | 47 | impl Node { 48 | /// Remove nodes with one of the names in the list. 49 | /// It will remove the childs 50 | /// ``` 51 | /// use dynparser::ast; 52 | /// 53 | /// let ast_before_prune: ast::Node = ast::Node::Rule(( 54 | /// "root".to_string(), 55 | /// vec![ast::Node::Rule(( 56 | /// "a".to_string(), 57 | /// vec![ 58 | /// ast::Node::Rule(("_1".to_string(), vec![])), 59 | /// ast::Node::Rule(("_2".to_string(), vec![])), 60 | /// ], 61 | /// ))], 62 | /// )); 63 | /// 64 | /// let ast_after_prune = ast::Node::Rule(( 65 | /// "root".to_string(), 66 | /// vec![ast::Node::Rule(("a".to_string(), vec![]))], 67 | /// )); 68 | /// 69 | /// assert!(ast_before_prune.prune(&vec!["_1", "_2"]) == ast_after_prune) 70 | /// ``` 71 | 72 | pub fn prune(&self, nodes2prune: &[&str]) -> Self { 73 | let nname2prune = |nname: &str| nodes2prune.iter().find(|n| *n == &nname); 74 | let node2prune = |node: &Node| match node { 75 | Node::Rule((nname, _)) => nname2prune(nname).is_some(), 76 | _ => false, 77 | }; 78 | let prune_vn = |vnodes: &[Node]| { 79 | vnodes.iter().fold(vec![], |acc, n| { 80 | if !node2prune(n) { 81 | acc.ipush(n.prune(nodes2prune)) 82 | } else { 83 | acc 84 | } 85 | }) 86 | }; 87 | match self { 88 | Node::EOF => Node::EOF, 89 | Node::Val(v) => Node::Val(v.clone()), 90 | Node::Rule((n, vn)) => Node::Rule((n.clone(), prune_vn(vn))), 91 | } 92 | } 93 | 94 | /// Remove nodes excepting names in the list. 95 | /// Childs will be connected to the parent node removed 96 | /// ``` 97 | /// 98 | /// use dynparser::ast; 99 | /// 100 | /// let ast_before_pass_through: ast::Node = ast::Node::Rule(( 101 | /// "root".to_string(), 102 | /// vec![ast::Node::Rule(( 103 | /// "a".to_string(), 104 | /// vec![ast::Node::Rule(( 105 | /// "_1".to_string(), 106 | /// vec![ast::Node::Rule(("_2".to_string(), vec![]))], 107 | /// ))], 108 | /// ))], 109 | /// )); 110 | /// 111 | /// let ast_after_pass_through: ast::Node = ast::Node::Rule(( 112 | /// "root".to_string(), 113 | /// vec![ast::Node::Rule(( 114 | /// "a".to_string(), 115 | /// vec![ast::Node::Rule(("_2".to_string(), vec![]))], 116 | /// ))], 117 | /// )); 118 | /// 119 | /// assert!(ast_before_pass_through.pass_through_except(&vec!["root", "a", "_2"]) == ast_after_pass_through) 120 | /// ``` 121 | 122 | pub fn pass_through_except(&self, nodes2keep: &[&str]) -> Self { 123 | fn pthr_vn(vnodes: &[Node], nodes2keep: &[&str]) -> Vec { 124 | let nname2keep = |nname: &str| nodes2keep.iter().find(|n| *n == &nname); 125 | let node2keep = |node: &Node| match node { 126 | Node::Rule((nname, _)) => nname2keep(nname).is_some(), 127 | _ => true, 128 | }; 129 | vnodes.iter().fold(vec![], |acc, n| { 130 | if node2keep(n) { 131 | acc.ipush(n.pass_through_except(nodes2keep)) 132 | } else { 133 | match n { 134 | Node::Rule((_, new_nodes)) => acc.iappend(pthr_vn(new_nodes, nodes2keep)), 135 | _ => acc.ipush(n.pass_through_except(nodes2keep)), 136 | } 137 | } 138 | }) 139 | }; 140 | match self { 141 | Node::EOF => Node::EOF, 142 | Node::Val(v) => Node::Val(v.clone()), 143 | Node::Rule((n, vn)) => Node::Rule((n.clone(), pthr_vn(vn, nodes2keep))), 144 | } 145 | } 146 | 147 | /// Concat consecutive Val nodes 148 | /// ``` 149 | /// use dynparser::ast; 150 | /// 151 | /// let ast_before_compact: ast::Node = ast::Node::Rule(( 152 | /// "root".to_string(), 153 | /// vec![ast::Node::Rule(( 154 | /// "node".to_string(), 155 | /// vec![ 156 | /// ast::Node::Val("hello".to_string()), 157 | /// ast::Node::Val(" ".to_string()), 158 | /// ast::Node::Val("world".to_string()), 159 | /// ], 160 | /// ))], 161 | /// )); 162 | /// 163 | /// let ast_after_compact = ast::Node::Rule(( 164 | /// "root".to_string(), 165 | /// vec![ast::Node::Rule(( 166 | /// "node".to_string(), 167 | /// vec![ast::Node::Val("hello world".to_string())], 168 | /// ))], 169 | /// )); 170 | /// 171 | /// assert!(ast_before_compact.compact() == ast_after_compact) 172 | ///``` 173 | pub fn compact(&self) -> Self { 174 | fn concat_nodes(nodes: Vec, n: &Node) -> Vec { 175 | let get_val = |nodes: &Vec| match nodes.last() { 176 | Some(Node::Val(ref v)) => Some(v.to_string()), 177 | _ => None, 178 | }; 179 | let concat_v = |v: &String, prev_v: &Option| match (v, prev_v) { 180 | (v, Some(pv)) => Some(format!("{}{}", pv, v)), 181 | _ => None, 182 | }; 183 | 184 | match (n, get_val(&nodes)) { 185 | (Node::EOF, _) => nodes.ipush(Node::EOF), 186 | (Node::Val(ref v), ref prev_v) => match concat_v(v, prev_v) { 187 | Some(c) => { 188 | let (_, nodes) = nodes.ipop(); 189 | nodes.ipush(Node::Val(c.clone())) 190 | } 191 | _ => nodes.ipush(Node::Val(v.clone())), 192 | }, 193 | (Node::Rule((ref n, ref vn)), _) => { 194 | nodes.ipush(Node::Rule((n.clone(), compact_nodes(vn)))) 195 | } 196 | } 197 | }; 198 | fn compact_nodes(nodes: &[Node]) -> Vec { 199 | nodes 200 | .iter() 201 | .fold(vec![], |acc: Vec, n| (concat_nodes(acc, n))) 202 | }; 203 | match self { 204 | Node::EOF => Node::EOF, 205 | Node::Val(v) => Node::Val(v.clone()), 206 | Node::Rule((n, vn)) => Node::Rule((n.clone(), compact_nodes(vn))), 207 | } 208 | } 209 | } 210 | 211 | /// It will get the node name and a slice to the nodes contained by the node 212 | /// ``` 213 | /// use dynparser::ast::{self, get_nodename_and_nodes, Node}; 214 | /// 215 | /// let ast: Node = Node::Rule(( 216 | /// "root".to_string(), 217 | /// vec![Node::Val("hello".to_string())], 218 | /// )); 219 | /// 220 | /// let (node_name, nodes) = get_nodename_and_nodes(&ast).unwrap(); 221 | /// 222 | /// assert!(node_name == "root"); 223 | /// assert!(nodes[0] == ast::Node::Val("hello".to_string()),) 224 | /// ``` 225 | pub fn get_nodename_and_nodes(node: &Node) -> Result<(&str, &[Node]), Error> { 226 | match node { 227 | Node::Rule((nname, nodes)) => Ok((nname, nodes)), 228 | _ => Err(error("expected node::Rule", None)), 229 | } 230 | } 231 | 232 | /// Get the value of the Node 233 | /// If node is not a Node::Val, it will return an error 234 | ///``` 235 | /// use dynparser::ast::{self, get_node_val}; 236 | /// let ast = ast::Node::Val("hello".to_string()); 237 | /// 238 | /// let val = get_node_val(&ast).unwrap(); 239 | /// 240 | /// assert!(val == "hello"); 241 | ///``` 242 | pub fn get_node_val(node: &Node) -> Result<&str, Error> { 243 | match node { 244 | Node::Val(v) => Ok(v), 245 | _ => Err(error("expected node::Val", None)), 246 | } 247 | } 248 | 249 | /// Sometimes, processing the ast, you will exptect to have an unique 250 | /// child, and it will have to be a simple Node::Val 251 | /// This function will return the val, or error in other case 252 | /// 253 | ///``` 254 | /// use dynparser::ast; 255 | /// let nodes = vec![ast::Node::Val("hello".to_string())]; 256 | /// 257 | /// let val = ast::get_nodes_unique_val(&nodes).unwrap(); 258 | /// 259 | /// assert!(val == "hello"); 260 | ///``` 261 | /// 262 | /// If you pass an slice with more than one element, it will return 263 | /// an error 264 | /// 265 | ///``` 266 | /// use dynparser::ast; 267 | /// let nodes = vec![ast::Node::Val("hello".to_string()), 268 | /// ast::Node::Val("world".to_string())]; 269 | /// 270 | /// assert!(ast::get_nodes_unique_val(&nodes).is_err()); 271 | ///``` 272 | pub fn get_nodes_unique_val(nodes: &[Node]) -> Result<&str, Error> { 273 | match (nodes.first(), nodes.len()) { 274 | (Some(n), 1) => get_node_val(n), 275 | _ => Err(error("expected only one value in nodes", None)), 276 | } 277 | } 278 | 279 | /// Given a slice of nodes, return the value (&str) of first 280 | /// node if it is a Node::Rule and return the rest of nodes 281 | /// 282 | /// If it's not possible, return an error 283 | /// 284 | ///``` 285 | /// use dynparser::ast; 286 | /// let nodes = vec![ 287 | /// ast::Node::Val("hello".to_string()), 288 | /// ast::Node::Val("world".to_string()), 289 | /// ]; 290 | /// 291 | /// let (val, nodes) = ast::consume_val(&nodes).unwrap(); 292 | /// assert!(val == "hello"); 293 | /// assert!(nodes.len() == 1); 294 | /// 295 | /// let (val, nodes) = ast::consume_val(&nodes).unwrap(); 296 | /// assert!(val == "world"); 297 | /// assert!(nodes.len() == 0); 298 | ///``` 299 | /// 300 | pub fn consume_val(nodes: &[Node]) -> Result<(&str, &[Node]), Error> { 301 | let (node, nodes) = split_first_nodes(nodes)?; 302 | match node { 303 | Node::Val(v) => Ok((&v, nodes)), 304 | _ => Err(error("expected Val node", None)), 305 | } 306 | } 307 | 308 | /// Given a list of nodes, return the first and the rest on a tuple 309 | /// 310 | ///``` 311 | /// use dynparser::ast; 312 | /// let nodes = vec![ 313 | /// ast::Node::Val("hello".to_string()), 314 | /// ast::Node::Val("world".to_string()), 315 | /// ast::Node::Val(".".to_string()), 316 | /// ]; 317 | /// 318 | /// let (node, nodes) = ast::split_first_nodes(&nodes).unwrap(); 319 | /// assert!(ast::get_node_val(node).unwrap() == "hello"); 320 | /// assert!(nodes.len() == 2); 321 | /// 322 | /// let (node, nodes) = ast::split_first_nodes(&nodes).unwrap(); 323 | /// assert!(ast::get_node_val(node).unwrap() == "world"); 324 | /// assert!(nodes.len() == 1); 325 | 326 | /// let (node, nodes) = ast::split_first_nodes(&nodes).unwrap(); 327 | /// assert!(ast::get_node_val(node).unwrap() == "."); 328 | /// assert!(nodes.len() == 0); 329 | ///``` 330 | /// 331 | pub fn split_first_nodes(nodes: &[Node]) -> Result<(&Node, &[Node]), Error> { 332 | nodes 333 | .split_first() 334 | .ok_or_else(|| error("trying get first element from nodes on empty slice", None)) 335 | } 336 | 337 | /// Consume a node if it's a Val kind and the vaule is 338 | /// equal to the provider one 339 | /// 340 | ///``` 341 | /// use dynparser::ast; 342 | /// let nodes = vec![ 343 | /// ast::Node::Val("hello".to_string()), 344 | /// ast::Node::Val("world".to_string()), 345 | /// ast::Node::Val(".".to_string()), 346 | /// ]; 347 | /// 348 | /// let nodes = ast::consume_this_value("hello", &nodes).unwrap(); 349 | /// let nodes = ast::consume_this_value("world", &nodes).unwrap(); 350 | ///``` 351 | /// 352 | pub fn consume_this_value<'a>(v: &str, nodes: &'a [Node]) -> Result<&'a [Node], Error> { 353 | let (node, nodes) = split_first_nodes(nodes)?; 354 | 355 | let nv = get_node_val(node)?; 356 | if nv == v { 357 | Ok(nodes) 358 | } else { 359 | Err(error( 360 | "trying get first element from nodes on empty slice", 361 | None, 362 | )) 363 | } 364 | } 365 | 366 | /// Consume a node if it's a Rule kind with a specific value 367 | /// and return the rest of nodes and the sub_nodes for the consumed node 368 | /// 369 | ///``` 370 | /// use dynparser::ast; 371 | /// let nodes = vec![ 372 | /// ast::Node::Rule(("hello".to_string(), vec![ast::Node::Val("world".to_string())])), 373 | /// ]; 374 | /// 375 | /// let (nodes, sub_nodes) = ast::consume_node_get_subnodes_for_rule_name_is("hello", &nodes).unwrap(); 376 | /// assert!(nodes.len() == 0); 377 | /// let nodes = ast::consume_this_value("world", &sub_nodes).unwrap(); 378 | ///``` 379 | /// 380 | pub fn consume_node_get_subnodes_for_rule_name_is<'a>( 381 | name: &str, 382 | nodes: &'a [Node], 383 | ) -> Result<(&'a [Node], &'a [Node]), Error> { 384 | let (node, nodes) = split_first_nodes(nodes)?; 385 | match node { 386 | Node::Rule((n, sub_nodes)) => { 387 | if n == name { 388 | Ok((nodes, sub_nodes)) 389 | } else { 390 | Err(error( 391 | &format!("expected {} node, received {}", name, n), 392 | None, 393 | )) 394 | } 395 | } 396 | unknown => Err(error( 397 | &format!("expected {} Node::Rule, received {:?}", name, unknown), 398 | None, 399 | )), 400 | } 401 | } 402 | 403 | /// Consume a node if it's a Rule kind with a specific value 404 | /// and return the rest of nodes and the sub_nodes for the consumed node 405 | /// 406 | ///``` 407 | /// use dynparser::ast; 408 | /// let nodes = vec![]; 409 | /// 410 | /// assert!(ast::check_empty_nodes(&nodes).is_ok()); 411 | ///``` 412 | /// 413 | pub fn check_empty_nodes(nodes: &[Node]) -> Result<(), Error> { 414 | if nodes.is_empty() { 415 | Ok(()) 416 | } else { 417 | Err(error("not consumed full nodes", None)) 418 | } 419 | } 420 | 421 | /// Return a reference to first node 422 | /// 423 | ///``` 424 | /// use dynparser::ast; 425 | /// let nodes = vec![ 426 | /// ast::Node::Rule(("hello".to_string(), vec![])), 427 | /// ast::Node::Val("world".to_string())]; 428 | /// 429 | /// let first = ast::peek_first_node(&nodes).unwrap(); 430 | /// assert!(first == &ast::Node::Rule(("hello".to_string(), vec![]))); 431 | ///``` 432 | /// 433 | pub fn peek_first_node(nodes: &[Node]) -> Result<&Node, Error> { 434 | if nodes.is_empty() { 435 | Err(error("exptected node on peek_first_node", None)) 436 | } else { 437 | Ok(&nodes[0]) 438 | } 439 | } 440 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DynParser 2 | 3 | - [repository](https://github.com/jleahred/dynparser) 4 | - [doc](https://docs.rs/dynparser/) 5 | - [rust-crate](https://crates.io/crates/dynparser) 6 | 7 | A small and simple Dynamic Parser. It's not a compile time parser. 8 | 9 | You can create and modify the grammar on runtime. 10 | 11 | A parser is something that takes an `input`, process it with some `rules` 12 | and generate an `AST` 13 | 14 | There are also some tools to manage the `AST` (pruning, compacting, flattening...) 15 | 16 | ![simple_parser](./doc_images/simple_parser.png "Simple parser") 17 | 18 | In order to create the grammar, you can build a set of rules, or you can use 19 | macros to use a better syntax. But, the easier way, is to use a `peg` grammar. 20 | 21 | Then we need an additional step. 22 | 23 | ![basic_diagram](./doc_images/basic.png "Basic diagram") 24 | 25 | More info about the `peg` syntax bellow. 26 | 27 | You can also generate `rust` code from rules generated from `peg`. 28 | 29 | This allow you to avoid the `peg` step and more... 30 | 31 | In fact, in order to use a `peg` grammar, you have to parse it. 32 | How to parse a `peg` grammar? Well, this is a parser, therefore... 33 | 34 | More details about it bellow on section (parsing the parser) 35 | 36 | ## Usage 37 | 38 | Add to `cargo.toml` 39 | 40 | ```toml 41 | [dependencies] 42 | dynparser = "0.4.0" 43 | ``` 44 | 45 | Watch examples below 46 | 47 | ## Modifications 48 | 49 | 0.1.0 First version 50 | 51 | 0.2.0 Fixed some errors 52 | Rules code for peg parsing generated automatically from peg 53 | 54 | 0.3.0 pass_through method on AST 55 | 56 | 0.4.0 Literals with escape (optional) 57 | Error constructor on peg grammar 58 | Flattening the AST 59 | 60 | 0.4.2 Fixed error managing error("xxx") 61 | Working on modules 62 | 63 | 0.4.3 Compiled with 2018 edition 64 | 65 | ## TODO 66 | 67 | - move to macros by example 2.0 and improve some 68 | - apply tail recursion parsing rule 69 | - macro for eof 70 | 71 | ## Basic example 72 | 73 | Lets create the next grammar: 74 | 75 | ```ignore 76 | main = letter letter_or_num+ 77 | 78 | letter = [a-zA-Z] 79 | 80 | letter_or_num = letter 81 | / number 82 | 83 | number = [0-9] 84 | ``` 85 | 86 | This grammar will accept a letter, followed from one or more letters or 87 | numbers 88 | 89 | ### Just from peg 90 | 91 | ![basic_diagram](./doc_images/basic.png "Basic diagram") 92 | 93 | Straightforward... 94 | 95 | ```rust 96 | extern crate dynparser; 97 | use dynparser::{parse, rules_from_peg}; 98 | 99 | fn main() { 100 | let rules = rules_from_peg( 101 | r#" 102 | 103 | main = letter letter_or_num+ 104 | 105 | letter = [a-zA-Z] 106 | 107 | letter_or_num = letter 108 | / number 109 | 110 | number = [0-9] 111 | 112 | "#, 113 | ).unwrap(); 114 | 115 | assert!(parse("a2AA456bzJ88", &rules).is_ok()); 116 | } 117 | ``` 118 | 119 | If you want to print more information... 120 | 121 | ```rust 122 | extern crate dynparser; 123 | use dynparser::{parse, rules_from_peg}; 124 | 125 | fn main() { 126 | let rules = rules_from_peg( 127 | r#" 128 | 129 | main = letter letter_or_num+ 130 | 131 | letter = [a-zA-Z] 132 | 133 | letter_or_num = letter 134 | / number 135 | 136 | number = [0-9] 137 | 138 | "#, 139 | ).map_err(|e| { 140 | println!("{}", e); 141 | panic!("FAIL"); 142 | }) 143 | .unwrap(); 144 | 145 | println!("{:#?}", rules); 146 | 147 | let result = parse("a2Z", &rules); 148 | match result { 149 | Ok(ast) => println!("{:#?}", ast), 150 | Err(e) => println!("Error: {:?}", e), 151 | }; 152 | } 153 | ``` 154 | 155 | The AST produced will be: 156 | 157 | ```peg 158 | Rule( 159 | ( 160 | "main", 161 | [ 162 | Rule( 163 | ( 164 | "letter", 165 | [ 166 | Val( 167 | "a" 168 | ) 169 | ] 170 | ) 171 | ), 172 | Rule( 173 | ( 174 | "letter_or_num", 175 | [ 176 | Rule( 177 | ( 178 | "number", 179 | [ 180 | Val( 181 | "2" 182 | ) 183 | ] 184 | ) 185 | ) 186 | ] 187 | ) 188 | ), 189 | Rule( 190 | ( 191 | "letter_or_num", 192 | [ 193 | Rule( 194 | ( 195 | "letter", 196 | [ 197 | Val( 198 | "Z" 199 | ) 200 | ] 201 | ) 202 | ) 203 | ] 204 | ) 205 | ) 206 | ] 207 | ) 208 | ) 209 | ``` 210 | 211 | The AST type is: 212 | 213 | ```rust 214 | pub enum Node { 215 | Val(String), 216 | Rule((String, Vec)), 217 | EOF, 218 | } 219 | ``` 220 | 221 | You can also work with flattened AST.In several cases will be easier 222 | to visit a flattened AST. 223 | 224 | The Flattened AST is: 225 | 226 | ```rust 227 | pub enum Node { 228 | Val(String), 229 | BeginRule(String), 230 | EndRule(String), 231 | EOF, 232 | } 233 | } 234 | ``` 235 | 236 | Just it (remember, more information about the peg grammar bellow) 237 | 238 | ## Example 2 239 | 240 | You will configure a set of rules to parse. 241 | 242 | The rule is composed of a name followed by an arrow and an expression to be parsed. 243 | 244 | A basic example 245 | 246 | Lets create the next grammar: 247 | 248 | ```ignore 249 | main = 'a' ( 'bc' 'c' 250 | / 'bcdd' 251 | / b_and_c d_or_z 252 | ) 253 | 254 | b_and_c = 'b' 'c' 255 | d_or_z = 'd' / 'z' 256 | ``` 257 | 258 | ### Just from peg 2 259 | 260 | ```rust 261 | extern crate dynparser; 262 | use dynparser::{parse, rules_from_peg}; 263 | 264 | fn main() { 265 | let rules = rules_from_peg( 266 | r#" 267 | 268 | main = 'a' ( 'bc' 'c' 269 | / 'bcdd' 270 | / b_and_c d_or_z 271 | ) 272 | 273 | b_and_c = 'b' 'c' 274 | d_or_z = 'd' / 'z' 275 | 276 | "#, 277 | ).unwrap(); 278 | 279 | assert!(parse("abcz", &rules).is_ok()); 280 | assert!(parse("abcdd", &rules).is_ok()); 281 | assert!(parse("abcc", &rules).is_ok()); 282 | assert!(parse("bczd", &rules).is_err()); 283 | } 284 | ``` 285 | 286 | The exit will be the next AST 287 | 288 | ```ignore 289 | Rule( 290 | ( 291 | "main", 292 | [ 293 | Val( 294 | "a" 295 | ), 296 | Rule( 297 | ( 298 | "b_and_c", 299 | [ 300 | Val( 301 | "b" 302 | ), 303 | Val( 304 | "c" 305 | ) 306 | ] 307 | ) 308 | ), 309 | Rule( 310 | ( 311 | "d_or_z", 312 | [ 313 | Val( 314 | "d" 315 | ) 316 | ] 317 | ) 318 | ) 319 | ] 320 | ) 321 | ) 322 | ``` 323 | 324 | This is a dynamic parser, you can add rules at execution time. 325 | 326 | pending: example 327 | 328 | ### Generating the rules by hand with macros 329 | 330 | You can create this grammar and parse the string "abcd" with macros like: 331 | 332 | ```rust 333 | #[macro_use] 334 | extern crate dynparser; 335 | use dynparser::parse; 336 | 337 | fn main() { 338 | let rules = rules!{ 339 | "main" => and!{ 340 | lit!("a"), 341 | or!( 342 | and!(lit!("bc"), lit!("c")), 343 | lit!("bcdd"), 344 | and!( 345 | ref_rule!("b_and_c"), 346 | ref_rule!("d_or_z") 347 | ) 348 | ) 349 | }, 350 | "b_and_c" => and!(lit!("b"), lit!("c")), 351 | "d_or_z" => or!(lit!("d"), lit!("z")) 352 | }; 353 | 354 | let result = parse("abcd", &rules); 355 | match result { 356 | Ok(ast) => println!("{:#?}", ast), 357 | Err(e) => println!("Error: {:?}", e), 358 | }; 359 | } 360 | ``` 361 | 362 | Adding a rule on execution time: 363 | 364 | ```rust 365 | #[macro_use] extern crate dynparser; 366 | use dynparser::parse; 367 | fn main() { 368 | let rules = rules!{ 369 | "main" => and!{ 370 | rep!(lit!("a"), 1, 5), 371 | ref_rule!("rule2") 372 | } 373 | }; 374 | 375 | let rules = rules.add("rule2", lit!("bcd")); 376 | 377 | assert!(parse("aabcd", &rules).is_ok()) 378 | } 379 | ``` 380 | 381 | Of course, you could need to add (or merge) several rules at once 382 | 383 | And of course, you can add several rules at once 384 | 385 | ```rust 386 | #[macro_use] extern crate dynparser; 387 | use dynparser::parse; 388 | fn main() { 389 | let r = rules!{ 390 | "main" => and!{ 391 | rep!(lit!("a"), 1, 5), 392 | ref_rule!("rule2") 393 | } 394 | }; 395 | let r = r.merge(rules!{"rule2" => lit!("bcd")}); 396 | assert!(parse("aabcd", &r).is_ok()) 397 | } 398 | ``` 399 | 400 | `merge` takes the ownership of both set of rules and returns a "new" (in fact modified) 401 | set of rules. This helps to reduce mutability 402 | 403 | `main` rule is the entry point. 404 | 405 | More information in [doc](https://docs.rs/dynparser/) 406 | 407 | ### Calculator example 408 | 409 | A parser is not a parser without basic math expression parser example. 410 | 411 | Here it is... 412 | 413 | ```rust 414 | extern crate dynparser; 415 | use dynparser::{parse, rules_from_peg}; 416 | 417 | fn main() { 418 | let rules = rules_from_peg( 419 | r#" 420 | 421 | main = _ expr _ 422 | 423 | expr = add_t (_ add_op _ add_t)* 424 | / portion_expr 425 | 426 | add_t = fact_t (_ fact_op _ fact_t)* 427 | 428 | fact_t = portion_expr 429 | 430 | portion_expr = '(' expr ')' 431 | / item 432 | 433 | item = num 434 | 435 | num = [0-9]+ ('.' [0-9]+)? 436 | add_op = '+' / '-' 437 | fact_op = '*' / '/' 438 | 439 | _ = ' '* 440 | 441 | "#, 442 | ).map_err(|e| { 443 | println!("{}", e); 444 | panic!("FAIL"); 445 | }) 446 | .unwrap(); 447 | 448 | let result = parse(" 1 + 2* 3 +(5/5 - (8-7))", &rules); 449 | match result { 450 | Ok(ast) => println!( 451 | "{:#?}", 452 | ast.compact() 453 | .prune(&vec!["_"]) 454 | .pass_through_except(&vec!["main", "add_t", "fact_t"]) 455 | ), 456 | Err(e) => println!("Error: {:?}", e), 457 | }; 458 | } 459 | ``` 460 | 461 | ## PEG 462 | 463 | ### Rule elements enumeration 464 | 465 | Examples below 466 | 467 | | token | Description | 468 | | :----------- | :----------------------------------------------------- | 469 | | `=` | On left, symbol, on right expresion defining symbol | 470 | | `symbol` | It's an string without quotes | 471 | | `.` | Any char | 472 | | `'...'` | Literal delimited by single quotes | 473 | | `"..."` | Literal delimited by quotes. It accepts escape chars | 474 | | `space` | Separate tokens and Rule concatenation (and operation) | 475 | | `/` | Or operation | 476 | | `(...)` | A expression composed of sub expressions | 477 | | `?` | One optional | 478 | | `*` | Repeat 0 or more | 479 | | `+` | Repeat 1 or more | 480 | | `!` | negate expression | 481 | | `[...]` | Match chars. It's a list or ranges (or both) | 482 | | `error(...)` | Let us to define specific errors | 483 | | `->` | pending... | 484 | | `:` | pending... | 485 | 486 | Let's see by example 487 | 488 | #### Rules by example 489 | 490 | The best way to know the peg syntax, is to look the peg grammar. And yes it is on peg syntax :-) 491 | 492 | A simple literal string. 493 | 494 | ```peg 495 | main = 'Hello world' 496 | ``` 497 | 498 | There are two literal types. 499 | 500 | No escaped literals, are delimited by `'` 501 | 502 | And escaped literals, delimited by `"`. 503 | `"\n"` will be transformed in new-line char i.e. 504 | 505 | It's possible to represent a char by an hex number. 506 | i.e. `"0x13"` 507 | 508 | ```peg 509 | main = "Hello\nworld" 510 | 511 | main = "Hello\0x13world" 512 | 513 | main = 'Hello' "\n" 'world' 514 | 515 | main = 'Hello' "\0x13" 'world' 516 | ``` 517 | 518 | With this two types of literals, it's easy to have `"` and `'` 519 | 520 | ```peg 521 | main = "'" 522 | 523 | main = '"' 524 | ``` 525 | 526 | It's recomended to use non escaped literals as much as possible 527 | and use the escaped literals when necessary. 528 | 529 | Concatenation (and) 530 | 531 | ```peg 532 | main = 'Hello ' 'world' 533 | ``` 534 | 535 | Referencing symbols (rule) 536 | 537 | Symbol 538 | 539 | ```peg 540 | main = hi 541 | hi = 'Hello world' 542 | ``` 543 | 544 | Or `/` 545 | 546 | ```peg 547 | main = 'hello' / 'hi' 548 | ``` 549 | 550 | Or multiline 551 | 552 | ```peg 553 | main 554 | = 'hello' 555 | / 'hi' 556 | / 'hola' 557 | ``` 558 | 559 | Or multiline 2 560 | 561 | ```peg 562 | main = 'hello' 563 | / 'hi' 564 | / 'hola' 565 | ``` 566 | 567 | Or disorganized 568 | 569 | ```peg 570 | main = 'hello' 571 | / 'hi' / 'hola' 572 | ``` 573 | 574 | An important note about the `or` 575 | 576 | main = 'hello' 577 | / 'hello world' 578 | / 'hola' 579 | 580 | Given the text `hello world`, the first option will match processing 581 | the first word of the input, and the second one will never be executed. 582 | It could be fixed, but... doesn't look a great idea. 583 | 584 | Fixing the grammar to avoid this problems, it's very easy. Trying to fix 585 | the parser to let this kind of grammars, is expensive. 586 | 587 | Parenthesis 588 | 589 | ```peg 590 | main = ('hello' / 'hi') ' world' 591 | ``` 592 | 593 | Just multiline 594 | 595 | Multiline1 596 | 597 | ```peg 598 | main 599 | = ('hello' / 'hi') ' world' 600 | ``` 601 | 602 | Multiline2 603 | 604 | ```peg 605 | main 606 | = ('hello' / 'hi') 607 | ' world' 608 | ``` 609 | 610 | Multiline3 611 | 612 | ```peg 613 | main = ('hello' / 'hi') 614 | ' world' 615 | ``` 616 | 617 | It is recommended to use or operator `/` on each new line and `=` on first line, like 618 | 619 | Multiline organized 620 | 621 | ```peg 622 | main = ('hello' / 'hi') ' world' 623 | / 'bye' 624 | ``` 625 | 626 | One optional 627 | 628 | ```peg 629 | main = ('hello' / 'hi') ' world'? 630 | ``` 631 | 632 | Repetitions 633 | 634 | ```peg 635 | main = one_or_more_a / zero_or_many_b 636 | one_or_more = 'a'+ 637 | zero_or_many = 'b'* 638 | ``` 639 | 640 | Negation will not move current position 641 | 642 | Next example will consume all chars till get an 'a' 643 | 644 | Negation 645 | 646 | ```peg 647 | main = (!'a' .)* 'a' 648 | ``` 649 | 650 | Consume till 651 | 652 | ```peg 653 | // This is a line comment 654 | /* This is a 655 | multiline comment */ 656 | comment = '//' (!'\n' .)* // line comment can be at the end of line 657 | / '/*' (!'*/' .)* '*/' /* a multiline comment can start 658 | at any place 659 | */ 660 | ``` 661 | 662 | Match a set of chars. 663 | Chars can be defined by range. 664 | 665 | ```peg 666 | number = digit+ ('.' digit+)? 667 | digit = [0-9] 668 | a_or_b = [ab] 669 | id = [_a-zA-Z][_a-zA-Z0-9]* 670 | 671 | a_or_b_or_digit = [ab0-9] 672 | ``` 673 | 674 | Simple recursion 675 | 676 | one or more 'a' recursive 677 | 678 | ```peg 679 | as = 'a' as 680 | / 'a' 681 | 682 | // simplified with `+` 683 | ak = 'a'+ 684 | ``` 685 | 686 | Recursion to match parenthesis 687 | 688 | Recursion match par 689 | 690 | ```peg 691 | match_par = '(' match_par ')' 692 | / '(' ')' 693 | ``` 694 | 695 | That's ok and works fine, but we can inprove error messages... 696 | 697 | In order to improve error messages, would be interesting to modify the grammar. 698 | 699 | See next section. 700 | 701 | In some cases, we can have an error for no termination consuming full input. 702 | 703 | The reason is on 704 | 705 | ```peg 706 | ... 707 | and_expr = compl_expr ( ' ' _ and_expr)* 708 | ... 709 | ``` 710 | 711 | Showing an error informing that we didn't consume full input, is not the best. 712 | 713 | Here, we said, "hey, try to look for a sequence, or not `*`" 714 | 715 | And is not, then the parser say, I matched the rule, I have to continue verifying other 716 | previous branches. But there are no previous partial applied brunch. 717 | Then the parser ends not consuming all the input. 718 | 719 | To improve error messages, would be interesting to have something like: 720 | 721 | Errors included on peg grammar also will help in this case (see next section) 722 | 723 | Full grammar in peg format bellow (a grammar for the grammar)... 724 | 725 | ## Errors 726 | 727 | Errors are very important. 728 | 729 | Take a look to this grammar 730 | 731 | ```peg 732 | main = '(' main ')' 733 | / 'hello' 734 | ``` 735 | 736 | It will force to match parenthesis around the word 'hello' 737 | 738 | That's great, but what if we write `((hello)` 739 | 740 | The system will point the error place, but... witch is going to be the message? 741 | 742 | We would like to have a message like `unbalanced parenthesis` 743 | 744 | We can... 745 | 746 | ```peg 747 | main = '(' main ( ')' / error("unbalanced parenthesis") ) 748 | / 'hello' 749 | ``` 750 | 751 | With this constructor, we can improve our error messages :-) 752 | 753 | And we also can remove errors kind of `not consumed full input` 754 | 755 | Remember.The best way to know the peg syntax, is to look the peg grammar. And yes it is on peg syntax :-) 756 | 757 | Full exmample... 758 | 759 | ```Rust 760 | extern crate dynparser; 761 | use dynparser::{parse, rules_from_peg}; 762 | fn main() { 763 | let rules = rules_from_peg( 764 | r#" 765 | 766 | main = '(' main ( ')' / error("unbalanced parenthesis") ) 767 | / 'hello' 768 | 769 | "#, 770 | ).unwrap(); 771 | 772 | match parse("((hello)", &rules) { 773 | Ok(_) => panic!("It should fail"), 774 | Err(e) => assert!(e.descr == "unbalanced parenthesis"), 775 | } 776 | } 777 | ``` 778 | 779 | ## Text 780 | 781 | Hey, I'm a text parser, I need a text to parse ;-P 782 | 783 | If you want to parse text indentation sensitive, I recommend you the lib 784 | [indentation_flattener](https://github.com/jleahred/indentation_flattener) 785 | 786 | ## A grammar for the grammar 787 | 788 | A grammar to define the grammar to be parsed by de parser. ;-P 789 | 790 | I will define the grammar using the this parser grammar definition rules. 791 | 792 | A grammar is a set of rules. 793 | 794 | A rule, is a symbol followed by `=` and an expression 795 | 796 | ```peg 797 | grammar = rule+ 798 | rule = symbol '=' expr 799 | ``` 800 | 801 | Here we relax the verification to keep the grammar as simple as possible. 802 | It's missing also the non significant spaces. 803 | 804 | About the expression. 805 | 806 | As you know, it's important to accept valid inputs, but also it's important to 807 | build an AST with proper priority. 808 | 809 | Next grammar: 810 | 811 | ```peg 812 | main = 'A' 'B' / 'B' 'C' 813 | ``` 814 | 815 | It's equivalent to: 816 | 817 | ```peg 818 | main = ('A' 'B') / ('B' 'C') 819 | ``` 820 | 821 | But not to: 822 | 823 | ```peg 824 | main = (('A' 'B') / 'B') 'C' 825 | ``` 826 | 827 | To represent this priority, the expression rule has to be defined in a descendant priority way: 828 | 829 | ```peg 830 | expr = or_expr 831 | 832 | or_expr = and_expr ('/' or_expr)* 833 | 834 | and_expr = simpl_expr (' ' and_expr)* 835 | 836 | simpl_expr = '!' atom_or_par 837 | / simpl_par ('*' / '+') 838 | 839 | atom_or_par = (atom / parenth_expr) 840 | 841 | 842 | parenth_expr = '(' expr ')' 843 | ``` 844 | 845 | Descendant definition 846 | 847 | | expr | Description | 848 | | :---------- | :--------------------------------------------------------------------------------------- | 849 | | atom_or_par | It's an atom or a parenthesis expression | 850 | | rep_or_neg | It's not a composition of `and` or `or` expressions. It can have negation or repetitions | 851 | | parenth | It's an expressions with parenthesis | 852 | | and | Sequence of expressions separated by space | 853 | | or | Sequence of expression separated by '/' | 854 | 855 | Now, it's the `atom` turn: 856 | 857 | ```peg 858 | atom = literal 859 | / match 860 | / dot 861 | / symbol 862 | 863 | literal = "\"" (!"\"" .)* "\"" 864 | match = '[' ((. '-' .) / (.))+ ']' 865 | dot = '.' 866 | symbol = [a-zA-Z0-9_]+ 867 | ``` 868 | 869 | Hey, what about comments? 870 | 871 | What about non significate spaces and carry return? 872 | 873 | It will be defined on '\_' symbol 874 | 875 | This is the general idea. The peg used by the parser will evolve to add error control, vars, scape on strings, and other ideas. 876 | 877 | As the parser will generate the code from peg to parse itself... It's easy to keep updated the peg grammar used to parse from peg. 878 | 879 | ```peg 880 | main = grammar 881 | 882 | grammar = rule+ 883 | 884 | rule = _ symbol _ '=' _ expr _eol _ 885 | 886 | expr = or 887 | 888 | or = and ( _ '/' _ or )* 889 | 890 | and = rep_or_neg ( _1 _ !(symbol _ '=') and )* 891 | 892 | rep_or_neg = atom_or_par ('*' / '+' / '?')? 893 | / '!' atom_or_par 894 | 895 | atom_or_par = (atom / parenth) 896 | 897 | parenth = '(' _ expr _ ')' 898 | 899 | atom = literal 900 | / match 901 | / dot 902 | / symbol 903 | 904 | literal = lit_noesc / lit_esc 905 | 906 | lit_noesc = _' ( !_' . )* _' 907 | _' = "'" 908 | 909 | lit_esc = _" 910 | ( esc_char 911 | / hex_char 912 | / !_" . 913 | )* 914 | _" 915 | _" = '"' 916 | 917 | esc_char = '\r' 918 | / '\n' 919 | / '\\' 920 | / '\"' 921 | 922 | hex_char = '\0x' [0-9A-F] [0-9A-F] 923 | 924 | symbol = [_a-zA-Z0-9] [_'"a-zA-Z0-9]* 925 | 926 | eol = ("\r\n" / "\n" / "\r") 927 | _eol = ' '* eol 928 | 929 | match = '[' 930 | ( 931 | (mchars mbetween*) 932 | / mbetween+ 933 | ) 934 | ']' 935 | 936 | mchars = (!']' !(. '-') .)+ 937 | mbetween = (. '-' .) 938 | 939 | dot = '.' 940 | 941 | _ = ( ' ' 942 | / eol 943 | )* 944 | 945 | _1 = (' ' / eol) 946 | ``` 947 | 948 | ## Parsing the parser 949 | 950 | Or... how to parse yourself 951 | 952 | Remember, we started with the concept of a simple parser... 953 | 954 | Starting with a set of rules and the input to process, we will generate the `AST` 955 | 956 | ![simple_parser](./doc_images/simple_parser.png "Simple parser") 957 | 958 | On this, we added an additional step to generate the rules from a `peg grammar` 959 | avoiding written by hand on code. 960 | 961 | Then, we have a parser that accepts `peg` grammars. 962 | 963 | Now instead of giving the set of rules, we can provide a `peg` definition 964 | and the input to generate the `AST` 965 | 966 | ![basic_diagram](./doc_images/basic.png "Basic diagram") 967 | 968 | But the `input peg` grammar has to be processed (parsed). We have to writte `rules_from_peg` code to parse the `input peg` 969 | 970 | Who's gonna parse the grammar peg? A parser? 971 | 972 | Let me think... Ummmm!!! 973 | 974 | I'm a parser!!!!! 975 | 976 | We have a feature that allows us to generate the Rust code for an `AST` tree generated from a `peg` grammar. Oh?! 977 | 978 | So the code to parse the peg grammar will be generated automatically with this parser 979 | 980 | ![automatic_diagram](./doc_images/automatic_diagram.png "Automatic") 981 | 982 | Then we will generate automatically `rules_from_peg` recursively. 983 | 984 | Once this is done, we can now use the parser in a classic way 985 | 986 | Remember, a normal parsing, we have two inputs. 987 | 988 | 1. The `peg grammar` 989 | 1. The input text 990 | 991 | Now, for start with, both inputs will be a `peg grammar` defining it self (a `peg grammar` defining a `peg grammar`) 992 | 993 | 1. input: `peg grammar` defining itself 994 | 1. running `rules_from_peg` to generate a set of rules for this `peg grammar` 995 | 1. With the two previous points, we will parse creating the `AST` for the `peg grammar` 996 | 1. Now we will call `ast::generate_rust` to generate the code for `rules_from_peg` 997 | 1. We will insert this code on the parser 998 | 1. And we are ready to parse an `input` with a `peg grammar` to generate the `AST` 999 | 1000 | The point `rules_from_peg` it's special. 1001 | 1002 | ```rust 1003 | pub fn rules_from_peg(peg: &str) -> Result { 1004 | let ast = parse(peg, &rules::parse_peg())?; 1005 | let nodes = ast.compact().prune(&["_", "_1", "_eol"]).flatten(); 1006 | 1007 | rules_from_flat_ast(&nodes) 1008 | } 1009 | ``` 1010 | 1011 | As you can see, we parse the peg grammar (in this case a peg defining the peg grammar). 1012 | 1013 | After it, we transform the AST compacting, removing nodes, and flattening. 1014 | 1015 | An AST flattened, is just something to be parsed, but instead chars, we work with tokens, and it's a LL(1) parser. 1016 | 1017 | Errors will be found and registered in the previous parsing. 1018 | 1019 | Then, we have to write by hand the LL(1) parser, but it's easy (not necessary to control errors, not working with chars, just LL(1)) 1020 | 1021 | Why to do that? 1022 | 1023 | First, it's possible and a great test. 1024 | 1025 | Second. If we want to modify our `peg grammar`, it's boring and error 1026 | prone to write the code manually. 1027 | 1028 | Using a `peg` file to generate automatically `rules_from_peg`, keeps 1029 | document and code as one (always synchronized) 1030 | 1031 | ## diagrams generation 1032 | 1033 | ```ignore 1034 | echo "[ input peg ] -- rules_from_peg --> [ rules ][ input text ], [ rules ] --> { end: back,0; } [ AST ]" | graph-easy --dot | dot -Tpng -o doc_images/basic.png 1035 | ``` 1036 | 1037 | ```ignore 1038 | echo "[ rules ][ input text ], [ rules ] --> { end: back,0; } [ AST ]" | graph-easy --dot | dot -Tpng -o doc_images/simple_parser.png 1039 | ``` 1040 | 1041 | ```ignore 1042 | echo " 1043 | [input peg \\n 1044 | for peg grammar ] -- [rules_from_peg] { shape: none; } --> 1045 | [rules_peg_gramm] { label: rules\\n 1046 | for peg grammar } 1047 | [input peg \\n 1048 | for peg grammar ], [ rules_peg_gramm ] -- parse --> { end: back,0; } [ AST ] 1049 | 1050 | [AST] ~~ generate rust ~~> [rules_from_peg] { shape: none; } 1051 | 1052 | " | graph-easy --dot | dot -Tpng -o doc_images/automatic_diagram.png 1053 | ``` 1054 | -------------------------------------------------------------------------------- /src/peg/mod.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | //! Module with functions to generate rules from PEG grammar 3 | //! 4 | 5 | pub mod gcode; 6 | pub mod peg2code; 7 | mod rules; 8 | 9 | use crate::ast::{self, flat}; 10 | use crate::parse; 11 | use crate::parser::{ 12 | self, 13 | expression::{self, Expression}, 14 | }; 15 | use idata::{self, cont::IVec}; 16 | use std::{self, result}; 17 | 18 | #[cfg(test)] 19 | mod test; 20 | 21 | struct Context { 22 | // stack with the module paths we are inside 23 | // i.e. mod_a, mod_a.mod_b, mod_a.mod_b, mod_c 24 | inside_mods: Vec, 25 | } 26 | 27 | impl Context { 28 | fn new() -> Self { 29 | Context { 30 | inside_mods: vec![], 31 | } 32 | } 33 | fn add_module(mut self, mod_name: &str) -> Self { 34 | match self.inside_mods.last().cloned() { 35 | Some(mod_path) => self.inside_mods.push(format!("{}{}", mod_path, mod_name)), 36 | None => self.inside_mods.push(mod_name.to_string()), 37 | }; 38 | self 39 | } 40 | fn remove_module(mut self, mod_name: &str) -> result::Result { 41 | let last = self.inside_mods.last().cloned(); 42 | match last { 43 | Some(_mod_path) => { 44 | self.inside_mods.pop(); 45 | Ok(self) 46 | } 47 | None => Err(error_peg_s(&format!( 48 | "remove module on empty path statck: <{}>", 49 | mod_name 50 | ))), 51 | } 52 | } 53 | } 54 | 55 | #[derive(Debug)] 56 | /// Most of peg functions will return a result with this type 57 | /// on Error side 58 | pub enum Error { 59 | /// When error has been on `peg` side 60 | /// we will receive a description and 61 | /// optionally, a link to a stacked error 62 | /// Then, we can have a errors stack of ilimited size 63 | Peg((String, Option>)), 64 | /// When error is on parser side 65 | Parser(parser::Error), 66 | /// When error is on ast side 67 | Ast(ast::Error), 68 | } 69 | 70 | fn error_peg_s(s: &str) -> Error { 71 | Error::Peg((s.to_string(), None)) 72 | } 73 | 74 | impl Error { 75 | /// add an error description 76 | pub fn ipush(self, desc: &str) -> Self { 77 | Error::Peg((desc.to_string(), Some(Box::new(self)))) 78 | } 79 | } 80 | 81 | impl From for Error { 82 | fn from(e: parser::Error) -> Self { 83 | Error::Parser(e) 84 | } 85 | } 86 | 87 | impl From for Error { 88 | fn from(e: ast::Error) -> Self { 89 | Error::Ast(e) 90 | } 91 | } 92 | 93 | impl std::fmt::Display for Error { 94 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 95 | match self { 96 | Error::Peg((s, None)) => write!(f, "{}", s), 97 | Error::Peg((s, Some(b))) => write!(f, "{} > {}", s, b), 98 | Error::Parser(p) => write!(f, "Parser({:?})", p), 99 | Error::Ast(a) => write!(f, "AST({:?})", a), 100 | } 101 | } 102 | } 103 | 104 | /// Most of functions on peg module, will return a set of rules 105 | /// or an error 106 | pub type Result = result::Result; 107 | 108 | // ------------------------------------------------------------------------------------- 109 | // A P I 110 | 111 | /// Given a ```peg``` set of rules on an string, it will generate 112 | /// the set of rules to use in the parser 113 | /// 114 | /// Next, is a full example showing the error messages, if so 115 | /// ``` 116 | /// extern crate dynparser; 117 | /// use dynparser::{parse, rules_from_peg}; 118 | /// 119 | /// fn main() { 120 | /// let rules = rules_from_peg( 121 | /// r#" 122 | /// main = 'hello' ' ' 'world' dot 123 | /// dot = "\0x2E" 124 | /// "#, 125 | /// ).map_err(|e| { 126 | /// println!("{}", e); 127 | /// panic!("FAIL"); 128 | /// }) 129 | /// .unwrap(); 130 | /// 131 | /// println!("{:#?}", rules); 132 | /// 133 | /// let result = parse("hello world.", &rules); 134 | /// 135 | /// assert!(result.is_ok()); 136 | /// 137 | /// match result { 138 | /// Ok(ast) => println!("{:#?}", ast), 139 | /// Err(e) => println!("Error: {:?}", e), 140 | /// }; 141 | /// } 142 | /// ``` 143 | /// 144 | /// Next is an example with some ```and``` ```literals``` 145 | /// and comments on peg grammar 146 | /// ``` 147 | ///extern crate dynparser; 148 | ///use dynparser::{parse, rules_from_peg}; 149 | /// 150 | /// let rules = rules_from_peg( 151 | /// r#" 152 | /// // classic hello world 153 | /// main = 'hello' ' ' 'world' 154 | /// 155 | /// /* with a multiline comment 156 | /// */ 157 | /// "#, 158 | /// ).unwrap(); 159 | /// 160 | /// assert!(parse("hello world", &rules).is_ok()); 161 | /// ``` 162 | /// 163 | /// Next is an example with some error info 164 | /// 165 | /// ``` 166 | /// extern crate dynparser; 167 | /// use dynparser::{parse, rules_from_peg}; 168 | /// 169 | /// let rules = rules_from_peg( 170 | /// r#" 171 | /// main = '(' main ( ')' / error("unbalanced parenthesys") ) 172 | /// / 'hello' 173 | /// "#, 174 | /// ).unwrap(); 175 | /// 176 | /// assert!(parse("hello", &rules).is_ok()); 177 | /// println!("{:?}", parse("(hello)", &rules)); 178 | /// assert!(parse("(hello)", &rules).is_ok()); 179 | /// assert!(parse("((hello))", &rules).is_ok()); 180 | /// assert!(parse("(((hello)))", &rules).is_ok()); 181 | /// match parse("(hello", &rules) { 182 | /// Err(e) => {assert!(e.descr == "unbalanced parenthesys");}, 183 | /// _ => () 184 | /// } 185 | /// match parse("((hello)", &rules) { 186 | /// Err(e) => {assert!(e.descr == "unbalanced parenthesys");}, 187 | /// _ => () 188 | /// } 189 | /// ``` 190 | 191 | pub fn rules_from_peg(peg: &str) -> Result { 192 | let ast = parse(peg, &rules::parse_peg())?; 193 | let nodes = ast.compact().prune(&["_", "_1", "_eol"]).flatten(); 194 | 195 | rules_from_flat_ast(&nodes) 196 | } 197 | 198 | // A P I 199 | // ------------------------------------------------------------------------------------- 200 | 201 | fn rules_from_flat_ast(nodes: &[flat::Node]) -> Result { 202 | let (rules, nodes, _context) = consume_main(&nodes, Context::new())?; 203 | if !nodes.is_empty() { 204 | Err(error_peg_s("expected empty nodes after processing main")) 205 | } else { 206 | Ok(rules) 207 | } 208 | } 209 | 210 | macro_rules! push_err { 211 | ($descr:expr, $e:expr) => {{ 212 | let l = move || $e; 213 | l().map_err(move |e: Error| e.ipush($descr)) 214 | }}; 215 | } 216 | 217 | fn consuming_rule<'a, F, R>( 218 | rule_name: &str, 219 | nodes: &'a [flat::Node], 220 | context: Context, 221 | f: F, 222 | ) -> result::Result<(R, &'a [flat::Node], Context), Error> 223 | where 224 | F: FnOnce(&'a [flat::Node], Context) -> result::Result<(R, &'a [flat::Node], Context), Error>, //result::Result<(expression::SetOfRules, &'a [flat::Node]), Error> 225 | // R: std::ops::Try, 226 | { 227 | push_err!(&format!("consuming {}", rule_name), { 228 | let nodes = flat::consume_node_start_rule_name(rule_name, &nodes)?; 229 | let (result, nodes, context) = f(&nodes, context)?; 230 | let nodes = flat::consume_node_end_rule_name(rule_name, &nodes)?; 231 | Ok((result, nodes, context)) 232 | }) 233 | } 234 | 235 | fn consume_main( 236 | nodes: &[flat::Node], 237 | context: Context, 238 | ) -> result::Result<(expression::SetOfRules, &[flat::Node], Context), Error> { 239 | // main = grammar 240 | 241 | consuming_rule("main", nodes, context, |nodes, context| { 242 | consume_grammar(&nodes, context) 243 | }) 244 | } 245 | 246 | fn consume_grammar( 247 | nodes: &[flat::Node], 248 | context: Context, 249 | ) -> result::Result<(expression::SetOfRules, &[flat::Node], Context), Error> { 250 | // grammar = (rule / module)+ 251 | 252 | fn consume_rule_and_add_set_of_rules( 253 | rules: expression::SetOfRules, 254 | nodes: &[flat::Node], 255 | context: Context, 256 | ) -> result::Result<(expression::SetOfRules, &[flat::Node], Context), Error> { 257 | let ((name, expr), nodes, context) = consume_rule(nodes, context)?; 258 | let rules = rules.add(&name, expr); 259 | Ok((rules, nodes, context)) 260 | } 261 | fn consume_module_and_add_set_of_rules( 262 | rules: expression::SetOfRules, 263 | nodes: &[flat::Node], 264 | context: Context, 265 | ) -> result::Result<(expression::SetOfRules, &[flat::Node], Context), Error> { 266 | let (mod_rules, nodes, context) = consume_module(nodes, context)?; 267 | let rules = rules.merge(mod_rules); 268 | Ok((rules, nodes, context)) 269 | } 270 | fn rec_consume_rules_or_modules( 271 | rules: expression::SetOfRules, 272 | nodes: &[flat::Node], 273 | context: Context, 274 | ) -> result::Result<(expression::SetOfRules, &[flat::Node], Context), Error> { 275 | match flat::peek_first_node(nodes)? { 276 | flat::Node::BeginRule(rule_or_module) => { 277 | let (rules, nodes, context) = match rule_or_module.as_ref() { 278 | "rule" => consume_rule_and_add_set_of_rules(rules, nodes, context), 279 | "module" => consume_module_and_add_set_of_rules(rules, nodes, context), 280 | unknown => Err(error_peg_s(&format!( 281 | "expected rule or module, received: {}", 282 | unknown 283 | ))), 284 | }?; 285 | rec_consume_rules_or_modules(rules, nodes, context) 286 | } 287 | _ => Ok((rules, nodes, context)), 288 | } 289 | } 290 | // -------------------------- 291 | 292 | consuming_rule("grammar", nodes, context, |nodes, context| { 293 | rec_consume_rules_or_modules(rules!(), &nodes, context) 294 | }) 295 | } 296 | 297 | fn consume_module( 298 | nodes: &[flat::Node], 299 | context: Context, 300 | ) -> result::Result<(expression::SetOfRules, &[flat::Node], Context), Error> { 301 | // module = _ mod_name _ '{' _ grammar _ '}' _eol _ 302 | 303 | consuming_rule("module", nodes, context, |nodes, context| { 304 | let (mod_name, nodes, context) = consume_mod_name(nodes, context)?; 305 | let nodes = flat::consume_this_value("{", nodes)?; 306 | let (rules, nodes, context) = consume_grammar(nodes, context.add_module(mod_name))?; 307 | let nodes = flat::consume_this_value("}", nodes)?; 308 | let context = context.remove_module(mod_name)?; 309 | Ok((rules, nodes, context)) 310 | }) 311 | } 312 | 313 | fn consume_mod_name( 314 | nodes: &[flat::Node], 315 | context: Context, 316 | ) -> result::Result<(&str, &[flat::Node], Context), Error> { 317 | // mod_name = symbol 318 | 319 | consuming_rule("mod_name", nodes, context, |nodes, context| { 320 | let (symbol, nodes, context) = consume_symbol(nodes, context)?; 321 | Ok((symbol, nodes, context)) 322 | }) 323 | } 324 | 325 | type StringExpression = (String, expression::Expression); 326 | fn consume_rule( 327 | nodes: &[flat::Node], 328 | context: Context, 329 | ) -> result::Result<(StringExpression, &[flat::Node], Context), Error> { 330 | // rule = _ rule_name _ '=' _ expr _eol _ 331 | 332 | consuming_rule("rule", nodes, context, |nodes, context| { 333 | let (rule_name, nodes, context) = consume_rule_name(nodes, context)?; 334 | let nodes = flat::consume_this_value("=", nodes)?; 335 | let (expr, nodes, context) = consume_peg_expr(nodes, context)?; 336 | 337 | Ok(((rule_name, expr), nodes, context)) 338 | }) 339 | } 340 | 341 | fn consume_rule_name( 342 | nodes: &[flat::Node], 343 | context: Context, 344 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 345 | // rule_name = '.'? symbol ('.' symbol)* 346 | 347 | fn rec_consume_dot_symbol( 348 | acc_name: String, 349 | nodes: &[flat::Node], 350 | context: Context, 351 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 352 | match flat::peek_first_node(nodes)? { 353 | flat::Node::Val(ch) => { 354 | if ch == "." { 355 | let (_, nodes) = flat::consume_val(nodes)?; 356 | let (symbol, nodes, context) = consume_symbol(nodes, context)?; 357 | let acc_name = format!("{}.{}", acc_name, symbol); 358 | rec_consume_dot_symbol(acc_name, nodes, context) 359 | } else { 360 | Ok((acc_name, nodes, context)) 361 | } 362 | } 363 | _ => Ok((acc_name, nodes, context)), 364 | } 365 | } 366 | 367 | let get_dot_or_empty = 368 | |nodes, context| -> result::Result<(&str, &[flat::Node], Context), Error> { 369 | match flat::peek_first_node(nodes)? { 370 | flat::Node::Val(ch) => { 371 | if ch == "." { 372 | Ok((".", flat::consume_this_value(".", nodes)?, context)) 373 | } else { 374 | Ok(("", nodes, context)) 375 | } 376 | } 377 | _ => Ok(("", nodes, context)), 378 | } 379 | }; 380 | // ---------------------- 381 | 382 | consuming_rule("rule_name", nodes, context, |nodes, context| { 383 | let (start_dot, nodes, context) = get_dot_or_empty(nodes, context)?; 384 | let (symbol, nodes, context) = consume_symbol(nodes, context)?; 385 | let (dot_symbol, nodes, context) = rec_consume_dot_symbol(String::new(), nodes, context)?; 386 | 387 | let str_result = format!("{}{}{}", start_dot, symbol, dot_symbol); 388 | Ok((str_result, nodes, context)) 389 | }) 390 | } 391 | 392 | fn consume_symbol( 393 | nodes: &[flat::Node], 394 | context: Context, 395 | ) -> result::Result<(&str, &[flat::Node], Context), Error> { 396 | // symbol = [_'a-zA-Z0-9] [_'"a-zA-Z0-9]* 397 | 398 | consuming_rule("symbol", nodes, context, |nodes, context| { 399 | let (val, nodes) = flat::consume_val(nodes)?; 400 | Ok((val, nodes, context)) 401 | }) 402 | } 403 | 404 | fn consume_peg_expr( 405 | nodes: &[flat::Node], 406 | context: Context, 407 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 408 | // expr = or 409 | 410 | consuming_rule("expr", nodes, context, |nodes, context| { 411 | consume_or(nodes, context) 412 | }) 413 | } 414 | 415 | // This is to manage And & Or multiexpressions 416 | // in consume_or and consume_and 417 | enum ExprOrVecExpr { 418 | Expr(Expression), 419 | VExpr(Vec), 420 | None, 421 | } 422 | impl ExprOrVecExpr { 423 | fn ipush(self, expr: Expression) -> Self { 424 | match self { 425 | ExprOrVecExpr::Expr(e) => ExprOrVecExpr::VExpr(vec![e, expr]), 426 | ExprOrVecExpr::VExpr(v) => ExprOrVecExpr::VExpr(v.ipush(expr)), 427 | ExprOrVecExpr::None => ExprOrVecExpr::Expr(expr), 428 | } 429 | } 430 | } 431 | 432 | fn consume_or( 433 | nodes: &[flat::Node], 434 | context: Context, 435 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 436 | // or = and ( _ '/' _ or )? 437 | 438 | fn rec_consume_or( 439 | eov: ExprOrVecExpr, 440 | nodes: &[flat::Node], 441 | context: Context, 442 | ) -> result::Result<(ExprOrVecExpr, &[flat::Node], Context), Error> { 443 | consuming_rule("or", nodes, context, |nodes, context| { 444 | let (expr, nodes, context) = consume_and(nodes, context)?; 445 | let eov = eov.ipush(expr); 446 | let next_node = flat::peek_first_node(nodes)?; 447 | 448 | match next_node { 449 | flat::Node::Val(_) => { 450 | let nodes = flat::consume_this_value("/", nodes)?; 451 | rec_consume_or(eov, nodes, context) 452 | } 453 | _ => Ok((eov, nodes, context)), 454 | } 455 | }) 456 | }; 457 | 458 | let build_or_expr = |vexpr| Expression::Or(expression::MultiExpr(vexpr)); 459 | // -------------------------- 460 | 461 | push_err!("or:", { 462 | let (eov, nodes, context) = rec_consume_or(ExprOrVecExpr::None, nodes, context)?; 463 | 464 | match eov { 465 | ExprOrVecExpr::None => Err(error_peg_s("logic error, empty or parsing???")), 466 | ExprOrVecExpr::Expr(e) => Ok((e, nodes, context)), 467 | ExprOrVecExpr::VExpr(v) => Ok((build_or_expr(v), nodes, context)), 468 | } 469 | }) 470 | } 471 | 472 | fn consume_error( 473 | nodes: &[flat::Node], 474 | context: Context, 475 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 476 | // error = 'error' _ '(' _ literal _ ')' 477 | let (val, nodes, context) = consuming_rule("error", nodes, context, |nodes, context| { 478 | let nodes = flat::consume_this_value("error", nodes)?; 479 | let nodes = flat::consume_this_value("(", nodes)?; 480 | let (text, nodes, context) = consume_literal_string(nodes, context)?; 481 | let nodes = flat::consume_this_value(")", nodes)?; 482 | Ok((text, nodes, context)) 483 | })?; 484 | 485 | Ok((error!(val), nodes, context)) 486 | } 487 | 488 | fn consume_and( 489 | nodes: &[flat::Node], 490 | context: Context, 491 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 492 | // and = error 493 | // / rep_or_neg ( _1 _ !(rule_name _ ('=' / '{')) and )* 494 | 495 | fn rec_consume_and( 496 | eov: ExprOrVecExpr, 497 | nodes: &[flat::Node], 498 | context: Context, 499 | ) -> result::Result<(ExprOrVecExpr, &[flat::Node], Context), Error> { 500 | consuming_rule("and", nodes, context, |nodes, context| { 501 | if "error" == flat::get_nodename(flat::peek_first_node(nodes)?)? { 502 | let (expr, nodes, context) = consume_error(nodes, context)?; 503 | let eov = eov.ipush(expr); 504 | Ok((eov, nodes, context)) 505 | } else { 506 | let (expr, nodes, context) = consume_rep_or_neg(nodes, context)?; 507 | let eov = eov.ipush(expr); 508 | let next_node = flat::peek_first_node(nodes)?; 509 | 510 | match (next_node, flat::get_nodename(next_node)) { 511 | (flat::Node::BeginRule(_), Ok("and")) => rec_consume_and(eov, nodes, context), 512 | _ => Ok((eov, nodes, context)), 513 | } 514 | } 515 | }) 516 | } 517 | 518 | let build_and_expr = |vexpr| Expression::And(expression::MultiExpr(vexpr)); 519 | // -------------------------- 520 | 521 | let (eov, nodes, context) = rec_consume_and(ExprOrVecExpr::None, nodes, context)?; 522 | match eov { 523 | ExprOrVecExpr::None => Err(error_peg_s("logic error, empty or parsing???")), 524 | ExprOrVecExpr::Expr(e) => Ok((e, nodes, context)), 525 | ExprOrVecExpr::VExpr(v) => Ok((build_and_expr(v), nodes, context)), 526 | } 527 | } 528 | 529 | fn consume_rep_or_neg( 530 | nodes: &[flat::Node], 531 | context: Context, 532 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 533 | // rep_or_neg = atom_or_par ("*" / "+" / "?")? 534 | // / "!" atom_or_par 535 | 536 | fn process_repetition_indicator( 537 | expr: Expression, 538 | rsymbol: &str, 539 | ) -> result::Result { 540 | match rsymbol { 541 | "+" => Ok(rep!(expr, 1)), 542 | "*" => Ok(rep!(expr, 0)), 543 | "?" => Ok(rep!(expr, 0, 1)), 544 | unknown => Err(error_peg_s(&format!( 545 | "repetition symbol unknown {}", 546 | unknown 547 | ))), 548 | } 549 | } 550 | 551 | let atom_and_rep = |nodes, context| { 552 | let (expr, nodes, context) = consume_atom_or_par(nodes, context)?; 553 | let next_node = flat::peek_first_node(nodes)?; 554 | 555 | match next_node { 556 | flat::Node::Val(_) => { 557 | let (sep, nodes) = flat::consume_val(nodes)?; 558 | Ok((process_repetition_indicator(expr, sep)?, nodes, context)) 559 | } 560 | _ => Ok((expr, nodes, context)), 561 | } 562 | }; 563 | let neg_and_atom = 564 | |nodes, context| -> result::Result<(Expression, &[flat::Node], Context), Error> { 565 | let nodes = flat::consume_this_value(r#"!"#, nodes)?; 566 | let (expr, nodes, context) = consume_atom_or_par(nodes, context)?; 567 | Ok((not!(expr), nodes, context)) 568 | }; 569 | // -------------------------- 570 | 571 | consuming_rule( 572 | "rep_or_neg", 573 | nodes, 574 | context, 575 | |nodes, context| match flat::peek_first_node(nodes)? { 576 | flat::Node::Val(v) => { 577 | if v == "!" { 578 | neg_and_atom(nodes, context) 579 | } else { 580 | Err(error_peg_s(&format!("expected '!', received {}", v))) 581 | } 582 | } 583 | _ => atom_and_rep(nodes, context), 584 | }, 585 | ) 586 | } 587 | 588 | fn consume_atom_or_par( 589 | nodes: &[flat::Node], 590 | context: Context, 591 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 592 | // atom_or_par = (atom / parenth) 593 | 594 | consuming_rule("atom_or_par", nodes, context, |nodes, context| { 595 | let next_node = flat::peek_first_node(nodes)?; 596 | let node_name = flat::get_nodename(next_node)?; 597 | 598 | let (expr, nodes, context) = push_err!(&format!("n:{}", node_name), { 599 | match &node_name as &str { 600 | "atom" => consume_atom(nodes, context), 601 | "parenth" => consume_parenth(nodes, context), 602 | unknown => Err(error_peg_s(&format!("unknown {}", unknown))), 603 | } 604 | })?; 605 | 606 | Ok((expr, nodes, context)) 607 | }) 608 | } 609 | 610 | fn consume_atom( 611 | nodes: &[flat::Node], 612 | context: Context, 613 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 614 | // atom = literal 615 | // / match 616 | // / dot 617 | // / rule_name 618 | 619 | consuming_rule("atom", nodes, context, |nodes, context| { 620 | let next_node = flat::peek_first_node(nodes)?; 621 | let node_name = flat::get_nodename(next_node)?; 622 | 623 | let (expr, nodes, context) = push_err!(&format!("n:{}", node_name), { 624 | match &node_name as &str { 625 | "literal" => consume_literal_expr(nodes, context), 626 | "rule_name" => consume_rule_ref(nodes, context), 627 | "dot" => consume_dot(nodes, context), 628 | "match" => consume_match(nodes, context), 629 | unknown => Err(error_peg_s(&format!("unknown {}", unknown))), 630 | } 631 | })?; 632 | 633 | Ok((expr, nodes, context)) 634 | }) 635 | } 636 | 637 | fn consume_parenth( 638 | nodes: &[flat::Node], 639 | context: Context, 640 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 641 | // parenth = "(" _ expr _ ")" 642 | 643 | consuming_rule("parenth", nodes, context, |nodes, context| { 644 | let nodes = flat::consume_this_value(r#"("#, nodes)?; 645 | let (expr, nodes, context) = consume_peg_expr(nodes, context)?; 646 | let nodes = flat::consume_this_value(r#")"#, nodes)?; 647 | Ok((expr, nodes, context)) 648 | }) 649 | } 650 | 651 | fn consume_literal_string( 652 | nodes: &[flat::Node], 653 | context: Context, 654 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 655 | // literal = lit_noesc / lit_esc 656 | 657 | consuming_rule("literal", nodes, context, |nodes, context| { 658 | let next_node_name = flat::get_nodename(flat::peek_first_node(nodes)?)?; 659 | match next_node_name { 660 | "lit_noesc" => consume_literal_no_esc(nodes, context), 661 | "lit_esc" => consume_literal_esc(nodes, context), 662 | _ => Err(error_peg_s(&format!("unexpected node {}", next_node_name))), 663 | } 664 | }) 665 | } 666 | 667 | fn consume_literal_expr( 668 | nodes: &[flat::Node], 669 | context: Context, 670 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 671 | let (val, nodes, context) = consume_literal_string(nodes, context)?; 672 | Ok((lit!(val), nodes, context)) 673 | } 674 | 675 | fn consume_literal_esc( 676 | nodes: &[flat::Node], 677 | context: Context, 678 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 679 | // lit_esc = _" 680 | // ( esc_char 681 | // / hex_char 682 | // / !_" . 683 | // )* 684 | 685 | fn consume_element( 686 | nodes: &[flat::Node], 687 | context: Context, 688 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 689 | let crule_name = |rule_name, nodes, context| match rule_name { 690 | "esc_char" => consume_esc_char(nodes, context), 691 | "hex_char" => consume_hex_char(nodes, context), 692 | _ => Err(error_peg_s(&format!("unknown rule_name: {}", rule_name))), 693 | }; 694 | 695 | let next_n = flat::peek_first_node(nodes)?; 696 | 697 | let (val, nodes, context) = match next_n { 698 | flat::Node::BeginRule(r_name) => crule_name(r_name, nodes, context), 699 | flat::Node::Val(_) => { 700 | let (val, nodes) = flat::consume_val(nodes).map(|(v, n)| (v.to_string(), n))?; 701 | Ok((val, nodes, context)) 702 | } 703 | _ => Err(error_peg_s(&format!("looking for element {:#?}", next_n))), 704 | }?; 705 | 706 | Ok((val.to_string(), nodes, context)) 707 | } 708 | 709 | fn rec_consume_lit_esc_ch( 710 | s: String, 711 | nodes: &[flat::Node], 712 | context: Context, 713 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 714 | let next_node_name = flat::get_nodename(flat::peek_first_node(nodes)?); 715 | 716 | match next_node_name { 717 | Ok("_\"") => Ok((s, nodes, context)), 718 | _ => { 719 | let (v, nodes, context) = consume_element(nodes, context)?; 720 | rec_consume_lit_esc_ch(s + &v.to_string(), nodes, context) 721 | } 722 | } 723 | } 724 | 725 | consuming_rule("lit_esc", nodes, context, |nodes, context| { 726 | let (nodes, context) = consume_quote(nodes, context)?; 727 | 728 | let (val, nodes, context) = rec_consume_lit_esc_ch(String::new(), nodes, context)?; 729 | 730 | let vclone = val.clone(); 731 | push_err!(&format!("lesc:({})", vclone), { 732 | let (nodes, context) = consume_quote(nodes, context)?; 733 | Ok((val, nodes, context)) 734 | }) 735 | }) 736 | } 737 | 738 | fn consume_esc_char( 739 | nodes: &[flat::Node], 740 | context: Context, 741 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 742 | // esc_char = '\r' 743 | // / '\n' 744 | // / '\t' 745 | // / '\\' 746 | // / '\"' 747 | 748 | consuming_rule("esc_char", nodes, context, |nodes, context| { 749 | let (val, nodes) = flat::consume_val(nodes)?; 750 | let val = match val { 751 | r#"\r"# => Ok("\r"), 752 | r#"\n"# => Ok("\n"), 753 | r#"\t"# => Ok("\t"), 754 | r#"\\"# => Ok(r#"\"#), 755 | r#"\""# => Ok(r#"""#), 756 | _ => Err(error_peg_s(&format!("unknow esc char: {}", val))), 757 | }?; 758 | Ok((val.to_string(), nodes, context)) 759 | }) 760 | } 761 | 762 | fn consume_hex_char( 763 | nodes: &[flat::Node], 764 | context: Context, 765 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 766 | // hex_char = '\0x' [0-9A-F] [0-9A-F] 767 | 768 | use std::u8; 769 | 770 | consuming_rule("hex_char", nodes, context, |nodes, context| { 771 | let (val, nodes) = flat::consume_val(nodes)?; 772 | let val = &val[3..]; 773 | 774 | let ch = match u8::from_str_radix(val, 16) { 775 | Ok(v) => Ok(v as char), 776 | _ => Err(error_peg_s(&format!("error parsing hex {}", &val[2..]))), 777 | }?; 778 | Ok((ch.to_string(), nodes, context)) 779 | }) 780 | } 781 | 782 | fn consume_literal_no_esc( 783 | nodes: &[flat::Node], 784 | context: Context, 785 | ) -> result::Result<(String, &[flat::Node], Context), Error> { 786 | // lit_noesc = _' ( !_' . )* _' 787 | // _' = "'" 788 | 789 | consuming_rule("lit_noesc", nodes, context, |nodes, context| { 790 | let (nodes, context) = consume_single_quote(nodes, context)?; 791 | let (val, nodes) = flat::consume_val(nodes)?; 792 | 793 | let val = val.replace(r#"\"#, r#"\\"#); 794 | let vclone = val.clone(); 795 | push_err!(&format!("l:({})", vclone), { 796 | let (nodes, context) = consume_single_quote(nodes, context)?; 797 | Ok((val, nodes, context)) 798 | }) 799 | }) 800 | } 801 | 802 | fn consume_quote( 803 | nodes: &[flat::Node], 804 | context: Context, 805 | ) -> result::Result<(&[flat::Node], Context), Error> { 806 | // _" = "\u{34}" 807 | 808 | let (_, nodes, context) = consuming_rule(r#"_""#, nodes, context, |nodes, context| { 809 | Ok(((), flat::consume_this_value(r#"""#, nodes)?, context)) 810 | })?; 811 | Ok((nodes, context)) 812 | } 813 | 814 | fn consume_single_quote( 815 | nodes: &[flat::Node], 816 | context: Context, 817 | ) -> result::Result<(&[flat::Node], Context), Error> { 818 | // _' = "'" 819 | 820 | let (_, nodes, context) = consuming_rule(r#"_'"#, nodes, context, |nodes, context| { 821 | Ok(((), flat::consume_this_value(r#"'"#, nodes)?, context)) 822 | })?; 823 | Ok((nodes, context)) 824 | } 825 | 826 | fn consume_dot( 827 | nodes: &[flat::Node], 828 | context: Context, 829 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 830 | // dot = "." 831 | 832 | consuming_rule("dot", nodes, context, |nodes, context| { 833 | let (_, nodes) = flat::consume_val(nodes)?; 834 | Ok((dot!(), nodes, context)) 835 | }) 836 | } 837 | 838 | fn consume_rule_ref( 839 | nodes: &[flat::Node], 840 | context: Context, 841 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 842 | push_err!("consuming symbol rule_ref", { 843 | let (symbol_name, nodes, context) = consume_rule_name(nodes, context)?; 844 | 845 | Ok((ref_rule!(symbol_name), nodes, context)) 846 | }) 847 | } 848 | 849 | fn consume_match( 850 | nodes: &[flat::Node], 851 | context: Context, 852 | ) -> result::Result<(Expression, &[flat::Node], Context), Error> { 853 | // match = "[" 854 | // ( 855 | // (mchars mbetween*) 856 | // / mbetween+ 857 | // ) 858 | // "]" 859 | 860 | type VecChCh = Vec<(char, char)>; 861 | consuming_rule("match", nodes, context, |nodes, context| { 862 | fn rec_consume_mbetween( 863 | acc: Vec<(char, char)>, 864 | nodes: &[flat::Node], 865 | context: Context, 866 | ) -> result::Result<(VecChCh, &[flat::Node], Context), Error> { 867 | let next_node = flat::peek_first_node(nodes)?; 868 | let node_name = flat::get_nodename(next_node); 869 | match node_name { 870 | Ok("mbetween") => { 871 | let ((from, to), nodes, context) = consume_mbetween(nodes, context)?; 872 | rec_consume_mbetween(acc.ipush((from, to)), nodes, context) 873 | } 874 | _ => Ok((acc, nodes, context)), 875 | } 876 | } 877 | // -------------------------- 878 | 879 | let nodes = flat::consume_this_value("[", nodes)?; 880 | 881 | let (omchars, nodes, context) = match flat::get_nodename(flat::peek_first_node(nodes)?)? { 882 | "mchars" => { 883 | let (mchars, nodes, context) = consume_mchars(nodes, context)?; 884 | (Some(mchars), nodes, context) 885 | } 886 | _ => (None, nodes, context), 887 | }; 888 | 889 | let (vchars, nodes, context) = rec_consume_mbetween(vec![], nodes, context)?; 890 | 891 | let (expr, nodes) = match (omchars, vchars.is_empty()) { 892 | (Some(chars), true) => Ok((ematch!(chlist chars, from2 vec![]), nodes)), 893 | (Some(chars), false) => Ok((ematch!(chlist chars, from2 vchars), nodes)), 894 | (None, false) => Ok((ematch!(chlist "", from2 vchars), nodes)), 895 | _ => Err(error_peg_s("Invalid match combination")), 896 | }?; 897 | 898 | let nodes = flat::consume_this_value("]", nodes)?; 899 | 900 | Ok((expr, nodes, context)) 901 | }) 902 | } 903 | 904 | fn consume_mchars( 905 | nodes: &[flat::Node], 906 | context: Context, 907 | ) -> result::Result<(&str, &[flat::Node], Context), Error> { 908 | // mchars = (!"]" !(. "-") .)+ 909 | 910 | consuming_rule("mchars", nodes, context, |nodes, context| { 911 | let (val, nodes) = flat::consume_val(nodes)?; 912 | Ok((val, nodes, context)) 913 | }) 914 | } 915 | 916 | type CharChar = (char, char); 917 | fn consume_mbetween( 918 | nodes: &[flat::Node], 919 | context: Context, 920 | ) -> result::Result<(CharChar, &[flat::Node], Context), Error> { 921 | // mbetween = (. "-" .) 922 | 923 | consuming_rule("mbetween", nodes, context, |nodes, context| { 924 | let (from_to, nodes) = flat::consume_val(nodes)?; 925 | 926 | let (from, chars) = idata::consume_char(from_to.chars()) 927 | .ok_or_else(|| error_peg_s("expected from char"))?; 928 | let (_, chars) = 929 | idata::consume_char(chars).ok_or_else(|| error_peg_s("expected '-' char"))?; 930 | let (to, _) = idata::consume_char(chars).ok_or_else(|| error_peg_s("expected to char"))?; 931 | Ok(((from, to), nodes, context)) 932 | }) 933 | } 934 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------