1#![deny(unsafe_code)]
2
3use cfg_history::RootHistoryNode;
4use cfg_regexp::CfgRegexpExt;
5use cfg_symbol_bit_matrix::Remap;
6use tiny_earley::{Recognizer, Symbol, forest, grammar};
7
8use cfg_grammar::{Cfg, SymbolBitSet};
9use cfg_sequence::CfgSequenceExt;
10use std::{
11 collections::{BTreeMap, BTreeSet, HashMap, HashSet},
12 convert::AsRef,
13 iter,
14 str::Chars,
15};
16
17use elsa::FrozenIndexSet;
18
19pub use cfg_regexp::LexerMap;
20
21use crate::LoadError;
22pub struct StringInterner {
23 set: FrozenIndexSet<String>,
24}
25
26impl StringInterner {
27 pub fn new() -> Self {
28 StringInterner {
29 set: FrozenIndexSet::new(),
30 }
31 }
32
33 pub fn get_or_intern<T>(&self, value: T) -> usize
34 where
35 T: AsRef<str>,
36 {
37 self.set.insert_full(value.as_ref().to_string()).0
40 }
41
42 }
53
54#[derive(Clone, Debug)]
55struct Rule {
56 lhs: String,
57 rhs: Vec<Fragment>,
58 action: Option<String>,
59}
60
61#[derive(Clone, Debug)]
62enum Fragment {
63 Rhs { ident: String, rep: Rep },
64 Lex { string: String },
65 Call { func: String, arg: Box<Fragment> },
66}
67
68#[derive(Clone, Copy, Debug)]
69enum Rep {
70 None,
71 ZeroOrMore,
72 OneOrMore,
73}
74
75#[derive(Clone, Debug)]
76enum Value {
77 Ident(String),
78 String(String),
79 Start(Vec<Rule>, Option<LexerVal>),
80 Rules(Vec<Rule>),
81 Lex(LexerVal),
82 Rhs(Vec<(Vec<Fragment>, Option<String>)>),
83 Fragment(Fragment),
84 Alt(Vec<Fragment>),
85 Alt2(Vec<Fragment>, Option<String>),
86 None,
87}
88
89#[derive(Clone, Debug)]
90struct LexerVal(Vec<Rule>);
91
92struct Evaluator {
93 symbols: [Symbol; 24],
94 tokens: Vec<(Token, usize, usize)>,
95}
96
97impl forest::Eval for Evaluator {
98 type Elem = Value;
99
100 fn leaf(&self, terminal: Symbol, values: u32) -> Self::Elem {
101 #[allow(unused_variables)]
102 let [
103 start,
104 rule,
105 alt,
106 rhs,
107 bnf_op,
108 ident,
109 pipe,
110 op_mul,
111 op_plus,
112 semicolon,
113 fragment,
114 string,
115 decl,
116 action,
117 lexer_keyword,
118 lexer,
119 lbrace,
120 rbrace,
121 rules,
122 gt_op,
123 lparen,
124 rparen,
125 alt2,
126 tilde_op,
127 ] = self.symbols;
128 if terminal == ident {
129 self.tokens[values as usize].0.ident()
130 } else if terminal == string {
131 self.tokens[values as usize].0.string()
132 } else {
133 Value::None
134 }
135 }
136
137 fn product(&self, action_num: u32, args: Vec<Self::Elem>) -> Self::Elem {
138 #[allow(unused_variables)]
139 let [
140 start,
141 rule,
142 alt,
143 rhs,
144 bnf_op,
145 ident,
146 pipe,
147 op_mul,
148 op_plus,
149 semicolon,
150 fragment,
151 string,
152 decl,
153 action,
154 lexer_keyword,
155 lexer,
156 lbrace,
157 rbrace,
158 rules,
159 gt_op,
160 lparen,
161 rparen,
162 alt2,
163 tilde_op,
164 ] = self.symbols;
165 match (
167 action_num,
168 args.get(0).cloned().unwrap_or(Value::None),
169 args.get(1).cloned().unwrap_or(Value::None),
170 args.get(2).cloned().unwrap_or(Value::None),
171 ) {
172 (2, Value::Start(mut rules, lex), Value::Rules(rule), _) => {
174 rules.extend(rule);
175 Value::Start(rules, lex)
176 }
177 (2, Value::Start(rules, None), Value::Lex(lex), _) => Value::Start(rules, Some(lex)),
179 (3, Value::Rules(rule), _, _) => Value::Start(rule, None),
181 (4, Value::Rules(rules), _, _) => Value::Rules(rules),
183 (5, Value::Lex(lex), _, _) => Value::Lex(lex),
185 (6, Value::Ident(lhs), ..) => {
187 let rules = vec![Rule {
188 lhs: lhs.clone(),
189 rhs: vec![],
190 action: None,
191 }];
192 Value::Rules(rules)
193 }
194 (7, Value::Ident(lhs), _, Value::Ident(action)) => {
196 let rules = vec![Rule {
197 lhs: lhs.clone(),
198 rhs: vec![],
199 action: Some(action),
200 }];
201 Value::Rules(rules)
202 }
203 (8, Value::Ident(lhs), _, Value::Rhs(rhs)) => {
205 let rules = rhs
206 .into_iter()
207 .map(|(rhs, action)| Rule {
208 lhs: lhs.clone(),
209 rhs,
210 action,
211 })
212 .collect();
213 Value::Rules(rules)
214 }
215 (9, Value::Rhs(mut rhs), _, Value::Alt2(alt, action)) => {
217 rhs.push((alt, action));
218 Value::Rhs(rhs)
219 }
220 (10, Value::Alt2(alt, action), _, _) => Value::Rhs(vec![(alt, action)]),
222 (11, Value::Alt(alt), _, _) => Value::Alt2(alt, None),
224 (12, Value::Alt(alt), Value::Ident(action), _) => Value::Alt2(alt, Some(action)),
226 (13, Value::Alt(mut alt), _, Value::Fragment(fragment)) => {
228 alt.push(fragment);
229 Value::Alt(alt)
230 }
231 (14, Value::Fragment(fragment), _, _) => Value::Alt(vec![fragment]),
233 (15, Value::Ident(ident), _, _) => Value::Fragment(Fragment::Rhs {
235 ident,
236 rep: Rep::OneOrMore,
237 }),
238 (16, Value::Ident(ident), _, _) => Value::Fragment(Fragment::Rhs {
240 ident,
241 rep: Rep::ZeroOrMore,
242 }),
243 (17, Value::Ident(ident), _, _) => Value::Fragment(Fragment::Rhs {
245 ident,
246 rep: Rep::None,
247 }),
248 (18, Value::String(string), _, _) => Value::Fragment(Fragment::Lex { string }),
250 (19, Value::Ident(ident), _, Value::String(string)) => {
252 Value::Fragment(Fragment::Call {
253 func: ident,
254 arg: Box::new(Fragment::Lex { string }),
255 })
256 }
257 (20, _, _, Value::Rules(rules)) => Value::Lex(LexerVal(rules)),
259 (21, _, Value::Ident(name), _) => Value::Ident(name),
261 (22, Value::Rules(rules), _, _) => Value::Rules(rules),
263 (23, Value::Rules(mut rules), Value::Rules(rules2), _) => {
265 rules.extend(rules2);
266 Value::Rules(rules)
267 }
268 args => panic!("unknown rule id {:?} or args {:?}", args.0, args),
269 }
270 }
271}
272
273struct Lexer<'a> {
274 chars: Chars<'a>,
275 line_no: usize,
276 col_no: usize,
277}
278
279#[derive(Debug, Clone, Eq, PartialEq)]
280pub enum Token {
281 Ident(String),
282 BnfOp,
283 Semicolon,
284 Pipe,
285 Plus,
286 Mul,
287 Whitespace,
288 String(String),
289 LBrace,
290 RBrace,
291 LParen,
292 RParen,
293 GtOp,
294 LexerKeyword,
295 TildeOp,
296 Error(usize, usize),
297}
298
299impl Token {
300 fn ident(&self) -> Value {
301 if let &Token::Ident(ref s) = self {
302 Value::Ident(s.clone())
303 } else {
304 panic!("cannot extract ident from token")
305 }
306 }
307
308 fn string(&self) -> Value {
309 if let &Token::String(ref s) = self {
310 Value::String(s.clone())
311 } else {
312 panic!("cannot extract ident from token")
313 }
314 }
315}
316
317impl<'a> Lexer<'a> {
318 fn tokenize(bnf: &str) -> Vec<(Token, usize, usize)> {
319 let mut lexer = Lexer {
320 chars: bnf.chars(),
321 line_no: 1,
322 col_no: 1,
323 };
324 let mut result = vec![];
325 let mut line_no = 1;
326 let mut col_no = 1;
327 while let Some(token) = lexer.eat_token() {
328 if token != Token::Whitespace {
329 result.push((token, line_no, col_no));
330 }
331 line_no = lexer.line_no;
332 col_no = lexer.col_no;
333 }
334 result
335 }
336
337 fn eat_token(&mut self) -> Option<Token> {
338 self.peek().map(|ch| self.eat(ch))
342 }
343
344 fn eat(&mut self, ch: char) -> Token {
345 match ch {
346 'a'..='z' | 'A'..='Z' | '_' => {
347 let substring = self.chars.as_str();
348 while let Some('a'..='z' | 'A'..='Z' | '_' | '0'..='9') = self.peek() {
349 self.advance();
350 }
351 let result = substring[..substring.len() - self.chars.as_str().len()].to_string();
352 if result == "lexer" {
353 Token::LexerKeyword
354 } else {
355 Token::Ident(result)
356 }
357 }
358 ':' => {
359 if self.chars.as_str().starts_with("::=") {
360 self.advance();
361 self.advance();
362 self.advance();
363 Token::BnfOp
364 } else {
365 Token::Error(self.line_no, self.col_no)
366 }
367 }
368 ';' => {
369 self.advance();
370 Token::Semicolon
371 }
372 '|' => {
373 self.advance();
374 Token::Pipe
375 }
376 '+' => {
377 self.advance();
378 Token::Plus
379 }
380 '*' => {
381 self.advance();
382 Token::Mul
383 }
384 '~' => {
385 self.advance();
386 Token::TildeOp
387 }
388 '(' => {
389 self.advance();
390 Token::LParen
391 }
392 ')' => {
393 self.advance();
394 Token::RParen
395 }
396 '{' => {
397 self.advance();
398 Token::LBrace
399 }
400 '}' => {
401 self.advance();
402 Token::RBrace
403 }
404 '>' => {
405 self.advance();
406 Token::GtOp
407 }
408 ' ' | '\n' | '\t' => {
409 self.advance();
410 Token::Whitespace
411 }
412 '"' => {
413 let mut result = String::new();
414 self.advance();
415 while self.peek().map_or(false, |ch| ch != '"') {
416 match self.peek() {
417 None => break,
418 Some('\\') => {
419 self.advance();
420 if let Some(ch) = self.peek() {
421 result.push(ch);
422 self.advance();
423 } else {
424 break;
425 }
426 }
427 Some(other) => {
428 self.advance();
429 result.push(other);
430 }
431 }
432 }
433 if Some('"') == self.peek() {
434 self.advance();
435 Token::String(result)
436 } else {
437 Token::Error(self.line_no, self.col_no)
438 }
439 }
440 _ => Token::Error(self.line_no, self.col_no),
441 }
442 }
443
444 fn advance(&mut self) {
445 match self.chars.next() {
446 Some('\n') => {
447 self.line_no += 1;
448 self.col_no = 1;
449 }
450 Some(_) => {
451 self.col_no += 1;
452 }
453 None => {}
454 }
455 }
456
457 fn peek(&self) -> Option<char> {
458 self.chars.as_str().chars().next()
459 }
460}
461
462pub trait CfgLoadAdvancedExt {
463 fn load_advanced(grammar: &str) -> Result<AdvancedGrammar, LoadError>;
464}
465
466pub struct AdvancedGrammar {
479 pub cfg: Cfg,
480 pub lexer_map: LexerMap,
481 pub sbs: SymbolBitSet,
482 pub actions: BTreeMap<usize, Option<String>>,
483}
484
485impl CfgLoadAdvancedExt for Cfg {
486 fn load_advanced(grammar: &str) -> Result<AdvancedGrammar, LoadError> {
487 use tiny_earley::Grammar;
488 let bnf_grammar = grammar! {
489 S = [start, rule, alt, rhs, bnf_op, ident, pipe, op_mul, op_plus, semicolon, fragment, string, decl, action, lexer_keyword, lexer, lbrace, rbrace, rules, gt_op, lparen, rparen, alt2, tilde_op]
490 R = {
491 start ::= start decl; start ::= decl; decl ::= rule; decl ::= lexer; rule ::= ident bnf_op semicolon; rule ::= ident bnf_op action semicolon; rule ::= ident bnf_op rhs semicolon; rhs ::= rhs pipe alt2; rhs ::= alt2; alt2 ::= alt; alt2 ::= alt action; alt ::= alt tilde_op fragment; alt ::= fragment; fragment ::= ident op_plus; fragment ::= ident op_mul; fragment ::= ident; fragment ::= string; fragment ::= ident lparen string rparen; lexer ::= lexer_keyword lbrace rules rbrace; action ::= gt_op ident; rules ::= rule; rules ::= rules rule; }
514 };
515 let symbols = bnf_grammar.symbols();
516 #[allow(unused_variables)]
517 let [
518 start,
519 rule,
520 alt,
521 rhs,
522 bnf_op,
523 ident,
524 pipe,
525 op_mul,
526 op_plus,
527 semicolon,
528 fragment,
529 string,
530 decl,
531 action,
532 lexer_keyword,
533 lexer,
534 lbrace,
535 rbrace,
536 rules,
537 gt_op,
538 lparen,
539 rparen,
540 alt2,
541 tilde_op,
542 ] = bnf_grammar.symbols();
543 let mut recognizer = Recognizer::new(&bnf_grammar);
544 let tokens = Lexer::tokenize(grammar);
545 for (i, &(ref ch, line, col)) in tokens.iter().enumerate() {
546 let terminal = match ch {
547 Token::BnfOp => bnf_op,
548 Token::Semicolon => semicolon,
549 Token::Pipe => pipe,
550 Token::Mul => op_mul,
551 Token::Plus => op_plus,
552 Token::Ident(_) => ident,
553 Token::String(_) => string,
554 Token::LBrace => lbrace,
555 Token::RBrace => rbrace,
556 Token::LParen => lparen,
557 Token::RParen => rparen,
558 Token::GtOp => gt_op,
559 Token::TildeOp => tilde_op,
560 Token::LexerKeyword => lexer_keyword,
561 Token::Whitespace => continue,
562 &Token::Error(line_no, col_no) => {
563 return Err(LoadError::Parse {
564 reason: "failed to tokenize".to_string(),
565 line: line_no as u32,
566 col: col_no as u32,
567 token: None,
568 });
569 }
570 };
571 recognizer.scan(terminal, i as u32);
572 let success = recognizer.end_earleme();
573 if !success {
574 return Err(LoadError::Parse {
575 reason: "parse failed".to_string(),
576 line: line as u32,
577 col: col as u32,
578 token: Some(ch.clone()),
579 });
580 }
581 }
583 let finished_node = if let Some(node) = recognizer.finished_node {
584 node
585 } else {
586 return Err(LoadError::Parse {
587 reason: "parse failed: no result".to_string(),
588 line: 1,
589 col: 1,
590 token: None,
591 });
592 };
593 let result = recognizer
594 .forest
595 .evaluator(Evaluator { symbols, tokens })
596 .evaluate(finished_node);
597 if let Value::Start(rules, lexer) = result {
601 let mut set_of_lexical: BTreeSet<_> = BTreeSet::new();
602 let mut cfg = Cfg::new();
603 let intern = StringInterner::new();
604 let lex_string_intern = StringInterner::new();
605 let mut sym_map = HashMap::new();
606 let mut intern_empty = true;
607 let mut lexer_classes = LexerMap::new();
608 let mut lhs_in_parser = HashSet::new();
609 let mut actions = BTreeMap::new();
610 for (idx, (rule, is_lexer)) in rules
612 .into_iter()
613 .zip(iter::repeat(false))
614 .chain(
615 lexer
616 .unwrap_or(LexerVal(vec![]))
617 .0
618 .into_iter()
619 .zip(iter::repeat(true)),
620 )
621 .enumerate()
622 {
623 let lhs = intern.get_or_intern(&rule.lhs[..]);
624 if is_lexer {
625 if lhs_in_parser.contains(&lhs) {
626 return Err(LoadError::Lex {
627 reason: format!("lhs shared between parser and lexer: {}", rule.lhs),
628 });
629 }
630 } else {
631 lhs_in_parser.insert(lhs);
632 }
633 let lhs_sym = *sym_map
634 .entry(lhs)
635 .or_insert_with(|| cfg.sym_source_mut().next_sym(Some(rule.lhs[..].into())));
636 if intern_empty {
637 cfg.set_roots([lhs_sym]);
638 intern_empty = false;
639 }
640 let rhs_syms: Result<Vec<_>, LoadError> = rule
641 .rhs
642 .into_iter()
643 .map(|fragment| match fragment {
644 Fragment::Call { func, arg } => {
645 if func != "Regexp" {
646 return Err(LoadError::Lex {
647 reason: format!("expected 'Regexp', found '{}'", func),
648 });
649 }
650 match &*arg {
651 &Fragment::Call { ref func, ref arg } => {
652 return Err(LoadError::Lex {
653 reason: format!(
654 "expected Regex(string), found {:?}({:?})",
655 func, arg
656 ),
657 });
658 }
659 &Fragment::Lex { ref string } => {
660 let (mut regexp_cfg, classes) = Cfg::from_regexp(string)
661 .map_err(|err| LoadError::Lex {
662 reason: err.to_string(),
663 })?;
664 let mut remap = Remap::new(&mut regexp_cfg);
665 let mut sym_map = HashMap::new();
666 for (class, sym) in classes.classes {
667 let new_sym = *lexer_classes
668 .classes
669 .entry(class)
670 .or_insert_with(|| cfg.next_sym(None));
671 sym_map.insert(sym, new_sym);
672 }
673 remap.remap_symbols(|sym| {
674 *sym_map.entry(sym).or_insert_with(|| cfg.next_sym(None))
675 });
676 cfg.extend(®exp_cfg);
677 assert_eq!(regexp_cfg.roots().len(), 1);
678 Ok(regexp_cfg.roots()[0])
679 }
680 &Fragment::Rhs { ref ident, rep } => {
681 return Err(LoadError::Lex {
682 reason: format!(
683 "expected Regex(string), found {:?} repeated {:?}",
684 ident, rep
685 ),
686 });
687 }
688 }
689 }
690 Fragment::Lex { string } => {
691 let id = lex_string_intern.get_or_intern(&string[..]);
692 let name = format!("__lex{}", id);
693 let id = intern.get_or_intern(&name[..]);
694 let rhs_sym = *sym_map.entry(id).or_insert_with(|| {
695 cfg.sym_source_mut().next_sym(Some(name.clone().into()))
696 });
697 let child: Vec<_> = string
698 .chars()
699 .map(|ch| {
700 *lexer_classes
701 .classes
702 .entry(ch.into())
703 .or_insert_with(|| cfg.next_sym(None))
704 })
705 .collect();
706 cfg.rule(rhs_sym).rhs(&child[..]);
707 set_of_lexical.insert(rhs_sym);
708 Ok(rhs_sym)
709 }
710 Fragment::Rhs { ident, rep } => {
711 let id = intern.get_or_intern(&ident[..]);
712 let rhs_sym = *sym_map.entry(id).or_insert_with(|| {
713 cfg.sym_source_mut().next_sym(Some(ident[..].into()))
714 });
715 match rep {
716 Rep::None => Ok(rhs_sym),
717 Rep::ZeroOrMore => {
718 let [new_sym] = cfg.sym();
719 cfg.sequence(new_sym).inclusive(0, None).rhs(rhs_sym);
720 Ok(new_sym)
721 }
722 Rep::OneOrMore => {
723 let [new_sym] = cfg.sym();
724 cfg.sequence(new_sym).range(1..).rhs(rhs_sym);
725 Ok(new_sym)
726 }
727 }
728 }
729 })
730 .collect();
731 if is_lexer {
732 set_of_lexical.insert(lhs_sym);
733 }
734 cfg.rule(lhs_sym)
735 .history(RootHistoryNode::Origin { origin: idx + 1 }.into())
736 .rhs(rhs_syms?);
737 actions.insert(idx + 1, rule.action);
738 }
739 let mut sbs = SymbolBitSet::new();
740 sbs.reset(cfg.sym_source());
741 for sym in set_of_lexical {
742 sbs.set(sym, true);
743 }
744 Ok(AdvancedGrammar {
745 cfg,
746 lexer_map: lexer_classes,
747 sbs,
748 actions,
749 })
750 } else {
751 return Err(LoadError::Eval {
752 reason: format!("evaluation failed: Expected Value::Rules, got {:?}", result),
753 });
754 }
755 }
756}