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
use core::{Automaton, Dfa, Letter, Token};
use std::fmt;
use std::iter::Iterator;
use std::marker::PhantomData;

pub struct Expression<T: Token, S> {
    dfa: Dfa<S>,
    phantom: PhantomData<T>,
}

impl<T: Token, S> Expression<T, S> {
    fn empty() -> Expression<T, S> {
        Expression {
            dfa: Dfa::empty(),
            phantom: PhantomData,
        }
    }

    /// Returns an automaton that accepts the given token
    pub fn token(input: T) -> Expression<T, S> {
        Expression {
            dfa: Dfa::token(Letter(input.as_range())),
            phantom: PhantomData,
        }
    }

    pub fn sequence<I: Iterator<Item=T>>(tokens: I) -> Expression<T, S> {
        Expression {
            dfa: Dfa::sequence(tokens.map(|t| Letter(t.as_range()))),
            phantom: PhantomData,
        }
    }

    /// Concatenate two automata
    pub fn concat(mut self, mut other: Expression<T, S>) -> Expression<T, S> {
        Expression {
            dfa: self.dfa.concat(other.dfa),
            phantom: PhantomData,
        }
    }

    pub fn union(mut self, mut other: Expression<T, S>) -> Expression<T, S> {
        Expression {
            dfa: self.dfa.union(other.dfa),
            phantom: PhantomData,
        }
    }

    pub fn intersection(mut self, mut other: Expression<T, S>) -> Expression<T, S> {
        Expression {
            dfa: self.dfa.intersection(other.dfa),
            phantom: PhantomData,
        }
    }

    pub fn kleene(mut self) -> Expression<T, S> {
        Expression {
            dfa: self.dfa.kleene(),
            phantom: PhantomData,
        }
    }

    pub fn optional(mut self) -> Expression<T, S> {
        self.union(Expression::empty())
    }

    /// Specify an action to be invoked when evaluation enters the machine
    pub fn on_enter<F: Fn(&mut S) + 'static>(mut self, action: F) -> Expression<T, S> {
        self.dfa.on_enter(Box::new(action));
        self
    }

    /// Specify an action to be invoked when evaluation leaves the machine
    pub fn on_exit<F: Fn(&mut S) + 'static>(mut self, action: F) -> Expression<T, S> {
        self.dfa.on_exit(Box::new(action));
        self
    }

    /// Compile the expression for evaluation
    pub fn compile(self) -> Automaton<T, S> {
        From::from(self.dfa)
    }

    /*
     *
     * ===== Inspection helpers =====
     *
     */

    pub fn alphabet(&self) -> Vec<T> {
        self.dfa.alphabet().iter()
            .map(|r| <T as Token>::from_range(r))
            .collect()
    }

    /*
     *
     * ===== DOT file generation =====
     *
     */

    pub fn dot(&self) -> String {
        format!("digraph finite_state_machine {{\n
                 rankdir=LR;size=\"8,5\"\n
                 node [shape = point];\n
                   start\n
                 node [shape = doublecircle];\n
                 {};\nnode [shape = circle];\n
                 {}
                 }}\n",
                self.dot_terminal(),
                self.dot_edges())
    }

    fn dot_terminal(&self) -> String {
        let mut ret = String::new();

        for (state, _) in self.dfa.terminal() {
            ret.push_str(&format!("  {}", state));
        }

        ret
    }

    fn dot_edges(&self) -> String {
        let mut ret = String::new();

        self.dfa.transitions().each(|t| {
            let mut actions = "";

            if !t.actions().is_empty() {
                actions = "!";
            }

            match t.input() {
                Some(i) => {
                    ret.push_str(
                        &format!(
                            "{} -> {} [ label = \"{:?}{}\" ];\n",
                            t.from(), t.to(), i.to_token::<T>(), actions));
                }
                None => {
                    ret.push_str(
                        &format!(
                            "{} -> {} [ label = \"ε{}\" ];\n",
                            t.from(), t.to(), actions));
                }
            }
        });

        ret.push_str(
            &format!(
                "start -> {} [ ];\n",
                self.dfa.start()));

        ret
    }
}

impl<T: Token, S> fmt::Debug for Expression<T, S> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Expression {{ ... }}")
    }
}