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_]*\.[0-9][0-9_]*", |lex| lex.slice().replace('_', "").parse::<f64>().ok())]
61    Float(f64),
62
63    #[regex(r"[0-9][0-9_]*", |lex| lex.slice().replace('_', "").parse::<i64>().ok(), priority = 3)]
64    Int(i64),
65
66    #[regex(r#""([^"\\]|\\.)*""#, |lex| unescape(&lex.slice()[1..lex.slice().len()-1]))]
67    Str(String),
68
69    #[regex(r#"b"([^"\\]|\\.)*""#, |lex| unescape(&lex.slice()[2..lex.slice().len()-1]).map(|s| s.into_bytes()))]
70    Bytes(Vec<u8>),
71
72    // Identifier. Two alternatives so a bare `_` keeps lexing as
73    // the discard token (used by `match _ => ...` and the new
74    // `let _ := ...`) while `_name` is recognized as a real
75    // identifier (#200). Logos picks the longer match: for `_`
76    // alone only Underscore matches (Ident requires ≥2 chars on
77    // the underscore branch); for `_x` the Ident branch wins.
78    #[regex(r"[a-zA-Z][a-zA-Z0-9_]*", |lex| lex.slice().to_string())]
79    #[regex(r"_[a-zA-Z0-9_]+", |lex| lex.slice().to_string())]
80    Ident(String),
81}
82
83fn unescape(s: &str) -> Option<String> {
84    let mut out = String::with_capacity(s.len());
85    let mut chars = s.chars();
86    while let Some(c) = chars.next() {
87        if c == '\\' {
88            match chars.next()? {
89                'n' => out.push('\n'),
90                't' => out.push('\t'),
91                'r' => out.push('\r'),
92                '\\' => out.push('\\'),
93                '"' => out.push('"'),
94                '0' => out.push('\0'),
95                _ => return None,
96            }
97        } else {
98            out.push(c);
99        }
100    }
101    Some(out)
102}
103
104#[derive(Debug, Clone)]
105pub struct Token {
106    pub kind: TokenKind,
107    pub span: Range<usize>,
108}
109
110pub fn lex(src: &str) -> Result<Vec<Token>, LexError> {
111    let mut toks = Vec::new();
112    let mut lx = TokenKind::lexer(src);
113    while let Some(res) = lx.next() {
114        match res {
115            Ok(kind) => toks.push(Token { kind, span: lx.span() }),
116            Err(_) => {
117                return Err(LexError {
118                    span: lx.span(),
119                    snippet: lx.slice().to_string(),
120                });
121            }
122        }
123    }
124    Ok(toks)
125}
126
127#[derive(Debug, thiserror::Error)]
128#[error("unrecognized token `{snippet}` at {span:?}")]
129pub struct LexError {
130    pub span: Range<usize>,
131    pub snippet: String,
132}