Skip to main content

lex_syntax/
token.rs

1use logos::Logos;
2use std::ops::Range;
3
4#[derive(Logos, Debug, Clone, PartialEq)]
5#[logos(skip r"[ \t\r\f]+")]
6#[logos(skip(r"#[^\n]*", allow_greedy = true))]
7pub enum TokenKind {
8    // keywords
9    #[token("fn")]      Fn,
10    #[token("let")]     Let,
11    #[token("type")]    Type,
12    #[token("match")]   Match,
13    #[token("if")]      If,
14    #[token("else")]    Else,
15    #[token("return")]  Return,
16    #[token("import")]  Import,
17    #[token("as")]      As,
18    #[token("true")]    True,
19    #[token("false")]   False,
20    #[token("and")]     And,
21    #[token("or")]      Or,
22    #[token("not")]     Not,
23
24    // multi-char operators (longer first to win the match race)
25    #[token("|>")] Pipe,
26    #[token("->")] Arrow,
27    #[token("=>")] FatArrow,
28    #[token(":=")] ColonEq,
29    #[token("::")] ColonColon,
30    #[token("==")] EqEq,
31    #[token("!=")] BangEq,
32    #[token("<=")] LtEq,
33    #[token(">=")] GtEq,
34
35    // single-char operators
36    #[token("+")] Plus,
37    #[token("-")] Minus,
38    #[token("*")] Star,
39    #[token("/")] Slash,
40    #[token("%")] Percent,
41    #[token("<")] Lt,
42    #[token(">")] Gt,
43    #[token(".")] Dot,
44    #[token(",")] Comma,
45    #[token(";")] Semi,
46    #[token(":")] Colon,
47    #[token("?")] Question,
48    #[token("(")] LParen,
49    #[token(")")] RParen,
50    #[token("{")] LBrace,
51    #[token("}")] RBrace,
52    #[token("[")] LBracket,
53    #[token("]")] RBracket,
54    #[token("=")] Eq,
55    #[token("|")] Bar,
56    #[token("_")] Underscore,
57    #[token("\n")] Newline,
58
59    // literals
60    #[regex(r"[0-9][0-9_]*[eE][+-]?[0-9]+", |lex| lex.slice().replace('_', "").parse::<f64>().ok())]
61    #[regex(r"[0-9][0-9_]*\.[0-9][0-9_]*([eE][+-]?[0-9]+)?", |lex| lex.slice().replace('_', "").parse::<f64>().ok())]
62    Float(f64),
63
64    #[regex(r"[0-9][0-9_]*", |lex| lex.slice().replace('_', "").parse::<i64>().ok(), priority = 3)]
65    Int(i64),
66
67    #[regex(r#""([^"\\]|\\.)*""#, |lex| unescape(&lex.slice()[1..lex.slice().len()-1]))]
68    Str(String),
69
70    #[regex(r#"b"([^"\\]|\\.)*""#, |lex| unescape(&lex.slice()[2..lex.slice().len()-1]).map(|s| s.into_bytes()))]
71    Bytes(Vec<u8>),
72
73    // Identifier. Two alternatives so a bare `_` keeps lexing as
74    // the discard token (used by `match _ => ...` and the new
75    // `let _ := ...`) while `_name` is recognized as a real
76    // identifier (#200). Logos picks the longer match: for `_`
77    // alone only Underscore matches (Ident requires ≥2 chars on
78    // the underscore branch); for `_x` the Ident branch wins.
79    #[regex(r"[a-zA-Z][a-zA-Z0-9_]*", |lex| lex.slice().to_string())]
80    #[regex(r"_[a-zA-Z0-9_]+", |lex| lex.slice().to_string())]
81    Ident(String),
82}
83
84fn unescape(s: &str) -> Option<String> {
85    let mut out = String::with_capacity(s.len());
86    let mut chars = s.chars();
87    while let Some(c) = chars.next() {
88        if c == '\\' {
89            match chars.next()? {
90                'n' => out.push('\n'),
91                't' => out.push('\t'),
92                'r' => out.push('\r'),
93                '\\' => out.push('\\'),
94                '"' => out.push('"'),
95                '0' => out.push('\0'),
96                _ => return None,
97            }
98        } else {
99            out.push(c);
100        }
101    }
102    Some(out)
103}
104
105#[derive(Debug, Clone)]
106pub struct Token {
107    pub kind: TokenKind,
108    pub span: Range<usize>,
109}
110
111pub fn lex(src: &str) -> Result<Vec<Token>, LexError> {
112    let mut toks = Vec::new();
113    let mut lx = TokenKind::lexer(src);
114    while let Some(res) = lx.next() {
115        match res {
116            Ok(kind) => toks.push(Token { kind, span: lx.span() }),
117            Err(_) => {
118                return Err(LexError {
119                    span: lx.span(),
120                    snippet: lx.slice().to_string(),
121                });
122            }
123        }
124    }
125    Ok(toks)
126}
127
128#[derive(Debug, thiserror::Error)]
129#[error("unrecognized token `{snippet}` at {span:?}")]
130pub struct LexError {
131    pub span: Range<usize>,
132    pub snippet: String,
133}