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 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
//! This module implements a zero-copy version of the runtime parser that
//! uses the LR statemachine generated by rustlr. It will (for now), live
//! side along with the original parser implemented as [crate::RuntimeParser].
//! Since Version 0.2.3, this module can now generate a basic lexical
//! scanner based on [crate::RawToken] and [crate::StrTokenizer].
//!
//! This module implements the parsing routines that uses the state machine
//! generated by rustlr. **The main structure here is [ZCParser]**.
//! All parsing functions are organized around the [ZCParser::parse_core]
//! function, which implements the basic LR parsing algorithm. This function
//! expects dynamic [Tokenizer] and [ErrReporter] trait-objects.
//! This module provides generic
//! parsing and parser-training routines that use stdio for interface, but
//! the [ErrReporter] trait allows custom user interfaces to be build separately.
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![allow(unused_parens)]
#![allow(unused_mut)]
#![allow(unused_assignments)]
#![allow(unused_doc_comments)]
#![allow(unused_imports)]
use std::fmt::Display;
use std::default::Default;
use std::collections::{HashMap,HashSet,BTreeSet};
use std::io::{self,Read,Write,BufReader,BufRead};
use std::rc::Rc;
use std::cell::{RefCell,Ref,RefMut};
use std::hash::{Hash,Hasher};
use std::any::Any;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::mem;
//use crate::{Stateaction,Statemachine,TerminalToken,Tokenizer};
use crate::{Stateaction,iserror,TerminalToken,Tokenizer};
use crate::{LBox,LRc,LC};
use crate::Stateaction::*;
use crate::{lbup,lbdown,lbget};
use crate::{StandardReporter};
#[cfg(feature = "generator")]
use crate::{Statemachine};
//extern crate termion;
//use termion::{color,style};
/// this structure is only exported because it is required by the generated parsers.
/// There is no reason to use it in other programs. Replaces [crate::RProduction] for new parsers since version 0.2.0
#[derive(Clone)]
pub struct ZCRProduction<AT:Default,ET:Default> // runtime rep of grammar rule
{
pub lhs: &'static str, // left-hand side nonterminal of rule
pub Ruleaction : fn(&mut ZCParser<AT,ET>) -> AT, //parser as arg
}
impl<AT:Default,ET:Default> ZCRProduction<AT,ET>
{
pub fn new_skeleton(lh:&'static str) -> ZCRProduction<AT,ET>
{
ZCRProduction {
lhs : lh,
Ruleaction : |p|{ <AT>::default() },
}
}
}//impl ZCRProduction
/// These structures are what's on the parse stack.
pub struct StackedItem<AT:Default> // replaces Stackelement
{
si : usize, // state index
pub value : AT, // semantic value (don't clone grammar symbols)
pub line: usize, // line and column
pub column: usize,
}
impl<AT:Default> StackedItem<AT>
{
pub fn new(si:usize,value:AT,line:usize,column:usize) -> StackedItem<AT>
{ StackedItem{si,value,line,column} }
/// converts the information in a stacked item to an [LBox] enclosing
/// the abstract syntax value along with starting line and column numbers
pub fn lbox(self) -> LBox<AT> // no longer used
{ LBox::new(self.value,self.line,self.column) }
}
/// this is the structure created by the generated parser. The generated parser
/// program will contain a make_parser function that returns this structure.
/// Most of the pub items are, however, only exported to support the operation
/// of the parser, and should not be accessed directly. Only the functions
/// [ZCParser::parse], [ZCParser::report], [ZCParser::abort]
/// and [ZCParser::error_occurred] should be called directly
/// from user programs. Only the field [ZCParser::exstate] should be accessed
/// by user programs.
pub struct ZCParser<AT:Default,ET:Default>
{
/// this is the "external state" structure, with type ET defined by the grammar.
/// The semantic actions associated with each grammar rule, which are written
/// in the grammar, have ref mut access to the ZCParser structure, which
/// allows them to read and change the external state object. This gives
/// the parsers greater flexibility and capability, including the ability to
/// parse some non-context free languages. See
/// [this sample grammar](<https://cs.hofstra.edu/~cscccl/rustlr_project/ncf.grammar>).
/// The exstate is initialized to ET::default().
pub exstate : ET, // external state structure, usage optional
/// External state that can be shared
pub shared_state : Rc<RefCell<ET>>,
/// used only by generated parser: do not reference
pub RSM : Vec<HashMap<&'static str,Stateaction>>, // runtime state machine
// do not reference
//pub Expected : Vec<Vec<&'static str>>,
/// do not reference
pub Rules : Vec<ZCRProduction<AT,ET>>, //rules with just lhs and delegate function
////// this value should be set through abort or report
stopparsing : bool,
/// do not reference
pub stack : Vec<StackedItem<AT>>, // parse stack
// pub recover : HashSet<&'static str>, // for error recovery
pub resynch : HashSet<&'static str>,
pub Errsym : &'static str,
err_occurred : bool,
/// axiom: linenum and column represents the starting position of the
/// topmost StackedItem.
pub linenum : usize,
pub column : usize,
pub position : usize, // absolute byte position of input
pub prev_position : usize,
pub src_id : usize,
report_line : usize,
/// Hashset containing all grammar symbols (terminal and non-terminal). This is used for error reporting and training.
pub Symset : HashSet<&'static str>,
//pub tokenizer:&'t mut dyn Tokenizer<'t,AT>,
popped : Vec<(usize,usize)>,
gindex : RefCell<u32>, // global index for uid
err_report : Option<String>, // optional err report with logging reporter
}//struct ZCParser
impl<AT:Default,ET:Default> ZCParser<AT,ET>
{
/// this is only called by the make_parser function in the machine-generated
/// parser program. *Do not call this function in other places* as it
/// only generates a skeleton.
pub fn new(rlen:usize, slen:usize/*,tk:&'t mut dyn Tokenizer<'t,AT>*/) -> ZCParser<AT,ET>
{ // given number of rules and number states
let mut p = ZCParser {
RSM : Vec::with_capacity(slen),
//Expected : Vec::with_capacity(slen),
Rules : Vec::with_capacity(rlen),
stopparsing : false,
exstate : ET::default(),
shared_state: Rc::new(RefCell::new(ET::default())),
stack : Vec::with_capacity(1024),
Errsym : "",
err_occurred : false,
linenum : 0,
column : 0,
position : 0,
prev_position: 0,
src_id : 0,
report_line : 0,
resynch : HashSet::new(),
//added for training
//training : false,
//trained : HashMap::new(),
Symset : HashSet::with_capacity(64),
//tokenizer:tk,
popped: Vec::with_capacity(8),
gindex: RefCell::new(0),
err_report : None,
};
for _ in 0..slen {
p.RSM.push(HashMap::with_capacity(16));
//p.Expected.push(Vec::new());
}
return p;
}//new
/// returns the current line number
pub fn current_line(&self)->usize {self.linenum}
/// returns the current column number
pub fn current_column(&self)->usize {self.column}
/// returns the current absolute byte position according to tokenizer
pub fn current_position(&self)->usize {self.position}
/// returns the previous position (before shift) according to tokenizer
pub fn previous_position(&self)->usize {self.prev_position}
/// this function can be called from with the "semantic" actions attached
/// to grammar production rules that are executed for each
/// "reduce" action of the parser.
pub fn abort(&mut self, msg:&str)
{
self.err_report.as_mut().map_or_else(
||eprintln!("\n!!!Parsing Aborted: {}",msg),
|x|x.push_str(&format!("\n!!!Parsing Aborted: {}\n",msg)));
self.err_occurred = true;
self.stopparsing=true;
}
/// may be called from grammar semantic actions to report error.
/// this report function will print to stdout.
pub fn report(&mut self, errmsg:&str) {self.report_error(errmsg,false)}
/// same as [ZCParser::report] but with option to display line/column
pub fn report_error(&mut self, errmsg:&str, showlc: bool)
{
//eprint!("{}",color::Fg(color::Yellow));
if (self.report_line != self.linenum || self.linenum==0) {
if showlc {
self.err_report.as_mut().map_or_else(
||eprintln!("ERROR on line {}, column {}: {}",self.linenum,self.column,errmsg),
|x|x.push_str(&format!("ERROR on line {}, column {}: {}\n",self.linenum,self.column,errmsg)));
}
else {
self.err_report.as_mut().map_or_else(
||eprintln!("PARSER ERROR: {}",errmsg),
|x|x.push_str(&format!("PARSER ERROR: {}\n",errmsg)));
}
self.report_line = self.linenum;
}
else {
if showlc {
self.err_report.as_mut().map_or_else(
||eprint!(" ({},{}): {}",self.linenum,self.column,errmsg),
|x|x.push_str(&format!(" ({},{}): {}",self.linenum,self.column,errmsg)));
}
else {
self.err_report.as_mut().map_or_else(
||eprint!(" {}",errmsg),
|x|{x.push(' '); x.push_str(errmsg)});
}
}
//eprint!("{}",color::Fg(color::Reset));
self.err_occurred = true;
}// report
/// this function is only exported to support the generated code
pub fn bad_pattern(&mut self,pattern:&str) -> AT
{
let msg = format!("pattern {} failed to bind to stacked values\n",pattern);
self.report(&msg);
//println!("FROM BAD PATTERN:");
AT::default()
}
/*
/// sets an index that index source information, such as the source file
/// when compiling multiple sources. This information must be maintained externally.
/// The source id will also be passed on to the [LBox] and [LRc] smartpointers by
/// the [ZCParser::lb] function.
pub fn set_src_id(&mut self, id:usize)
{ self.src_id =id; }
*/
//called to simulate a shift
fn errshift(&mut self, sym:&str) -> bool
{
let csi = self.stack[self.stack.len()-1].si; // current state
let actionopt = self.RSM[csi].get(sym);
if let Some(Shift(ni)) = actionopt {
self.stack.push(StackedItem::new(*ni,AT::default(),self.linenum,self.column)); true
}
else {false}
}
// this is the LR parser shift action: push the next state, along with the
// value of the current lookahead token onto the parse stack, returns the
// next token
fn shift<'t>(&mut self, nextstate:usize, lookahead:TerminalToken<'t,AT>, tokenizer:&mut dyn Tokenizer<'t,AT>) -> TerminalToken<'t, AT>
{
self.linenum = lookahead.line; self.column=lookahead.column;
self.prev_position = self.position; self.position = tokenizer.position();
self.stack.push(StackedItem::new(nextstate,lookahead.value,lookahead.line,lookahead.column));
//self.nexttoken()
tokenizer.next_tt()
}
/// this function is called from the generated semantic actions and should
/// most definitely not be called from elsewhere as it would corrupt
/// the base parser.
pub fn popstack(&mut self) -> StackedItem<AT>
{
let item = self.stack.pop().expect("PARSER STATE MACHINE/STACK CORRUPTED");
self.linenum = item.line; self.column=item.column;
self.popped.push((item.line,item.column));
item
}//popstack
pub fn popstack_as_lbox(&mut self) -> LBox<AT>
{
let item = self.stack.pop().expect("PARSER STATE MACHINE/STACK CORRUPTED");
self.linenum = item.line; self.column=item.column;
self.popped.push((item.line,item.column));
let newuid = *self.gindex.borrow();
*self.gindex.borrow_mut() += 1;
LBox::make(item.value,item.line,item.column,newuid)
}//popstack_as_lbox
fn reduce(&mut self, ri:&usize)
{
self.popped.clear();
let rulei = &self.Rules[*ri];
let ruleilhs = rulei.lhs; // &'static : Copy
//let mut dummy = RuntimeParser::new(1,1);
let val = (rulei.Ruleaction)(self); // should be self
let newtop = self.stack[self.stack.len()-1].si;
let goton = self.RSM[newtop].get(ruleilhs).expect("PARSER STATEMACHINE CORRUPTED");
if let Stateaction::Gotonext(nsi) = goton {
/*
the line/column must be the last thing that was popped, but how is this communicated from the semantic actions?
Solution: When the semantic action pops, it changes self.linenum,self.column,
instead of pop, there should be a function self.popstack() that returns value.
This is correct because linenum/column will again reflect start of tos item
*/
self.stack.push(StackedItem::new(*nsi,val,self.linenum,self.column));
//self.stack.push(Stackelement{si:*nsi,value:val});
}// goto next state after reduce
else {
self.report("state transition table corrupted: no suitable action after reduce");
self.stopparsing=true;
}
}//reduce
/// can be called to determine if an error occurred during parsing. The parser
/// will not panic.
pub fn error_occurred(&self) -> bool {self.err_occurred}
// there may need to be other lb functions, perhaps from terminalToken
// or stackedItem (at least for transfer)
/// creates a [LBox] smart pointer that includes line/column information;
/// should be called from the semantic actions of a grammar rule, e.g.
///```ignore
/// E --> E:a + E:b {PlusExpr(parser.lb(a),parser.lb(b))}
///```
pub fn lb<T>(&self,e:T) -> LBox<T> {
let newuid = *self.gindex.borrow();
*self.gindex.borrow_mut() += 1;
LBox::make(e,self.linenum,self.column,newuid)
}
/// creates a `LBox<dyn Any>`, which allows attributes of different types to
/// be associated with grammar symbols. Use in conjuction with [LBox::downcast], [LBox::upcast] and the [lbdown], [lbup] macros.
pub fn lba<T:'static>(&self,e:T) -> LBox<dyn Any> {
let newuid = *self.gindex.borrow();
*self.gindex.borrow_mut() += 1;
LBox::upcast(LBox::make(e,self.linenum,self.column,newuid))
}
/// similar to [ZCParser::lb], but creates a [LRc] instead of [LBox]
pub fn lrc<T>(&self,e:T) -> LRc<T> { LRc::new(e,self.linenum,self.column /*,self.src_id*/) }
/// similar to [ZCParser::lba] but creates a [LRc]
pub fn lrca<T:'static>(&self,e:T) -> LRc<dyn Any> { LRc::upcast(LRc::new(e,self.linenum,self.column /*,self.src_id*/)) }
/// creates LBox enclosing e using line/column information associated
/// with right-hand side symbols, numbered left-to-right starting at 0
pub fn lbx<T>(&self,i:usize,e:T) -> LBox<T>
{
let (mut ln,mut cl) = (self.linenum,self.column);
if i<self.popped.len() {
let index = self.popped.len() - 1 - i;
let lc = self.popped[index];
ln = lc.0; cl=lc.1;
}
let newuid = *self.gindex.borrow();
*self.gindex.borrow_mut() += 1;
LBox::make(e,ln,cl,newuid)
}//lbx
/// alias for [Self::lbx]
pub fn lbox<T>(&self,i:usize,e:T) -> LBox<T> { self.lbx(i,e) }
/// creates [LC] enclosing e using line/column information associated
/// with right-hand side symbols, numbered left-to-right starting at 0
pub fn lc<T>(&self,i:usize,e:T) -> LC<T>
{
let (mut ln,mut cl) = (self.linenum,self.column);
if i<self.popped.len() {
let index = self.popped.len() - 1 - i;
let lc = self.popped[index];
ln = lc.0; cl=lc.1;
}
let uid = *self.gindex.borrow();
*self.gindex.borrow_mut() += 1;
LC::make(e,ln,cl,uid)
}//lbx
/// Like lbx but creates an LRc
pub fn lrcn<T>(&self,i:usize,e:T) -> LRc<T>
{
let (mut ln,mut cl) = (self.linenum,self.column);
if i<self.popped.len() {
let index = self.popped.len() - 1 - i;
let lc = self.popped[index];
ln = lc.0; cl=lc.1;
}
LRc::new(e,ln,cl)
}//lbx
}// impl ZCParser
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//// new version of write_fsm: (include calls to genlexer)
#[cfg(feature = "generator")]
impl Statemachine
{ /////// zc version
pub fn writezcparser(&self, filename:&str)->Result<(),std::io::Error>
{
let ref absyn = self.Gmr.Absyntype;
let ref extype = self.Gmr.Externtype;
let ref lifetime = self.Gmr.lifetime;
let has_lt = lifetime.len()>0 && (absyn.contains(lifetime) || extype.contains(lifetime));
let ltopt = if has_lt {format!("<{}>",lifetime)} else {String::from("")};
let mut fd = File::create(filename)?;
write!(fd,"//Parser generated by rustlr for grammar {}",&self.Gmr.name)?;
write!(fd,"\n
#![allow(unused_variables)]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![allow(unused_parens)]
#![allow(unused_mut)]
#![allow(unused_imports)]
#![allow(unused_assignments)]
#![allow(dead_code)]
#![allow(irrefutable_let_patterns)]
#![allow(unreachable_patterns)]
use std::rc::Rc;
use std::cell::RefCell;
extern crate rustlr;
use rustlr::{{Tokenizer,TerminalToken,ZCParser,ZCRProduction,Stateaction,decode_action}};\n")?;
if self.Gmr.genlex {
write!(fd,"use rustlr::{{StrTokenizer,RawToken,LexSource}};
use std::collections::{{HashMap,HashSet}};\n")?;
}
write!(fd,"{}\n",&self.Gmr.Extras)?; // use clauses and such
// write static array of symbols
write!(fd,"static SYMBOLS:[&'static str;{}] = [",self.Gmr.Symbols.len())?;
for i in 0..self.Gmr.Symbols.len()-1
{
write!(fd,"\"{}\",",&self.Gmr.Symbols[i].sym)?;
}
write!(fd,"\"{}\"];\n\n",&self.Gmr.Symbols[self.Gmr.Symbols.len()-1].sym)?;
// position of symbols must be inline with self.Gmr.Symhash
// record table entries in a static array
let mut totalsize = 0;
for i in 0..self.FSM.len() { totalsize+=self.FSM[i].len(); }
write!(fd,"static TABLE:[u64;{}] = [",totalsize)?;
// generate table to represent FSM
let mut encode:u64 = 0;
for i in 0..self.FSM.len() // for each state index i
{
let row = &self.FSM[i]; // this is a hashmap<usize,stateaction>
for key in row.keys()
{ // see function decode for opposite translation
let k = *key; //*self.Gmr.Symhash.get(key).unwrap(); // index of symbol
encode = ((i as u64) << 48) + ((k as u64) << 32);
match row.get(key) {
Some(Shift(statei)) => { encode += (*statei as u64) << 16; },
Some(Gotonext(statei)) => { encode += ((*statei as u64) << 16)+1; },
Some(Reduce(rulei)) => { encode += ((*rulei as u64) << 16)+2; },
Some(Accept) => {encode += 3; },
_ => {encode += 4; }, // 4 indicates Error
}//match
write!(fd,"{},",encode)?;
} //for symbol index k
}//for each state index i
write!(fd,"];\n\n")?;
// must know what absyn type is when generating code.
write!(fd,"pub fn make_parser{}() -> ZCParser<{},{}>",<opt,absyn,extype)?;
write!(fd,"\n{{\n")?;
// write code to pop stack, assign labels to variables.
write!(fd," let mut parser1:ZCParser<{},{}> = ZCParser::new({},{});\n",absyn,extype,self.Gmr.Rules.len(),self.FSM.len())?;
// generate rules and Ruleaction delegates, must pop values from runtime stack
write!(fd," let mut rule = ZCRProduction::<{},{}>::new_skeleton(\"{}\");\n",absyn,extype,"start")?;
for i in 0..self.Gmr.Rules.len()
{
write!(fd," rule = ZCRProduction::<{},{}>::new_skeleton(\"{}\");\n",absyn,extype,self.Gmr.Rules[i].lhs.sym)?;
write!(fd," rule.Ruleaction = |parser|{{ ")?;
let mut k = self.Gmr.Rules[i].rhs.len();
//form if-let labels and patterns as we go...
let mut labels = String::from("(");
let mut patterns = String::from("(");
while k>0 // k is length of right-hand side
{
let mut boxedlabel = false; // see if named label is of form [x]
let gsym = &self.Gmr.Rules[i].rhs[k-1];
let findat = gsym.label.find('@');
let mut plab = format!("_item{}_",k-1);
match &findat {
None if gsym.label.len()>0 && !gsym.label.contains('(') => {
let rawlabel = gsym.label.trim();
let truelabel = checkboxlabel(rawlabel);
boxedlabel = truelabel != rawlabel;
plab = String::from(truelabel);
// plab=format!("{}",gsym.label.trim());
},
Some(ati) if *ati>0 => {
let rawlabel = gsym.label[0..*ati].trim();
let truelabel = checkboxlabel(rawlabel);
boxedlabel = truelabel != rawlabel;
plab = String::from(truelabel);
},
_ => {},
}//match
let poppedlab = plab.as_str();
if !boxedlabel {
write!(fd,"let mut {} = parser.popstack(); ",poppedlab)?;
} else {
write!(fd,"let mut {} = parser.popstack_as_lbox(); ",poppedlab)?;
}
if gsym.label.len()>1 && findat.is_some() { // if-let pattern
let atindex = findat.unwrap();
if atindex>0 { // label like es:@Exp(..)@
//let varlab = &gsym.label[0..atindex]; //es before @: es:@..@
labels.push_str("&mut "); // for if-let
if boxedlabel {labels.push('*');}
labels.push_str(poppedlab); labels.push_str(".value,");
//write!(fd," let mut {}={}.value; ",varlab,poppedlab)?;
}
else { // non-labeled pattern: E:@..@
labels.push_str(poppedlab); labels.push_str(".value,");
}
patterns.push_str(&gsym.label[atindex+1..]); patterns.push(',');
} // @@ pattern exists, with or without label
else if gsym.label.len()>0 && gsym.label.contains('(') // simple label like E:(a,b)
{ // label exists but only simple pattern
labels.push_str(poppedlab); labels.push_str(".value,");
patterns.push_str(&gsym.label[..]); // non-mutable
patterns.push(',')
}// simple label
// else simple label is not a pattern, so do nothing
k -= 1;
}// for each symbol on right hand side of rule
// form if let pattern=labels ...
let defaultaction = format!("<{}>::default()}}",absyn);
let mut semaction = &self.Gmr.Rules[i].action; //string that ends with }
if semaction.len()<=1 {semaction = &defaultaction;}
if labels.len()<2 { write!(fd,"{};\n",semaction.trim_end())?; } //empty pattern
else { // write an if-let
labels.push(')'); patterns.push(')');
write!(fd,"\n if let {}={} {{ {} else {{parser.bad_pattern(\"{}\")}} }};\n",&patterns,&labels,semaction.trim_end(),&patterns)?;
}// if-let semantic action
write!(fd," parser1.Rules.push(rule);\n")?;
}// for each rule
write!(fd," parser1.Errsym = \"{}\";\n",&self.Gmr.Errsym)?;
// resynch vector
for s in &self.Gmr.Resynch {write!(fd," parser1.resynch.insert(\"{}\");\n",s)?;}
// generate code to load RSM from TABLE
write!(fd,"\n for i in 0..{} {{\n",totalsize)?;
write!(fd," let symi = ((TABLE[i] & 0x0000ffff00000000) >> 32) as usize;\n")?;
write!(fd," let sti = ((TABLE[i] & 0xffff000000000000) >> 48) as usize;\n")?;
write!(fd," parser1.RSM[sti].insert(SYMBOLS[symi],decode_action(TABLE[i]));\n }}\n\n")?;
// write!(fd,"\n for i in 0..{} {{for k in 0..{} {{\n",rows,cols)?;
// write!(fd," parser1.RSM[i].insert(SYMBOLS[k],decode_action(TABLE[i*{}+k]));\n }}}}\n",cols)?;
write!(fd," for s in SYMBOLS {{ parser1.Symset.insert(s); }}\n\n")?;
write!(fd," load_extras(&mut parser1);\n")?;
write!(fd," return parser1;\n")?;
write!(fd,"}} //make_parser\n\n")?;
////// WRITE parse_with and parse_train_with
let lexerlt = if has_lt {<opt} else {"<'t>"};
let traitlt = if has_lt {&self.Gmr.lifetime} else {"'t"};
let lexername = format!("{}lexer{}",&self.Gmr.name,lexerlt);
let abindex = *self.Gmr.enumhash.get(absyn).unwrap();
write!(fd,"pub fn parse_with{}(parser:&mut ZCParser<{},{}>, lexer:&mut dyn Tokenizer<{},{}>) -> Result<{},{}>\n{{\n",lexerlt,absyn,extype,traitlt,absyn,absyn,absyn)?;
write!(fd," let _xres_ = parser.parse(lexer); ")?;
write!(fd," if !parser.error_occurred() {{Ok(_xres_)}} else {{Err(_xres_)}}\n}}//parse_with public function\n")?;
// training version
write!(fd,"\npub fn parse_train_with{}(parser:&mut ZCParser<{},{}>, lexer:&mut dyn Tokenizer<{},{}>, parserpath:&str) -> Result<{},{}>\n{{\n",lexerlt,absyn,extype,traitlt,absyn,absyn,absyn)?;
write!(fd," let _xres_ = parser.parse_train(lexer,parserpath); ")?;
write!(fd," if !parser.error_occurred() {{Ok(_xres_)}} else {{Err(_xres_)}}\n}}//parse_train_with public function\n")?;
////// WRITE LEXER
if self.Gmr.genlex { self.Gmr.genlexer(&mut fd,"from_raw")?; }
////// AUGMENT!
write!(fd,"fn load_extras{}(parser:&mut ZCParser<{},{}>)\n{{\n",<opt,absyn,extype)?;
write!(fd,"}}//end of load_extras: don't change this line as it affects augmentation\n")?;
Ok(())
}//writezcparser
/////////////////////LBA VERSION//////////////////////////////////////
///// semantic acition fn is _semaction_for_{rule index}
////////////////////////////////////////////////
//////////////////////////// write parser for LBox<dyn Any>
pub fn writelbaparser(&self, filename:&str)->Result<(),std::io::Error>
{
let ref absyn = self.Gmr.Absyntype;
if !is_lba(absyn) /*absyn!="LBox<dyn Any>" && absyn!="LBox<Any>"*/ {
return self.writezcparser(filename);
}
let ref extype = self.Gmr.Externtype;
let ref lifetime = self.Gmr.lifetime;
let has_lt = lifetime.len()>0 && (absyn.contains(lifetime) || extype.contains(lifetime));
let ltopt = if has_lt {format!("<{}>",lifetime)} else {String::from("")};
let rlen = self.Gmr.Rules.len();
// generate action fn's from strings stored in gen-time grammar
let mut actions:Vec<String> = Vec::with_capacity(rlen);
for ri in 0..rlen
{
let lhs = &self.Gmr.Rules[ri].lhs.sym;
let lhsi = &self.Gmr.Rules[ri].lhs.index;
//self.Gmr.Symhash.get(lhs).expect("GRAMMAR REPRESENTATION CORRUPTED");
let rettype = &self.Gmr.Symbols[*lhsi].rusttype; // return type
let ltoptr = if has_lt || (lifetime.len()>0 && rettype.contains(lifetime))
{format!("<{}>",lifetime)} else {String::from("")};
let mut fndef = format!("fn _semaction_for_{}_{}(parser:&mut ZCParser<{},{}>) -> {} {{\n",ri,<optr,absyn,extype,rettype);
let mut k = self.Gmr.Rules[ri].rhs.len();
//form if-let labels and patterns as we go...
let mut labels = String::from("(");
let mut patterns = String::from("(");
while k>0 // k is length of right-hand side
{
let gsym = &self.Gmr.Rules[ri].rhs[k-1]; // rhs symbols right to left...
let gsymi = gsym.index; //*self.Gmr.Symhash.get(&gsym.sym).unwrap();
let findat = gsym.label.find('@');
let mut plab = format!("_item{}_",k-1);
match &findat {
None if gsym.label.len()>0 => {plab = format!("{}",&gsym.label);},
Some(ati) if *ati>0 => {plab=format!("{}",&gsym.label[0..*ati]);},
_ => {},
}//match
let poppedlab = plab.as_str();
let ref symtype = self.Gmr.Symbols[gsymi].rusttype; //gsym.rusttype;
let mut stat = format!("let mut {} = lbdown!(parser.popstack().value,{}); ",poppedlab,symtype); // no longer stackitem but lbdown!
if symtype.len()<2 || symtype=="LBox<dyn Any>" || symtype=="LBox<Any>" {
stat = format!("let mut {} = parser.popstack().value; ",poppedlab);
// no need for lbdown if type is already LBA
}
fndef.push_str(&stat);
// poppedlab now bound to lbdown!
if gsym.label.len()>1 && findat.is_some() { // if-let pattern
labels.push_str("&mut *"); // for if-let // *box.exp gets value
labels.push_str(poppedlab); /*labels.push_str(".exp");*/ labels.push(',');
// closing @ trimed in grammar_processor.rs
let atindex = findat.unwrap();
patterns.push_str(&gsym.label[atindex+1..]); patterns.push(',');
} // @@ pattern exists, with or without label
k -= 1;
}// for each symbol on right hand side of rule (while k)
// form if let pattern=labels ...
let defaultaction = format!("<{}>::default()}}",rettype);
let mut semaction = &self.Gmr.Rules[ri].action; //string that ends w/ rbr
if semaction.len()<=1 {semaction = &defaultaction;}
if labels.len()<2 {
fndef.push_str(semaction.trim_end()); fndef.push_str("\n");
} //empty pattern
else { // write an if-let
labels.push(')'); patterns.push(')');
let pat2= format!("\n if let {}={} {{ {} else {{parser.report(\"{}\"); <{}>::default()}} }}\n",&patterns,&labels,semaction.trim_end(),&patterns,rettype);
fndef.push_str(&pat2);
}// if-let semantic action
actions.push(fndef);
}// generate action function for each rule (for ri..
////// write to file
let mut fd = File::create(filename)?;
write!(fd,"//Parser generated by rustlr for grammar {}",&self.Gmr.name)?;
write!(fd,"\n
#![allow(unused_variables)]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![allow(unused_parens)]
#![allow(unused_mut)]
#![allow(unused_imports)]
#![allow(unused_assignments)]
#![allow(dead_code)]
#![allow(irrefutable_let_patterns)]
use std::any::Any;
use std::rc::Rc;
use std::cell::RefCell;
extern crate rustlr;
use rustlr::{{Tokenizer,TerminalToken,ZCParser,ZCRProduction,Stateaction,decode_action,LBox,lbdown,lbup,lbget,unbox}};\n")?;
if self.Gmr.genlex {
write!(fd,"use rustlr::{{StrTokenizer,RawToken,LexSource}};
use std::collections::{{HashMap,HashSet}};\n")?;
}
write!(fd,"{}\n",&self.Gmr.Extras)?; // use clauses and such
// write static array of symbols
write!(fd,"static SYMBOLS:[&'static str;{}] = [",self.Gmr.Symbols.len())?;
for i in 0..self.Gmr.Symbols.len()-1
{
write!(fd,"\"{}\",",&self.Gmr.Symbols[i].sym)?;
}
write!(fd,"\"{}\"];\n\n",&self.Gmr.Symbols[self.Gmr.Symbols.len()-1].sym)?;
// position of symbols must be inline with self.Gmr.Symhash
// record table entries in a static array
let mut totalsize = 0;
for i in 0..self.FSM.len() { totalsize+=self.FSM[i].len(); }
write!(fd,"static TABLE:[u64;{}] = [",totalsize)?;
// generate table to represent FSM
let mut encode:u64 = 0;
for i in 0..self.FSM.len() // for each state index i
{
let row = &self.FSM[i]; ////////LBA VERSION
for key in row.keys()
{ // see function decode for opposite translation
let k = *key; //*self.Gmr.Symhash.get(key).unwrap(); // index of symbol
encode = ((i as u64) << 48) + ((k as u64) << 32);
match row.get(key) {
Some(Shift(statei)) => { encode += (*statei as u64) << 16; },
Some(Gotonext(statei)) => { encode += ((*statei as u64) << 16)+1; },
Some(Reduce(rulei)) => { encode += ((*rulei as u64) << 16)+2; },
Some(Accept) => {encode += 3; },
_ => {encode += 4; }, // 4 indicates Error
}//match
write!(fd,"{},",encode)?;
} //for symbol index k
}//for each state index i
write!(fd,"];\n\n")?;
// write action functions
for deffn in &actions { write!(fd,"{}",deffn)?; }
// must know what absyn type is when generating code.
write!(fd,"\npub fn make_parser{}() -> ZCParser<{},{}>",<opt,absyn,extype)?;
write!(fd,"\n{{\n")?;
// write code to pop stack, assign labels to variables.
write!(fd," let mut parser1:ZCParser<{},{}> = ZCParser::new({},{});\n",absyn,extype,self.Gmr.Rules.len(),self.FSM.len())?;
// generate rules and Ruleaction delegates to call action fns
write!(fd," let mut rule = ZCRProduction::<{},{}>::new_skeleton(\"{}\");\n",absyn,extype,"start")?; // dummy for init
for i in 0..self.Gmr.Rules.len()
{
write!(fd," rule = ZCRProduction::<{},{}>::new_skeleton(\"{}\");\n",absyn,extype,self.Gmr.Rules[i].lhs.sym)?;
write!(fd," rule.Ruleaction = |parser|{{ ")?;
// write code to call action function, then enclose in lba
let lhsi = self.Gmr.Symhash.get(&self.Gmr.Rules[i].lhs.sym).expect("GRAMMAR REPRESENTATION CORRUPTED");
let fnname = format!("_semaction_for_{}_",i);
let typei = &self.Gmr.Symbols[*lhsi].rusttype;
if is_lba(typei) {
write!(fd," {}(parser) }};\n",&fnname)?;
}
else {
write!(fd," lbup!( LBox::new({}(parser),parser.linenum,parser.column)) }};\n",&fnname)?;
}
write!(fd," parser1.Rules.push(rule);\n")?;
}// write each rule action
write!(fd," parser1.Errsym = \"{}\";\n",&self.Gmr.Errsym)?;
// resynch vector
for s in &self.Gmr.Resynch {write!(fd," parser1.resynch.insert(\"{}\");\n",s)?;}
// generate code to load RSM from TABLE
write!(fd,"\n for i in 0..{} {{\n",totalsize)?;
write!(fd," let symi = ((TABLE[i] & 0x0000ffff00000000) >> 32) as usize;\n")?;
write!(fd," let sti = ((TABLE[i] & 0xffff000000000000) >> 48) as usize;\n")?;
write!(fd," parser1.RSM[sti].insert(SYMBOLS[symi],decode_action(TABLE[i]));\n }}\n\n")?;
// write!(fd,"\n for i in 0..{} {{for k in 0..{} {{\n",rows,cols)?;
// write!(fd," parser1.RSM[i].insert(SYMBOLS[k],decode_action(TABLE[i*{}+k]));\n }}}}\n",cols)?;
write!(fd," for s in SYMBOLS {{ parser1.Symset.insert(s); }}\n\n")?;
write!(fd," load_extras(&mut parser1);\n")?;
write!(fd," return parser1;\n")?;
write!(fd,"}} //make_parser\n\n")?;
////// WRITE ENUM (test)
if !self.Gmr.sametype { self.Gmr.gen_enum(&mut fd)?; }
////// WRITE LEXER
if self.Gmr.genlex { self.Gmr.genlexer(&mut fd,"raw_to_lba")?; }
////// Augment!
write!(fd,"fn load_extras{}(parser:&mut ZCParser<{},{}>)\n{{\n",<opt,absyn,extype)?;
write!(fd,"}}//end of load_extras: don't change this line as it affects augmentation\n")?;
Ok(())
}//writelbaparser
//write-verbose no longer supported
} // impl Statemachine
/*
////// independent function
fn iserror(actionopt:&Option<&Stateaction>) -> bool
{
match actionopt {
None => true,
Some(Error(_)) => true,
_ => false,
}
}//iserror
*/
////// independent function
#[cfg(feature = "generator")]
fn is_lba(t:&str) -> bool {
t.trim().starts_with("LBox") && t.contains("Any") && t.contains('<') && t.contains('>')
// for s in ["", "LBox<dyn Any>","LBox<Any>","LBox< dyn Any>","LBox<dyn Any >",
// "LBox< dyn Any >"] { if s==t {return true;}}
// return false;
}//is_lba to check type
///////////////////////////////////////////////////////////////////////////
////// reimplementing the parsing algorithm more modularly, with aim of
////// allowing custom parsers
//////////// errors should compile a report
impl<AT:Default,ET:Default> ZCParser<AT,ET>
{
/// Error recovery routine of rustlr, separate from error_reporter.
/// This function will modify the parser and lookahead symbol and return
/// either the next action the parser should take (if recovery succeeded)
/// or None if recovery failed.
pub fn error_recover<'t>(&mut self, lookahead:&mut TerminalToken<'t,AT>, tokenizer:&mut dyn Tokenizer<'t,AT>) -> Option<Stateaction>
{
let mut erraction = None;
///// prefer to ue Errsym method
if self.Errsym.len()>0 {
let errsym = self.Errsym;
// lookdown stack for state with transition on Errsym
// but that could be current state too (start at top)
let mut k = self.stack.len(); // offset by 1 because of usize
let mut spos = k+1;
while k>0 && spos>k
{
let ksi = self.stack[k-1].si;
erraction = self.RSM[ksi].get(errsym);
if let None = erraction {k-=1;} else {spos=k;}
}//while k>0
if spos==k { self.stack.truncate(k); } // new current state revealed
// run all reduce actions that are valid before the Errsym:
while let Some(Reduce(ri)) = erraction // keep reducing
{
//self.reduce(ri); // borrow error- only need mut self.stack
self.popped.clear();
let rulei = &self.Rules[*ri];
let ruleilhs = rulei.lhs; // &'static : Copy
//let mut dummy = RuntimeParser::new(1,1);
let val = (rulei.Ruleaction)(self);
let newtop = self.stack[self.stack.len()-1].si;
let gotonopt = self.RSM[newtop].get(ruleilhs);
match gotonopt {
Some(Gotonext(nsi)) => {
//self.stack.push(Stackelement{si:*nsi,value:val});
self.stack.push(StackedItem::new(*nsi,val,self.linenum,self.column));
},// goto next state after reduce
_ => {self.abort("recovery failed"); },
}//match
// end reduce
let tos=self.stack[self.stack.len()-1].si;
erraction = self.RSM[tos].get(self.Errsym).clone();
} // while let erraction is reduce
// remaining defined action on Errsym must be shift
if let Some(Shift(i)) = erraction { // simulate shift errsym
self.stack.push(StackedItem::new(*i,AT::default(),lookahead.line,lookahead.column));
// keep lookahead until action is found that transitions from
// current state (i). but skipping ahead without reducing
// the error production is not a good idea. This implementation
// does NOT assume that everything following the ERROR symbol is
// terminal.
while let None = self.RSM[*i].get(lookahead.sym) {
if lookahead.sym=="EOF" {break;}
*lookahead = tokenizer.next_tt();
}//while let
// either at end of input or found action on next symbol
erraction = self.RSM[*i].get(lookahead.sym);
} // if shift action found down under stack
}//errsym exists
// at this point, if erraction is None, then Errsym failed to recover,
// try the resynch symbol method next ...
if iserror(&erraction) && self.resynch.len()>0 {
while lookahead.sym!="EOF" &&
!self.resynch.contains(lookahead.sym) {
self.linenum = lookahead.line; self.column = lookahead.column; self.prev_position=self.position; self.position = tokenizer.position();
*lookahead = tokenizer.next_tt();
}//while
if lookahead.sym!="EOF" {
// look for state on stack that has action defined on next symbol
self.linenum = lookahead.line; self.column = lookahead.column; self.prev_position=self.position; self.position=tokenizer.position();
*lookahead = tokenizer.next_tt();
}
let mut k = self.stack.len()-1; // offset by 1 because of usize
let mut position = 0;
while k>0 && erraction==None
{
let ksi = self.stack[k-1].si;
erraction = self.RSM[ksi].get(lookahead.sym);
if let None=erraction {k-=1;}
}//while k>0 && erraction==None
match erraction {
None => {}, // do nothing, whill shift next symbol
_ => { self.stack.truncate(k);},//pop stack
}//match
}// there are resync symbols
// at this point, if erraction is None, then resynch recovery failed too.
// only action left is to skip ahead...
let mut eofcx = 0;
while iserror(&erraction) && eofcx<1 { //skip input
self.linenum = lookahead.line; self.column = lookahead.column; self.prev_position=self.position; self.position=tokenizer.position();
*lookahead = tokenizer.next_tt();
//*lookahead = self.nexttoken();
if lookahead.sym=="EOF" {eofcx+=1;}
let csi =self.stack[self.stack.len()-1].si;
erraction = self.RSM[csi].get(lookahead.sym);
}// skip ahead
match erraction {
Some(act) if eofcx<1 => Some(*act),
_ => None,
}//return match
}//error_recover function
/// resets parser, including external state
pub fn reset(&mut self) {
self.stack.clear();
self.err_occurred = false;
let mut result = AT::default();
self.exstate = ET::default();
}//reset
/// Retrieves recorded error report. This function will return an empty string
/// if [ZCParser::set_err_report] is not called. It will also return an
/// empty string if there was no error
pub fn get_err_report(&self) -> &str {
self.err_report.as_deref().unwrap_or("")
}
/// When given true as argument, this option will disable the output of
/// parser errors to stderr, and instead log them internally until retrieved
/// with [ZCParser::get_err_report]. Each call to this function will
/// clear the previous report and begin a new one.
/// If the bool argument is false, it will erase and turn off error logging
/// and print all parser errors to stderr. This function does not affect
/// interactive training, which uses stdio.
pub fn set_err_report(&mut self, onof:bool) {
if onof {self.err_report = Some(String::new());}
else {self.err_report = None;}
}
}//impl ZCParser 2
/////////////////////////////////////////////////////////////////////////
/////////////// new approach using more flexible trait object
/// A trait object that implements ErrReporter is expected by the [ZCParser::parse_core]
/// function, which implements the basic LR parsing algorithm using the
/// generated state machine. The struct [StandardReporter] is provided as
/// the default ErrReporter that uses standard I/O as interface and has the
/// ability to train the parser. But other implementations of the trait
/// can be created that use different interfaces, such as a graphical IDE.
///
/// This trait replaces [crate::ErrHandler] in the [crate::runtime_parser] module.
pub trait ErrReporter<AT:Default,ET:Default> // not same as error recovery
{
fn err_reporter(&mut self, parser:&mut ZCParser<AT,ET>, lookahead:&TerminalToken<AT>, erropt:&Option<Stateaction>, tokenizer:& dyn Tokenizer<'_,AT>);
fn report_err(&self, parser:&mut ZCParser<AT,ET>, msg:&str) { parser.report(msg) }
// fn training_mode(&self, parser:&ZCParser<AT,ET>) -> bool {false}
// fn interactive_mode(&self, parser:&ZCParser<AT,ET>) -> bool {false}
}// ErrReporter trait // not same as RuntimeParser::ErrHandler
/*
The structure here is a bit strange. The script file is written to in
interactive training mode and read from in script-training mode. However,
the actual modification of the parser file is done after the training, by
the augmenter module. Thus there's another wrapper function that's needed
besides the creation of the right kind of StandardReporter.
*/
impl<AT:Default,ET:Default> ErrReporter<AT,ET> for StandardReporter
{
// this function will be able to write training script to file
fn err_reporter(&mut self, parser:&mut ZCParser<AT,ET>, lookahead:&TerminalToken<AT>, erropt:&Option<Stateaction>, tokenizer:& dyn Tokenizer<'_,AT>)
{
let mut wresult:std::io::Result<()> = Err(std::io::Error::new(std::io::ErrorKind::Other,"")); // dummy
// known that actionop is None or Some(Error(_))
let cstate = parser.stack[parser.stack.len()-1].si; // current state
let mut actionopt = if let Some(act)=erropt {Some(act)} else {None};
let lksym = &lookahead.sym[..];
// is lookahead recognized as a grammar symbol?
// if actionopt is NONE, check entry for ANY_ERROR
if parser.Symset.contains(lksym) {
if let None=actionopt {
actionopt = parser.RSM[cstate].get("ANY_ERROR");
}
}// lookahead is recognized grammar sym
else {
actionopt = parser.RSM[cstate].get("ANY_ERROR");
}// lookahead is not a grammar sym
let mut errmsg = if let Some(Error(em)) = &actionopt {
format!("unexpected symbol '{}' on line {}, column {}: ** {} ** ..",lksym,lookahead.line,lookahead.column,em.trim())
} else {format!("unexpected symbol '{}' on line {}, column {} .. ",lksym,lookahead.line,lookahead.column)};
////// augment errmsg with current line (version 0.2.6)
let srcline = tokenizer.current_line();
if (srcline.len()>0) {
errmsg.push_str("\n >>");
errmsg.push_str(srcline);
errmsg.push_str("\n");
let mut cln = lookahead.column+2;
while cln>0 { errmsg.push(' '); cln-=1; }
//let mut tokenlen = srcline[cln-2..].find(char::is_whitespace).unwrap_or(1);
let mut tokenlen = lookahead.sym.len();
if is_alphanum(&lookahead.sym) {tokenlen = 3;}
while tokenlen>0 { errmsg.push('^'); tokenlen-=1; }
errmsg.push('\n');
}// augment errmsg with current line
parser.report(&errmsg);
if self.training { ////// Training mode
let csym = lookahead.sym.to_owned();
let mut inp = String::from("");
if let None=self.scriptinopt { // interactive mode
if let Some(outfd1) = &self.scriptoutopt {
let mut outfd = outfd1;
print!("\n>>>TRAINER: if this message is not adequate (for state {}), enter a replacement (default no change): ",cstate);
let rrrflush = io::stdout().flush();
if let Ok(n) = io::stdin().read_line(&mut inp) {
if inp.len()>5 && parser.Symset.contains(lksym) {
print!(">>>TRAINER: should this message be given for all unexpected symbols in the current state? (default yes) ");
let rrrflush2 = io::stdout().flush();
let mut inp2 = String::new();
if let Ok(n) = io::stdin().read_line(&mut inp2) {
if inp2.trim()=="no" || inp2.trim()=="No" {
wresult = write!(outfd,"{}\t{}\t{} ::: {}\n",lookahead.line,lookahead.column,&csym,inp.trim());
self.trained.insert((cstate,csym),inp);
}
else {// insert for any error
wresult = write!(outfd,"{}\t{}\t{} ::: {}\n",lookahead.line,lookahead.column,"ANY_ERROR",inp.trim());
self.trained.insert((cstate,String::from("ANY_ERROR")),inp);
}
}// read ok
}// unexpected symbol is grammar sym
else if inp.len()>5 && !parser.Symset.contains(lksym) {
wresult = write!(outfd,"{}\t{}\t{} ::: {}\n",lookahead.line,lookahead.column,"ANY_ERROR",inp.trim());
self.trained.insert((cstate,String::from("ANY_ERROR")),inp);
}
}// process user response
}}// interactive mode
else { // training from script mode (non-interactive)
if let Some(brfd) = &mut self.scriptinopt {
let mut scin = brfd;
let mut readn = 0;
while readn < 1
{
inp = String::new();
match scin.read_line(&mut inp) {
Ok(n) if n>1 && &inp[0..1]!="#" && inp.trim().len()>0 => {readn=n;},
Ok(n) if n>0 => { readn=0; }, // keep reading
_ => {readn = 1; } // stop - this means End of Stream
}//match
if readn>1 { // read something
let inpsplit:Vec<&str> = inp.split_whitespace().collect();
if inpsplit.len()>4 && inpsplit[3].trim()==":::" {
let inline = inpsplit[0].trim().parse::<usize>().unwrap();
let incolumn = inpsplit[1].trim().parse::<usize>().unwrap();
let insym = inpsplit[2].trim();
if parser.linenum==inline && parser.column==incolumn {
if &csym==insym || insym=="ANY_ERROR" {
let posc = inp.find(":::").unwrap()+4;
println!("\n>>>Found matching entry from training script for {}, error message: {}",insym,&inp[posc..]);
self.trained.insert((cstate,String::from(insym)),String::from(&inp[posc..]));
} // unexpected symbol match
}// line/column match
}//inpsplit check
}// valid training line read
}//while readn<2
}}//training from script mode
}//if training //// END TRAINING MODE
}// standardreporter function
}// impl ErrReporter for StandardReporter
/////////////////////////////////////////////////////////////
//////////////// parse_core replaced: now uses zc tokenizer
impl<AT:Default,ET:Default> ZCParser<AT,ET>
{
/// This function provides a core parser that uses the LR state machine
/// generated by rustlr. It takes as trait objects a tokenizer and an
/// [ErrReporter] object that handles the display of error messages.
/// This function will reset the parse stack but it will not reset the
/// Tokenizer or the *external state* of the parser.
pub fn parse_core<'u,'t:'u>(&mut self, tokenizer:&'u mut dyn Tokenizer<'t,AT>, err_handler:&mut dyn ErrReporter<AT,ET>) -> AT
{
self.stack.clear();
self.err_occurred = false;
let mut result = AT::default();
//self.exstate = ET::default();
self.stack.push(StackedItem::new(0,AT::default(),0,0));
self.stopparsing = false;
let mut action = Stateaction::Error("");
let mut lookahead = TerminalToken::new("EOF",AT::default(),0,0); //just init
// nextsym() should only be called here
if let Some(tok) = tokenizer.nextsym() {lookahead=tok;}
//else {self.stopparsing=true;}
while !self.stopparsing
{
let tos = self.stack.len()-1;
self.linenum = self.stack[tos].line;
self.column=self.stack[tos].column;
//self.prev_position = tokenizer.previous_position();
//self.position = tokenizer.position();
let currentstate = self.stack[tos].si;
let mut actionopt = self.RSM[currentstate].get(lookahead.sym);
if actionopt.is_none() && lookahead.sym!="EOF" { // added in version 0.2.9
actionopt = self.RSM[currentstate].get("_WILDCARD_TOKEN_");
// added for 0.2.94:
lookahead = tokenizer.transform_wildcard(lookahead);
}
let actclone:Option<Stateaction> = match actionopt {
Some(a) => Some(*a),
None => None,
};
if iserror(&actionopt) { // either None or Error
if !self.err_occurred {self.err_occurred = true;}
err_handler.err_reporter(self,&lookahead,&actclone, tokenizer);
match self.error_recover(&mut lookahead,tokenizer) {
None => { self.stopparsing=true; break; }
Some(act) => {action = act;}, // lookahead=la;},
}//match
}// iserror
else { action = actclone.unwrap(); }
match &action {
Shift(nextstate) => {
lookahead = self.shift(*nextstate,lookahead,tokenizer);
},
Reduce(rulei) => { self.reduce(rulei); },
Accept => {
self.stopparsing=true;
if self.stack.len()>0 {result = self.stack.pop().unwrap().value;}
else {self.err_occurred=true;}
},
_ => {}, // continue
}//match action
}// main parse loop
return result;
}//parse_core
///provided generic parsing function that reports errors on std::io.
pub fn parse<'t>(&mut self, tokenizer:&mut dyn Tokenizer<'t,AT>) -> AT
{
let mut stdeh = StandardReporter::new();
self.parse_core(tokenizer,&mut stdeh)
}//parse_stdio
///Parses in interactive training mode with provided path to parserfile.
///The parser file will be modified and a training script file will be
///created for future retraining after grammar is modified.
///
/// When an error occurs, the parser will
/// ask the human trainer for an appropriate error message: it will
/// then insert an entry into its state transition table to
/// give the same error message on future errors of the same type.
/// If the error is caused by an unexpected token that is recognized
/// as a terminal symbol of the grammar, the trainer can select to
/// enter the entry
/// under the reserved ANY_ERROR symbol. If the unexpected token is
/// not recognized as a grammar symbol, then the entry will always
/// be entered under ANY_ERROR. ANY_ERROR entries for a state will match
/// all future unexpected symbols for that state: however, entries for
/// valid grammar symbols will still override the generic entry.
///
/// Example: with the parser for this [toy grammar](https://cs.hofstra.edu/~cscccl/rustlr_project/cpm.grammar), parse_train can run as follows:
///```ignore
/// Write something in C+- : cout << x y ;
/// ERROR on line 1, column 0: unexpected symbol y ..
/// >>>TRAINER: is this error message adequate? If not, enter a better one: need another <<
/// >>>TRAINER: should this message be given for all unexpected symbols in the current state? (default yes) yes
///```
/// (ignore the column number as the lexer for this toy language does not implement it)
///
/// parse_train will then produced a [modified parser](https://cs.hofstra.edu/~cscccl/rustlr_project/cpmparser.rs) as specified
/// by the filename (path) argument. When the augmented parser is used, it will
/// give a more helpful error message:
///```
/// Write something in C+- : cout << x endl
/// ERROR on line 1, column 0: unexpected symbol endl, ** need another << ** ..
///```
///
/// parse_stdio_train calls parse_stdio, which uses stdin/stdout for user interface.
/// Parsing in interactive training mode also produces a [training script file](http://cs.hofstra.edu/~cscccl/rustlr_project/cpmparser.rs_script.txt) which can
/// be used to re-train a parser using [ZCParser::train_from_script].
/// This is useful after a grammar is modified with extensions to a language.
pub fn parse_train<'t>(&mut self, tokenizer:&mut dyn Tokenizer<'t,AT>, parserfile:&str) -> AT
{
let mut stdtrainer = StandardReporter::new_interactive_training(parserfile);
let result = self.parse_core(tokenizer,&mut stdtrainer);
if let Err(m) = stdtrainer.augment_training(parserfile) {
eprintln!("Error in augmenting parser: {:?}",m)
}
return result;
}//parse_stdio_train
/// trains parser from a [training script](https://cs.hofstra.edu/~cscccl/rustlr_project/cpmparser.rs_script.txt)
/// created by interactive training. This
/// is intended to be used after a grammar has been modified and the parser
/// is regenerated with different state numbers. It is the user's
/// responsibility to keep consistent the parser file, script file, and sample
/// input that was used when the script was created. The script contains
/// the line and column numbers of each error encountered, along with either
/// the unexpected symbol that caused the error, or the reserved ANY_ERROR
/// symbol if the error message is to be applied to all unexpected symbols.
/// These entries must match, in sequence, the errors encountered during
/// retraining - it is therefore recommended that the same tokenizer be used
/// during retraining so that the same line/column information are given.
/// The trainer will augment the parser (parserfile) with new Error
/// entries, overriding any previous ones. It is also recommended that the
/// user examines the "load_extras" function that appears at the end of
/// the [augmented parser](https://cs.hofstra.edu/~cscccl/rustlr_project/cpmparser.rs).
/// The train_from_script function does not return
/// a value, unlike [ZCParser::parse] and [ZCParser::parse_train].
pub fn train_from_script<'t>(&mut self, tokenizer:&mut dyn Tokenizer<'t,AT>,parserfile:&str, scriptfile:&str)
{
let mut stdtrainer = StandardReporter::new_script_training(parserfile,scriptfile);
let result = self.parse_core(tokenizer,&mut stdtrainer);
if let Err(m) = stdtrainer.augment_training(parserfile) {
eprintln!("Error in augmenting parser: {:?}",m)
}
if !self.err_occurred {println!("no errors encountered during parsing");}
}//train_from_script
}// 3rd impl ZCParser
#[cfg(feature = "generator")]
fn checkboxlabel(s:&str) -> &str
{
if s.starts_with('[') && s.ends_with(']') {s[1..s.len()-1].trim()} else {s}
}// check if label is of form [x], returns x, or s if not of this form.
// used by genlex routines
fn is_alphanum(x:&str) -> bool
{
// let alphan = Regex::new(r"^[_a-zA-Z][_\da-zA-Z]*$").unwrap();
// alphan.is_match(x)
if x.len()<1 {return false};
let mut chars = x.chars();
let first = chars.next().unwrap();
if !(first=='_' || first.is_alphabetic()) {return false;}
for c in chars
{
if !(c=='_' || c.is_alphanumeric()) {return false;}
}
true
}//is_alphanum