#![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::collections::{HashMap,HashSet,BTreeSet};
use std::cell::{RefCell,Ref,RefMut};
use std::hash::{Hash,Hasher};
use std::io::{self,Read,Write,BufReader,BufRead};
use std::fs::File;
use std::io::prelude::*;
pub const DEFAULTPRECEDENCE:i32 = 20;
pub const TRACE:usize = 0;
#[derive(Clone)]
pub struct Gsym {
pub sym : String,
pub rusttype : String, pub terminal : bool,
pub label : String, pub precedence : i32, }
impl Gsym
{
pub fn new(s:&str,isterminal:bool) -> Gsym {
Gsym {
sym : s.to_owned(),
terminal : isterminal,
label : String::default(),
rusttype : String::from("String"),
precedence : DEFAULTPRECEDENCE, }
}
pub fn setlabel(&mut self, la:&str)
{ self.label = String::from(la); }
pub fn settype(&mut self, rt:&str)
{ self.rusttype = String::from(rt); }
pub fn setprecedence(&mut self, p:i32)
{ self.precedence = p; }
}
pub struct Grule {
pub lhs : Gsym, pub rhs : Vec<Gsym>, pub action : String, pub precedence : i32, }
impl Grule
{
pub fn new_skeleton(lh:&str) -> Grule
{
Grule {
lhs : Gsym::new(lh,false),
rhs : Vec::new(),
action : String::default(),
precedence : 0,
}
}
}
pub fn printrule(rule:&Grule) {
print!("PRODUCTION: {} --> ",rule.lhs.sym);
for s in &rule.rhs {
print!("{}",s.sym);
if s.label.len()>0 {print!(":{}",s.label);}
print!(" ");
}
println!("{{ {}, preclevel {}",rule.action,rule.precedence); }
pub struct Grammar
{
pub name : String,
pub Symbols : Vec<Gsym>,
pub Symhash : HashMap<String,usize>,
pub Rules: Vec<Grule>,
pub topsym : String,
pub Nullable : HashSet<String>,
pub First : HashMap<String,HashSet<String>>,
pub Rulesfor: HashMap<String,HashSet<usize>>, pub Absyntype : String, pub Externtype : String, pub Resynch : HashSet<String>, pub Errsym : String, pub Lexnames : HashMap<String,String>, pub Extras : String, }
impl Grammar
{
pub fn new() -> Grammar
{
Grammar {
name : String::from(""), Symbols: Vec::new(), Symhash: HashMap::new(),
Rules: Vec::new(), topsym : String::default(), Nullable : HashSet::new(),
First : HashMap::new(),
Rulesfor: HashMap::new(),
Absyntype:String::from("i64"), Externtype:String::from(""), Resynch : HashSet::new(),
Errsym : String::new(),
Lexnames : HashMap::new(),
Extras: String::new(),
}
}
pub fn nonterminal(&self,s:&str) -> bool
{
match self.Symhash.get(s) {
Some(symi) => !self.Symbols[*symi].terminal,
_ => false,
}
}
pub fn terminal(&self,s:&str) -> bool
{
match self.Symhash.get(s) {
Some(symi) => self.Symbols[*symi].terminal,
_ => false,
}
}
fn using_generic(&self) -> bool
{ self.Absyntype=="GenAbsyn" || self.Absyntype=="ABox" }
pub fn parse_grammar(&mut self, filename:&str)
{
let mut reader = match File::open(filename) {
Ok(f) => { Some(BufReader::new(f)) },
_ => { eprintln!("cannot open file, reading from stdin..."); None},
};
let mut line=String::from("");
let mut atEOF = false;
let mut linenum = 0;
let mut linelen = 0;
let mut stage = 0;
let mut multiline = false; let mut foundeol = false;
while !atEOF
{
if !multiline {line = String::new();}
if foundeol { multiline=false;} else {
let result = if let Some(br)=&mut reader {br.read_line(&mut line)}
else {std::io::stdin().read_line(&mut line)};
match result {
Ok(0) | Err(_) => { line = String::from("EOF"); },
Ok(n) => {linenum+=1;},
} }
linelen = line.len();
if multiline && linelen>1 && &line[0..1]!="#" {
if linelen==3 && &line[0..3]=="EOF" {
panic!("MULTI-LINE GRAMMAR PRODUCTION DID NOT END WITH <==");
}
match line.rfind("<==") {
None => {}, Some(eoli) => {
line.truncate(eoli);
foundeol = true;
}
} }
else if linelen>1 && &line[0..1]=="!" {
self.Extras.push_str(&line[1..]);
}
else if linelen>1 && &line[0..1]!="#" {
let toksplit = line.split_whitespace();
let stokens:Vec<&str> = toksplit.collect();
if stokens.len()<1 {continue;}
match stokens[0] {
"use" => {
self.Extras.push_str("use ");
self.Extras.push_str(stokens[1]);
self.Extras.push_str("\n");
},
"extern" if stokens.len()>2 && stokens[1]=="crate" => {
self.Extras.push_str("extern crate ");
self.Extras.push_str(stokens[2]);
self.Extras.push_str("\n");
},
"!" => {
let pbi = line.find('!').unwrap();
self.Extras.push_str(&line[pbi+1..]);
self.Extras.push_str("\n");
},
"grammarname" | "grammar_name" => {
self.name = String::from(stokens[1]);
},
"EOF" => {atEOF=true},
("terminal" | "terminals") if stage==0 => {
for i in 1..stokens.len() {
let newterm = Gsym::new(stokens[i],true);
self.Symhash.insert(stokens[i].to_owned(),self.Symbols.len());
self.Symbols.push(newterm);
if TRACE>2 {println!("terminal {}",stokens[i]);}
}
}, "typedterminal" if stage==0 => {
let mut newterm = Gsym::new(stokens[1],true);
if stokens.len()>2 {newterm.settype(stokens[2]);}
self.Symhash.insert(stokens[1].to_owned(),self.Symbols.len());
self.Symbols.push(newterm);
}, "nonterminal" if stage==0 => {
let mut newterm = Gsym::new(stokens[1],false);
if stokens.len()>2 {newterm.settype(stokens[2]);}
self.Symhash.insert(stokens[1].to_owned(),self.Symbols.len());
self.Symbols.push(newterm);
}, "nonterminals" if stage==0 => {
for i in 1..stokens.len() {
let newterm = Gsym::new(stokens[i],false);
self.Symhash.insert(stokens[i].to_owned(),self.Symbols.len());
self.Symbols.push(newterm);
if TRACE>2 {println!("nonterminal {}",stokens[i]);}
}
},
"topsym" | "startsymbol" if stage==0 => {
match self.Symhash.get(stokens[1]) {
Some(tsi) if *tsi<self.Symbols.len() && !self.Symbols[*tsi].terminal => {
self.topsym = String::from(stokens[1]);
},
_ => { panic!("top symbol {} not found in declared non-terminals; check ordering of declarations, line {}",stokens[1],linenum);
},
} }, "errsym" | "errorsymbol" => {
if stage>1 {
panic!("!!! Error recover symbol must be declared before production rules, line {}",linenum);
}
if stage==0 {stage=1;}
if !self.terminal(stokens[1]) {
panic!("!!!Error recover symbol {} is not a terminal, line {} ",stokens[1],linenum);
}
self.Errsym = stokens[1].to_owned();
},
"resynch" | "resync" => {
if stage==0 {stage=1;}
for i in 1..stokens.len()
{
if !self.terminal(stokens[i]) {
panic!("!!!Error recovery re-synchronization symbol {} is not a declared terminal, line {}",stokens[i],linenum);
}
self.Resynch.insert(stokens[i].trim().to_owned());
} },
"absyntype" | "valuetype" if stage==0 => {
let pos = line.find(stokens[0]).unwrap() + stokens[0].len();
self.Absyntype = String::from(line[pos..].trim());
if TRACE>2 {println!("abstract syntax type is {}",&self.Absyntype);}
},
"externtype" | "externaltype" if stage==0 => {
let pos = line.find(stokens[0]).unwrap() + stokens[0].len();
self.Externtype = String::from(line[pos..].trim());
if TRACE>2 {println!("external structure type is {}",&self.Externtype);}
},
"left" | "right" if stage<2 => {
if stage==0 {stage=1;}
if stokens.len()<3 {continue;}
let mut preclevel:i32 = 0;
if let Ok(n)=stokens[2].parse::<i32>() {preclevel = n;}
else {panic!("did not read precedence level on line {}",linenum);}
if stokens[0]=="right" && preclevel>0 {preclevel = -1 * preclevel;}
if let Some(index) = self.Symhash.get(stokens[1]) {
self.Symbols[*index].precedence = preclevel;
}
}, "flexname" | "lexname" => {
if stokens.len()<3 {continue;}
self.Lexnames.insert(stokens[1].to_string(),stokens[2].to_string());
},
LHS if (stokens[1]=="-->" || stokens[1]=="::=" || stokens[1]=="==>") => {
if !foundeol && stokens[1]=="==>" {multiline=true; continue;}
else if foundeol {foundeol=false;}
if stage<2 {stage=2;}
let symindex = match self.Symhash.get(LHS) {
Some(smi) if *smi<self.Symbols.len() && !self.Symbols[*smi].terminal => smi,
_ => {panic!("unrecognized non-terminal symbol {}, line {}",LHS,linenum);},
};
let lhsym = &self.Symbols[*symindex];
let pos0 = line.find(stokens[1]).unwrap() + stokens[1].len();
let mut linec = line[pos0..].to_string();
let barsplit:Vec<_> = linec.split('|').collect();
for rul in &barsplit
{ let bstokens:Vec<_> = rul.trim().split_whitespace().collect();
let mut rhsyms:Vec<Gsym> = Vec::new();
let mut semaction = "}";
let mut i:usize = 0;
let mut maxprec:i32 = 0;
let mut seenerrsym = false;
while i<bstokens.len() {
let strtok = bstokens[i];
i+=1;
if strtok.len()>0 && &strtok[0..1]=="{" {
let position = rul.find('{').unwrap();
semaction = rul.split_at(position+1).1;
break;
}
let toks:Vec<&str> = strtok.split(':').collect();
if TRACE>2&&toks.len()>1 {println!("see labeled token {}",strtok);}
match self.Symhash.get(toks[0]) {
None => {panic!("unrecognized grammar symbol {}, line {}",toks[0],linenum); },
Some(symi) => {
let sym = &self.Symbols[*symi];
if self.Errsym.len()>0 && &sym.sym == &self.Errsym {
if !seenerrsym { seenerrsym = true; }
else { panic!("Error symbol {} can only appear once in a production, line {}",&self.Errsym,linenum); }
}
if !sym.terminal && seenerrsym {
panic!("Only terminal symbols may follow the error recovery symbol {}, line {}",&self.Errsym, linenum);
}
let mut newsym = sym.clone();
if toks.len()>1 && toks[1].trim().len()>0
{ newsym.setlabel(toks[1].trim()); }
if maxprec.abs() < newsym.precedence.abs() {
maxprec=newsym.precedence;
}
rhsyms.push(newsym);
}
} } let rule = Grule {
lhs : lhsym.clone(),
rhs : rhsyms,
action: semaction.to_owned(),
precedence : maxprec,
};
if TRACE>2 {printrule(&rule);}
self.Rules.push(rule);
} },
_ => {panic!("error parsing grammar on line {}, grammar stage {}",linenum,stage);},
} } } if self.Symhash.contains_key("START") || self.Symhash.contains_key("EOF") || self.Symhash.contains_key("ANY_ERROR")
{
panic!("Error in grammar: START and EOF are reserved symbols");
}
let startnt = Gsym::new("START",false);
let eofterm = Gsym::new("EOF",true);
self.Symhash.insert(String::from("START"),self.Symbols.len());
self.Symhash.insert(String::from("EOF"),self.Symbols.len()+1);
self.Symbols.push(startnt.clone());
self.Symbols.push(eofterm.clone());
let topgsym = &self.Symbols[*self.Symhash.get(&self.topsym).unwrap()];
let startrule = Grule { lhs:startnt,
rhs:vec![topgsym.clone()], action: String::default(),
precedence : 0,
};
self.Rules.push(startrule); if TRACE>0 {println!("{} rules in grammar",self.Rules.len());}
if self.Externtype.len()<1 {self.Externtype = self.Absyntype.clone();} }}
impl Grammar
{
pub fn compute_NullableRf(&mut self)
{
let mut changed = true;
let mut rulei:usize = 0;
while changed
{
changed = false;
rulei = 0;
for rule in &self.Rules
{
let mut addornot = true;
for gs in &rule.rhs
{
if gs.terminal || !self.Nullable.contains(&gs.sym) {addornot=false;}
} if (addornot) {
changed = self.Nullable.insert(rule.lhs.sym.clone()) || changed;
if TRACE>3 {println!("{} added to Nullable",rule.lhs.sym);}
}
if let None = self.Rulesfor.get(&rule.lhs.sym) {
self.Rulesfor.insert(rule.lhs.sym.clone(),HashSet::new());
}
let ruleset = self.Rulesfor.get_mut(&rule.lhs.sym).unwrap();
ruleset.insert(rulei);
rulei += 1;
} } }
pub fn compute_FirstIM(&mut self)
{
let mut FIRST:HashMap<String,RefCell<HashSet<String>>> = HashMap::new();
let mut changed = true;
while changed
{
changed = false;
for rule in &self.Rules
{
let ref nt = rule.lhs.sym; if !FIRST.contains_key(nt) {
changed = true;
FIRST.insert(String::from(nt),RefCell::new(HashSet::new()));
} let mut Firstnt = FIRST.get(nt).unwrap().borrow_mut();
let mut i = 0;
let mut isnullable = true;
while i< rule.rhs.len() && isnullable
{
let gs = &rule.rhs[i];
if gs.terminal {
changed=Firstnt.insert(gs.sym.clone()) || changed;
isnullable = false;
}
else if &gs.sym!=nt { if let Some(firstgs) = FIRST.get(&gs.sym) {
let firstgsb = firstgs.borrow();
for sym in firstgsb.iter() {
changed=Firstnt.insert(sym.clone())||changed;
}
} } if gs.terminal || !self.Nullable.contains(&gs.sym) {isnullable=false;}
i += 1;
} } } for nt in FIRST.keys() {
if let Some(rcell) = FIRST.get(nt) {
self.First.insert(nt.to_owned(),rcell.take());
}
}
}
pub fn Firstseq(&self, Gs:&[Gsym], la:&str) -> HashSet<String>
{
let mut Fseq = HashSet::new();
let mut i = 0;
let mut nullable = true;
while nullable && i<Gs.len()
{
if (Gs[i].terminal) {Fseq.insert(Gs[i].sym.clone()); nullable=false; }
else {
let firstgsym = self.First.get(&Gs[i].sym).unwrap();
for s in firstgsym { Fseq.insert(s.to_owned()); }
if !self.Nullable.contains(&Gs[i].sym) {nullable=false;}
}
i += 1;
} if nullable {Fseq.insert(la.to_owned());}
Fseq
}
}