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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Module for handling all symbols related operations.
//!
//! It defines a `Symbol` type which can be used to conveniently work with symbols in grammars and productions
//! and provide abstraction over normal collection of chars.
//!
//! It can be easily constructed from `&str`s.

use crate::tokenizer;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fmt;

const EPSILON: char = 'ε';

#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum SymbolError {
    /// Error resulting from the attempt to create a Symbol from an empty collection of chars.
    EmptySymbol,
    /// Error resulting from the the attempt to create a Symbol from an invalid collection of chars.
    /// It also provides the `String` used to attempt the Symbol creation, which generated the error.
    InvalidSymbol(String),
}

impl fmt::Display for SymbolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SymbolError::EmptySymbol => write!(f, "SymbolError: Empty input given for symbol"),
            SymbolError::InvalidSymbol(symbol) => {
                write!(f, "SymbolError: Invalid symbol \"{}\"", symbol)
            }
        }
    }
}

impl Error for SymbolError {}

/// The main type of this module. It provides abstraction over symbols.
/// Great to work with correct dataset when dealing with grammars and productions, or similar.
///
/// A Symbol can be made of every ascii-graphic chars,
/// like the one described in [rust documentation](https://doc.rust-lang.org/std/primitive.char.html#method.is_ascii_graphic)
/// for chars `ascii_graphic` method, which accept chars going from U+0021 '!' ..= U+007E '~', including 'ε', the "empty word" symbol.
///
/// Symbols can be logically divided in 2 major categories, defined as follow:
/// - non terminals, which start with an uppercase letter (A-Z)
/// - terminals, which start with everything else
///
/// Checking if a symbol is terminal or non terminal can be done using the according boolean methods you can find below.
///
/// A symbol can be created easily from strings, following these rules:
/// - string can contain any number of whitespace
/// - string has to contain at least one valid char (see above)
/// - string can't contain anything else
///
/// It also implements the `IntoIterator` to iterate over the collection of chars which make up the Symbol.
#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Symbol {
    string: String,
}

impl fmt::Display for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.string)
    }
}

impl std::convert::TryFrom<&str> for Symbol {
    type Error = SymbolError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Symbol::new(value)
    }
}

impl<'a> IntoIterator for &'a Symbol {
    type Item = char;
    type IntoIter = std::str::Chars<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.string.chars()
    }
}

impl Symbol {
    /// Creates a new Symbol based on the chars in the input.
    ///
    /// # Errors
    /// It can return an error if the input is empty or contains invalid chars.
    ///
    /// ## Examples
    /// ```rust
    /// use liblet::symbol::Symbol;
    ///
    /// // create a new symbol based from the string "mysymbol"
    /// let symbol = Symbol::new("mysymbol");
    ///
    /// assert!(symbol.is_ok());
    /// ```
    pub fn new(string: &str) -> Result<Symbol, SymbolError> {
        if string.is_empty() {
            return Err(SymbolError::EmptySymbol);
        }

        let s = string.to_string();

        if !Symbol::is_valid_symbol(string) {
            return Err(SymbolError::InvalidSymbol(s));
        }

        Ok(Symbol { string: s })
    }

    /// Return the `&str` representing this symbol chars.
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::symbol::Symbol;
    ///
    /// // create a new symbol based from the string "mysymbol"
    /// let symbol = Symbol::new("mysymbol")?;
    ///
    /// assert_eq!(symbol.as_str(), "mysymbol");
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn as_str(&self) -> &str {
        self.string.as_str()
    }

    /// Return the `String` representing this symbol chars.
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::symbol::Symbol;
    ///
    /// // create a new symbol based from the string "mysymbol"
    /// let symbol = Symbol::new("mysymbol")?;
    ///
    /// assert_eq!(symbol.to_string(), String::from("mysymbol"));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn to_string(&self) -> String {
        self.string.clone()
    }

    /// Check if symbol is terminal.
    /// You can expect the call to `is_non_terminal` to return an opposite result.
    ///
    /// `true` if symbol is terminal, `false` otherwise
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::symbol::Symbol;
    ///
    /// // create a new symbol based from the string "mysymbol"
    /// let symbol = Symbol::new("mysymbol").unwrap();
    ///
    /// assert!(symbol.is_terminal());
    /// assert!(!symbol.is_non_terminal());
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn is_terminal(&self) -> bool {
        !self.is_non_terminal()
    }

    /// Check if symbol is non terminal.
    /// You can expect the call to `is_terminal` to return an opposite result.
    ///
    /// `true` if symbol is non terminal, `false` otherwise
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::symbol::Symbol;
    ///
    /// // create a new symbol based from the string "Mysymbol"
    /// let symbol = Symbol::new("Mysymbol")?;
    ///
    /// assert!(symbol.is_non_terminal());
    /// assert!(!symbol.is_terminal());
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn is_non_terminal(&self) -> bool {
        match self.string.chars().next() {
            Some(c) => c.is_ascii_uppercase(),
            None => unreachable!(),
        }
    }

    /// Check if char is a valid symbol char.
    /// `true` if char is a valid symbol char, `false` otherwise
    ///
    /// # Examples
    /// ```rust
    /// use liblet::symbol::Symbol;
    ///
    /// assert!(Symbol::is_valid_char(&'c'));
    /// assert!(!Symbol::is_valid_char(&'\n'));
    /// ```
    pub fn is_valid_char(c: &char) -> bool {
        c.is_ascii_graphic()
    }

    /// Check if a string is a valid symbol.
    /// `true` if the string is a valid symbol, `false` otherwise
    ///
    /// # Examples
    /// ```rust
    /// use liblet::symbol::Symbol;
    ///
    /// assert!(Symbol::is_valid_symbol("A"));
    /// assert!(!Symbol::is_valid_symbol("\n"));
    /// ```
    pub fn is_valid_symbol(string: &str) -> bool {
        string == EPSILON.to_string() || string.chars().all(|c| Symbol::is_valid_char(&c))
    }

    /// Create a collection of symbols from a raw input string.
    ///
    /// # Errors
    /// Can return an error if the raw string can't be parsed to obtain actual symbols both due to wrong
    /// string formatting (symbols should be contiguous chars separated between them by every kind of whitespace) and due to
    /// symbol creation error (invalid char, empty symbol, etc.).
    ///
    /// In the case an empty or whitespace only string is given, it just returns an empty collection of symbols.
    ///
    /// # Examples
    /// ```rust
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use liblet::symbol::Symbol;
    ///
    /// let result = Symbol::from_string("A B C")?;
    ///
    /// assert_eq!(result.len(), 3);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn from_string(string: &str) -> Result<Vec<Symbol>, SymbolError> {
        tokenizer::symbols_from_string(string)
            .iter()
            .try_fold(Vec::new(), |mut acc, s| {
                let s = Symbol::new(s)?;
                acc.push(s);
                Ok(acc)
            })
    }

    /// Return a new symbol which represents the empty symbol 'ε'.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::symbol::Symbol;
    ///
    /// let symbol = Symbol::epsilon();
    ///
    /// assert_eq!(symbol.to_string(), "ε");
    /// ```
    pub fn epsilon() -> Symbol {
        Symbol {
            string: EPSILON.to_string(),
        }
    }

    /// Check if a symbol is the empty symbol ε.
    ///
    /// Return `true` if it is, `false` otherwise.
    ///
    /// # Examples
    /// ```rust
    /// use liblet::symbol::{Symbol,symbol};
    ///
    /// let symbol_epsilon = Symbol::epsilon();
    /// let symbol_other = symbol("A");
    ///
    /// assert!(symbol_epsilon.is_epsilon());
    /// assert!(!symbol_other.is_epsilon());
    /// ```
    pub fn is_epsilon(&self) -> bool {
        self == &Symbol::epsilon()
    }
}

/// Convenience function for creating a symbol from a raw string.
///
/// It returns the symbol directly,
/// as opposed to the `Result` returned from the Symbol constructor.
///
/// # Panics
/// Panics if some error occurred during symbol creation (see Symbol [consructor](struct.Symbol.html#method.new) for further details)
///
/// # Examples
/// ```rust
/// use liblet::symbol::symbol;
///
/// let symbol = symbol("A");
///
/// assert_eq!(symbol.as_str(), "A");
/// ```
pub fn symbol(string: &str) -> Symbol {
    Symbol::new(string).unwrap()
}

/// Convenience function for creating a collection of symbols from a raw string.
///
/// It returns the symbols directly,
/// as opposed to the `Result` returned from the Symbol `from_string` method.
///
/// # Panics
/// Panics if some error occurred during symbol creation or string parsing (see Symbol [from_string](struct.Symbol.html#method.from_string) method for further details)
///
/// # Examples
/// ```rust
/// use liblet::symbol::symbols;
///
/// let result = symbols("A B C");
///
/// assert_eq!(result.len(), 3);
/// ```
pub fn symbols(string: &str) -> Vec<Symbol> {
    Symbol::from_string(string).unwrap()
}

/// Convenience function for creating a string represention of
/// a collection of symbols
///
/// # Examples
/// ```rust
/// use liblet::symbol::{symbols,sentential_form};
///
/// let result = sentential_form(symbols("A B C"));
///
/// assert_eq!(result, "A B C");
/// ```
pub fn sentential_form<I>(symbols: I) -> String
where
    I: IntoIterator<Item = Symbol>,
{
    symbols
        .into_iter()
        .map(|s| s.to_string())
        .collect::<Vec<String>>()
        .join(" ")
}

#[cfg(test)]
mod tests {

    use super::*;
    use std::convert::TryFrom;
    use std::fmt::Write;

    // struct.Symbol

    #[test]
    fn new() {
        let symbol = "A";
        let result = Symbol::new(symbol);

        assert!(result.is_ok(), "Error creating new symbol from string");
    }

    #[test]
    fn new_empty_symbol() {
        let symbol = "";
        let result = Symbol::new(symbol);

        assert!(
            result.is_err(),
            "Creation of symbol from test input should return an Err result"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            SymbolError::EmptySymbol,
            "Creation of symbol from test input returned the wrong error"
        );
    }

    #[test]
    fn new_invalid_char() {
        let invalid_symbol = "Aλ";
        let result = Symbol::new(invalid_symbol);

        assert!(
            result.is_err(),
            "Creation of symbol from test input should return an Err result"
        );
        let e = result.unwrap_err();
        assert_eq!(
            e,
            SymbolError::InvalidSymbol(invalid_symbol.to_string()),
            "Creation of symbol from test input returned the wrong error"
        );
    }

    #[test]
    fn as_str() {
        let s = "A";
        assert_eq!(
            Symbol::new(s).unwrap().as_str(),
            s,
            "Symbol as_str doesn't correspond to expected one"
        )
    }

    #[test]
    fn to_string() {
        let s = "A";
        assert_eq!(
            Symbol::new(s).unwrap().to_string(),
            s,
            "Symbol to_string doesn't correspond to expected one"
        )
    }

    #[test]
    fn is_terminal() {
        let s = "a";
        let symbol = Symbol::new(s).unwrap();
        assert!(
            symbol.is_terminal(),
            "Symbol {} should be flagged as terminal",
            symbol
        );
        assert!(
            !symbol.is_non_terminal(),
            "Symbol {} should not be flagged as non terminal",
            symbol
        )
    }

    #[test]
    fn is_non_terminal() {
        let s = "A";
        let symbol = Symbol::new(s).unwrap();
        assert!(
            !symbol.is_terminal(),
            "Symbol {} should not flagged as terminal",
            symbol
        );
        assert!(
            symbol.is_non_terminal(),
            "Symbol {} should be flagged as non terminal",
            symbol
        )
    }

    #[test]
    fn is_valid_char() {
        let valid_symbol = 'A';
        let invalid_symbol_1 = 'Σ';
        let invalid_symbol_2 = '\n';
        assert!(
            Symbol::is_valid_char(&valid_symbol),
            "Char {} should be flagged as valid",
            valid_symbol
        );
        assert!(
            !Symbol::is_valid_char(&invalid_symbol_1),
            "Char {} should not be flagged as valid",
            invalid_symbol_1
        );
        assert!(
            !Symbol::is_valid_char(&invalid_symbol_2),
            "Char {} should not be flagged as valid",
            invalid_symbol_2
        );
        assert!(
            !Symbol::is_valid_char(&EPSILON),
            "Empty word char should not be flagged as valid"
        );
    }

    #[test]
    fn is_valid_symbol() {
        let valid_symbol = "A";
        let invalid_symbol_1 = "Σ";
        let invalid_symbol_2 = "\n";
        assert!(
            Symbol::is_valid_symbol(&valid_symbol),
            "String {} should be flagged as valid",
            valid_symbol
        );
        assert!(
            !Symbol::is_valid_symbol(&invalid_symbol_1),
            "String {} should not be flagged as valid",
            invalid_symbol_1
        );
        assert!(
            !Symbol::is_valid_symbol(&invalid_symbol_2),
            "String {} should not be flagged as valid",
            invalid_symbol_2
        );
        assert!(
            Symbol::is_valid_symbol(&EPSILON.to_string()),
            "Empty word char should be flagged as valid"
        );
    }

    #[test]
    fn from_string() {
        let symbols = vec![
            Symbol::new("A").unwrap(),
            Symbol::new("B").unwrap(),
            Symbol::new("a").unwrap(),
        ];
        assert_eq!(
            Symbol::from_string("A B a").unwrap(),
            symbols,
            "Parsed symbols"
        );
    }

    #[test]
    fn epsilon() {
        let symbol = Symbol::epsilon();
        assert_eq!(symbol.to_string(), EPSILON.to_string());
    }

    #[test]
    fn into_iter() {
        let symbol = super::symbol("Abcdef");
        let chars_check: &Vec<char> = &vec!['A', 'b', 'c', 'd', 'e', 'f'];
        let chars: &Vec<char> = &symbol.into_iter().collect();

        assert_eq!(
            chars, chars_check,
            "Chars collected from iterating over the symbol are not those expected"
        )
    }

    #[test]
    fn symbol_display() {
        let mut buf = String::new();
        let symbol = "A";

        let result = write!(buf, "{}", Symbol::new(symbol).unwrap());
        assert!(result.is_ok());
        assert_eq!(buf, symbol)
    }

    #[test]
    fn symbol_try_from() {
        let result = Symbol::try_from("A");
        assert!(result.is_ok());
    }

    #[test]
    fn symbol_try_from_invalid() {
        let result = Symbol::try_from("\n");
        assert!(result.is_err());
        let e = result.unwrap_err();
        assert_eq!(e, SymbolError::InvalidSymbol("\n".to_string()));
    }

    #[test]
    fn symbol_try_from_empty() {
        let result = Symbol::try_from("");
        assert!(result.is_err());
        let e = result.unwrap_err();
        assert_eq!(e, SymbolError::EmptySymbol);
    }

    #[test]
    fn symbol_is_epsilon() {
        let symbol_epsilon = Symbol::epsilon();
        let symbol_other = super::symbol("A");

        assert!(symbol_epsilon.is_epsilon());
        assert!(!symbol_other.is_epsilon());
    }

    // mod.symbol

    #[test]
    fn symbol() {
        let s = "A";
        assert_eq!(super::symbol(s).as_str(), s)
    }

    #[test]
    fn symbols() {
        let s = "A B C D";
        assert_eq!(
            super::symbols(s),
            vec![
                super::symbol("A"),
                super::symbol("B"),
                super::symbol("C"),
                super::symbol("D"),
            ]
        )
    }

    #[test]
    fn sentential_form() {
        let result = super::sentential_form(super::symbols("A B C"));
        assert_eq!(
            result, "A B C",
            "Sentential form from collection of symbols is wrong"
        );
    }

    // enum.SymbolError

    #[test]
    fn symbol_error_display_empty_symbol() {
        let mut buf = String::new();

        let result = write!(buf, "{}", SymbolError::EmptySymbol);
        assert!(result.is_ok());
        assert_eq!(buf, "SymbolError: Empty input given for symbol")
    }

    #[test]
    fn symbol_error_display_invalid_symbol() {
        let mut buf = String::new();
        let symbol = "\n";

        let result = write!(buf, "{}", SymbolError::InvalidSymbol(symbol.to_string()));
        assert!(result.is_ok());
        assert_eq!(buf, format!("SymbolError: Invalid symbol \"{}\"", symbol))
    }
}