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
use crate::compiling::failing::failure::Failure;
use colored::Colorize;

use super::Metadata;

#[macro_export]
/// This macro is a syntax sugar for the name method
/// All this does is setting the new name without all the syntax clutter.
/// # Example
/// ```
/// # use heraclitus_compiler::prelude::*;
/// # struct MySyntax;
/// impl SyntaxModule<DefaultMetadata> for MySyntax {
///     syntax_name!("MySyntax");
/// #   fn new() -> Self { Self {} }
/// #   fn parse(&mut self, meta: &mut DefaultMetadata) -> SyntaxResult { Ok(()) }
///     // ...
/// }
/// ```
macro_rules! syntax_name {
    ($expr:expr) => {
        fn name() -> &'static str {
            $expr
        }
    };
}

/// Result that should be returned in the parsing phase
pub type SyntaxResult = Result<(), Failure>;

/// Trait for parsing
/// 
/// Trait that should be implemented in order to parse tokens with heraklit
/// ```
/// # use heraclitus_compiler::prelude::*;
/// struct MySyntax {
///     name: String
///     // ... (you decide what you need to store)
/// }
/// 
/// impl SyntaxModule<DefaultMetadata> for MySyntax {
///     syntax_name!("MySyntax");
/// 
///     fn new() -> MySyntax {
///         MySyntax {
///             name: format!(""),
///             // Default initialization
///         }
///     }
/// 
///     // Here you can parse the actual code
///     fn parse(&mut self, meta: &mut DefaultMetadata) -> SyntaxResult {
///         token(meta, "var")?;
///         self.name = variable(meta, vec!['_'])?;
///         Ok(())
///     }
/// }
/// ```
pub trait SyntaxModule<M: Metadata> {
    /// Create a new default implementation of syntax module
    fn new() -> Self;
    /// Name of this module
    fn name() -> &'static str;
    /// Parse and create AST
    /// 
    /// This method is fundamental in creating a functional AST node that can determine 
    /// if tokens provided by metadata can be consumed to create this particular AST node.
    fn parse(&mut self, meta: &mut M) -> SyntaxResult;
    /// Do not implement this function as this is a predefined function for debugging
    fn parse_debug(&mut self, meta: &mut M) -> SyntaxResult {
        match meta.get_debug() {
            Some(debug) => {
                let padding = "  ".repeat(debug);
                println!("{padding}[Entered] {}", Self::name());
                meta.set_debug(debug + 1);
                let time = std::time::Instant::now();
                let result = self.parse(meta);
                match result {
                    Ok(()) => println!("{padding}{} {} ({}ms)", "[Left]".green(), Self::name(), time.elapsed().as_millis()),
                    Err(_) => println!("{padding}{} {} ({}ms)", "[Failed]".red(), Self::name(), time.elapsed().as_millis())
                }
                meta.set_debug(debug);
                result
            }
            None => {
                meta.set_debug(0);
                self.parse_debug(meta)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::compiling::parser::pattern::*;
    use crate::compiling::parser::preset::*;
    use crate::compiling::{ Token, DefaultMetadata, Metadata };

    struct Expression {}
    impl SyntaxModule<DefaultMetadata> for Expression {
        syntax_name!("Expression");

        fn new() -> Self {
            Expression { }
        }
        fn parse(&mut self, meta: &mut DefaultMetadata) -> SyntaxResult {
            token(meta, "let")?;
            Ok(())
        }
    }

    #[test]
    fn test_token_match() {
        let mut exp = Expression {};
        let dataset1 = vec![
            Token {
                word: format!("let"),
                pos: (0, 0)
            }
        ];
        let dataset2 = vec![
            Token {
                word: format!("tell"),
                pos: (0, 0)
            }
        ];
        let path = Some(format!("path/to/file"));
        let result1 = exp.parse(&mut DefaultMetadata::new(dataset1, path.clone(), None));
        let result2 = exp.parse(&mut DefaultMetadata::new(dataset2, path.clone(), None));
        assert!(result1.is_ok());
        assert!(result2.is_err());
    }

    struct Preset {}
    impl SyntaxModule<DefaultMetadata> for Preset {
        syntax_name!("Preset");
        fn new() -> Self {
            Preset {  }
        }
        fn parse(&mut self, meta: &mut DefaultMetadata) -> SyntaxResult {
            variable(meta, vec!['_'])?;
            numeric(meta, vec![])?;
            number(meta, vec![])?;
            integer(meta, vec![])?;
            float(meta, vec![])?;
            Ok(())
        }
    }

    #[test]
    fn test_preset_match() {
        let mut exp = Preset {};
        let dataset = vec![
            // Variable
            Token { word: format!("_text"), pos: (0, 0) },
            // Numeric
            Token { word: format!("12321"), pos: (0, 0) },
            // Number
            Token { word: format!("-123.12"), pos: (0, 0) },
            // Integer
            Token { word: format!("-12"), pos: (0, 0) },
            // Float
            Token { word: format!("-.681"), pos: (0, 0)}
        ];
        let path = Some(format!("path/to/file"));
        let result = exp.parse(&mut DefaultMetadata::new(dataset, path, None));
        assert!(result.is_ok());
    }

    struct PatternModule {}
    impl SyntaxModule<DefaultMetadata> for PatternModule {
        syntax_name!("Pattern Module");
        fn new() -> Self {
            PatternModule {  }
        }
        #[allow(unused_must_use)]
        fn parse(&mut self, meta: &mut DefaultMetadata) -> SyntaxResult {
            // Any
            if let Ok(_) = token(meta, "apple") {}
            else if let Ok(_) = token(meta, "orange") {}
            else if let Ok(_) = token(meta, "banana") {}
            else { 
                if let Err(details) = token(meta, "banana") {
                    return Err(details);
                }
            }
            // Optional
            token(meta, "optional");
            // Syntax
            syntax(meta, &mut Expression::new())?;
            // Repeat
            loop {
                if let Err(_) = token(meta, "test") {
                    break;
                }
                if let Err(_) = token(meta, ",") {
                    break;
                }
            }
            // End token
            token(meta, "end");
            Ok(())
        }
    }

    #[test]
    fn rest_match() {
        let mut exp = PatternModule {};
        // Everything should pass
        let dataset1 = vec![
            Token { word: format!("orange"), pos: (0, 0) },
            Token { word: format!("optional"), pos: (0, 0) },
            Token { word: format!("let"), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!(","), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!("end"), pos: (0, 0) }
        ];
        // Token should fail
        let dataset2 = vec![
            Token { word: format!("kiwi"), pos: (0, 0) },
            Token { word: format!("optional"), pos: (0, 0) },
            Token { word: format!("let"), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!(","), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!("end"), pos: (0, 0) }
        ];
        // Syntax should fail
        let dataset3 = vec![
            Token { word: format!("orange"), pos: (0, 0) },
            Token { word: format!("tell"), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!(","), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!("end"), pos: (0, 0) }
        ];
        // Token should fail because of repeat matching (this , this) ,
        let dataset4 = vec![
            Token { word: format!("orange"), pos: (0, 0) },
            Token { word: format!("tell"), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!(","), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!("this"), pos: (0, 0) },
            Token { word: format!("end"), pos: (0, 0) }
        ];
        let path = Some(format!("path/to/file"));
        let result1 = exp.parse(&mut DefaultMetadata::new(dataset1, path.clone(), None));
        let result2 = exp.parse(&mut DefaultMetadata::new(dataset2, path.clone(), None));
        let result3 = exp.parse(&mut DefaultMetadata::new(dataset3, path.clone(), None));
        let result4 = exp.parse(&mut DefaultMetadata::new(dataset4, path.clone(), None));
        assert!(result1.is_ok());
        assert!(result2.is_err());
        assert!(result3.is_err());
        assert!(result4.is_err());
    }

}