hurl 8.0.0

Hurl, run and test HTTP requests
Documentation
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
 * Hurl (https://hurl.dev)
 * Copyright (C) 2026 Orange
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

use crate::jsonpath::parser::primitives::{expect_str, match_str};
use crate::jsonpath::parser::{ParseError, ParseErrorKind, ParseResult};
use hurl_core::reader::Reader;

/// Try to parse a string literal
/// if it does not start with a quote it returns `None` rather than a `ParseError`
pub fn try_parse(reader: &mut Reader) -> ParseResult<Option<String>> {
    if let Some(s) = try_double_quoted_string(reader)? {
        Ok(Some(s))
    } else if let Some(s) = try_single_quoted_string(reader)? {
        Ok(Some(s))
    } else {
        Ok(None)
    }
}

/// Try to parse a double-quoted string
fn try_double_quoted_string(reader: &mut Reader) -> ParseResult<Option<String>> {
    if match_str("\"", reader) {
        let mut result = String::new();

        while !reader.is_eof() {
            let pos = reader.cursor().pos;
            let ch = reader.peek().unwrap_or('\0');

            if ch == '"' {
                // End of string
                reader.read();
                return Ok(Some(result));
            } else if ch == '\'' {
                // Single quote is allowed in double-quoted strings
                result.push(ch);
                reader.read();
            } else if ch == '\\' {
                // Escape sequence
                reader.read(); // consume backslash
                let escaped = parse_escape_sequence(reader, '"')?;

                result.push(escaped);
            } else if is_unescaped_char(ch) {
                result.push(ch);
                reader.read();
            } else {
                return Err(ParseError::new(pos, ParseErrorKind::InvalidCharacter(ch)));
            }
        }

        Err(ParseError::new(
            reader.cursor().pos,
            ParseErrorKind::Expecting("\"".to_string()),
        ))
    } else {
        Ok(None)
    }
}

/// Try to parse a single-quoted string literal
fn try_single_quoted_string(reader: &mut Reader) -> ParseResult<Option<String>> {
    if match_str("\'", reader) {
        let mut result = String::new();

        while !reader.is_eof() {
            let pos = reader.cursor().pos;
            let ch = reader.peek().unwrap_or('\0');

            if ch == '\'' {
                // End of string
                reader.read();
                return Ok(Some(result));
            } else if ch == '"' {
                // Double quote is allowed in single-quoted strings
                result.push(ch);
                reader.read();
            } else if ch == '\\' {
                // Escape sequence
                reader.read(); // consume backslash
                let escaped = parse_escape_sequence(reader, '\'')?;
                result.push(escaped);
            } else if is_unescaped_char(ch) {
                result.push(ch);
                reader.read();
            } else {
                return Err(ParseError::new(pos, ParseErrorKind::InvalidCharacter(ch)));
            }
        }

        Err(ParseError::new(
            reader.cursor().pos,
            ParseErrorKind::Expecting("'".to_string()),
        ))
    } else {
        Ok(None)
    }
}

/// Check if character is unescaped according to the spec
fn is_unescaped_char(ch: char) -> bool {
    let code = ch as u32;

    // unescaped = %x20-21 / %x23-26 / %x28-5B / %x5D-D7FF / %xE000-10FFFF
    (0x20..=0x21).contains(&code) ||  // omit 0x22 "
    (0x23..=0x26).contains(&code) ||  // omit 0x27 '
    (0x28..=0x5B).contains(&code) ||  // omit 0x5C \
    (0x5D..=0xD7FF).contains(&code) || // skip surrogate code points
    (0xE000..=0x10FFFF).contains(&code)
}

/// Parse escape sequence after backslash
fn parse_escape_sequence(reader: &mut Reader, quote_char: char) -> ParseResult<char> {
    let pos = reader.cursor().pos;

    let ch = if let Some(value) = reader.read() {
        value
    } else {
        return Err(ParseError::new(
            pos,
            ParseErrorKind::Expecting("escape character".to_string()),
        ));
    };

    match ch {
        'b' => Ok('\u{0008}'),                  // BS backspace
        'f' => Ok('\u{000C}'),                  // FF form feed
        'n' => Ok('\n'),                        // LF line feed
        'r' => Ok('\r'),                        // CR carriage return
        't' => Ok('\t'),                        // HT horizontal tab
        '/' => Ok('/'),                         // slash
        '\\' => Ok('\\'),                       // backslash
        '"' if quote_char == '"' => Ok('"'),    // escaped double quote in double-quoted string
        '\'' if quote_char == '\'' => Ok('\''), // escaped single quote in single-quoted string
        'u' => {
            // Unicode escape sequence \uXXXX
            parse_unicode_escape(reader)
        }
        _ => Err(ParseError::new(
            pos,
            ParseErrorKind::InvalidEscapeSequence(format!("\\{}", ch)),
        )),
    }
}

/// Parse Unicode escape sequence after \u
fn parse_unicode_escape(reader: &mut Reader) -> ParseResult<char> {
    if let Some(ch) = try_non_surrogate(reader)? {
        Ok(ch)
    } else if let Some(ch) = try_surrogate_pair(reader)? {
        Ok(ch)
    } else {
        Err(ParseError::new(
            reader.cursor().pos,
            ParseErrorKind::InvalidUnicodeEscape("invalid unicode escape".to_string()),
        ))
    }
}

/// Try to parse a non-surrogate Unicode code unit
fn try_non_surrogate(reader: &mut Reader) -> ParseResult<Option<char>> {
    let save = reader.cursor();
    let c1 = hex_digit(reader)?;
    if c1 == 13 {
        // D
        let c2 = hex_digit(reader)?;
        if c2 >= 8 {
            reader.seek(save);
            Ok(None)
        } else {
            let c3 = hex_digit(reader)?;
            let c4 = hex_digit(reader)?;
            let code_point = c1 * 4096 + c2 * 256 + c3 * 16 + c4;
            Ok(Some(char::from_u32(code_point).ok_or_else(|| {
                ParseError::new(
                    save.pos,
                    ParseErrorKind::InvalidUnicodeEscape(format!("{:04X}", code_point)),
                )
            })?))
        }
    } else {
        let c2 = hex_digit(reader)?;
        let c3 = hex_digit(reader)?;
        let c4 = hex_digit(reader)?;
        let code_point = c1 * 4096 + c2 * 256 + c3 * 16 + c4;
        Ok(Some(char::from_u32(code_point).ok_or_else(|| {
            ParseError::new(
                save.pos,
                ParseErrorKind::InvalidUnicodeEscape(format!("{:04X}", code_point)),
            )
        })?))
    }
}

/// Try to parse a surrogate pair Unicode code unit
fn try_surrogate_pair(reader: &mut Reader) -> ParseResult<Option<char>> {
    let pos = reader.cursor().pos;
    if let Some(high_surrogate) = try_high_surrogate(reader)? {
        expect_str("\\u", reader)?;
        let low_surrogate = low_surrogate(reader)?;
        let combined = 0x10000 + (high_surrogate << 10) + low_surrogate;
        Ok(Some(char::from_u32(combined).ok_or_else(|| {
            ParseError::new(
                pos,
                ParseErrorKind::InvalidUnicodeEscape(format!("{:06X}", combined)),
            )
        })?))
    } else {
        Ok(None)
    }
}

/// Try to parse a high surrogate code unit
/// If found, returns the value of the high surrogate 10 bits
fn try_high_surrogate(reader: &mut Reader) -> ParseResult<Option<u32>> {
    if match_str("D", reader) {
        let c1 = hex_digit(reader)?;
        if (8..=11).contains(&c1) {
            let c2 = hex_digit(reader)?;
            let c3 = hex_digit(reader)?;
            Ok(Some((c1 - 8) * 256 + c2 * 16 + c3))
        } else {
            Ok(None)
        }
    } else {
        Ok(None)
    }
}

/// Parse a low surrogate code unit
/// If found, returns the value of the low surrogate 10 bits
fn low_surrogate(reader: &mut Reader) -> ParseResult<u32> {
    let pos = reader.cursor().pos;
    expect_str("D", reader).map_err(|_| {
        ParseError::new(pos, ParseErrorKind::Expecting("low surrogate".to_string()))
    })?;
    let c1 = hex_digit(reader)?;
    if c1 >= 12 {
        let c2 = hex_digit(reader)?;
        let c3 = hex_digit(reader)?;
        Ok((c1 - 12) * 256 + c2 * 16 + c3)
    } else {
        Err(ParseError::new(
            pos,
            ParseErrorKind::Expecting("low surrogate".to_string()),
        ))
    }
}

/// Parse a single hex digit and return its value
fn hex_digit(reader: &mut Reader) -> ParseResult<u32> {
    let pos = reader.cursor().pos;
    if let Some(ch) = reader.read() {
        if ch.is_ascii_hexdigit() {
            let value = ch.to_digit(16).unwrap();
            Ok(value)
        } else {
            Err(ParseError::new(
                pos,
                ParseErrorKind::Expecting("hex digit".to_string()),
            ))
        }
    } else {
        Err(ParseError::new(
            pos,
            ParseErrorKind::Expecting("hex digit".to_string()),
        ))
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::jsonpath::parser::{ParseError, ParseErrorKind};
    use hurl_core::reader::{CharPos, Pos, Reader};

    #[test]
    fn test_string_literal() {
        let mut reader = Reader::new("'store'");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "store".to_string()
        );
        assert_eq!(reader.cursor().index, CharPos(7));

        let mut reader = Reader::new("\"store\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "store".to_string()
        );
        assert_eq!(reader.cursor().index, CharPos(7));

        let mut reader = Reader::new("0");
        assert!(try_parse(&mut reader).unwrap().is_none());
        assert_eq!(reader.cursor().index, CharPos(0));
    }

    #[test]
    fn test_escape_character() {
        // Test escaped quotes
        let mut reader = Reader::new("'quoted\\' literal'");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "quoted' literal".to_string()
        );

        let mut reader = Reader::new("\"quoted\\\" literal\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "quoted\" literal".to_string()
        );

        // Test standard escape sequences
        let mut reader = Reader::new("\"line1\\nline2\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "line1\nline2".to_string()
        );

        let mut reader = Reader::new("\"tab\\there\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "tab\there".to_string()
        );

        let mut reader = Reader::new("\"back\\\\slash\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "back\\slash".to_string()
        );

        let mut reader = Reader::new("\"slash\\/here\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "slash/here".to_string()
        );
    }

    #[test]
    fn test_unicode_escape() {
        // Basic Unicode escape
        let mut reader = Reader::new("\"Hello \\u0041\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "Hello A".to_string()
        );

        // Test valid 4-digit Unicode character (Ï€ - pi symbol)
        let mut reader = Reader::new("\"\\u03C0\"");
        assert_eq!(try_parse(&mut reader).unwrap().unwrap(), "Ï€".to_string());

        // Test another valid 4-digit Unicode character (© - copyright symbol)
        let mut reader = Reader::new("\"\\u00A9\"");
        assert_eq!(try_parse(&mut reader).unwrap().unwrap(), "©".to_string());

        // Unicode surrogate pair - emoji
        let mut reader = Reader::new("\"\\uD83D\\uDE00\"");
        assert_eq!(try_parse(&mut reader).unwrap().unwrap(), "😀".to_string());
    }

    #[test]
    fn test_mixed_quotes() {
        // Single quote inside double-quoted string
        let mut reader = Reader::new("\"it's fine\"");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "it's fine".to_string()
        );

        // Double quote inside single-quoted string
        let mut reader = Reader::new("'say \"hello\"'");
        assert_eq!(
            try_parse(&mut reader).unwrap().unwrap(),
            "say \"hello\"".to_string()
        );
    }

    #[test]
    fn test_string_literal_error() {
        let mut reader = Reader::new("'store");
        assert_eq!(
            try_parse(&mut reader).unwrap_err(),
            ParseError::new(Pos::new(1, 7), ParseErrorKind::Expecting("'".to_string()))
        );

        let mut reader = Reader::new("\"store");
        assert_eq!(
            try_parse(&mut reader).unwrap_err(),
            ParseError::new(Pos::new(1, 7), ParseErrorKind::Expecting("\"".to_string()))
        );
    }

    #[test]
    fn test_invalid_escape_sequences() {
        let mut reader = Reader::new("\"invalid\\x escape\"");
        assert!(try_parse(&mut reader).is_err());

        let mut reader = Reader::new("\"incomplete\\u123\"");
        assert!(try_parse(&mut reader).is_err());

        let mut reader = Reader::new("\"incomplete\\u\"");
        assert!(try_parse(&mut reader).is_err());
    }

    #[test]
    fn test_parse_escape_sequence() {
        let mut reader = Reader::new("/");
        assert_eq!(parse_escape_sequence(&mut reader, '"').unwrap(), '/');
        assert_eq!(reader.cursor().index, CharPos(1));

        // Unicode Character 'GRINNING FACE' (U+1F600)
        let mut reader = Reader::new("uD83D\\uDE00\"");
        assert_eq!(parse_escape_sequence(&mut reader, '"').unwrap(), '😀');
        assert_eq!(reader.cursor().index, CharPos(11));
    }

    #[test]
    fn test_parse_unicode_escape() {
        let mut reader = Reader::new("00E9");
        assert_eq!(parse_unicode_escape(&mut reader).unwrap(), 'é');
        assert_eq!(reader.cursor().index, CharPos(4));

        // Unicode Character 'GRINNING FACE' (U+1F600)
        let mut reader = Reader::new("D83D\\uDE00\"");
        assert_eq!(parse_unicode_escape(&mut reader).unwrap(), '😀');
        assert_eq!(reader.cursor().index, CharPos(10));
    }

    #[test]
    fn test_non_surrogate() {
        let mut reader = Reader::new("00E9");
        assert_eq!(try_non_surrogate(&mut reader).unwrap().unwrap(), 'é');
        assert_eq!(reader.cursor().index, CharPos(4));

        let mut reader = Reader::new("D83D");
        assert!(try_non_surrogate(&mut reader).unwrap().is_none());
        assert_eq!(reader.cursor().index, CharPos(0));
    }

    #[test]
    fn test_surrogate_pairs() {
        // Unicode Character 'GRINNING FACE' (U+1F600)
        let mut reader = Reader::new("D83D\\uDE00\"");
        assert_eq!(try_surrogate_pair(&mut reader).unwrap().unwrap(), '😀');
        assert_eq!(reader.cursor().index, CharPos(10));

        let mut reader = Reader::new("00E9");
        assert!(try_surrogate_pair(&mut reader).unwrap().is_none());
        assert_eq!(reader.cursor().index, CharPos(0));

        let mut reader = Reader::new("D83D\\u00E9\"");
        assert_eq!(
            try_surrogate_pair(&mut reader).unwrap_err(),
            ParseError::new(
                Pos::new(1, 7),
                ParseErrorKind::Expecting("low surrogate".to_string())
            )
        );
    }

    #[test]
    fn test_high_surrogate() {
        let mut reader = Reader::new("D83D");
        assert_eq!(try_high_surrogate(&mut reader).unwrap().unwrap(), 61);
        assert_eq!(reader.cursor().index, CharPos(4));

        let mut reader = Reader::new("00E9");
        assert!(try_high_surrogate(&mut reader).unwrap().is_none());
        assert_eq!(reader.cursor().index, CharPos(0));
    }

    #[test]
    fn test_low_surrogate() {
        let mut reader = Reader::new("DE00");
        assert_eq!(low_surrogate(&mut reader).unwrap(), 512);
        assert_eq!(reader.cursor().index, CharPos(4));

        let mut reader = Reader::new("00E9");
        assert_eq!(
            low_surrogate(&mut reader).unwrap_err(),
            ParseError::new(
                Pos::new(1, 1),
                ParseErrorKind::Expecting("low surrogate".to_string())
            )
        );
    }

    #[test]
    fn test_hex_digit() {
        let mut reader = Reader::new("D83D");
        assert_eq!(hex_digit(&mut reader).unwrap(), 13);
        assert_eq!(reader.cursor().index, CharPos(1));

        let mut reader = Reader::new("x");
        assert_eq!(
            hex_digit(&mut reader).unwrap_err(),
            ParseError::new(
                Pos::new(1, 1),
                ParseErrorKind::Expecting("hex digit".to_string())
            )
        );
    }
}