Skip to content

Commit 1ac3d98

Browse files
add example app showing nfa OR dfa in rust
1 parent 408325b commit 1ac3d98

File tree

4 files changed

+70
-0
lines changed

4 files changed

+70
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
*.iml
22
dist/
3+
Cargo.lock
34
target/
45
.idea
56
lex.yy.c

rust/show-nfa-dfa/Cargo.toml

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[package]
2+
name = "showfa"
3+
version = "0.1.0"
4+
authors = ["Yu Chen <[email protected]>"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]
10+
smallvec = "0.6.9"
11+
nom = "5.0"
12+
bitset = { git = "https://github.com/MashPlant/bitset" }
13+
re2dfa = { git = "https://github.com/MashPlant/re2dfa" }
14+
clap = "2.33.0"

rust/show-nfa-dfa/README.md

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Example
2+
convert a Regular Expression to NFA(Nondeterministic Finite Automata) to DFA(Deterministic Finite Automata)
3+
4+
## pre-requirement
5+
rust toolchain (nightly OR 1.39+) is installed.
6+
7+
## usage
8+
tested on ubuntu 19.10 x86-64
9+
10+
```
11+
# run the example with help
12+
cargo run -- -h
13+
14+
# run the example for RE to NFA
15+
cargo run -- --nfa nfa.dot "(1|0)*1*0*10(1|0)*"
16+
17+
# show the figure of NFA
18+
xdot nfa.dot
19+
20+
# run the example for RE to NFA to raw DFA
21+
cargo run -- --raw_dfa raw_dfa.dot "(1|0)*1*0*10(1|0)*"
22+
23+
# show the figure of raw DFA
24+
xdot raw_dfa.dot
25+
26+
# run the example for RE to NFA to raw DFA to small DFA
27+
cargo run -- --dfa dfa.dot "(1|0)*1*0*10(1|0)*"
28+
29+
# show the figure of small DFA
30+
xdot dfa.dot
31+
```

rust/show-nfa-dfa/src/main.rs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
use re2dfa::*;
2+
use clap::{App, Arg};
3+
use std::{io, fs, process};
4+
5+
fn main() -> io::Result<()> {
6+
let m = App::new("show_fa")
7+
.arg(Arg::with_name("input").required(true))
8+
.arg(Arg::with_name("nfa").long("nfa").takes_value(true))
9+
.arg(Arg::with_name("raw_dfa").long("raw_dfa").takes_value(true).help("show the dfa directly converted from nfa"))
10+
.arg(Arg::with_name("dfa").long("dfa").takes_value(true).help("show the minimized dfa"))
11+
.get_matches();
12+
let input = m.value_of("input").unwrap();
13+
let re = parse(input).unwrap_or_else(|e| {
14+
eprintln!("Invalid regex `{}`: {}", input, e);
15+
process::exit(1);
16+
});
17+
let nfa = Nfa::from_re(&re);
18+
if let Some(path) = m.value_of("nfa") { fs::write(path, nfa.print_dot())?; }
19+
let dfa = Dfa::from_nfa(&nfa, 0);
20+
if let Some(path) = m.value_of("raw_dfa") { fs::write(path, dfa.print_dot())?; }
21+
let dfa = dfa.minimize();
22+
if let Some(path) = m.value_of("dfa") { fs::write(path, dfa.print_dot())?; }
23+
Ok(())
24+
}

0 commit comments

Comments
 (0)