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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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