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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// +-----------------------------------------------------------------------------------------------+
// | Copyright 2016 Sean Kerr                                                                      |
// |                                                                                               |
// | Licensed under the Apache License, Version 2.0 (the "License");                               |
// | you may not use this file except in compliance with the License.                              |
// | You may obtain a copy of the License at                                                       |
// |                                                                                               |
// |  http://www.apache.org/licenses/LICENSE-2.0                                                   |
// |                                                                                               |
// | Unless required by applicable law or agreed to in writing, software                           |
// | distributed under the License is distributed on an "AS IS" BASIS,                             |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                      |
// | See the License for the specific language governing permissions and                           |
// | limitations under the License.                                                                |
// +-----------------------------------------------------------------------------------------------+
// | Author: Sean Kerr <sean@metatomic.io>                                                         |
// +-----------------------------------------------------------------------------------------------+

//! Finite state machine macros and enums.

use std::fmt;

/// Execute callback `$function`. If it returns `true`, execute `$exec`. Otherwise exit with
/// `Success::Callback`.
macro_rules! callback {
    ($parser:expr, $handler:expr, $context:expr, $function:ident, $data:expr, $exec:expr) => ({
        if $handler.$function($data) {
            $exec
        } else {
            exit_callback!($parser, $context);
        }
    });

    ($parser:expr, $handler:expr, $context:expr, $function:ident, $exec:expr) => ({
        let slice = bs_slice!($context);

        if slice.len() > 0 {
            if $handler.$function(slice) {
                $exec
            } else {
                exit_callback!($parser, $context);
            }
        } else {
            $exec
        }
    });
}

/// Reusable callback EOS expression that executes `$function`.
macro_rules! callback_eos_expr {
    ($parser:expr, $handler:expr, $context:expr, $function:ident) => ({
        callback!($parser, $handler, $context, $function, {
            exit_eos!($parser, $context);
        });
    });
}

/// Execute callback `$function` ignoring the last collected byte. If it returns `true`, transition
/// to `$state`. Otherwise exit with `Success::Callback`.
macro_rules! callback_ignore_transition {
    ($parser:expr, $handler:expr, $context:expr, $function:ident, $state:ident,
     $state_function:ident) => ({
        let slice = bs_slice_ignore!($context);

        set_state!($parser, $state, $state_function);

        if slice.len() > 0 {
            if $handler.$function(slice) {
                transition!($parser, $context);
            } else {
                exit_callback!($parser, $context);
            }
        } else {
            transition!($parser, $context);
        }
    });
}

/// Execute callback `$function` ignoring the last collected byte. If it returns `true`, transition
/// to the next `$state` quickly by directly calling `$state_function`. Otherwise exit with
/// `Success::Callback`.
macro_rules! callback_ignore_transition_fast {
    ($parser:expr, $handler:expr, $context:expr, $function:ident, $state:ident,
     $state_function:ident) => ({
        let slice = bs_slice_ignore!($context);

        set_state!($parser, $state, $state_function);

        if slice.len() > 0 {
            if $handler.$function(slice) {
                transition_fast!($parser, $handler, $context);
            } else {
                exit_callback!($parser, $context);
            }
        } else {
            transition_fast!($parser, $handler, $context);
        }
    });
}

/// Execute callback `$function`. If it returns `true`, transition to `$state`. Otherwise exit
/// with `Success::Callback`.
///
/// This macro exists to enforce the design decision that after each callback, state must either
/// change, or the parser must exit with `Success::Callback`.
macro_rules! callback_transition {
    ($parser:expr, $handler:expr, $context:expr, $function:ident, $data:expr, $state:ident,
     $state_function:ident) => ({
        set_state!($parser, $state, $state_function);
        callback!($parser, $handler, $context, $function, $data, {
            transition!($parser, $context);
        });
    });

    ($parser:expr, $handler:expr, $context:expr, $function:ident, $state:ident,
     $state_function:ident) => ({
        set_state!($parser, $state, $state_function);
        callback!($parser, $handler, $context, $function, {
            transition!($parser, $context);
        });
    });
}

/// Execute callback `$function`. If it returns `true`, transition to `$state` quickly by
/// directly calling `$state_function`. Otherwise exit with `Success::Callback`.
///
/// This macro exists to enforce the design decision that after each callback, state must either
/// change, or the parser must exit with `Success::Callback`.
macro_rules! callback_transition_fast {
    ($parser:expr, $handler:expr, $context:expr, $function:ident, $data:expr, $state:ident,
     $state_function:ident) => ({
        set_state!($parser, $state, $state_function);
        callback!($parser, $handler, $context, $function, $data, {
            transition_fast!($parser, $handler, $context);
        });
    });

    ($parser:expr, $handler:expr, $context:expr, $function:ident, $state:ident,
     $state_function:ident) => ({
        set_state!($parser, $state, $state_function);
        callback!($parser, $handler, $context, $function, {
            transition_fast!($parser, $handler, $context);
        });
    });
}

/// Exit parser with `Success::Callback`.
macro_rules! exit_callback {
    ($parser:expr, $context:expr, $state:ident, $state_function:ident) => ({
        set_state!($parser, $state, $state_function);

        return Ok(ParserValue::Exit(Success::Callback($context.stream_index)));
    });

    ($parser:expr, $context:expr) => ({
        return Ok(ParserValue::Exit(Success::Callback($context.stream_index)));
    });
}

/// Exit parser with `Success::Eos`.
macro_rules! exit_eos {
    ($parser:expr, $context:expr) => ({
        return Ok(ParserValue::Exit(Success::Eos($context.stream_index)));
    });
}

/// Exit parser with `ParserError`.
macro_rules! exit_error {
    ($error:ident, $byte:expr) => ({
        return Err(ParserError::$error($byte));
    });

    ($error:ident) => ({
        return Err(ParserError::$error);
    });
}

/// Exit parser with `Success::Finished`.
macro_rules! exit_finished {
    ($parser:expr, $context:expr) => ({
        return Ok(ParserValue::Exit(Success::Finished($context.stream_index)));
    });
}

/// If the stream is EOS, exit with `Success::Eos`. Otherwise do nothing.
macro_rules! exit_if_eos {
    ($parser:expr, $context:expr) => ({
        if bs_is_eos!($context) {
            exit_eos!($parser, $context);
        }
    });
}

/// Retrieve the state.
macro_rules! get_state {
    ($parser:expr) => ({
        $parser.state
    })
}

/// Set state and state function.
macro_rules! set_state {
    ($parser:expr, $state:ident, $state_function:ident) => ({
        $parser.state          = ParserState::$state;
        $parser.state_function = Parser::$state_function;
    });
}

/// Transition to `$state`.
macro_rules! transition {
    ($parser:expr, $context:expr, $state:ident, $state_function:ident) => ({
        set_state!($parser, $state, $state_function);

        bs_mark!($context, $context.stream_index);

        return Ok(ParserValue::Continue);
    });

    ($parser:expr, $context:expr) => ({
        $context.mark_index = $context.stream_index;

        return Ok(ParserValue::Continue);
    });
}

/// Transition to `$state` quickly by directly calling `$state_function`.
macro_rules! transition_fast {
    ($parser:expr, $handler:expr, $context:expr, $state:ident, $state_function:ident) => ({
        set_state!($parser, $state, $state_function);

        bs_mark!($context, $context.stream_index);

        return ($parser.state_function)($parser, $handler, $context);
    });

    ($parser:expr, $handler:expr, $context:expr) => ({
        $context.mark_index = $context.stream_index;

        return ($parser.state_function)($parser, $handler, $context);
    });
}

// -------------------------------------------------------------------------------------------------

/// Parsing function return values.
pub enum ParserValue {
    /// Continue the parser loop.
    Continue,

    /// Exit the parser loop.
    Exit(Success)
}

// -------------------------------------------------------------------------------------------------

/// Parsing function success return values.
#[derive(Clone,Copy,PartialEq)]
pub enum Success {
    /// A callback returned `false` and the parser function exited prematurely. This can be
    /// treated the same as `Success::Finished`.
    ///
    /// # Arguments
    ///
    /// **(1)**: The amount of `stream` bytes that were processed before the callback was executed.
    ///          In most cases this will not match `stream.len()`.
    Callback(usize),

    /// Additional `stream` data is expected. Continue executing the parser function until
    /// `Success::Finished` is returned.
    ///
    /// # Arguments
    ///
    /// **(1)**: The amount of `stream` bytes that were processed. This value will always match
    ///          `stream.len()`.
    Eos(usize),

    /// The parser function finished successfully.
    ///
    /// # Arguments
    ///
    /// **(1)**: The amount of `stream` bytes that were processed. Under some circumstances this
    ///          will be less than `stream.len()`. This indicates that there must be a transition
    ///          between the current parser function and the next one. For example, a typical HTTP
    ///          request would consist of a call to
    ///          [Parser::parse_head()](../http1/struct.Parser.html#method.parse_head), and
    ///          depending on the content type you may need to transition to
    ///          [Parser::parse_chunked()](../http1/struct.Parser.html#method.parse_chunked),
    ///          [Parser::parse_multipart()](../http1/struct.Parser.html#method.parse_multipart), or
    ///          [Parser::parse_url_encoded()](../http1/struct.Parser.html#method.parse_url_encoded).
    Finished(usize)
}

impl fmt::Debug for Success {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Success::Callback(length) => {
                write!(formatter, "Success::Callback({})", length)
            },
            Success::Eos(length) => {
                write!(formatter, "Success::Eos({})", length)
            },
            Success::Finished(length) => {
                write!(formatter, "Success::Finished({})", length)
            }
        }
    }
}

impl fmt::Display for Success {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Success::Callback(length) => {
                write!(formatter, "{}", length)
            },
            Success::Eos(length) => {
                write!(formatter, "{}", length)
            },
            Success::Finished(length) => {
                write!(formatter, "{}", length)
            }
        }
    }
}