aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 17e265e5b3955a4ae298a879f990adc8200b806b (plain) (blame)
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
mod table;
mod definitions;
mod utf8;

pub use definitions::{Action, State, unpack};

use table::{EXIT_ACTIONS, ENTRY_ACTIONS, STATE_CHANGE};

impl State {
    /// Get exit action for this state
    #[inline(always)]
    pub fn exit_action(&self) -> Action {
        unsafe {
            *EXIT_ACTIONS.get_unchecked(*self as usize)
        }
    }

    /// Get entry action for this state
    #[inline(always)]
    pub fn entry_action(&self) -> Action {
        unsafe {
            *ENTRY_ACTIONS.get_unchecked(*self as usize)
        }
    }
}


const MAX_INTERMEDIATES: usize = 2;
const MAX_PARAMS: usize = 16;

struct VtUtf8Receiver<'a, P: Parser + 'a>(&'a mut P, &'a mut State);

impl<'a, P: Parser> utf8::Receiver for VtUtf8Receiver<'a, P> {
    fn codepoint(&mut self, c: char) {
        self.0.print(c);
        *self.1 = State::Ground;
    }

    fn invalid_sequence(&mut self) {
        self.0.print('�');
        *self.1 = State::Ground;
    }
}

/// ANSI VTE Parser
///
/// As described in http://vt100.net/emu/dec_ansi_parser
///
/// TODO: utf8 support
pub struct StateMachine {
    state: State,
    intermediates: [u8; MAX_INTERMEDIATES],
    intermediate_idx: usize,
    params: [i64; MAX_PARAMS],
    num_params: usize,
    ignoring: bool,
    utf8_parser: utf8::Parser,
}

impl StateMachine {
    pub fn new() -> StateMachine {
        StateMachine {
            state: State::Ground,
            intermediates: [0u8; MAX_INTERMEDIATES],
            intermediate_idx: 0,
            params: [0i64; MAX_PARAMS],
            num_params: 0,
            ignoring: false,
            utf8_parser: utf8::Parser::new(),
        }
    }

    pub fn params(&self) -> &[i64] {
        &self.params[..self.num_params]
    }

    pub fn intermediates(&self) -> &[u8] {
        &self.intermediates[..self.intermediate_idx]
    }

    pub fn advance<P: Parser>(&mut self, parser: &mut P, byte: u8) {
        // Utf8 characters are handled out-of-band.
        if let State::Utf8 = self.state {
            self.process_utf8(parser, byte);
            return;
        }

        // Handle state changes in the anywhere state before evaluating changes
        // for current state.
        let mut change = STATE_CHANGE[State::Anywhere as usize][byte as usize];

        if change == 0 {
            change = STATE_CHANGE[self.state as usize][byte as usize];
        }

        // Unpack into a state and action
        let (state, action) = unpack(change);

        self.perform_state_change(parser, state, action, byte);
    }

    #[inline]
    fn process_utf8<P>(&mut self, parser: &mut P, byte: u8)
        where P: Parser
    {
        let mut receiver = VtUtf8Receiver(parser, &mut self.state);
        let utf8_parser = &mut self.utf8_parser;
        utf8_parser.advance(&mut receiver, byte);
    }

    fn perform_state_change<P>(&mut self, parser: &mut P, state: State, action: Action, byte: u8)
        where P: Parser
    {
        macro_rules! maybe_action {
            ($action:expr, $arg:expr) => {
                match $action {
                    Action::None => (),
                    action => {
                        self.perform_action(parser, action, $arg);
                    },
                }
            }
        }

        match state {
            State::Anywhere => {
                // Just run the action
                self.perform_action(parser, action, byte);
            },
            state => {
                // Exit action for previous state
                let exit_action = self.state.exit_action();
                maybe_action!(exit_action, 0);

                // Transition action
                maybe_action!(action, byte);

                // Entry action for new state
                maybe_action!(state.entry_action(), 0);

                // Assume the new state
                self.state = state;
            }
        }
    }

    fn perform_action<P: Parser>(&mut self, parser: &mut P, action: Action, byte: u8) {
        match action {
            Action::Print => parser.print(byte as char),
            Action::Execute => parser.execute(self, byte),
            Action::Hook => parser.hook(self, byte),
            Action::Put => parser.put(self, byte),
            Action::OscStart => parser.osc_start(self, byte),
            Action::OscPut => parser.osc_put(self, byte),
            Action::OscEnd => parser.osc_end(self, byte),
            Action::Unhook => parser.unhook(self, byte),
            Action::CsiDispatch => parser.csi_dispatch(self, byte as char),
            Action::EscDispatch => parser.esc_dispatch(self, byte),
            Action::Ignore | Action::None => (),
            Action::Collect => {
                if self.intermediate_idx == MAX_INTERMEDIATES {
                    self.ignoring = true;
                } else {
                    self.intermediates[self.intermediate_idx] = byte;
                    self.intermediate_idx += 1;
                }
            },
            Action::Param => {
                // if byte == ';'
                if byte == 0x3b {
                    // end of param; advance to next
                    self.num_params += 1;
                    let idx = self.num_params - 1; // borrowck
                    self.params[idx] = 0;
                } else {
                    if self.num_params == 0 {
                        self.num_params = 1;
                        self.params[0] = 0;
                    }

                    let idx = self.num_params - 1;
                    self.params[idx] *= 10;
                    self.params[idx] += (byte - ('0' as u8)) as i64;
                }
            },
            Action::Clear => {
                self.intermediate_idx = 0;
                self.num_params = 0;
                self.ignoring = false;
            },
            Action::BeginUtf8 => {
                self.process_utf8(parser, byte);
            },
        }
    }
}

pub trait Parser {
    fn print(&mut self, c: char);
    fn execute(&mut self, &StateMachine, byte: u8);
    fn hook(&mut self, &StateMachine, byte: u8);
    fn put(&mut self, &StateMachine, byte: u8);
    fn osc_start(&mut self, &StateMachine, byte: u8);
    fn osc_put(&mut self, &StateMachine, byte: u8);
    fn osc_end(&mut self, &StateMachine, byte: u8);
    fn unhook(&mut self, &StateMachine, byte: u8);
    fn csi_dispatch(&mut self, &StateMachine, c: char);
    fn esc_dispatch(&mut self, &StateMachine, byte: u8);
}