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
//  NULL.rs
//    by Lut99
//
//  Created:
//    19 Dec 2022, 10:04:38
//  Last edited:
//    08 Dec 2023, 11:09:15
//  Auto updated?
//    Yes
//
//  Description:
//!   Implements a traversal that resolves null-types from the tree,
//!   resolving them with more proper types.
//

use brane_dsl::ast::{Block, Expr, Literal, Program, Stmt};
use enum_debug::EnumDebug as _;

use crate::errors::AstError;
pub use crate::errors::NullError as Error;


/***** TESTS *****/
#[cfg(test)]
mod tests {
    use brane_dsl::ParserOptions;
    use brane_shr::utilities::{create_data_index, create_package_index, test_on_dsl_files};
    use specifications::data::DataIndex;
    use specifications::package::PackageIndex;

    use super::super::print::symbol_tables;
    use super::*;
    use crate::{CompileResult, CompileStage, compile_program_to};


    /// Tests the traversal by generating symbol tables for every file.
    #[test]
    fn test_null() {
        test_on_dsl_files("BraneScript", |path, code| {
            // Start by the name to always know which file this is
            println!("{}", (0..80).map(|_| '-').collect::<String>());
            println!("File '{}' gave us:", path.display());

            // Load the package index
            let pindex: PackageIndex = create_package_index();
            let dindex: DataIndex = create_data_index();

            let program: Program = match compile_program_to(code.as_bytes(), &pindex, &dindex, &ParserOptions::bscript(), CompileStage::Null) {
                CompileResult::Program(p, warns) => {
                    // Print warnings if any
                    for w in warns {
                        w.prettyprint(path.to_string_lossy(), &code);
                    }
                    p
                },
                CompileResult::Eof(err) => {
                    // Print the error
                    err.prettyprint(path.to_string_lossy(), &code);
                    panic!("Failed to analyse null-usage (see output above)");
                },
                CompileResult::Err(errs) => {
                    // Print the errors
                    for e in errs {
                        e.prettyprint(path.to_string_lossy(), &code);
                    }
                    panic!("Failed to analyse null-usage (see output above)");
                },

                _ => {
                    unreachable!();
                },
            };

            // Now print the symbol tables for prettyness
            symbol_tables::do_traversal(program, std::io::stdout()).unwrap();
            println!("{}\n\n", (0..80).map(|_| '-').collect::<String>());
        });
    }
}





/***** TRAVERSAL FUNCTIONS *****/
/// Traverses a Block to find any null-occurances.
///
/// # Arguments
/// - `block`: The Block to traverse.
/// - `errors`: The list that accumulates errors as we do the traversal.
///
/// # Returns
/// Nothing, but might change internal nodes to get rid of null-casts.
///
/// # Errors
/// This function may error if the user made incorrect usage of `null`. In that case, the error is appended to `errors` and the function might return early.
fn pass_block(block: &mut Block, errors: &mut Vec<Error>) {
    // Simply do all statements in this block
    for s in &mut block.stmts {
        pass_stmt(s, errors);
    }
}

/// Traverses a Stmt to find any null-occurances.
///
/// # Arguments
/// - `stmt`: The Stmt to traverse.
/// - `errors`: The list that accumulates errors as we do the traversal.
///
/// # Returns
/// Nothing, but might change internal nodes to get rid of null-casts.
///
/// # Errors
/// This function may error if the user made incorrect usage of `null`. In that case, the error is appended to `errors` and the function might return early.
fn pass_stmt(stmt: &mut Stmt, errors: &mut Vec<Error>) {
    // Match on the given statement
    use Stmt::*;
    match stmt {
        Block { block } => {
            pass_block(block, errors);
        },

        FuncDef { code, .. } => {
            pass_block(code, errors);
        },
        ClassDef { methods, .. } => {
            for m in methods {
                pass_stmt(m, errors);
            }
        },
        Return { expr, .. } => {
            if let Some(expr) = expr {
                pass_expr(expr, errors);
            }
        },

        If { cond, consequent, alternative, .. } => {
            pass_expr(cond, errors);
            pass_block(consequent, errors);
            if let Some(alternative) = alternative {
                pass_block(alternative, errors);
            }
        },
        For { initializer, condition, increment, consequent, .. } => {
            pass_stmt(initializer, errors);
            pass_expr(condition, errors);
            pass_stmt(increment, errors);
            pass_block(consequent, errors);
        },
        While { condition, consequent, .. } => {
            pass_expr(condition, errors);
            pass_block(consequent, errors);
        },
        Parallel { blocks, .. } => {
            for b in blocks {
                pass_block(b, errors);
            }
        },

        LetAssign { value, .. } => {
            // We'll allow it if this value is a null
            match value {
                // Null is allowed, and no need to traverse it
                brane_dsl::ast::Expr::Literal { literal: Literal::Null { .. } } => {},

                // Otherwise, traverse
                value => pass_expr(value, errors),
            }
        },
        Assign { value, .. } => {
            // We always crawl since null is not allowed
            pass_expr(value, errors);
        },
        Expr { expr, .. } => {
            pass_expr(expr, errors);
        },

        // The rest we don't care.
        Import { .. } | Empty {} => {},
        Attribute(_) | AttributeInner(_) => panic!("Encountered {:?} in resolve traversal", stmt.variant()),
    }
}

/// Traverses an Expr to get rid of null-casts.
///
/// Note that at this time, we have already treated any legal null's; so any we find here are always illegal.
///
/// # Arguments
/// - `expr`: The Expr to traverse.
/// - `errors`: The list that accumulates errors as we do the traversal.
///
/// # Returns
/// Nothing, but might change this or internal nodes to get rid of null-casts.
///
/// # Errors
/// This function may error if the user made incorrect usage of `null`. In that case, the error is appended to `errors` and the function might return early.
fn pass_expr(expr: &mut Expr, errors: &mut Vec<Error>) {
    // Match the expression given
    use Expr::*;
    match expr {
        Cast { expr, .. } => {
            pass_expr(expr, errors);
        },

        Call { expr, args, .. } => {
            // Pass 'em all
            pass_expr(expr, errors);
            for a in args {
                pass_expr(a, errors);
            }
        },
        Array { values, .. } => {
            for v in values {
                pass_expr(v, errors);
            }
        },
        ArrayIndex { array, index, .. } => {
            pass_expr(array, errors);
            pass_expr(index, errors);
        },
        Pattern { exprs, .. } => {
            for e in exprs {
                pass_expr(e, errors);
            }
        },

        UnaOp { expr, .. } => {
            pass_expr(expr, errors);
        },
        BinOp { lhs, rhs, .. } => {
            pass_expr(lhs, errors);
            pass_expr(rhs, errors);
        },
        Proj { lhs, rhs, .. } => {
            pass_expr(lhs, errors);
            pass_expr(rhs, errors);
        },

        Instance { properties, .. } => {
            for p in properties {
                pass_expr(&mut p.value, errors);
            }
        },
        Literal { literal } => {
            pass_literal(literal, errors);
        },

        // The rest we don't interact with
        Identifier { .. } | VarRef { .. } | Empty {} => {},
    }
}

/// Traverses a Literal to detect illegal usage of null.
///
/// Note that at this time, we have already treated any legal null's; so any we find here are always illegal.
///
/// # Arguments
/// - `lit`: The Literal to traverse.
/// - `errors`: The list that accumulates errors as we do the traversal.
///
/// # Errors
/// This function may error if the user made incorrect usage of `null`. In that case, the error is appended to `errors` and the function might return early.
fn pass_literal(lit: &Literal, errors: &mut Vec<Error>) {
    // We only do one thing: error if we see a `null` here
    if let Literal::Null { range } = lit {
        errors.push(Error::IllegalNull { range: range.clone() });
    }
}





/***** LIBRARY *****/
/// Resolves null-typing in the given `brane-dsl` AST.
///
/// Note that the symbol tables must already have been constructed.
///
/// The goal of this traversal is to get rid of `DataType::Null` occurrances, asserting that null is only used in let-assignments.
///
/// # Arguments
/// - `root`: The root node of the tree on which this compiler pass will be done.
///
/// # Returns
/// The same nodes as went in, but now with proper null-usage.
///
/// # Errors
/// This pass may throw multiple `AstError::NullError`s if the user made mistakes with their variable references.
pub fn do_traversal(root: Program) -> Result<Program, Vec<AstError>> {
    let mut root = root;

    // Iterate over the statements to find usage of nulls.
    let mut errors: Vec<Error> = vec![];
    pass_block(&mut root.block, &mut errors);

    // Returns the errors
    if errors.is_empty() { Ok(root) } else { Err(errors.into_iter().map(|e| e.into()).collect()) }
}