Skip to main content

wgslift_syntax/
lexer.rs

1//! Splits source text into tokens.
2
3use std::borrow::Cow;
4
5use crate::diagnostic::Diagnostic;
6use crate::span::{FileId, Span};
7
8/// The kind of a token.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[non_exhaustive]
11pub enum TokenKind {
12    /// A name or a keyword. The parser tells keywords from names by their text.
13    Ident,
14    /// An integer literal, with its suffix.
15    Int,
16    /// A floating-point literal, with its suffix.
17    Float,
18    /// A string literal, with its quotes.
19    Str,
20    /// A character literal, with its quotes.
21    Char,
22    /// An operator or punctuation mark.
23    Punct(Punct),
24    /// A character that is not part of the language.
25    Other,
26}
27
28/// Operators and punctuation marks.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30#[allow(missing_docs)]
31#[non_exhaustive]
32pub enum Punct {
33    LParen,
34    RParen,
35    LBracket,
36    RBracket,
37    LBrace,
38    RBrace,
39    Semi,
40    Comma,
41    Dot,
42    Colon,
43    Question,
44    Tilde,
45    Bang,
46    Plus,
47    Minus,
48    Star,
49    Slash,
50    Percent,
51    Caret,
52    Amp,
53    Pipe,
54    Eq,
55    Lt,
56    Gt,
57    PlusPlus,
58    MinusMinus,
59    PlusEq,
60    MinusEq,
61    StarEq,
62    SlashEq,
63    PercentEq,
64    CaretEq,
65    AmpEq,
66    PipeEq,
67    ShlEq,
68    ShrEq,
69    Shl,
70    Shr,
71    EqEq,
72    NotEq,
73    LtEq,
74    GtEq,
75    AndAnd,
76    OrOr,
77    Hash,
78    HashHash,
79    ColonColon,
80    Arrow,
81    Ellipsis,
82}
83
84/// Longest first, so that `<<=` wins over `<<` and `<`.
85const PUNCTS: [(&str, Punct); 49] = [
86    ("<<=", Punct::ShlEq),
87    ("...", Punct::Ellipsis),
88    (">>=", Punct::ShrEq),
89    ("##", Punct::HashHash),
90    ("::", Punct::ColonColon),
91    ("->", Punct::Arrow),
92    ("++", Punct::PlusPlus),
93    ("--", Punct::MinusMinus),
94    ("+=", Punct::PlusEq),
95    ("-=", Punct::MinusEq),
96    ("*=", Punct::StarEq),
97    ("/=", Punct::SlashEq),
98    ("%=", Punct::PercentEq),
99    ("^=", Punct::CaretEq),
100    ("&=", Punct::AmpEq),
101    ("|=", Punct::PipeEq),
102    ("<<", Punct::Shl),
103    (">>", Punct::Shr),
104    ("==", Punct::EqEq),
105    ("!=", Punct::NotEq),
106    ("<=", Punct::LtEq),
107    (">=", Punct::GtEq),
108    ("&&", Punct::AndAnd),
109    ("||", Punct::OrOr),
110    ("(", Punct::LParen),
111    (")", Punct::RParen),
112    ("[", Punct::LBracket),
113    ("]", Punct::RBracket),
114    ("{", Punct::LBrace),
115    ("}", Punct::RBrace),
116    (";", Punct::Semi),
117    (",", Punct::Comma),
118    (".", Punct::Dot),
119    (":", Punct::Colon),
120    ("?", Punct::Question),
121    ("~", Punct::Tilde),
122    ("!", Punct::Bang),
123    ("+", Punct::Plus),
124    ("-", Punct::Minus),
125    ("*", Punct::Star),
126    ("/", Punct::Slash),
127    ("%", Punct::Percent),
128    ("^", Punct::Caret),
129    ("&", Punct::Amp),
130    ("|", Punct::Pipe),
131    ("=", Punct::Eq),
132    ("<", Punct::Lt),
133    (">", Punct::Gt),
134    ("#", Punct::Hash),
135];
136
137impl Punct {
138    /// The source text of the mark.
139    pub fn as_str(self) -> &'static str {
140        PUNCTS
141            .iter()
142            .find(|(_, p)| *p == self)
143            .map_or("", |(s, _)| s)
144    }
145}
146
147/// One token.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Token {
150    /// What the token is.
151    pub kind: TokenKind,
152    /// The token's text. A token made by macro pasting or `#` has text that is
153    /// not in any file.
154    pub text: String,
155    /// Where the token's text is: in the file, or in the macro body it came from.
156    pub span: Span,
157    /// Space or a comment comes before the token on its line.
158    pub space_before: bool,
159    /// The token is the first one on its line.
160    pub line_start: bool,
161    /// For a token from a macro body: the macro call in the source it came from.
162    pub expanded_from: Option<Span>,
163}
164
165impl Token {
166    /// Where the token is in the text the author wrote: the macro call for a
167    /// token from a macro body, else the token itself.
168    pub fn site(&self) -> Span {
169        self.expanded_from.unwrap_or(self.span)
170    }
171
172    /// The token is this punctuation mark.
173    pub fn is(&self, punct: Punct) -> bool {
174        self.kind == TokenKind::Punct(punct)
175    }
176
177    /// The token is a name or keyword with this text.
178    pub fn is_word(&self, word: &str) -> bool {
179        self.kind == TokenKind::Ident && self.text == word
180    }
181}
182
183/// Splits `text` into tokens. Comments become space, and a backslash-newline is
184/// removed everywhere, also inside a token. Spans point at the text as written.
185pub fn lex(file: FileId, text: &str, diagnostics: &mut Vec<Diagnostic>) -> Vec<Token> {
186    let spliced = Spliced::new(text);
187    let span = |start: usize, end: usize| spliced.span(file, start, end);
188    let text: &str = &spliced.text;
189    let bytes = text.as_bytes();
190    let mut tokens = Vec::new();
191    // A UTF-8 byte order mark is not part of the source.
192    let mut i = if text.starts_with('\u{FEFF}') { 3 } else { 0 };
193    let mut space = false;
194    let mut line_start = true;
195    while i < bytes.len() {
196        let b = bytes[i];
197        let next = bytes.get(i + 1).copied();
198        match b {
199            b'\n' => {
200                line_start = true;
201                space = true;
202                i += 1;
203                continue;
204            }
205            b' ' | b'\t' | b'\r' | 0x0b | 0x0c => {
206                space = true;
207                i += 1;
208                continue;
209            }
210            b'/' if next == Some(b'/') => {
211                while i < bytes.len() && bytes[i] != b'\n' {
212                    i += 1;
213                }
214                space = true;
215                continue;
216            }
217            b'/' if next == Some(b'*') => {
218                match text[i + 2..].find("*/") {
219                    Some(end) => i += end + 4,
220                    None => {
221                        diagnostics.push(Diagnostic::error(
222                            span(i, i + 2),
223                            "this comment has no closing `*/`",
224                        ));
225                        i = bytes.len();
226                    }
227                }
228                space = true;
229                continue;
230            }
231            _ => {}
232        }
233        let start = i;
234        let kind = if is_ident_start(b) {
235            while i < bytes.len() && is_ident_continue(bytes[i]) {
236                i += 1;
237            }
238            TokenKind::Ident
239        } else if b.is_ascii_digit() || (b == b'.' && next.is_some_and(|n| n.is_ascii_digit())) {
240            let (end, float) = scan_number(bytes, i);
241            i = end;
242            if float {
243                TokenKind::Float
244            } else {
245                TokenKind::Int
246            }
247        } else if b == b'"' {
248            i = scan_string(bytes, i);
249            if i <= start + 1 || bytes[i - 1] != b'"' {
250                diagnostics.push(Diagnostic::error(
251                    span(start, i),
252                    "this string has no closing quote",
253                ));
254            }
255            TokenKind::Str
256        } else if let Some(end) = (b == b'\'').then(|| scan_char(bytes, i)).flatten() {
257            i = end;
258            TokenKind::Char
259        } else if let Some((s, punct)) = PUNCTS
260            .iter()
261            .find(|(s, _)| bytes[i..].starts_with(s.as_bytes()))
262        {
263            i += s.len();
264            TokenKind::Punct(*punct)
265        } else {
266            i += text[i..].chars().next().map_or(1, char::len_utf8);
267            TokenKind::Other
268        };
269        tokens.push(Token {
270            kind,
271            text: text[start..i].to_string(),
272            span: span(start, i),
273            space_before: space,
274            line_start,
275            expanded_from: None,
276        });
277        space = false;
278        line_start = false;
279    }
280    tokens
281}
282
283/// Source text with every backslash-newline removed.
284struct Spliced<'a> {
285    text: Cow<'a, str>,
286    /// For each removed backslash-newline: the offset in `text` after it, and
287    /// the bytes removed before that offset.
288    marks: Vec<(usize, usize)>,
289}
290
291impl Spliced<'_> {
292    fn new(text: &str) -> Spliced<'_> {
293        let bytes = text.as_bytes();
294        let mut out = String::new();
295        let mut marks = Vec::new();
296        let mut copied = 0;
297        let mut i = 0;
298        while i < bytes.len() {
299            let len = match (bytes[i], bytes.get(i + 1), bytes.get(i + 2)) {
300                (b'\\', Some(b'\n'), _) => 2,
301                (b'\\', Some(b'\r'), Some(b'\n')) => 3,
302                _ => 0,
303            };
304            if len == 0 {
305                i += 1;
306                continue;
307            }
308            out.push_str(&text[copied..i]);
309            i += len;
310            copied = i;
311            marks.push((out.len(), i - out.len()));
312        }
313        if marks.is_empty() {
314            return Spliced {
315                text: Cow::Borrowed(text),
316                marks,
317            };
318        }
319        out.push_str(&text[copied..]);
320        Spliced {
321            text: Cow::Owned(out),
322            marks,
323        }
324    }
325
326    fn original(&self, offset: usize) -> usize {
327        let n = self.marks.partition_point(|(at, _)| *at <= offset);
328        offset + n.checked_sub(1).map_or(0, |n| self.marks[n].1)
329    }
330
331    /// The span in the original text of the spliced range `start..end`.
332    fn span(&self, file: FileId, start: usize, end: usize) -> Span {
333        let end = if end > start {
334            self.original(end - 1) + 1
335        } else {
336            self.original(end)
337        };
338        Span::new(file, self.original(start), end)
339    }
340}
341
342fn is_ident_start(b: u8) -> bool {
343    b.is_ascii_alphabetic() || b == b'_'
344}
345
346fn is_ident_continue(b: u8) -> bool {
347    b.is_ascii_alphanumeric() || b == b'_'
348}
349
350/// Scans a number from `i`. Returns its end and if it is a floating-point literal.
351fn scan_number(b: &[u8], mut i: usize) -> (usize, bool) {
352    let at = |i: usize| b.get(i).copied().unwrap_or(0);
353    if at(i) == b'0' && matches!(at(i + 1), b'b' | b'B') && at(i + 2).is_ascii_digit() {
354        i += 2;
355        while is_ident_continue(at(i)) {
356            i += 1;
357        }
358        return (i, false);
359    }
360    if at(i) == b'0' && matches!(at(i + 1), b'x' | b'X') && at(i + 2).is_ascii_hexdigit() {
361        i += 2;
362        while at(i).is_ascii_hexdigit() {
363            i += 1;
364        }
365        // A hex float needs its `p` exponent; without one, `0x1.b` is a swizzle.
366        let mut exponent = i;
367        if at(exponent) == b'.' {
368            exponent += 1;
369            while at(exponent).is_ascii_hexdigit() {
370                exponent += 1;
371            }
372        }
373        if matches!(at(exponent), b'p' | b'P') {
374            i = exponent + 1;
375            if matches!(at(i), b'+' | b'-') {
376                i += 1;
377            }
378            while is_ident_continue(at(i)) {
379                i += 1;
380            }
381            return (i, true);
382        }
383        while matches!(at(i), b'u' | b'U' | b'l' | b'L') {
384            i += 1;
385        }
386        return (i, false);
387    }
388    let mut float = false;
389    while at(i).is_ascii_digit() {
390        i += 1;
391    }
392    if at(i) == b'.' {
393        float = true;
394        i += 1;
395        while at(i).is_ascii_digit() {
396            i += 1;
397        }
398    }
399    if matches!(at(i), b'e' | b'E') {
400        let digits = if matches!(at(i + 1), b'+' | b'-') {
401            i + 2
402        } else {
403            i + 1
404        };
405        float = true;
406        i = digits;
407        if at(i).is_ascii_digit() {
408            while at(i).is_ascii_digit() {
409                i += 1;
410            }
411        } else {
412            // A bad exponent stays in the number, for the parser to report.
413            while is_ident_continue(at(i)) {
414                i += 1;
415            }
416            return (i, float);
417        }
418    }
419    while matches!(at(i), b'f' | b'F' | b'h' | b'H' | b'l' | b'L' | b'u' | b'U') {
420        float |= matches!(at(i), b'f' | b'F' | b'h' | b'H');
421        i += 1;
422    }
423    (i, float)
424}
425
426/// A number token has digits after its exponent and a suffix that HLSL accepts
427/// for its kind. HLSL has no binary or hexadecimal floating-point literals.
428pub(crate) fn is_valid_number(text: &str) -> bool {
429    let int_suffix = |s: &str| matches!(s, "" | "u" | "l" | "ul" | "lu" | "ll" | "ull" | "llu");
430    let lower = text.to_ascii_lowercase();
431    if lower.starts_with("0b") {
432        return false;
433    }
434    if let Some(hex) = lower.strip_prefix("0x") {
435        let digits = hex.trim_end_matches(['u', 'l']);
436        return digits.bytes().all(|b| b.is_ascii_hexdigit()) && int_suffix(&hex[digits.len()..]);
437    }
438    let body = lower.trim_end_matches(['f', 'h', 'l', 'u']);
439    let suffix = &lower[body.len()..];
440    if let Some((_, exponent)) = body.split_once('e') {
441        let digits = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
442        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
443            return false;
444        }
445    }
446    if body.contains(['.', 'e']) || suffix.contains(['f', 'h']) {
447        matches!(suffix, "" | "f" | "h" | "l")
448    } else {
449        int_suffix(suffix)
450    }
451}
452
453/// Scans a string from the quote at `i` to its closing quote or the end of the line.
454fn scan_string(b: &[u8], mut i: usize) -> usize {
455    i += 1;
456    while i < b.len() && b[i] != b'\n' {
457        match b[i] {
458            b'"' => return i + 1,
459            b'\\' if i + 1 < b.len() && b[i + 1] != b'\n' => i += 2,
460            _ => i += 1,
461        }
462    }
463    i
464}
465
466/// Scans a character literal from the quote at `i`. Returns its end, or `None`
467/// when it is empty or has no closing quote on its line.
468fn scan_char(b: &[u8], i: usize) -> Option<usize> {
469    let mut j = i + 1;
470    while j < b.len() && b[j] != b'\n' {
471        match b[j] {
472            b'\'' => return (j > i + 1).then_some(j + 1),
473            b'\\' if j + 1 < b.len() && b[j + 1] != b'\n' => j += 2,
474            _ => j += 1,
475        }
476    }
477    None
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483
484    fn kinds(text: &str) -> Vec<(TokenKind, String)> {
485        let mut d = Vec::new();
486        let tokens = lex(FileId(0), text, &mut d);
487        assert!(d.is_empty(), "{d:?}");
488        tokens.into_iter().map(|t| (t.kind, t.text)).collect()
489    }
490
491    #[test]
492    fn numbers_keep_their_suffixes_and_kinds() {
493        let k = kinds("1 1.0 .5 2. 1e3 1e-3f 0x1Fu 10u 1.0h 3f 1.5L");
494        let expected = [
495            (TokenKind::Int, "1"),
496            (TokenKind::Float, "1.0"),
497            (TokenKind::Float, ".5"),
498            (TokenKind::Float, "2."),
499            (TokenKind::Float, "1e3"),
500            (TokenKind::Float, "1e-3f"),
501            (TokenKind::Int, "0x1Fu"),
502            (TokenKind::Int, "10u"),
503            (TokenKind::Float, "1.0h"),
504            (TokenKind::Float, "3f"),
505            (TokenKind::Float, "1.5L"),
506        ];
507        let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
508        assert_eq!(k, expected);
509    }
510
511    #[test]
512    fn a_malformed_exponent_stays_in_the_number() {
513        let k = kinds("1e+x 2e 3E-;");
514        let expected = [
515            (TokenKind::Float, "1e+x"),
516            (TokenKind::Float, "2e"),
517            (TokenKind::Float, "3E-"),
518            (TokenKind::Punct(Punct::Semi), ";"),
519        ];
520        let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
521        assert_eq!(k, expected);
522        assert!(!is_valid_number("1e+x") && is_valid_number("1e-3f"));
523    }
524
525    #[test]
526    fn hex_floats_and_binary_literals_are_one_token_but_not_valid_numbers() {
527        let k = kinds("0x1.8p3 0x1p-4 0X1P+4f 0x1p 0b1010 0B11u 0x1.b");
528        let expected = [
529            (TokenKind::Float, "0x1.8p3"),
530            (TokenKind::Float, "0x1p-4"),
531            (TokenKind::Float, "0X1P+4f"),
532            (TokenKind::Float, "0x1p"),
533            (TokenKind::Int, "0b1010"),
534            (TokenKind::Int, "0B11u"),
535            (TokenKind::Int, "0x1"),
536            (TokenKind::Punct(Punct::Dot), "."),
537            (TokenKind::Ident, "b"),
538        ];
539        let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
540        assert_eq!(k, expected);
541        for (_, text) in &k[..6] {
542            assert!(!is_valid_number(text), "{text}");
543        }
544        for text in [
545            "0x1F", "0x1Ful", "10lu", "5ll", "5ull", "1.5L", "2h", "1e-3f",
546        ] {
547            assert!(is_valid_number(text), "{text}");
548        }
549    }
550
551    #[test]
552    fn longest_punctuation_wins() {
553        let k = kinds("a<<=b>>c##d->e::f...g");
554        let texts: Vec<_> = k.iter().map(|(_, s)| s.as_str()).collect();
555        assert_eq!(
556            texts,
557            [
558                "a", "<<=", "b", ">>", "c", "##", "d", "->", "e", "::", "f", "...", "g"
559            ]
560        );
561    }
562
563    #[test]
564    fn comments_are_space_and_block_comments_do_not_end_a_line() {
565        let mut d = Vec::new();
566        let t = lex(FileId(0), "a // x\nb/* y\n z */c", &mut d);
567        assert!(d.is_empty());
568        let flags: Vec<_> = t
569            .iter()
570            .map(|t| (t.text.as_str(), t.line_start, t.space_before))
571            .collect();
572        assert_eq!(
573            flags,
574            [("a", true, false), ("b", true, true), ("c", false, true)]
575        );
576    }
577
578    #[test]
579    fn a_continuation_joins_lines() {
580        let mut d = Vec::new();
581        let t = lex(FileId(0), "#define A 1 \\\r\n + 2\nB", &mut d);
582        let starts: Vec<_> = t
583            .iter()
584            .filter(|t| t.line_start)
585            .map(|t| t.text.as_str())
586            .collect();
587        assert_eq!(starts, ["#", "B"]);
588    }
589
590    #[test]
591    fn a_continuation_extends_a_line_comment() {
592        let mut d = Vec::new();
593        let t = lex(FileId(0), "// note \\\n#define A 1\nA", &mut d);
594        let texts: Vec<_> = t.iter().map(|t| t.text.as_str()).collect();
595        assert_eq!(texts, ["A"]);
596    }
597
598    #[test]
599    fn a_continuation_inside_a_token_is_spliced_and_spans_keep_the_source() {
600        let text = "flo\\\nat4 +\\\r\n= \"ab\\\ncd\" 1.\\\n5";
601        let mut d = Vec::new();
602        let t = lex(FileId(0), text, &mut d);
603        assert!(d.is_empty(), "{d:?}");
604        let texts: Vec<_> = t.iter().map(|t| t.text.as_str()).collect();
605        assert_eq!(texts, ["float4", "+=", "\"abcd\"", "1.5"]);
606        let source: Vec<_> = t
607            .iter()
608            .map(|t| &text[t.span.start as usize..t.span.end as usize])
609            .collect();
610        assert_eq!(
611            source,
612            ["flo\\\nat4", "+\\\r\n=", "\"ab\\\ncd\"", "1.\\\n5"]
613        );
614        assert!(t.iter().skip(1).all(|t| t.space_before && !t.line_start));
615    }
616
617    #[test]
618    fn a_continuation_before_a_parenthesis_adds_no_space() {
619        let mut d = Vec::new();
620        let t = lex(FileId(0), "F\\\n(x)", &mut d);
621        assert!(!t[1].space_before);
622    }
623
624    #[test]
625    fn strings_and_unknown_characters() {
626        let k = kinds(r#""a\"b" @ é"#);
627        assert_eq!(k[0], (TokenKind::Str, r#""a\"b""#.to_string()));
628        assert_eq!(k[1], (TokenKind::Other, "@".to_string()));
629        assert_eq!(k[2], (TokenKind::Other, "é".to_string()));
630    }
631
632    #[test]
633    fn character_literals_are_one_token_and_hide_comment_marks() {
634        let k = kinds(r"'a' '\n' '\'' '/*' x");
635        let expected = [
636            (TokenKind::Char, "'a'"),
637            (TokenKind::Char, r"'\n'"),
638            (TokenKind::Char, r"'\''"),
639            (TokenKind::Char, "'/*'"),
640            (TokenKind::Ident, "x"),
641        ];
642        let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
643        assert_eq!(k, expected);
644    }
645
646    #[test]
647    fn a_quote_without_a_closing_quote_is_an_unknown_character() {
648        let k = kinds("don't\n''");
649        let kinds: Vec<_> = k.iter().map(|(k, _)| *k).collect();
650        assert_eq!(
651            kinds,
652            [
653                TokenKind::Ident,
654                TokenKind::Other,
655                TokenKind::Ident,
656                TokenKind::Other,
657                TokenKind::Other
658            ]
659        );
660    }
661
662    #[test]
663    fn unterminated_comment_and_string_are_errors() {
664        let mut d = Vec::new();
665        lex(FileId(0), "\"abc\n/* x", &mut d);
666        assert_eq!(d.len(), 2);
667    }
668
669    #[test]
670    fn spans_cover_the_token_text() {
671        let mut d = Vec::new();
672        let t = lex(FileId(3), "  float4", &mut d);
673        assert_eq!(t[0].span, Span::new(FileId(3), 2, 8));
674        assert_eq!(Punct::ShlEq.as_str(), "<<=");
675    }
676}