Skip to content

Commit

Permalink
feat: table view for follow set
Browse files Browse the repository at this point in the history
  • Loading branch information
Devin-Yeung committed Nov 22, 2023
1 parent f41ec00 commit a49f840
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/utils/follow/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use crate::utils::follow::builder::FollowBuilder;
use bnf::{Grammar, Term};
use itertools::Itertools;
use std::collections::{HashMap, HashSet};
use tabled::builder::Builder;
use tabled::Table;

mod builder;

Expand All @@ -17,4 +20,58 @@ impl<'grammar> Follow<'grammar> {
// TODO: remove the unwrap?
self.follow.get(x).unwrap().iter()
}

pub fn tabled(&self) -> Table {
let mut table = Builder::new();
table.set_header(["Term", "Follow(X)"]);
for (term, first) in self
.follow
.iter()
.filter(|(term, _)| matches!(term, Term::Nonterminal(_)))
.sorted_by(|a, b| a.0.cmp(b.0))
{
table.push_record([term.to_string(), first.iter().sorted().join(", ")]);
}
table.build()
}
}

#[cfg(test)]
mod tests {
use crate::utils::follow::Follow;
use bnf::Term;
use std::str::FromStr;

#[test]
fn it_works() {
let grammar = r#"
<E> ::= <T> <E'>
<E'> ::= '+' <T> <E'> | 'ε'
<T> ::= <F> <T'>
<T'> ::= '*' <F> <T'> | 'ε'
<F> ::= '(' <E> ')' | 'id'
"#
.parse()
.unwrap();
let start = Term::from_str("<E>").unwrap();
let follow = Follow::new(&grammar, &start);
insta::assert_display_snapshot!(follow.tabled());
}

#[test]
fn test_case_1() {
let grammar = r#"
<P> ::= <Q> 'id' <R>
<Q> ::= '∃' | '∀'
<R> ::= <E> '=' <E>
<E> ::= <T> <E'>
<E'> ::= '+' <T> <E'> | 'ε'
<T> ::= '(' <E> ')' | 'id'
"#
.parse()
.unwrap();
let start = Term::from_str("<P>").unwrap();
let follow = Follow::new(&grammar, &start);
insta::assert_display_snapshot!(follow.tabled());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
source: src/utils/follow/mod.rs
expression: follow.tabled()
---
+------+--------------------+
| Term | Follow(X) |
+------+--------------------+
| <E> | "$", ")", "=" |
+------+--------------------+
| <E'> | "$", ")", "=" |
+------+--------------------+
| <P> | "$" |
+------+--------------------+
| <Q> | "id" |
+------+--------------------+
| <R> | "$" |
+------+--------------------+
| <T> | "$", ")", "+", "=" |
+------+--------------------+
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
source: src/utils/follow/mod.rs
expression: follow.tabled()
---
+------+--------------------+
| Term | Follow(X) |
+------+--------------------+
| <E> | "$", ")" |
+------+--------------------+
| <E'> | "$", ")" |
+------+--------------------+
| <F> | "$", ")", "*", "+" |
+------+--------------------+
| <T> | "$", ")", "+" |
+------+--------------------+
| <T'> | "$", ")", "+" |
+------+--------------------+

0 comments on commit a49f840

Please sign in to comment.