1
use crate::errors::RecoverableParseError;
2
use crate::parser::traversal::WalkDFS;
3
use capitalize::Capitalize;
4
use std::collections::HashSet;
5
use tree_sitter::Node;
6

            
7
1016
pub fn detect_syntactic_errors(
8
1016
    source: &str,
9
1016
    tree: &tree_sitter::Tree,
10
1016
    errors: &mut Vec<RecoverableParseError>,
11
1016
) {
12
1016
    let mut malformed_lines_reported = HashSet::new();
13

            
14
1016
    let root_node = tree.root_node();
15
22784
    let retract: &dyn Fn(&tree_sitter::Node) -> bool = &|node: &tree_sitter::Node| {
16
22784
        node.is_missing() || node.is_error() || node.start_position() == node.end_position()
17
22784
    };
18

            
19
22784
    for node in WalkDFS::with_retract(&root_node, &retract) {
20
22784
        if node.start_position() == node.end_position() {
21
212
            errors.push(classify_missing_token(node));
22
212
            continue;
23
22572
        }
24
22572
        if node.is_error() {
25
1277
            let line = node.start_position().row;
26
            // If this line has already been reported as malformed, skip all error nodes on this line
27
1277
            if malformed_lines_reported.contains(&line) {
28
407
                continue;
29
870
            }
30
870
            if is_malformed_line_error(&node, source) {
31
259
                malformed_lines_reported.insert(line);
32
259
                let start_byte = node.start_byte();
33
259
                let end_byte = node.end_byte();
34

            
35
259
                let last_char = source.lines().nth(line).map_or(0, |l| l.len());
36
259
                errors.push(RecoverableParseError::new(
37
259
                    format!(
38
                        "Malformed line {}: '{}'",
39
259
                        line + 1,
40
259
                        source.lines().nth(line).unwrap_or("")
41
                    ),
42
259
                    Some(tree_sitter::Range {
43
259
                        start_byte,
44
259
                        end_byte,
45
259
                        start_point: tree_sitter::Point {
46
259
                            row: line,
47
259
                            column: 0,
48
259
                        },
49
259
                        end_point: tree_sitter::Point {
50
259
                            row: line,
51
259
                            column: last_char,
52
259
                        },
53
259
                    }),
54
                ));
55
259
                continue;
56
611
            } else {
57
611
                errors.push(classify_unexpected_token_error(node, source));
58
611
            }
59
611
            continue;
60
21295
        }
61
    }
62
1016
}
63

            
64
/// Classifies a missing token node and generates a diagnostic with a context-aware message.
65
212
fn classify_missing_token(node: Node) -> RecoverableParseError {
66
212
    let start = node.start_position();
67
212
    let end = node.end_position();
68

            
69
212
    let message = if let Some(parent) = node.parent() {
70
212
        match parent.kind() {
71
212
            "letting_statement" => "Missing Expression or Domain".to_string(),
72
179
            _ => format!("Missing {}", user_friendly_token_name(node.kind(), false)),
73
        }
74
    } else {
75
        format!("Missing {}", user_friendly_token_name(node.kind(), false))
76
    };
77

            
78
212
    RecoverableParseError::new(
79
212
        message,
80
212
        Some(tree_sitter::Range {
81
212
            start_byte: node.start_byte(),
82
212
            end_byte: node.end_byte(),
83
212
            start_point: start,
84
212
            end_point: end,
85
212
        }),
86
    )
87
212
}
88

            
89
/// Classifies an unexpected token error node and generates a diagnostic.
90
611
fn classify_unexpected_token_error(node: Node, source_code: &str) -> RecoverableParseError {
91
611
    let message = if let Some(parent) = node.parent() {
92
611
        let start_byte = node.start_byte().min(source_code.len());
93
611
        let end_byte = node.end_byte().min(source_code.len());
94
611
        let src_token = &source_code[start_byte..end_byte];
95

            
96
611
        if parent.kind() == "program"
97
        // ERROR node is the direct child of the root node
98
        {
99
            // A case where the unexpected token is at the end of a valid statement
100
248
            format!("Unexpected {}", src_token)
101
            // }
102
        } else {
103
            // Unexpected token inside a construct
104
363
            format!(
105
                "Unexpected {} inside {}",
106
                src_token,
107
363
                user_friendly_token_name(parent.kind(), true)
108
            )
109
        }
110
    } else {
111
        // Should never happen since an ERROR node would always have a parent.
112
        "Unexpected token".to_string()
113
    };
114

            
115
611
    RecoverableParseError::new(
116
611
        message,
117
611
        Some(tree_sitter::Range {
118
611
            start_byte: node.start_byte(),
119
611
            end_byte: node.end_byte(),
120
611
            start_point: node.start_position(),
121
611
            end_point: node.end_position(),
122
611
        }),
123
    )
124
611
}
125

            
126
/// Determines if an error node represents a malformed line error.
127
593
fn is_malformed_line_error(node: &tree_sitter::Node, source: &str) -> bool {
128
593
    if node.start_position().column == 0 || error_node_out_of_range(node, source) {
129
182
        return true;
130
411
    }
131
411
    let parent = node.parent();
132
411
    let grandparent = parent.and_then(|n| n.parent());
133
411
    let root = grandparent.and_then(|n| n.parent());
134

            
135
411
    if let (Some(parent), Some(grandparent), Some(root)) = (parent, grandparent, root) {
136
220
        parent.kind() == "set_comparison"
137
            && grandparent.kind() == "comparison_expr"
138
            && root.kind() == "program"
139
    } else {
140
191
        false
141
    }
142
593
}
143

            
144
/// Coverts a token name into a more user-friendly format for error messages.
145
/// Removes underscores, replaces certain keywords with more natural language, and adds appropriate articles.
146
551
fn user_friendly_token_name(token: &str, article: bool) -> String {
147
551
    let capitalized = if token.contains("atom") {
148
33
        "Expression".to_string()
149
518
    } else if token == "COLON" {
150
36
        ":".to_string()
151
    } else {
152
482
        let friendly_name = token
153
482
            .replace("literal", "")
154
482
            .replace("int", "Integer")
155
482
            .replace("expr", "Expression")
156
482
            .replace('_', " ");
157
482
        friendly_name
158
482
            .split_whitespace()
159
862
            .map(|word| word.capitalize())
160
482
            .collect::<Vec<_>>()
161
482
            .join(" ")
162
    };
163

            
164
551
    if !article {
165
185
        return capitalized;
166
366
    }
167
366
    let first_char = capitalized.chars().next().unwrap();
168
366
    let article = match first_char.to_ascii_lowercase() {
169
102
        'a' | 'e' | 'i' | 'o' | 'u' => "an",
170
264
        _ => "a",
171
    };
172
366
    format!("{} {}", article, capitalized)
173
551
}
174

            
175
/// Returns true if the node's start or end column is out of range for its line in the source.
176
807
fn error_node_out_of_range(node: &tree_sitter::Node, source: &str) -> bool {
177
807
    let lines: Vec<&str> = source.lines().collect();
178
807
    let start = node.start_position();
179
807
    let end = node.end_position();
180

            
181
807
    let start_line_len = lines.get(start.row).map_or(0, |l| l.len());
182
807
    let end_line_len = lines.get(end.row).map_or(0, |l| l.len());
183

            
184
807
    (start.column > start_line_len) || (end.column > end_line_len)
185
807
}
186

            
187
#[cfg(test)]
188
mod test {
189

            
190
    use super::{detect_syntactic_errors, is_malformed_line_error, user_friendly_token_name};
191
    use crate::errors::RecoverableParseError;
192
    use crate::{parser::traversal::WalkDFS, util::get_tree};
193

            
194
    /// Helper function for tests to compare the actual error with the expected one.
195
3
    fn assert_essence_parse_error_eq(a: &RecoverableParseError, b: &RecoverableParseError) {
196
3
        assert_eq!(a.msg, b.msg, "error messages differ");
197
3
        assert_eq!(a.range, b.range, "error ranges differ");
198
3
    }
199

            
200
    #[test]
201
3
    fn malformed_line() {
202
3
        let source = " a,a,b: int(1..3)";
203
3
        let (tree, _) = get_tree(source).expect("Should parse");
204
3
        let root_node = tree.root_node();
205

            
206
3
        let error_node = WalkDFS::with_retract(&root_node, &|_node| false)
207
39
            .find(|node| node.is_error())
208
3
            .expect("Should find an error node");
209

            
210
3
        assert!(is_malformed_line_error(&error_node, source));
211
3
    }
212

            
213
    #[test]
214
3
    fn user_friendly_token_name_article() {
215
3
        assert_eq!(
216
3
            user_friendly_token_name("int_domain", false),
217
            "Integer Domain"
218
        );
219
3
        assert_eq!(
220
3
            user_friendly_token_name("int_domain", true),
221
            "an Integer Domain"
222
        );
223
        // assert_eq!(user_friendly_token_name("atom", true), "an Expression");
224
3
        assert_eq!(user_friendly_token_name("COLON", false), ":");
225
3
    }
226

            
227
    #[test]
228
3
    fn missing_domain() {
229
3
        let source = "find x:";
230
3
        let (tree, _) = get_tree(source).expect("Should parse");
231
3
        let mut errors = vec![];
232
3
        detect_syntactic_errors(source, &tree, &mut errors);
233
3
        assert_eq!(errors.len(), 1, "Expected exactly one diagnostic");
234

            
235
3
        let error = &errors[0];
236

            
237
3
        assert_essence_parse_error_eq(
238
3
            error,
239
3
            &RecoverableParseError::new(
240
3
                "Missing Domain".to_string(),
241
3
                Some(tree_sitter::Range {
242
3
                    start_byte: 7,
243
3
                    end_byte: 7,
244
3
                    start_point: tree_sitter::Point { row: 0, column: 7 },
245
3
                    end_point: tree_sitter::Point { row: 0, column: 7 },
246
3
                }),
247
3
            ),
248
        );
249
3
    }
250
}