1
/*
2
 * Hurl (https://hurl.dev)
3
 * Copyright (C) 2026 Orange
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *          http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 *
17
 */
18
use std::cmp;
19

            
20
use crate::ast::SourceInfo;
21
use crate::error;
22
use crate::error::DisplaySourceError;
23
use crate::reader::Pos;
24
use crate::text::{Style, StyledString};
25

            
26
/// Represents a parser error.
27
#[derive(Clone, Debug, PartialEq, Eq)]
28
pub struct ParseError {
29
    pub pos: Pos,
30
    pub recoverable: bool,
31
    pub kind: ParseErrorKind,
32
}
33

            
34
#[derive(Clone, Debug, PartialEq, Eq)]
35
pub enum ParseErrorKind {
36
    DuplicateSection,
37
    EscapeChar,
38
    Expecting { value: String },
39
    FileContentType,
40
    Filename,
41
    GraphQlVariables,
42
    HexDigit,
43
    InvalidCookieAttribute,
44
    InvalidDurationUnit(String),
45
    InvalidOption(String),
46
    Json(JsonErrorVariant),
47
    JsonPathExpr,
48
    Method { name: String },
49
    Multiline,
50
    MultilineLanguageHint(String),
51
    OddNumberOfHexDigits,
52
    Predicate,
53
    PredicateValue,
54
    RegexExpr { message: String },
55
    RequestSection,
56
    RequestSectionName { name: String },
57
    ResponseSection,
58
    ResponseSectionName { name: String },
59
    Space,
60
    Status,
61
    TemplateVariable,
62
    Unicode,
63
    UrlIllegalCharacter(char),
64
    UrlInvalidStart,
65
    Variable(String),
66
    Version,
67
    XPathExpr,
68
    Xml,
69
}
70

            
71
#[derive(Clone, Debug, PartialEq, Eq)]
72
pub enum JsonErrorVariant {
73
    MaxDepthExceeded { max_depth: usize },
74
    TrailingComma,
75
    ExpectingElement,
76
    EmptyElement,
77
}
78

            
79
impl ParseError {
80
    /// Creates a new error for the position `pos`, of type `inner`.
81
13240660
    pub fn new(pos: Pos, recoverable: bool, kind: ParseErrorKind) -> ParseError {
82
13240660
        ParseError {
83
13240660
            pos,
84
13240660
            recoverable,
85
13240660
            kind,
86
        }
87
    }
88
}
89

            
90
impl DisplaySourceError for ParseError {
91
1325
    fn source_info(&self) -> SourceInfo {
92
1325
        SourceInfo {
93
1325
            start: self.pos,
94
1325
            end: self.pos,
95
        }
96
    }
97

            
98
505
    fn description(&self) -> String {
99
505
        match self.kind {
100
20
            ParseErrorKind::DuplicateSection => "Parsing section".to_string(),
101
10
            ParseErrorKind::EscapeChar => "Parsing escape character".to_string(),
102
110
            ParseErrorKind::Expecting { .. } => "Parsing literal".to_string(),
103
10
            ParseErrorKind::FileContentType => "Parsing file content type".to_string(),
104
20
            ParseErrorKind::Filename => "Parsing filename".to_string(),
105
            ParseErrorKind::GraphQlVariables => "Parsing GraphQL variables".to_string(),
106
10
            ParseErrorKind::HexDigit => "Parsing hexadecimal number".to_string(),
107
10
            ParseErrorKind::InvalidCookieAttribute => "Parsing cookie attribute".to_string(),
108
20
            ParseErrorKind::InvalidOption(_) => "Parsing option".to_string(),
109
10
            ParseErrorKind::InvalidDurationUnit(_) => "Parsing duration".to_string(),
110
70
            ParseErrorKind::Json(_) => "Parsing JSON".to_string(),
111
            ParseErrorKind::JsonPathExpr => "Parsing JSONPath expression".to_string(),
112
60
            ParseErrorKind::Method { .. } => "Parsing method".to_string(),
113
            ParseErrorKind::Multiline => "Parsing multiline".to_string(),
114
10
            ParseErrorKind::MultilineLanguageHint(..) => "Parsing multiline".to_string(),
115
            ParseErrorKind::OddNumberOfHexDigits => "Parsing hex bytearray".to_string(),
116
10
            ParseErrorKind::Predicate => "Parsing predicate".to_string(),
117
20
            ParseErrorKind::PredicateValue => "Parsing predicate value".to_string(),
118
10
            ParseErrorKind::RegexExpr { .. } => "Parsing regex".to_string(),
119
            ParseErrorKind::RequestSection => "Parsing section".to_string(),
120
20
            ParseErrorKind::RequestSectionName { .. } => "Parsing request section name".to_string(),
121
            ParseErrorKind::ResponseSection => "Parsing section".to_string(),
122
            ParseErrorKind::ResponseSectionName { .. } => {
123
                "Parsing response section name".to_string()
124
            }
125
25
            ParseErrorKind::Space => "Parsing space".to_string(),
126
10
            ParseErrorKind::Status => "Parsing status code".to_string(),
127
10
            ParseErrorKind::TemplateVariable => "Parsing template variable".to_string(),
128
10
            ParseErrorKind::Unicode => "Parsing unicode literal".to_string(),
129
            ParseErrorKind::UrlIllegalCharacter(_) => "Parsing URL".to_string(),
130
            ParseErrorKind::UrlInvalidStart => "Parsing URL".to_string(),
131
10
            ParseErrorKind::Variable(_) => "Parsing variable".to_string(),
132
10
            ParseErrorKind::Version => "Parsing version".to_string(),
133
            ParseErrorKind::XPathExpr => "Parsing XPath expression".to_string(),
134
10
            ParseErrorKind::Xml => "Parsing XML".to_string(),
135
        }
136
    }
137

            
138
265
    fn fixme(&self, content: &[&str]) -> StyledString {
139
265
        let message = match &self.kind {
140
10
            ParseErrorKind::DuplicateSection => "the section is already defined".to_string(),
141
5
            ParseErrorKind::EscapeChar => "the escaping sequence is not valid".to_string(),
142
55
            ParseErrorKind::Expecting { value } => format!("expecting '{value}'"),
143
5
            ParseErrorKind::FileContentType => "expecting a content type".to_string(),
144
10
            ParseErrorKind::Filename => "expecting a filename".to_string(),
145
            ParseErrorKind::GraphQlVariables => {
146
                "GraphQL variables is not a valid JSON object".to_string()
147
            }
148
5
            ParseErrorKind::HexDigit => "expecting a valid hexadecimal number".to_string(),
149
            ParseErrorKind::InvalidCookieAttribute => {
150
5
                "the cookie attribute is not valid".to_string()
151
            }
152
5
            ParseErrorKind::InvalidDurationUnit(name) => {
153
5
                let valid_values = ["ms", "s"];
154
5
                let default = format!("Valid values are {}", valid_values.join(", "));
155
5
                let did_you_mean = did_you_mean(&valid_values, name.as_str(), &default);
156
5
                format!("the duration unit is not valid. {did_you_mean}")
157
            }
158
10
            ParseErrorKind::InvalidOption(name) => {
159
10
                let valid_values = [
160
10
                    "aws-sigv4",
161
10
                    "cacert",
162
10
                    "cert",
163
10
                    "compressed",
164
10
                    "connect-timeout",
165
10
                    "connect-to",
166
10
                    "delay",
167
10
                    "digest",
168
10
                    "header",
169
10
                    "http1.0",
170
10
                    "http1.1",
171
10
                    "http2",
172
10
                    "http2-prior-knowledge",
173
10
                    "http3",
174
10
                    "insecure",
175
10
                    "ipv4",
176
10
                    "ipv6",
177
10
                    "key",
178
10
                    "limit-rate",
179
10
                    "location",
180
10
                    "location-trusted",
181
10
                    "max-redirs",
182
10
                    "max-time",
183
10
                    "negotiate",
184
10
                    "netrc",
185
10
                    "netrc-file",
186
10
                    "netrc-optional",
187
10
                    "no-proxy",
188
10
                    "ntlm",
189
10
                    "output",
190
10
                    "path-as-is",
191
10
                    "pinnedpubkey",
192
10
                    "proxy",
193
10
                    "repeat",
194
10
                    "resolve",
195
10
                    "retry",
196
10
                    "retry-interval",
197
10
                    "skip",
198
10
                    "unix-socket",
199
10
                    "user",
200
10
                    "variable",
201
10
                    "variables-file",
202
10
                    "verbose",
203
10
                    "verbosity",
204
10
                    "very-verbose",
205
10
                ];
206
10
                let default = format!("Valid values are {}", valid_values.join(", "));
207
10
                let did_you_mean = did_you_mean(&valid_values, name.as_str(), &default);
208
10
                format!("the option name is not valid. {did_you_mean}")
209
            }
210
35
            ParseErrorKind::Json(variant) => match variant {
211
5
                JsonErrorVariant::MaxDepthExceeded { max_depth } => {
212
5
                    format!("maximum nesting depth of {max_depth} exceeded")
213
                }
214
10
                JsonErrorVariant::TrailingComma => "trailing comma is not allowed".to_string(),
215
                JsonErrorVariant::EmptyElement => {
216
5
                    "expecting an element; found empty element instead".to_string()
217
                }
218
                JsonErrorVariant::ExpectingElement => {
219
15
                    "expecting a boolean, number, string, array, object or null".to_string()
220
                }
221
            },
222
            ParseErrorKind::JsonPathExpr => "expecting a JSONPath expression".to_string(),
223
35
            ParseErrorKind::Method { name } => {
224
35
                let valid_values = [
225
35
                    "GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH",
226
35
                ];
227
35
                let default = format!("Valid values are {}", valid_values.join(", "));
228
35
                let did_you_mean = did_you_mean(&valid_values, name.as_str(), &default);
229
35
                format!("the HTTP method <{name}> is not valid. {did_you_mean}")
230
            }
231
            ParseErrorKind::Multiline => "the multiline is not valid".to_string(),
232
5
            ParseErrorKind::MultilineLanguageHint(name) => format!("Invalid language hint {name}"),
233
            ParseErrorKind::OddNumberOfHexDigits => {
234
                "expecting an even number of hex digits".to_string()
235
            }
236
5
            ParseErrorKind::Predicate => "expecting a predicate".to_string(),
237
10
            ParseErrorKind::PredicateValue => "invalid predicate value".to_string(),
238
5
            ParseErrorKind::RegexExpr { message } => format!("invalid Regex expression: {message}"),
239
            ParseErrorKind::RequestSection => {
240
                "this is not a valid section for a request".to_string()
241
            }
242
10
            ParseErrorKind::RequestSectionName { name } => {
243
10
                let valid_values = ["Query", "Form", "Multipart", "Cookies", "Options"];
244
10
                let default = format!("Valid values are {}", valid_values.join(", "));
245
10
                let did_you_mean = did_you_mean(&valid_values, name.as_str(), &default);
246
10
                format!("the section is not valid. {did_you_mean}")
247
            }
248
            ParseErrorKind::ResponseSection => {
249
                "this is not a valid section for a response".to_string()
250
            }
251
            ParseErrorKind::ResponseSectionName { name } => {
252
                let valid_values = ["Captures", "Asserts"];
253
                let default = "Valid values are Captures or Asserts";
254
                let did_your_mean = did_you_mean(&valid_values, name.as_str(), default);
255
                format!("the section is not valid. {did_your_mean}")
256
            }
257
20
            ParseErrorKind::Space => "expecting a space".to_string(),
258
5
            ParseErrorKind::Status => "HTTP status code is not valid".to_string(),
259
5
            ParseErrorKind::TemplateVariable => "expecting a variable".to_string(),
260
5
            ParseErrorKind::Unicode => "Invalid unicode literal".to_string(),
261
            ParseErrorKind::UrlIllegalCharacter(c) => format!("illegal character <{c}>"),
262
            ParseErrorKind::UrlInvalidStart => "expecting http://, https:// or {{".to_string(),
263
5
            ParseErrorKind::Variable(message) => message.clone(),
264
            ParseErrorKind::Version => {
265
5
                "HTTP version must be HTTP, HTTP/1.0, HTTP/1.1, HTTP/2 or HTTP/3".to_string()
266
            }
267
            ParseErrorKind::XPathExpr => "expecting a XPath expression".to_string(),
268
5
            ParseErrorKind::Xml => "invalid XML".to_string(),
269
        };
270

            
271
265
        let message = error::add_carets(&message, self.source_info(), content);
272
265
        let mut s = StyledString::new();
273
265
        s.push_with(&message, Style::new().red().bold());
274
265
        s
275
    }
276
}
277

            
278
impl crate::combinator::ParseError for ParseError {
279
3236400
    fn is_recoverable(&self) -> bool {
280
3236400
        self.recoverable
281
    }
282

            
283
223350
    fn to_recoverable(self) -> Self {
284
223350
        ParseError {
285
223350
            recoverable: true,
286
223350
            ..self
287
        }
288
    }
289

            
290
165
    fn to_non_recoverable(self) -> Self {
291
165
        ParseError {
292
165
            recoverable: false,
293
165
            ..self
294
        }
295
    }
296
}
297

            
298
60
fn did_you_mean(valid_values: &[&str], actual: &str, default: &str) -> String {
299
60
    if let Some(suggest) = suggestion(valid_values, actual) {
300
15
        format!("Did you mean {suggest}?")
301
    } else {
302
45
        default.to_string()
303
    }
304
}
305

            
306
60
fn suggestion(valid_values: &[&str], actual: &str) -> Option<String> {
307
780
    for value in valid_values {
308
780
        if levenshtein_distance(
309
780
            value.to_lowercase().as_str(),
310
780
            actual.to_lowercase().as_str(),
311
780
        ) < 2
312
        {
313
15
            return Some(value.to_string());
314
        }
315
    }
316
45
    None
317
}
318

            
319
// From https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Rust
320
780
fn levenshtein_distance(s1: &str, s2: &str) -> usize {
321
780
    let v1: Vec<char> = s1.chars().collect();
322
780
    let v2: Vec<char> = s2.chars().collect();
323

            
324
34100
    fn min3<T: Ord>(v1: T, v2: T, v3: T) -> T {
325
34100
        cmp::min(v1, cmp::min(v2, v3))
326
    }
327
34100
    fn delta(x: char, y: char) -> usize {
328
34100
        usize::from(x != y)
329
    }
330

            
331
780
    let mut column: Vec<usize> = (0..=v1.len()).collect();
332
4565
    for x in 1..=v2.len() {
333
4565
        column[0] = x;
334
4565
        let mut lastdiag = x - 1;
335
34100
        for y in 1..=v1.len() {
336
34100
            let olddiag = column[y];
337
34100
            column[y] = min3(
338
34100
                column[y] + 1,
339
34100
                column[y - 1] + 1,
340
34100
                lastdiag + delta(v1[y - 1], v2[x - 1]),
341
34100
            );
342
34100
            lastdiag = olddiag;
343
        }
344
    }
345
780
    column[v1.len()]
346
}
347

            
348
#[cfg(test)]
349
mod tests {
350
    use super::*;
351
    use crate::error::OutputFormat;
352

            
353
    #[test]
354
    fn test_levenshtein() {
355
        assert_eq!(levenshtein_distance("kitten", "sitting"), 3);
356
        assert_eq!(levenshtein_distance("Saturday", "Sunday"), 3);
357
    }
358

            
359
    #[test]
360
    fn test_suggestion() {
361
        let valid_values = ["Captures", "Asserts"];
362
        assert_eq!(
363
            suggestion(&valid_values, "Asserts"),
364
            Some("Asserts".to_string())
365
        );
366
        assert_eq!(
367
            suggestion(&valid_values, "Assert"),
368
            Some("Asserts".to_string())
369
        );
370
        assert_eq!(
371
            suggestion(&valid_values, "assert"),
372
            Some("Asserts".to_string())
373
        );
374
        assert_eq!(suggestion(&valid_values, "asser"), None);
375
    }
376

            
377
    #[test]
378
    fn test_parsing_error() {
379
        let content = "GET abc";
380
        let filename = "test.hurl";
381
        let error = ParseError {
382
            pos: Pos::new(1, 5),
383
            recoverable: false,
384
            kind: ParseErrorKind::UrlInvalidStart,
385
        };
386
        assert_eq!(
387
            error.render(filename, content, None, OutputFormat::Terminal(false)),
388
            r#"Parsing URL
389
  --> test.hurl:1:5
390
   |
391
 1 | GET abc
392
   |     ^ expecting http://, https:// or {{
393
   |"#
394
        );
395
    }
396
}