luaparse-rs 0.1.1

Multi-version Lua parser supporting Lua 5.1-5.4 and Luau
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! Turns source text into a stream of tokens.
//!
//! You normally won't use this module directly. The [`Parser`](crate::Parser)
//! calls [`lex_for_version`] internally. But the types here are public so you
//! can inspect tokens if you need to.

use alloc::{string::String, vec::Vec, format};

use logos::Logos;
use crate::{Span, LexError};

/// A single token produced by the lexer.
///
/// Includes Lua keywords, operators, literals, and punctuation.
/// The lexer is version agnostic; version specific keyword demotion
/// (e.g. treating `continue` as an identifier in Lua 5.1) happens
/// in [`lex_for_version`].
#[derive(Logos, Debug, Clone, PartialEq)]
#[logos(skip r"[ \t\r\n]+")]
pub enum Token {
    #[token("true")]
    True,
    
    #[token("false")]
    False,
    
    #[token("nil")]
    Nil,
    
    #[token("and")]
    And,
    
    #[token("break")]
    Break,
    
    #[token("do")]
    Do,
    
    #[token("else")]
    Else,
    
    #[token("elseif")]
    Elseif,
    
    #[token("end")]
    End,
    
    #[token("for")]
    For,
    
    #[token("function")]
    Function,
    
    #[token("if")]
    If,
    
    #[token("in")]
    In,
    
    #[token("local")]
    Local,
    
    #[token("not")]
    Not,
    
    #[token("or")]
    Or,
    
    #[token("repeat")]
    Repeat,
    
    #[token("return")]
    Return,
    
    #[token("then")]
    Then,
    
    #[token("until")]
    Until,
    
    #[token("while")]
    While,
    
    #[token("continue")]
    Continue,
    
    #[token("export")]
    Export,
    
    #[token("type")]
    Type,
    
    #[token("goto")]
    Goto,
    
    #[token("const")]
    Const,
    
    // here, we use \p{L} for any unciode letter and \p{N} for any unicode number
    // as lua 5.3+ allows for unicode identifiers to be used
    // see: https://www.lua.org/manual/5.4/manual.html#3.1
    #[regex(r"[\p{L}_][\p{L}\p{N}_]*", |lex| lex.slice().to_string())]
    Identifier(String),
    
   #[regex(r"0[xX][0-9a-fA-F_]*(\.[0-9a-fA-F_]*)?([pP][+-]?\d*)?|\d[0-9_]*(\.\d[0-9_]*)?([eE][+-]?\d*)?|\.\d[0-9_]*([eE][+-]?\d*)?|0[bB][01_]*", |lex| lex.slice().to_string())]
    Number(String),
    
    #[regex(r#""([^"\\]|\\.)*""#, parse_string)]
    #[regex(r#"'([^'\\]|\\.)*'"#, parse_string)]
    String(String),
    
    #[token("`", parse_interpolation_parts)]
    InterpolatedString(Vec<InterpolationPart>),
    
    #[regex(r"--", parse_comment)]
    Comment(String),
    
    #[regex(r"\[[=]*\[", parse_long_string)]
    LongString(String),
    
    #[token("+")]
    Plus,
    
    #[token("-")]
    Minus,
    
    #[token("*")]
    Star,
    
    #[token("/")]
    Slash,
    
    #[token("//")]
    FloorDiv,
    
    #[token("%")]
    Percent,
    
    #[token("^")]
    Caret,
    
    #[token("#")]
    Hash,
    
    #[token("==")]
    EqEq,
    
    #[token("~=")]
    NotEq,
    
    #[token("<=")]
    LessEq,
    
    #[token(">=")]
    GreaterEq,
    
    #[token("<")]
    Less,
    
    #[token(">")]
    Greater,
    
    #[token("=")]
    Eq,
    
    #[token("+=")]
    PlusEq,
    
    #[token("-=")]
    MinusEq,
    
    #[token("*=")]
    StarEq,
    
    #[token("/=")]
    SlashEq,
    
    #[token("//=")]
    FloorDivEq,
    
    #[token("%=")]
    PercentEq,
    
    #[token("^=")]
    CaretEq,
    
    #[token("..=")]
    ConcatEq,
    
    #[token("(")]
    LParen,
    
    #[token(")")]
    RParen,
    
    #[token("{")]
    LBrace,
    
    #[token("}")]
    RBrace,
    
    #[token("[")]
    LBracket,
    
    #[token("]")]
    RBracket,
    
    #[token("::")]
    ColonColon,
    
    #[token(":")]
    Colon,
    
    #[token(";")]
    Semi,
    
    #[token(",")]
    Comma,
    
    #[token("...")]
    Dot3,
    
    #[token("..")]
    Dot2,
    
    #[token(".")]
    Dot,
    
    #[token("->")]
    Arrow,
    
    #[token("|")]
    Pipe,
    
    #[token("&")]
    Ampersand,
    
    #[token("?")]
    Question,
    
    #[token("@")]
    At,
    
    #[token("<<")]
    LeftShift,
    
    #[token(">>")]
    RightShift,
    
    #[token("~")]
    Tilde,
    
    Eof,
}

/// A piece of a Luau interpolated string token.
///
/// The lexer splits `` `hello {expr} world` `` into a sequence of these parts
/// so the parser can handle the embedded expressions.
#[derive(Debug, Clone, PartialEq)]
pub enum InterpolationPart {
    /// A literal text segment.
    Text(String),
    /// The byte range of an embedded expression.
    ExprSpan { start: usize, end: usize },
}

fn parse_string(lex: &mut logos::Lexer<Token>) -> Option<String> {
    let slice = lex.slice();
    let content = &slice[1..slice.len() - 1];
    Some(unescape_string(content))
}

fn parse_interpolation_parts(lex: &mut logos::Lexer<Token>) -> Option<Vec<InterpolationPart>> {
    let start = lex.span().end;
    let source = lex.source();
    let bytes = source.as_bytes();
    
    let mut parts = Vec::new();
    let mut current_text = String::new();
    let mut pos = start;
    
    while pos < bytes.len() {
        match bytes[pos] {
            b'`' => {
                if !current_text.is_empty() {
                    parts.push(InterpolationPart::Text(current_text));
                }
                lex.bump(pos - start + 1);
                return Some(parts);
            }
            b'{' => {
                if !current_text.is_empty() {
                    parts.push(InterpolationPart::Text(current_text.clone()));
                    current_text.clear();
                }
                
                let expr_start = pos + 1;
                let mut depth = 1;
                pos += 1;
                
                while pos < bytes.len() && depth > 0 {
                    match bytes[pos] {
                        b'{' => depth += 1,
                        b'}' => depth -= 1,
                        _ => {}
                    }
                    pos += 1;
                }
                
                if depth != 0 {
                    return None;
                }
                
                let expr_end = pos - 1;
                parts.push(InterpolationPart::ExprSpan {
                    start: expr_start,
                    end: expr_end,
                });
            }
            b'\\' if pos + 1 < bytes.len() => {
                match bytes[pos + 1] {
                    b'n' => {
                        current_text.push('\n');
                        pos += 2;
                    }
                    b't' => {
                        current_text.push('\t');
                        pos += 2;
                    }
                    b'r' => {
                        current_text.push('\r');
                        pos += 2;
                    }
                    b'\\' | b'`' | b'{' | b'}' => {
                        current_text.push(bytes[pos + 1] as char);
                        pos += 2;
                    }
                    _ => {
                        current_text.push(bytes[pos] as char);
                        pos += 1;
                    }
                }
            }
            b => {
                current_text.push(b as char);
                pos += 1;
            }
        }
    }
    
    None
}

fn parse_comment(lex: &mut logos::Lexer<Token>) -> Option<String> {
    let start = lex.span().end;
    let source = lex.source();
    let rest = &source[start..];
    
    // Check if this is a block comment: --[[ or --[=*[
    if rest.starts_with('[') {
        let after_bracket = &rest[1..];
        let eq_count = after_bracket.chars().take_while(|&c| c == '=').count();
        if after_bracket.len() > eq_count && after_bracket[eq_count..].starts_with('[') {
            // It's a block comment; find the matching closing ]=*]
            let closing = format!("]{}]", "=".repeat(eq_count));
            let block_start = 1 + eq_count + 1; // skip [=*[
            let content_start = start + block_start;
            
            if let Some(end_pos) = source[content_start..].find(&closing) {
                let content = source[content_start..content_start + end_pos].to_string();
                lex.bump(block_start + end_pos + closing.len());
                return Some(content);
            } else {
                // Unterminated block comment; consume rest as comment
                let content = source[content_start..].to_string();
                lex.bump(source.len() - start);
                return Some(content);
            }
        }
    }
    
    // Regular line comment: consume until newline or EOF
    if let Some(newline_pos) = rest.find('\n') {
        let content = rest[..newline_pos].trim().to_string();
        lex.bump(newline_pos);
        Some(content)
    } else {
        let content = rest.trim().to_string();
        lex.bump(rest.len());
        Some(content)
    }
}

fn parse_long_string(lex: &mut logos::Lexer<Token>) -> Option<String> {
    let slice = lex.slice();
    
    let equals_count = slice.chars().filter(|&c| c == '=').count();
    let closing = format!("]{}]", "=".repeat(equals_count));
    
    let start = lex.span().end;
    let source = lex.source();
    
    let actual_start = if source[start..].starts_with('\n') {
        start + 1
    } else if source[start..].starts_with("\r\n") {
        start + 2
    } else {
        start
    };
    
    if let Some(end_pos) = source[actual_start..].find(&closing) {
        let content = source[actual_start..actual_start + end_pos].to_string();
        lex.bump(actual_start - start + end_pos + closing.len());
        Some(content)
    } else {
        None
    }
}

fn unescape_string(s: &str) -> String {
    let mut result = String::new();
    let mut chars = s.chars().peekable();
    
    while let Some(ch) = chars.next() {
        if ch == '\\' {
            match chars.next() {
                Some('n') => result.push('\n'),
                Some('t') => result.push('\t'),
                Some('r') => result.push('\r'),
                Some('\\') => result.push('\\'),
                Some('"') => result.push('"'),
                Some('\'') => result.push('\''),
                Some('0') => result.push('\0'),
                Some('a') => result.push('\x07'), // bell
                Some('b') => result.push('\x08'), // backspace
                Some('f') => result.push('\x0C'), // form feed
                Some('v') => result.push('\x0B'), // vertical tab
                
                // \xHH
                Some('x') => {
                    let mut hex = String::new();
                    if let Some(&h1) = chars.peek() {
                        if h1.is_ascii_hexdigit() {
                            hex.push(chars.next().unwrap());
                            if let Some(&h2) = chars.peek() {
                                if h2.is_ascii_hexdigit() {
                                    hex.push(chars.next().unwrap());
                                }
                            }
                        }
                    }
                    if let Ok(byte) = u8::from_str_radix(&hex, 16) {
                        result.push(byte as char);
                    } else {
                        result.push('\\');
                        result.push('x');
                        result.push_str(&hex);
                    }
                }
                
                // \u{XXXX}
                Some('u') => {
                    if chars.peek() == Some(&'{') {
                        chars.next(); // consume '{'
                        let mut hex = String::new();
                        
                        while let Some(&ch) = chars.peek() {
                            if ch == '}' {
                                chars.next();
                                break;
                            }
                            if ch.is_ascii_hexdigit() {
                                hex.push(chars.next().unwrap());
                            } else {
                                break;
                            }
                        }
                        
                        if let Ok(code) = u32::from_str_radix(&hex, 16) {
                            if let Some(unicode_char) = char::from_u32(code) {
                                result.push(unicode_char);
                            }
                        }
                    } else {
                        result.push('\\');
                        result.push('u');
                    }
                }
                
                // \z
                Some('z') => {
                    while let Some(&ch) = chars.peek() {
                        if ch.is_whitespace() {
                            chars.next();
                        } else {
                            break;
                        }
                    }
                }
                
                // \ddd
                Some(d) if d.is_ascii_digit() => {
                    let mut num = String::new();
                    num.push(d);
                    
                    for _ in 0..2 {
                        if let Some(&next) = chars.peek() {
                            if next.is_ascii_digit() {
                                num.push(chars.next().unwrap());
                            } else {
                                break;
                            }
                        }
                    }
                    
                    if let Ok(byte) = num.parse::<u8>() {
                        result.push(byte as char);
                    } else {
                        result.push('\\');
                        result.push_str(&num);
                    }
                }
                
                Some(c) => {
                    result.push('\\');
                    result.push(c);
                }
                None => result.push('\\'),
            }
        } else {
            result.push(ch);
        }
    }
    
    result
}

/// Tokenizes source code into a list of `(Token, Span)` pairs.
///
/// This is the version agnostic entry point. If the source starts with a
/// `#!` shebang line, it is silently skipped. For version aware tokenization
/// (which demotes certain keywords to identifiers based on the Lua version),
/// use [`lex_for_version`] instead.
pub fn lex(source: &str) -> Result<Vec<(Token, Span)>, LexError> {
    // skip shebang line if present as this is a unix execution hint, not a language token
    let source = if source.starts_with("#!") {
        match source.find('\n') {
            Some(pos) => &source[pos + 1..],
            None => "",
        }
    } else {
        source
    };

    let mut tokens = Vec::new();
    let mut lexer = Token::lexer(source);
    
    while let Some(token_result) = lexer.next() {
        let span = lexer.span();
        match token_result {
            Ok(token) => {
                if let Token::Number(ref num) = token {
                    if !validate_number(num) {
                        return Err(LexError::InvalidNumber { span });
                    }
                }
                tokens.push((token, span));
            }
            Err(_) => {
                return Err(LexError::InvalidNumber { span });
            }
        }
    }
    
    let eof_pos = source.len();
    tokens.push((Token::Eof, eof_pos..eof_pos));
    
    Ok(tokens)
}

fn validate_number(s: &str) -> bool {
    if s.starts_with("0x") || s.starts_with("0X") {
        // HEX
        // has to have atleast one digit after 0x
        let after_prefix = &s[2..];
        if after_prefix.is_empty() {
            return false;
        }
        
        // check for valid hex with the optional p exponent
        let parts: Vec<&str> = after_prefix.split(|c| c == 'p' || c == 'P').collect();
        if parts.len() > 2 {
            return false;
        }
        
        // the first part must be valid hex (with an optional .)
        let hex_part = parts[0].replace('_', "");
        if !hex_part.chars().all(|c| c.is_ascii_hexdigit() || c == '.') {
            return false;
        }
        
        // if we encounter an exponent, then we validate it
        if parts.len() == 2 {
            let exp = parts[1].replace('_', "");
            let exp = exp.trim_start_matches('+').trim_start_matches('-');
            if exp.is_empty() || !exp.chars().all(|c| c.is_ascii_digit()) {
                return false;
            }
        }
    } else if s.starts_with("0b") || s.starts_with("0B") {
        // BINARY
        // has to have atleast one digit
        let after_prefix = &s[2..].replace('_', "");
        if after_prefix.is_empty() || !after_prefix.chars().all(|c| c == '0' || c == '1') {
            return false;
        }
    } else {
        // DECIMAL
        let cleaned = s.replace('_', "");
        
        // has to have at least one digit somewhere
        if !cleaned.chars().any(|c| c.is_ascii_digit()) {
            return false;
        }
        
        if cleaned.contains('e') || cleaned.contains('E') {
            let parts: Vec<&str> = cleaned.split(|c| c == 'e' || c == 'E').collect();
            if parts.len() != 2 {
                return false;
            }
            
            let exp = parts[1].trim_start_matches('+').trim_start_matches('-');
            if exp.is_empty() || !exp.chars().all(|c| c.is_ascii_digit()) {
                return false;
            }
        }
    }
    
    true
}

/// Tokenizes source code with version aware keyword handling.
///
/// Calls [`lex`] first, then demotes keywords that don't exist in version `V`
/// back to plain identifiers. For example, `continue` becomes
/// `Token::Identifier("continue")` when parsing as [`Lua51`](crate::Lua51).
pub fn lex_for_version<V: crate::marker::LuaVersion>(
    source: &str,
) -> Result<Vec<(Token, Span)>, LexError> {
    let tokens = lex(source)?;

    Ok(tokens
        .into_iter()
        .map(|(token, span)| {
            let t = match token {
                Token::Continue if !V::HAS_CONTINUE => Token::Identifier("continue".to_string()),
                Token::Export if !V::HAS_EXPORT => Token::Identifier("export".to_string()),
                Token::Type if !V::HAS_TYPE_ANNOTATIONS => Token::Identifier("type".to_string()),
                Token::Goto if !V::HAS_GOTO => Token::Identifier("goto".to_string()),
                Token::Const if !V::HAS_CONST => Token::Identifier("const".to_string()),
                t => t,
            };
            (t, span)
        })
        .collect()) 
}