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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#![deny(missing_docs)]
/*!
See [README.md](https://crates.io/crates/ssexp)
*/

/// Represents the tokens of the s-expressions.
/// An s-expression may be a list of symbols and other s-expressions or a symbol.
#[derive(Clone, Debug)]
pub enum Token {
    /// A Symbol Token represented by its name.
    Symbol(String),
    /// A List Token containing other tokens.
    List(Vec<Token>),
}

use Token::*;

impl Token {
    /// If the token is a `Symbol`, returns an `Option`, containing the symbol name.
    /// Else returns `None`.
    pub fn symbol(self) -> Option<String> {
        match self {
            Symbol(string) => Some(string),
            List(_) => None,
        }
    }

    /// Same as `fn symbol`, but returns a ref.
    pub fn symbol_ref(&self) -> Option<&String> {
        match self {
            Symbol(string) => Some(string),
            List(_) => None,
        }
    }

    /// If the token is a `List`, returns an `Option`, containing the elements.
    /// Else returns `None`.
    pub fn list(self) -> Option<Vec<Token>> {
        match self {
            Symbol(_) => None,
            List(tokens) => Some(tokens),
        }
    }

    /// Same as `fn list`, but returns a ref.
    pub fn list_ref(&self) -> Option<&Vec<Token>> {
        match self {
            Symbol(_) => None,
            List(tokens) => Some(tokens),
        }
    }
}

/// Useful for managing opening and closing subcontexts like brackets.
pub enum ParsingState {
    /// Doesn't do anything.
    Fine,
    /// Closes a subcontext.
    Finished,
    /// Closes a subcontext while carrying the closing character.
    Delegate(char),
}

use ParsingState::*;

mod implement_display {
    use std::fmt::{Display, Formatter, Result};

    use crate::Token;

    impl Display for Token {
        fn fmt(&self, f: &mut Formatter) -> Result {
            match self {
                Token::Symbol(string) => write!(f, "'{}'", string),
                Token::List(vec) => {
                    let mut first = true;
                    write!(f, "(").expect("Unexpected end of file");
                    for tok in vec.iter() {
                        if !first {
                            write!(f, " ").expect("Unexpected end of file");
                        } else {
                            first = false;
                        }
                        let result = write!(f, "{}", tok);
                        if result.is_err() {
                            return result;
                        }
                    }
                    write!(f, ")")
                }
            }
        }
    }
}

use std::collections::HashMap;

/// The function type for macro functions.
pub type MacroFn<T> = fn(
    input_char: Option<char>,
    token_list: &mut Vec<Token>,
    parser: &mut Parser<T>,
) -> ParsingState;

/// A map for storing the macro characters and their behaviours.
/// Every character may be set as macro character.
pub struct MacroMap<T: Iterator<Item = char>>(HashMap<char, MacroFn<T>>);

impl<T: Iterator<Item = char>> MacroMap<T> {
    /// Creates a new `MacroMap`, which is used to save macro characters
    pub fn new() -> Self {
        MacroMap(HashMap::new())
    }
    /// Adds whitespaces as macro characters for splitting there into tokens.
    pub fn with_separating_whitespaces(mut self) -> Self {
        self.set(' ', Some(parse_empty));
        self.set('\n', Some(parse_empty));
        self.set('\t', Some(parse_empty));
        self
    }
    /// Adds a `list_delimiter` as left delimiter of a list.
    /// Only following characters are supported as delimiters:
    /// `(` `)` `[` `]` `{` `}` `<` `>`
    pub fn with_lists(mut self, list_delimiter: char) -> Self {
        self.set(list_delimiter, Some(parse_list));
        self.set(
            closing_bracket(list_delimiter).expect("Not a possible opening bracket"),
            Some(parse_panic),
        );
        self
    }
    /// Adds the ability for parsing strings, using char `string_delimiter` for delimiting strings.
    /// A string will be parsed as list, whose first element is the symbol `string` and whose second element is the string itself as symbol.

    pub fn with_strings(mut self, string_delimiter: char) -> Self {
        self.set(string_delimiter, Some(parse_string));
        self
    }
    /// Adds `comment_char` as macro character for single line comments.
    pub fn with_comments(mut self, comment_char: char) -> Self {
        self.set(comment_char, Some(parse_comment));
        self
    }

    /// Adds `infix_char` as a left associative infix operator.
    pub fn with_infix_left(mut self, infix_char: char) -> Self {
        self.set(infix_char, Some(parse_infix_left));
        self
    }

    /// Adds `char` as a macro character with the user defined macro function `value`
    pub fn with_macro_character(mut self, char: char, value: MacroFn<T>) -> Self {
        self.set(char, Some(value));
        self
    }
    /// Creates a `MacroMap` from a `HashMap`
    pub fn from_hash_map(map: HashMap<char, MacroFn<T>>) -> Self {
        MacroMap(map)
    }
    /// Adds a new user defined macro character `char`.
    /// Takes an `Option` of the new macro function.
    /// If the
    pub fn set(&mut self, char: char, value: Option<MacroFn<T>>) -> Option<MacroFn<T>> {
        if let Some(value) = value {
            self.0.insert(char, value)
        } else {
            self.0.remove(&char)
        }
    }
}

/// Used in parsing process for getting chars and calling the macro functions.
pub struct Parser<T: Iterator<Item = char>> {
    char: Option<char>,
    chars: T,
    map: MacroMap<T>,
}

/// A handle for handling the next character
pub struct CharHandle<'a, T: Iterator<Item = char>>
where
    Parser<T>: 'a,
{
    char: char,
    parser: &'a mut Parser<T>,
    fun: Option<MacroFn<T>>,
}

use std::result::Result;

impl<'a, T: Iterator<Item = char>> CharHandle<'a, T> {
    /// Returns the next character from the handle without doing anything.
    pub fn char(self) -> char {
        self.char
    }
    /// Tests, if the character from the handle is defined as macro character.
    pub fn is_macro(&self) -> bool {
        self.fun.is_some()
    }
    /// Tries to call the macro character. If none is defined, it some character.
    pub fn call(self, vec: &mut Vec<Token>) -> Result<ParsingState, char> {
        let Self { char, parser, fun } = self;
        if let Some(fun) = fun {
            Ok(fun(Some(char), vec, parser))
        } else {
            Err(char)
        }
    }
    /// Discards this handle. When calling the next time, the same character will be used for dispatch.
    pub fn discard(self) {
        self.parser.char = Some(self.char);
    }
}

impl<T: Iterator<Item = char>> Parser<T> {
    /// Returns some handle for the next character
    pub fn get(&mut self) -> Option<CharHandle<T>> {
        let char = if let Some(old_char) = self.char {
            self.char = None;
            old_char
        } else {
            self.chars.next()?
        };
        let fun = if self.map.0.contains_key(&char) {
            Some(self.map.0[&char])
        } else {
            None
        };
        Some(CharHandle {
            char,
            parser: self,
            fun,
        })
    }

    /// Sets a macro character and returns some previous, if there was one defined, else returns `None`
    pub fn set(&mut self, char: char, value: Option<MacroFn<T>>) -> Option<MacroFn<T>> {
        self.map.set(char, value)
    }
}

/// The main function for running the parser. It takes some input stream, a macro function, and a macro map.
pub fn parse_sexp<T: IntoIterator<Item = char>>(
    stream: T,
    macro_fn: MacroFn<T::IntoIter>,
    map: MacroMap<T::IntoIter>,
) -> Vec<Token> {
    let mut parser = Parser {
        chars: stream.into_iter(),
        map,
        char: None,
    };
    let mut tokens = Vec::new();
    macro_fn(None, &mut tokens, &mut parser);
    tokens
}

use crate::functions::*;

/// Defines useful helper and starting functions.
pub mod functions {
    use super::*;
    /// A macro function to mark some char as macro character without doing anything.
    pub fn parse_empty<T: Iterator<Item = char>>(
        _: Option<char>,
        _: &mut Vec<Token>,
        _: &mut Parser<T>,
    ) -> ParsingState {
        Fine
    }

    /// A macro function, that just panics. Instead of using this, it's preferable to use `parse_delegate`
    pub fn parse_panic<T: Iterator<Item = char>>(
        char: Option<char>,
        _: &mut Vec<Token>,
        _: &mut Parser<T>,
    ) -> ParsingState {
        panic!("Invalid macro character {:?}", char)
    }

    /// A macro function, that delegates the handling of some macro character to the function.
    pub fn parse_delegate<T: Iterator<Item = char>>(
        char: Option<char>,
        _: &mut Vec<Token>,
        _: &mut Parser<T>,
    ) -> ParsingState {
        Delegate(char.expect("Delegate as main function not possible"))
    }

    /// Parses a string delimited by the input char.
    // The string will be represented as List with the symbol `string` as first element and the parsed string as symbol as second element.
    pub fn parse_string<T: Iterator<Item = char>>(
        char: Option<char>,
        vec: &mut Vec<Token>,
        parser: &mut Parser<T>,
    ) -> ParsingState {
        use std::str::FromStr;
        let mut str = String::new();
        loop {
            if let Some(handle) = parser.get() {
                let new_char = handle.char();
                if let Some(char) = char {
                    if new_char == char {
                        let list = List(vec![
                            Symbol(String::from_str("string").unwrap()),
                            Symbol(str),
                        ]);
                        vec.push(list);
                        return Fine;
                    }
                }
                str.push(new_char)
            } else {
                if char.is_none() {
                    let list = List(vec![
                        Symbol(String::from_str("string").unwrap()),
                        Symbol(str),
                    ]);
                    vec.push(list);
                    return Fine;
                } else {
                    panic!("End of file inside string");
                }
            }
        }
    }

    /// Parses a single line comment delimited by `'\n'`
    pub fn parse_comment<T: Iterator<Item = char>>(
        _: Option<char>,
        _: &mut Vec<Token>,
        parser: &mut Parser<T>,
    ) -> ParsingState {
        loop {
            if let Some(handle) = parser.get() {
                let new_char = handle.char();
                if new_char == '\n' {
                    return Fine;
                }
            } else {
                return Finished;
            }
        }
    }

    /// Parses a list and adds it to the current list `vec`
    pub fn parse_list<T: Iterator<Item = char>>(
        char: Option<char>,
        vec: &mut Vec<Token>,
        parser: &mut Parser<T>,
    ) -> ParsingState {
        let mut in_vec = Vec::new();
        let result = parse_list_inline(char, &mut in_vec, parser);
        vec.push(List(in_vec));
        result
    }

    /// When `bracket` represents a bracket, it returns `Some` matching closing bracket, else `None` is returned.
    pub fn closing_bracket(bracket: char) -> Option<char> {
        match bracket {
            '(' => Some(')'),
            ')' => Some('('),
            '[' => Some(']'),
            ']' => Some('['),
            '{' => Some('}'),
            '}' => Some('{'),
            '<' => Some('>'),
            '>' => Some('<'),
            _ => None,
        }
    }

    /// Parses a list and appends it to the current list `vec`
    pub fn parse_list_inline<T: Iterator<Item = char>>(
        char: Option<char>,
        vec: &mut Vec<Token>,
        parser: &mut Parser<T>,
    ) -> ParsingState {
        let mut str = String::new();
        let (end, set_back) = if let Some(char) = char {
            let close = closing_bracket(char).expect("This character is not a list delimiter");
            (Some(close), Some(parser.set(close, Some(parse_delegate))))
        } else {
            (None, None)
        };
        let result = loop {
            if let Some(handle) = parser.get() {
                if handle.is_macro() {
                    if !str.is_empty() {
                        vec.push(Symbol(str));
                        str = String::new();
                    }
                    let state = handle.call(vec).unwrap();
                    match state {
                        Fine => (),
                        Finished => {
                            if char.is_none() {
                                break Finished;
                            } else {
                                panic!("End of file inside list")
                            }
                        }
                        Delegate(char) => {
                            if let Some(end) = end {
                                if char == end {
                                    if !str.is_empty() {
                                        vec.push(Symbol(str));
                                    }
                                    break Fine;
                                } else {
                                    panic!("Unexpected delegate")
                                }
                            } else {
                                panic!("Unexpected delegate")
                            }
                        }
                    }
                } else {
                    let char = handle.char();
                    if let Some(end) = end {
                        if end == char {}
                    }
                    str.push(char);
                }
            } else {
                if char.is_none() {
                    break Finished;
                } else {
                    panic!("End of file inside list")
                }
            }
        };
        if let (Some(end), Some(set_back)) = (end, set_back) {
            parser.set(end, set_back);
        }
        result
    }

    /// Parses a sublist as left associative infix operation using `char` as infix operator.
    pub fn parse_infix_left<T: Iterator<Item = char>>(
        char: Option<char>,
        vec: &mut Vec<Token>,
        parser: &mut Parser<T>,
    ) -> ParsingState {
        let mut str = String::new();
        let mut new_vec = Vec::new();
        let mut char_string = String::new();
        char_string.push(char.expect("Infix can only be called with a character"));
        new_vec.push(Symbol(char_string));
        new_vec.push(vec.pop().expect("Infix operator cannot stand alone"));
        loop {
            if let Some(handle) = parser.get() {
                if handle.is_macro() {
                    if !str.is_empty() {
                        new_vec.push(Symbol(str));
                        vec.push(List(new_vec));
                        handle.discard();
                        break Fine;
                    }
                    let state = handle.call(&mut new_vec).unwrap();
                    match state {
                        Fine => (),
                        Finished => break Finished,
                        Delegate(char) => break Delegate(char),
                    }
                } else {
                    let char = handle.char();
                    str.push(char);
                }
            } else {
                if char.is_none() {
                    break Finished;
                } else {
                    panic!("End of file inside list")
                }
            }
        }
    }
}