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

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

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

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

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

            
69
78
    let message = if let Some(parent) = node.parent() {
70
78
        match parent.kind() {
71
78
            "letting_statement" => "Missing Expression or Domain".to_string(),
72
67
            _ => 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
78
    RecoverableParseError::new(
79
78
        message,
80
78
        Some(tree_sitter::Range {
81
78
            start_byte: node.start_byte(),
82
78
            end_byte: node.end_byte(),
83
78
            start_point: start,
84
78
            end_point: end,
85
78
        }),
86
    )
87
78
}
88

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

            
96
211
        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
90
            format!("Unexpected {}", src_token)
101
            // }
102
        } else {
103
            // Unexpected token inside a construct
104
121
            format!(
105
                "Unexpected {} inside {}",
106
                src_token,
107
121
                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
211
    RecoverableParseError::new(
116
211
        message,
117
211
        Some(tree_sitter::Range {
118
211
            start_byte: node.start_byte(),
119
211
            end_byte: node.end_byte(),
120
211
            start_point: node.start_position(),
121
211
            end_point: node.end_position(),
122
211
        }),
123
    )
124
211
}
125

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

            
135
211
    if let (Some(parent), Some(grandparent), Some(root)) = (parent, grandparent, root) {
136
110
        parent.kind() == "set_comparison"
137
            && grandparent.kind() == "comparison_expr"
138
            && root.kind() == "program"
139
    } else {
140
101
        false
141
    }
142
313
}
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
191
fn user_friendly_token_name(token: &str, article: bool) -> String {
147
191
    let capitalized = if token.contains("atom") {
148
11
        "Expression".to_string()
149
180
    } else if token == "COLON" {
150
12
        ":".to_string()
151
    } else {
152
168
        let friendly_name = token
153
168
            .replace("literal", "")
154
168
            .replace("int", "Integer")
155
168
            .replace("expr", "Expression")
156
168
            .replace('_', " ");
157
168
        friendly_name
158
168
            .split_whitespace()
159
302
            .map(|word| word.capitalize())
160
168
            .collect::<Vec<_>>()
161
168
            .join(" ")
162
    };
163

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

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

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

            
184
291
    (start.column > start_line_len) || (end.column > end_line_len)
185
291
}
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
1
    fn assert_essence_parse_error_eq(a: &RecoverableParseError, b: &RecoverableParseError) {
196
1
        assert_eq!(a.msg, b.msg, "error messages differ");
197
1
        assert_eq!(a.range, b.range, "error ranges differ");
198
1
    }
199

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

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

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

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

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

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

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