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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use std::fmt;

use num::ToPrimitive;

#[cfg(feature = "compile")]
use serde::{Serialize, Deserialize};

use crate::Value;

/// Denotes a specific position within a script.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "compile", derive(Serialize, Deserialize))]
pub struct Pos {
    pub filename: String,
    pub line: usize,
    pub col: usize,
}
impl Pos {
    /**
    Constructs a `Pos` at the beginning of the given filename, i.e. line 1
    column 1.
    */
    #[must_use]
    pub fn start(filename: &str) -> Self {
        Pos {
            filename: filename.into(),
            line: 1,
            col: 1,
        }
    }
    pub(crate) fn from_value(v: &Value) -> Option<Self> {
        if let Value::Struct(hm) = v {
            return Some(Pos {
                filename: match &hm.get("filename")?.clone_out().val {
                    Value::String(s) => s.clone(),
                    _ => return None,
                },
                line: match &hm.get("line")?.clone_out().val {
                    Value::Number(n) => n.to_usize()?,
                    _ => return None,
                },
                col: match &hm.get("col")?.clone_out().val {
                    Value::Number(n) => n.to_usize()?,
                    _ => return  None,
                },
            });
        }
        None
    }
}
impl fmt::Display for Pos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}:{}", self.filename, self.line, self.col)
    }
}

enum SplitAmount {
    Set(usize),
    Increase(isize),
}
enum SplitItem<'a> {
    Lines(&'a mut Lines),
    Exprs(&'a mut Exprs),
}
impl<'a> SplitItem<'a> {
    fn get_pos(&self) -> Pos {
        match self {
            SplitItem::Lines(ls) => ls.pos.clone(),
            SplitItem::Exprs(es) => es.pos.clone(),
        }
    }
    fn get_remainder(&self) -> String {
        match self {
            SplitItem::Lines(ls) => ls.remainder.clone(),
            SplitItem::Exprs(es) => es.remainder.clone(),
        }
    }

    fn set_remainder(&mut self, rem: String) {
        match self {
            SplitItem::Lines(ls) => ls.remainder = rem,
            SplitItem::Exprs(es) => es.remainder = rem,
        }
    }
    fn pos_set_line(&mut self, amount: SplitAmount) {
        let mut line = match self {
            SplitItem::Lines(ls) => ls.pos.line,
            SplitItem::Exprs(es) => es.pos.line,
        };
        match amount {
            SplitAmount::Set(a) => line = a,
            SplitAmount::Increase(a) => {
                let iline = line.to_isize().unwrap();
                if a <= iline {
                    line = (iline + a).to_usize().unwrap();
                }
            },
        };
        match self {
            SplitItem::Lines(ls) => ls.pos.line = line,
            SplitItem::Exprs(es) => es.pos.line = line,
        }
    }
    fn pos_set_col(&mut self, amount: SplitAmount) {
        let mut col = match self {
            SplitItem::Lines(ls) => ls.pos.col,
            SplitItem::Exprs(es) => es.pos.col,
        };
        match amount {
            SplitAmount::Set(a) => col = a,
            SplitAmount::Increase(a) => {
                let icol = col.to_isize().unwrap();
                if a <= icol {
                    col = (icol + a).to_usize().unwrap();
                }
            },
        }
        match self {
            SplitItem::Lines(ls) => ls.pos.col = col,
            SplitItem::Exprs(es) => es.pos.col = col,
        }
    }
}
trait SplitResult {
    fn new(pos: Pos, data: String) -> Self;
}
fn split<'a, SR>(si: &mut SplitItem<'a>, schar: char) -> Option<SR>
where
    SR: SplitResult,
{
    let remainder = si.get_remainder();
    if remainder.is_empty() {
        return None;
    }

    let remainder: Vec<char> = remainder.chars().collect();
    let mut sc: usize = 0;
    // Eat whitespace before token
    while sc < remainder.len() && remainder[sc].is_whitespace() {
        match remainder.get(sc).unwrap() {
            '\n' => {
                si.pos_set_line(SplitAmount::Increase(1));
                si.pos_set_col(SplitAmount::Set(1));
            },
            '\t' => si.pos_set_col(SplitAmount::Increase(4)),
            _ => si.pos_set_col(SplitAmount::Increase(1)),
        }
        sc += 1;
    }
    let startpos = si.get_pos();

    // Find the next schar that's not inside a container
    let mut containers: Vec<char> = vec![];
    let mut prev: Option<char> = None;
    while sc < remainder.len() {
        match remainder.get(sc).unwrap() {
            c if c == &schar => {
                if containers.is_empty() {
                    break;
                }
            },
            '/' => { // Skip comments
                if let Some(p) = prev {
                    if p == '/' && containers.is_empty() {
                        loop {
                            sc += 1;
                            match remainder.get(sc) {
                                Some('\n') => {
                                    si.pos_set_line(SplitAmount::Increase(1));
                                    break;
                                },
                                None => break,
                                _ => {},
                            }
                        }
                        break;
                    }
                }
            },
            '\n' => si.pos_set_line(SplitAmount::Increase(1)),

            '(' => containers.push('('),
            '{' => containers.push('{'),
            '[' => containers.push('['),
            ')' => {
                if containers.last() == Some(&'(') {
                    containers.pop();
                } else {
                    panic!("mismatched containers at {}: {:?}", si.get_pos(), containers);
                }
            },
            '}' => {
                if containers.last() == Some(&'{') {
                    containers.pop();
                } else {
                    panic!("mismatched containers at {}: {:?}", si.get_pos(), containers);
                }
            },
            ']' => {
                if containers.last() == Some(&'[') {
                    containers.pop();
                } else {
                    panic!("mismatched containers at {}: {:?}", si.get_pos(), containers);
                }
            },

            _ => {},
        }
        prev = Some(remainder[sc]);
        sc += 1;
    }

    // Split off the front up to the found schar
    let data = si.get_remainder().get(0..sc)?.trim().to_string();
    si.set_remainder(
        si.get_remainder().get(sc+1..)
            .unwrap_or("")
            .to_string()
    );
    if data.is_empty() {
        return None;
    }
    Some(SR::new(startpos, data))
}

pub struct Line {
    pub pos: Pos,
    pub data: String,
}
impl fmt::Display for Line {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.pos, self.data)
    }
}
impl SplitResult for Line {
    fn new(pos: Pos, data: String) -> Self {
        Self { pos, data }
    }
}
#[derive(Debug)]
pub struct Lines {
    pos: Pos,
    remainder: String,
}
impl Lines {
    pub fn split(scriptname: &str, script: &str, pos: Option<Pos>) -> Lines {
        Lines {
            pos: match pos {
                Some(pos) => pos,
                None => Pos::start(scriptname)
            },
            remainder: script.into(),
        }
    }
}
impl Iterator for Lines {
    type Item = Line;
    fn next(&mut self) -> Option<Self::Item> {
        split(&mut SplitItem::Lines(self), ';')
    }
}

pub struct Expr {
    pub pos: Pos,
    pub data: String,
}
impl SplitResult for Expr {
    fn new(pos: Pos, data: String) -> Self {
        Self { pos, data }
    }
}
pub struct Exprs {
    pos: Pos,
    remainder: String,
}
impl Exprs {
    pub fn split(line: &Line) -> Exprs {
        Exprs {
            pos: line.pos.clone(),
            remainder: line.data.clone(),
        }
    }
}
impl Iterator for Exprs {
    type Item = Expr;
    fn next(&mut self) -> Option<Self::Item> {
        split(&mut SplitItem::Exprs(self), ',')
    }
}

/// Easily differentiates `Token`s.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "compile", derive(Serialize, Deserialize))]
pub enum TokenType {
    /// Anything alphanumeric not beginning with a number.
    Identifier,
    /// Anything numeric containing at most one `.` and `e` each.
    Number,
    /**
    Anything enclosed by double quotes.
    May contain escaped quotes, newlines, tabs, and backslashes.
    */
    String,
    /**
    A collection of untokenized data.
    Enclosed in either `()`, `[]`, or `{}`.
    */
    Container,
    /// Another symbol, typically an operator. May have multiple characters.
    Symbol,
    Comment,
}
impl TokenType {
    fn from_value(v: &Value) -> Option<Self> {
        if let Value::Enum(_es, e) = v {
            return Some(match &*(**e).0 {
                "Identifier" => TokenType::Identifier,
                "Number" => TokenType::Number,
                "String" => TokenType::String,
                "Container" => TokenType::Container,
                "Symbol" => TokenType::Symbol,
                "Comment" => TokenType::Comment,
                _ => return None,
            });
        }
        None
    }
}

/**
A piece of the tokenized script.

Usually a singular piece but may be a `Container`.
*/
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "compile", derive(Serialize, Deserialize))]
pub struct Token {
    pub ttype: TokenType,
    pub pos: Pos,
    pub data: String,
}
impl Token {
    pub(crate) fn from_value(v: &Value) -> Option<Self> {
        if let Value::Struct(hm) = v {
            return Some(Token {
                ttype: TokenType::from_value(&hm.get("ttype")?.clone_out().val)?,
                pos: Pos::from_value(&hm.get("pos")?.clone_out().val)?,
                data: match &hm.get("data")?.clone_out().val {
                    Value::String(s) => s.clone(),
                    _ => return None,
                },
            });
        }
        None
    }
}
impl fmt::Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}
#[derive(Debug, Clone)]
pub struct Tokens {
    pos: Pos,
    remainder: String,
}
impl Tokens {
    pub fn tokenize(expr: &Expr) -> Tokens {
        Tokens {
            pos: expr.pos.clone(),
            remainder: expr.data.clone(),
        }
    }
}
impl Iterator for Tokens {
    type Item = Token;
    fn next(&mut self) -> Option<Self::Item> {
        if self.remainder.is_empty() {
            return None;
        }

        let remainder: Vec<char> = self.remainder.chars().collect();
        let mut tc: usize = 0;
        // Eat whitespace before token
        while tc < remainder.len() && remainder[tc].is_whitespace() {
            match remainder.get(tc).unwrap() {
                '\t' => self.pos.col += 4,
                _ => self.pos.col += 1,
            }
            tc += 1;
        }
        let startpos = self.pos.clone();

        // Find the next token type
        let ttype: TokenType = {
            match remainder.get(tc) {
                Some(&nc) => {
                    if nc.is_alphabetic() || nc == '_' {
                        TokenType::Identifier
                    } else if nc.is_numeric() {
                        TokenType::Number
                    } else if nc == '"' {
                        TokenType::String
                    } else if nc == '/' {
                        match remainder.get(tc+1) {
                            Some('/') => TokenType::Comment,
                            _ => TokenType::Symbol,
                        }
                    } else {
                        match nc {
                            '(' | ')' | '{' | '}' | '[' | ']' => TokenType::Container,
                            _ => TokenType::Symbol,
                        }
                    }
                },
                None => return None,
            }
        };
        tc += 1;

        // Find the next token change
        while tc < remainder.len() {
            let nc = remainder[tc];
            match nc {
                '\n' => {
                    self.pos.line += 1;
                    self.pos.col = 1;
                },
                '\t' => self.pos.col += 4,
                _ => self.pos.col += 1,
            }

            match ttype {
                TokenType::Identifier => {
                    // Allow alphanumeric and underscores
                    if !nc.is_alphanumeric() && nc != '_' {
                        break;
                    }
                },
                TokenType::Number => {
                    // Allow numbers, a single period, and a single 'e'/'E'
                    // TODO add support for hex and binary numbers
                    if !nc.is_numeric() {
                        let token = self.remainder.get(0..=tc)?.trim();
                        if token.matches('.').count() > 1
                            || token.to_lowercase().matches('e').count() > 1
                            || !token.to_lowercase()
                                .replace('.', "")
                                .replace('e', "")
                                .chars().all(char::is_numeric)
                        {
                            // Check that if there's a dot that it's not for Op::Dot
                            let dot = token.find('.');
                            if let Some(dot) = dot {
                                if let Some(dec) =  token.get(dot+1..) {
                                    if !dec.chars().all(char::is_numeric) {
                                        tc -= 1;
                                    }
                                }
                            }
                            break;
                        }
                    }
                },
                TokenType::String => {
                    // Remove escaped backslashes then remove escaped quotes to determine actual quotes
                    let token = self.remainder.get(0..=tc)?.trim();
                    let unescaped = token.replace(r"\\", "")
                        .replace(r#"\""#, "");

                    if unescaped.len() > 1 && unescaped.ends_with('"') {
                        tc += 1;
                        break;
                    }
                },
                TokenType::Container => {
                    // Check container matching
                    let mut containers = vec![];
                    let token: Vec<char> = self.remainder.get(0..=tc)?.trim()
                        .chars().collect();
                    for c in &token {
                        match c {
                            '(' | '{' | '[' => containers.push(c),
                            ')' => {
                                if containers.is_empty() || containers.last().unwrap() != &&'(' {
                                    panic!("mismatched containers at {}: {:?}", self.pos, token);
                                }
                                containers.pop();
                            },
                            '}' => {
                                if containers.is_empty() || containers.last().unwrap() != &&'{' {
                                    panic!("mismatched containers at {}: {:?}", self.pos, token);
                                }
                                containers.pop();
                            },
                            ']' => {
                                if containers.is_empty() || containers.last().unwrap() != &&'[' {
                                    panic!("mismatched containers at {}: {:?}", self.pos, token);
                                }
                                containers.pop();
                            },
                            _ => {},
                        }
                    }

                    // If the original container is closed then we're done
                    if containers.is_empty() {
                        tc += 1;
                        break;
                    }
                },
                TokenType::Symbol => {
                    let token = self.remainder.get(0..=tc)?.trim();
                    match token {
                        "::" |
                        "**" |
                        "<<" |
                        ">>" |
                        "<=>" |
                        "<=" |
                        ">=" |
                        "==" |
                        "!=" |
                        "&&" |
                        "||" |
                        ".." |
                        "..=" |
                        "->" |
                        "<-" |
                        "=>" |
                        "|>" => {},
                        _ => break,
                    }
                },
                TokenType::Comment => {},
            }
            tc += 1;
        }

        // Split off the front up to the found token change
        let token = self.remainder.get(0..tc)?.trim().to_string();
        self.remainder = self.remainder.get(tc..)
            .unwrap_or("")
            .to_string();
        if token.is_empty() {
            return None;
        }
        Some(Token {
            ttype,
            pos: startpos,
            data: token,
        })
    }
}

pub fn unescape(s: &str) -> String {
    s.chars()
        .fold((String::new(), None), |(mut ns, prev), c| {
            if let Some('\\') = prev {
                match c {
                    '\\' => {
                        return (ns, None);
                    },
                    '"' => {
                        ns.pop();
                        ns.push(c);
                        return (ns, None);
                    },
                    'n' => {
                        ns.pop();
                        ns.push('\n');
                        return (ns, None);
                    },
                    't' => {
                        ns.pop();
                        ns.push('\t');
                        return (ns, None);
                    },
                    _ => {},
                }
            }
            ns.push(c);
            (ns, Some(c))
        }).0
}