1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
/*! This crate provides a binary to compile grammars into Rust code and a library implementing Earley's parsing algorithm to parse the grammars specified. # Usage This crate is `gramatica`. To use it you should install it in order to acquire the `gramatica_compiler` binary and also add `gramatica` to your dependencies in your project's `Cargo.toml`. ```toml [dependencies] gramatica = "0.1" ``` Then, if you have made a grammar file `example.rsg` execute `gramatica_compiler example.rsg > example.rs`. Afterwards you may use the generated file `example.rs` as a source Rust file. # Example: calculator The classical example is to implement a calculator. ```rust //This is a just Rust header that it is copied literally extern crate gramatica; use std::cmp::Ordering; use gramatica::{Associativity,EarleyKind,State,Parser,ParsingTablesTrait,AmbiguityInfo}; //Here the proper grammar begins. //These lines are processed by gramatica_compiler to generate the Token enum and the parsing tables. //We begin by terminal tokens (symbols that are not in the left of any rule but have a literal representation). //For this example all terminals are regular expressions. The first argument of re_terminal! is the type entry, as used in a enum. re_terminal!(Num(f64),"[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"); re_terminal!(Plus,"\\+"); re_terminal!(Minus,"-"); re_terminal!(Star,"\\*"); re_terminal!(Slash,"/"); re_terminal!(Caret,"\\^"); re_terminal!(LPar,"\\("); re_terminal!(RPar,"\\)"); re_terminal!(NewLine,"\\n"); re_terminal!(_,"\\s+");//Otherwise skip spaces //Now is the turn of nonterminal tokens. The first one is the default start symbol. //These have rules written as match clauses, with the pattern being the reduction of the nonterminal token and the expression being the value the token takes when reducing. //In this case the type of the symbol is empty and so is the expression nonterminal Input { () => (), (Input,Line) => (), } //Although the value type of Line is empty we may have code executed on the reduction nonterminal Line { (NewLine) => (), (Expression(value), NewLine) => { println!("{}",value); }, } //Finally a token with value type. Each rule creates the value in a different way. //Most rules are annotated to avoid ambiguities nonterminal Expression(f64) { (Num(value)) => value, #[priority(addition)] #[associativity(left)] (Expression(l),Plus,Expression(r)) => l+r, #[priority(addition)] #[associativity(left)] (Expression(l),Minus,Expression(r)) => l-r, #[priority(multiplication)] #[associativity(left)] (Expression(l),Star,Expression(r)) => l*r, #[priority(multiplication)] #[associativity(left)] (Expression(l),Slash,Expression(r)) => l/r, #[priority(addition)] #[associativity(left)] (Minus,Expression(value)) => -value, #[priority(exponentiation)] #[associativity(right)] (Expression(l),Caret,Expression(r)) => l.powf(r), (LPar,Expression(value),RPar) => value, } //The ordering macro-like sets the order of application of the previously annotated rules ordering!(exponentiation,multiplication,addition); //Finally an example of using the grammar to parse some lines from stdin. //We could do this or something similar in a different file if we desired to. use std::io::BufRead; fn main() { let stdin=std::io::stdin(); for rline in stdin.lock().lines() { let line=rline.unwrap()+"\n"; println!("line={}",line); match Parser::<Token,ParsingTables>::parse(&line,None) { Err(x) => println!("error parsing: {:?}",x), Ok(x) => println!("parsed correctly: {:?}",x), }; } } ``` # Advanced Lexer To define terminal tokens not expressable with regular expressions you may use the following. It must containg a _match function returning an option containing the number of chars mathed and the value of the token. ```rust terminal LitChar(char) { fn _match(parser: &mut Parser<Token,ParsingTables>, source:&str) -> Option<(usize,char)> { let mut characters=source.chars(); if (characters.next())==(Some('\'')) { let mut c=characters.next().unwrap(); let mut size=3; if c=='\\' { c=(characters.next().unwrap()); size=4; } if characters.next().unwrap()=='\'' { Some((size,c)) } else { None } } else { None } } } ``` Since version 0.1.1 there is also a `keyword_terminal!` macro: ```rust keyword_terminal!(Const,"const"); ``` # Parsing values as match clauses Each rule is written as a match clause, whose ending expression is the value that the nonterminal token gets after being parsed. For example, to parse a list of statements: ```rust nonterminal Stmts(Vec<StmtKind>) { (Stmt(ref stmt)) => vec![stmt.clone()], (Stmts(ref stmts),Stmt(ref stmt)) => { let mut new=(stmts.clone()); new.push(stmt.clone()); new }, } ``` Reductions only execute if they are part of the final syntactic tree. # Precedence by annotations To avoid ambiguities you have two options: to ensure the grammar does not contain them or to priorize rules by introducing annotations. In the example of the calculator we have seen two kinds: - `#[priority(p_name)]` to declare a rule with priority `p_name`. Later there should be a `ordering!(p_0,p_1,p_2,...)` macro-like to indicate that `p_0` should reduce before `p_1`. - `#[associativity(left/right)]` to decide how to proceed when nesting the same rule. # Example: Parsing JSON ```rust extern crate gramatica; use std::cmp::Ordering; use gramatica::{Associativity,EarleyKind,State,Parser,ParsingTablesTrait,AmbiguityInfo}; //See https://www.json.org/ use std::rc::Rc; //We define an auxiliar type to store JSON values #[derive(Clone,Debug,PartialEq)] enum JsonValue { Literal(String), Number(f64), Object(Vec<(String,JsonValue)>), Array(Vec<JsonValue>), True, False, Null, } // ---- Start of the grammar ---- keyword_terminal!(True,"true"); keyword_terminal!(False,"false"); keyword_terminal!(Null,"null"); re_terminal!(Number(f64),"[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"); terminal LitStr(String) { //This function has limited escaping capabilities fn _match(parser: &mut Parser<Token,ParsingTables>, source:&str) -> Option<(usize,String)> { let mut ret=None; let mut characters=source.chars(); if (characters.next())!=(Some('"')) { } else { let mut size=1; let mut r=String::from("\""); while true { match characters.next() { None => break, Some('"') => { ret=(Some((size+1,r+&"\""))); break; }, Some('\\') => { match characters.next() { None => break, //Some(c) => r+='\\'+c, Some(c) => { r.push('\\'); r.push(c); } }; size+=2; }, Some(c) => { //r+=&String::from(c); r.push(c); size+=1; }, }; } } ret } } re_terminal!(LBrace,"\\{"); re_terminal!(RBrace,"\\}"); re_terminal!(LBracket,"\\["); re_terminal!(RBracket,"\\]"); re_terminal!(Comma,","); re_terminal!(Colon,":"); re_terminal!(_,"\\s+|\n");//Otherwise skip spaces nonterminal Object(JsonValue) { (LBrace,RBrace) => JsonValue::Object(vec![]), (LBrace,Members(ref list),RBrace) => JsonValue::Object(list.clone()), } nonterminal Members(Vec<(String,JsonValue)>) { (Pair(ref s,ref value)) => vec![(s.clone(),value.clone())], //(Pair,Comma,Members) => (), (Members(ref list),Comma,Pair(ref s,ref value)) => { let mut new=(list.clone()); new.push((s.clone(),value.clone())); new }, } nonterminal Pair(String,JsonValue) { (LitStr(ref s),Colon,Value(ref value)) => (s.clone(),value.clone()), } nonterminal Array(Vec<JsonValue>) { (LBracket,RBracket) => vec![], (LBracket,Elements(ref list),RBracket) => list.clone(), } nonterminal Elements(Vec<JsonValue>) { (Value(ref value)) => vec![value.clone()], //(Value,Comma,Elements) => (), (Elements(ref list),Comma,Value(ref value)) => { let mut new=(list.clone()); new.push(value.clone()); new }, } nonterminal Value(JsonValue) { (LitStr(ref s)) => JsonValue::Literal(s.clone()), (Number(v)) => JsonValue::Number(v), (Object(ref value)) => value.clone(), (Array(ref list)) => JsonValue::Array(list.clone()), (True) => JsonValue::True, (False) => JsonValue::False, (Null) => JsonValue::Null, } // ---- End of the grammar ---- use std::io::{BufRead,Read}; //As example, we parse stdin for a JSON object fn main() { let stdin=std::io::stdin(); let mut buf=String::new(); stdin.lock().read_to_string(&mut buf); match Parser::<Token,ParsingTables>::parse(&buf,None) { Err(x) => println!("error parsing: {:?}",x), Ok(x) => println!("parsed correctly: {:?}",x), }; } ``` # Example: Parsing basic XML ```rust //A very basic xml grammar extern crate gramatica; use std::cmp::Ordering; use gramatica::{Associativity,EarleyKind,State,Parser,ParsingTablesTrait,AmbiguityInfo}; // see https://www.w3.org/People/Bos/meta-bnf // also http://cs.lmu.edu/~ray/notes/xmlgrammar/ use std::rc::Rc; //We define an auxiliar type to store XML elements #[derive(Clone,Debug,PartialEq)] struct XMLElement { name: String, attrs: Vec<(String,String)>, contents: Vec<XMLContent>, } #[derive(Clone,Debug,PartialEq)] enum XMLContent { Element(XMLElement), Data(String), } // ---- Start of the grammar ---- re_terminal!(Space(String),"(\\s|\n)+"); re_terminal!(Ident(String),"[a-zA-Z\\x80-\\xff_][a-zA-Z0-9\\x80-\\xff_]*"); terminal LitStr(String) { fn _match(parser: &mut Parser<Token,ParsingTables>, source:&str) -> Option<(usize,String)> { let mut ret=None; let mut characters=source.chars(); if (characters.next())!=(Some('"')) { } else { let mut size=1; let mut r=String::from("\""); while true { match characters.next() { None => break, Some('"') => { ret=(Some((size+1,r+&"\""))); break; }, Some('\\') => { match characters.next() { None => break, //Some(c) => r+='\\'+c, Some(c) => { r.push('\\'); r.push(c); } }; size+=2; }, Some(c) => { //r+=&String::from(c); r.push(c); size+=1; }, }; } } ret } } re_terminal!(CloseEmpty,"/>"); re_terminal!(BeginClose,"</"); re_terminal!(Equal,"="); re_terminal!(LT,"<"); re_terminal!(GT,">"); re_terminal!(Other(char),"."); nonterminal Document(XMLElement) { (Element(ref elem)) => elem.clone(), } nonterminal Element(XMLElement) { (EmptyElemTag(ref name,ref attrs)) => XMLElement{name:name.clone(),attrs:attrs.clone(),contents:vec![]}, (STag(ref name, ref attrs),Content(ref content),ETag) => XMLElement{name:name.clone(),attrs:attrs.clone(),contents:content.clone()}, } nonterminal EmptyElemTag(String,Vec<(String,String)>) { (LT,Ident(ref name),Attributes(ref attrs),MaybeSpace,CloseEmpty) => (name.clone(),attrs.clone()), } nonterminal Attributes(Vec<(String,String)>) { () => vec![], (Attributes(ref attrs),Space,Attribute(ref a, ref b)) => { let mut new=(attrs.clone()); new.push((a.clone(),b.clone())); new }, } nonterminal Attribute(String,String) { (Ident(ref a),Equal,LitStr(ref b)) => (a.clone(),b.clone()), } nonterminal STag(String,Vec<(String,String)>) { (LT,Ident(ref name),Attributes(ref attrs),MaybeSpace,GT) => (name.clone(),attrs.clone()), } nonterminal ETag(String) { (BeginClose,Ident(ref s),MaybeSpace,GT) => s.clone(), } nonterminal Content(Vec<XMLContent>) { (CharData(ref s)) => vec![XMLContent::Data(s.clone())], (CharData(ref s),Contents(ref list)) => { let mut new=vec![XMLContent::Data(s.clone())]; new.extend(list.iter().map(|x|x.clone())); new }, } nonterminal Contents(Vec<XMLContent>) { () => vec![], (Contents(ref list),Element(ref elem),CharData(ref s)) => { let mut new=(list.clone()); new.push(XMLContent::Element(elem.clone())); if s!="" { new.push(XMLContent::Data(s.clone())); } new }, } nonterminal MaybeSpace { () => (), (Space) => (), } nonterminal CharData(String) { () => String::new(), (CharData(ref s),Space(ref o)) => format!("{}{}",s,o), (CharData(ref s),Ident(ref o)) => format!("{}{}",s,o), (CharData(ref s),Equal) => format!("{}=",s), (CharData(ref s),Other(o)) => format!("{}{}",s,o), } // ---- End of the grammar ---- use std::io::{BufRead,Read}; //As example, we parse stdin for a XML element fn main() { let stdin=std::io::stdin(); let mut buf=String::new(); stdin.lock().read_to_string(&mut buf); match Parser::<Token,ParsingTables>::parse(&buf,None) { Err(x) => println!("error parsing: {:?}",x), Ok(x) => println!("parsed correctly: {:?}",x), }; } ``` */ extern crate regex; use std::collections::HashMap; use regex::Regex; use std::cmp::Ordering; use std::marker::PhantomData; use std::fmt::Debug; #[derive(Debug)] pub enum Associativity { Left, Right, } #[derive(Debug)] pub enum ParsingError { NotInGrammar, Ambiguous, } #[derive(Clone,Debug)] pub enum EarleyKind { Complete(usize,usize,usize),//reduced state, set, state Scan(usize,usize),//set, state Predict(usize),//state index } #[derive(Clone,Debug)] pub struct AmbiguityInfo<T> { states: Vec<State<T>>, index: usize, } impl<T> Default for AmbiguityInfo<T> { fn default() -> Self { AmbiguityInfo{ states: vec![], index: 0, } } } #[derive(Clone,Debug)] pub struct State<T> { pub rule: usize, pub left: usize, pub right: Vec<usize>, pub position: usize, pub original_set: usize, pub kind: EarleyKind, //values: Vec<Token>, pub values: Vec<T>, //computed_value: Token, pub computed_value: T, pub ambiguity_info: AmbiguityInfo<T>, } impl<T:Clone+Default> State<T> { pub fn finished(&self)->bool { self.position==self.right.len() } pub fn next(&self)->usize { self.right[self.position] } pub fn try_next(&self)->Option<usize> { if self.position==self.right.len() { None } else { Some(self.right[self.position]) } } //pub fn is_next_terminal(&self)->bool //{ // table_terminal(self.next()) //} pub fn advance(&self)->State<T> { State{ rule: self.rule, left:self.left, right:self.right.clone(), position:self.position+1, original_set: self.original_set, kind: self.kind.clone(), values: self.values.clone(), //computed_value: Token::DummyStart, computed_value: T::default(), ambiguity_info: self.ambiguity_info.clone(), } } } pub struct StateSet<T> { pub states: Vec<State<T>>, } impl<T> StateSet<T> { pub fn predict(&mut self, state: State<T>) { for s in self.states.iter() { //if s.left==state.left && s.position==state.position && s.right==state.right if s.rule==state.rule && s.position==state.position { return; } } self.states.push(state); } } pub trait ParsingTablesTrait<T> { fn initial()->usize; fn match_some(parser:&mut Parser<T,Self>) -> Option<(usize,T)> where Self:Sized; fn predict(parser:&mut Parser<T,Self>,index:usize,state_index:usize,token:usize) where Self:Sized; fn compute_value(state:&mut State<T>); fn table_terminal(token_index:usize)->bool; fn table_priority(a:usize, b:usize) -> Option<Ordering>; fn table_associativity(rule:usize) -> Option<Associativity>; fn to_usize(&T) -> usize; } pub struct Parser<'a,T,Tables:ParsingTablesTrait<T>> { pub sets: Vec<StateSet<T>>, pub source: &'a str, pub source_index: usize, pub tokens: Vec<T>, pub tokens_range: Vec<(usize,usize)>, pub regex_map: HashMap<String,Regex>, pub phantom: PhantomData<Tables>, } impl<'a,T:Default+PartialEq+Clone+Debug,Tables:ParsingTablesTrait<T>> Parser<'a,T,Tables> { pub fn parse(source:&str, initial:Option<usize>) -> Result<T,ParsingError> { let mut initial_state=Tables::initial(); if let Some(x)=initial { initial_state=x; } let mut parser=Parser::<T,Tables>{ sets:vec![ StateSet{ states:vec![ State{ rule:0, left:0, right:vec![initial_state], position:0, original_set: 0, kind: EarleyKind::Predict(0), //values: vec![Token::DummyStart], //computed_value: Token::DummyStart, values: vec![T::default()], computed_value: T::default(), ambiguity_info: AmbiguityInfo::default(), }] }], source, source_index:0, tokens: vec![], tokens_range: vec![], regex_map: HashMap::new(), phantom: PhantomData, }; //println!("::parse created parser"); parser.tokenize(); //println!("::parse tokenized"); parser.earley() } pub fn re(&mut self, regex:&'a str, source:&str) -> Option<(usize,String)> { //let s=String::from("^")+regex; let s=format!("^({})",regex); let r= { if !self.regex_map.contains_key(&s) { let x=Regex::new(&s).unwrap(); self.regex_map.insert(s.clone(),x); } self.regex_map.get(&s).expect("regex not in map even after inserting") }; match r.captures(source) { Some(cap) => { let m=cap.get(0).unwrap(); Some((m.end(),m.as_str().to_string())) }, None => None, } } pub fn keyword(&mut self, key:&str, source:&str) -> Option<(usize,String)> { let mut key_chars=key.chars(); let mut source_chars=source.chars(); loop { match (key_chars.next(),source_chars.next()) { //None => match source_chars.next() //{ // Some('a'...'z' | 'A'...'Z' | '_') => return None, // _ => return Some((key.len(),key.to_string())), //}, //Some(c) => //(None,Some('a'...'z' | 'A'...'Z' | '_')) => return None, (None,Some(d)) => match d { 'a'...'z' | 'A'...'Z' | '_' => return None, _ => return Some((key.len(),key.to_string())), }, (None,None) => return Some((key.len(),key.to_string())), (Some(c),Some(d)) => if c!=d { return None;}, _ => return None, }; } } pub fn tokenize(&mut self) { while self.source_index<self.source.len() { //match self.match_some() //match ParsingTables::match_some(self) match Tables::match_some(self) { None => { let s=self.source[self.source_index..self.source_index+100].to_string(); panic!("Did not match anything '{}'",s); }, Some((size,token)) => { //println!("Got token {:?} with size {}",token,size); //if let Token::DummyStart=token {} //else //{ // self.tokens.push(token); //} if T::default()!=token { self.tokens.push(token); self.tokens_range.push((self.source_index,self.source_index+size)); } self.source_index+=size; }, }; } } pub fn earley(&mut self) -> Result<T,ParsingError> { let n=self.tokens.len(); for index in 0..n+1 { if self.sets[index].states.len()==0 { println!("unexpected token {:?}",self.tokens[index-1]); let (start,end)=self.tokens_range[index-1]; let showing_start= if start>100 {start-100} else {0}; let showing_end= if end+100>=self.source.len() {self.source.len()} else {start+100}; println!("BEFORE<{}>",self.source[showing_start..start].to_string()); println!("THEN<{}>",self.source[start..end].to_string()); println!("AFTER<{}>",self.source[end..showing_end].to_string()); print!("Tokens=..."); let token_start = if index>20 { index-20 } else {0}; let token_end = if index+20>self.tokens.len() {self.tokens.len()} else { index+20 }; for i in token_start..index-1 { print!("{:?},",self.tokens[i]); } print!("[{:?}],",self.tokens[index-1]); for i in index..token_end { print!("{:?},",self.tokens[i]); } println!(""); return Err(ParsingError::NotInGrammar); } let last=index==n; //if last //{ // println!("At index={} END",index); //} //else //{ // println!("At index={} token={:?}",index,self.tokens[index]); //} let mut state_index=0; let mut newset=StateSet{states:vec![]}; while state_index < self.sets[index].states.len() { let state=self.sets[index].states[state_index].clone(); //println!("\tAt index={} state_index={} state={:?}",index,state_index,state); if state.finished() { //Completer let token=state.left; let x=state.original_set; let mut priority=true; let mut ambiguity=vec![state.clone()]; for i in 0..self.sets[index].states.len() { if i==state_index { continue; } let other=&self.sets[index].states[i]; if token!=other.left || x!=other.original_set || !other.finished() { continue; } //Two rules parse the same text to the same token, apply priority match Tables::table_priority(state.rule,other.rule) { None => { ambiguity.push(other.clone()); if i<state_index { priority=false; break; } }, Some(Ordering::Less) => { priority=false; //println!("set priority=false for {} because of {}",state_index,i); break; }, Some(Ordering::Equal) => { //Same priority, use associativity //match table_associativity(state.rule) match Tables::table_associativity(state.rule) { None => { ambiguity.push(other.clone()); if i<state_index { priority=false; break; } }, Some(Associativity::Left) => if state_index>i { priority=false; //println!("set priority=false for {} because of {} [left associativity]",state_index,i); break; }, Some(Associativity::Right) => if state_index<i { priority=false; //println!("set priority=false for {} because of {} [right associativity]",state_index,i); break; }, } }, Some(Ordering::Greater) => continue, }; } if priority { //for each state with next=token in set x, advance it to current set let mut i=0; while i<self.sets[x].states.len() { //if self.sets[x].states[i].next()==token if let Some(t)=self.sets[x].states[i].try_next() { if token==t { //self.sets[index].states.push(self.sets[x].states[i].advance()); let mut new=self.sets[x].states[i].advance(); new.kind=EarleyKind::Complete(state_index,x,i); if ambiguity.len()>1 { new.ambiguity_info.states=ambiguity.clone(); new.ambiguity_info.index=index; } self.sets[index].states.push(new); } } i+=1; } } } else { //if state.is_next_terminal() //if table_terminal(state.next()) if Tables::table_terminal(state.next()) { //Scanner //if !last && state.next()==self.tokens[index].to_usize() if !last && state.next()==Tables::to_usize(&self.tokens[index]) { //newset.states.push(state.advance()); let mut new=state.advance(); new.kind=EarleyKind::Scan(index,state_index); //new.value=self.tokens[index].clone(); new.values[new.position-1]=self.tokens[index].clone(); newset.states.push(new); } } else { //Predictor let token=state.next(); //for each token->right in grammar, add the rule to self.sets[index] //ParsingTables::predict(self,index,state_index,token); Tables::predict(self,index,state_index,token); } } state_index+=1; } self.sets.push(newset); } let mut values=vec![]; for state_index in 0..self.sets[n].states.len() { if self.sets[n].states[state_index].left==0 && self.sets[n].states[state_index].finished() { self.compute_value(n,state_index); if self.sets[n].states[state_index].ambiguity_info.states.len()>1 { let a=&self.sets[n].states[state_index].ambiguity_info; println!("Ambiguity at index={} token={:?}",a.index,self.tokens[a.index-1]); let (start,end)=self.tokens_range[a.index-1]; let showing_start= if start>100 {start-100} else {0}; let showing_end= if end+100>=self.source.len() {self.source.len()} else {start+100}; println!("BEFORE<{}>",self.source[showing_start..start].to_string()); println!("THEN<{}>",self.source[start..end].to_string()); println!("AFTER<{}>",self.source[end..showing_end].to_string()); return Err(ParsingError::Ambiguous); } values.push(self.sets[n].states[state_index].computed_value.clone()); } } //println!("values={:?}",values); if values.len()==0 { Err(ParsingError::NotInGrammar) } else if values.len()==1 { Ok(values[0].clone()) } else { Err(ParsingError::Ambiguous) } } pub fn compute_value(&mut self, set_index:usize, state_index:usize) { //println!(">>compute_value set_index={} state_index={} state={:?}",set_index,state_index,self.sets[set_index].states[state_index]); match self.sets[set_index].states[state_index].kind { EarleyKind::Complete(reduced,prev_set_index,prev_state_index) => { self.compute_value(set_index,reduced); self.compute_value(prev_set_index,prev_state_index); //let current=&mut self.sets[set_index].states[state_index]; let mut prop_ambiguity=None; self.sets[set_index].states[state_index].values= { let prev=&self.sets[prev_set_index].states[prev_state_index]; let red=&self.sets[set_index].states[reduced]; let mut current_values=prev.values.clone(); current_values[self.sets[set_index].states[state_index].position-1]=red.computed_value.clone(); if prev.ambiguity_info.states.len()>1 { prop_ambiguity=Some(prev.ambiguity_info.clone()); } else if red.ambiguity_info.states.len()>1 { prop_ambiguity=Some(red.ambiguity_info.clone()); } current_values }; if let Some(a)=prop_ambiguity { self.sets[set_index].states[state_index].ambiguity_info=a; } }, EarleyKind::Scan(prev_set_index,prev_state_index) => { //They have the value already self.compute_value(prev_set_index,prev_state_index); for i in 0..self.sets[set_index].states[state_index].position-1 { self.sets[set_index].states[state_index].values[i]=self.sets[prev_set_index].states[prev_state_index].values[i].clone(); } self.sets[set_index].states[state_index].ambiguity_info=self.sets[prev_set_index].states[prev_state_index].ambiguity_info.clone(); }, EarleyKind::Predict(_harbinger_state_index) => { }, } let current=&mut self.sets[set_index].states[state_index]; if current.finished() { //Compute its value //ParsingTables::compute_value(current); Tables::compute_value(current); } } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }