Skip to main content

lisette_syntax/lex/
token.rs

1use std::fmt;
2
3#[derive(Debug, Clone, Copy, PartialEq)]
4pub struct Token<'source> {
5    pub kind: TokenKind,
6    pub text: &'source str,
7    pub byte_offset: u32,
8    pub byte_length: u32,
9}
10
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum TokenKind {
13    Integer,
14    Imaginary,
15    String,
16    RawString,
17    FormatStringStart,
18    FormatStringText,
19    FormatStringInterpolationStart,
20    FormatStringInterpolationEnd,
21    FormatStringEnd,
22    Char,
23    Boolean,
24    Float,
25    Identifier,
26    Comment,
27    DocComment,
28    Semicolon,
29    LeftParen,
30    RightParen,
31    LeftSquareBracket,
32    RightSquareBracket,
33    LeftCurlyBrace,
34    RightCurlyBrace,
35    LeftAngleBracket,
36    RightAngleBracket,
37    Arrow,
38    ArrowDouble,
39    Equal,
40    EqualDouble,
41    NotEqual,
42    GreaterThanOrEqual,
43    LessThanOrEqual,
44    Colon,
45    Pipe,
46    PipeDouble,
47    Pipeline,
48    Ampersand,
49    AmpersandDouble,
50    Plus,
51    Minus,
52    Star,
53    Slash,
54    PlusEqual,
55    MinusEqual,
56    StarEqual,
57    SlashEqual,
58    PercentEqual,
59    AmpersandEqual,
60    PipeEqual,
61    CaretEqual,
62    ShiftLeftEqual,  // <<=
63    ShiftRightEqual, // >>=
64    AndNotEqual,     // &^=
65    Caret,
66    Percent,
67    Bang,
68    QuestionMark,
69    Dot,
70    Comma,
71    Hash,
72    DotDot,
73    DotDotEqual,
74    Ellipsis,
75    Backtick,
76    ShiftLeft,  // <<
77    ShiftRight, // >>
78    AndNot,     // &^ - Short hand for `x & (^y)` in Go
79    Function,
80    Let,
81    If,
82    Else,
83    Match,
84    Enum,
85    Struct,
86    Type,
87    Interface,
88    Impl,
89    Const,
90    Var,
91    Return,
92    Defer,
93    Import,
94    Mut,
95    Pub,
96    For,
97    In_,
98    While,
99    Loop,
100    Break,
101    Continue,
102    Select,
103    Task,
104    Try,
105    Recover,
106    Assert,
107    As,
108    Directive,
109    EOF,
110    Placeholder,
111    Error,
112}
113
114impl fmt::Display for TokenKind {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        use TokenKind::*;
117        let s = match self {
118            Integer => "integer",
119            Imaginary => "imaginary",
120            String => "string",
121            RawString => "raw string",
122            FormatStringStart => "format string",
123            FormatStringText => "format string",
124            FormatStringInterpolationStart => "`{`",
125            FormatStringInterpolationEnd => "`}`",
126            FormatStringEnd => "format string",
127            Char => "rune",
128            Boolean => "boolean",
129            Float => "float",
130            Identifier => "identifier",
131            Comment => "comment",
132            DocComment => "doc comment",
133            Semicolon => "`;`",
134            LeftParen => "`(`",
135            RightParen => "`)`",
136            LeftSquareBracket => "`[`",
137            RightSquareBracket => "`]`",
138            LeftCurlyBrace => "`{`",
139            RightCurlyBrace => "`}`",
140            LeftAngleBracket => "`<`",
141            RightAngleBracket => "`>`",
142            Arrow => "`->`",
143            ArrowDouble => "`=>`",
144            Equal => "`=`",
145            EqualDouble => "`==`",
146            NotEqual => "`!=`",
147            GreaterThanOrEqual => "`>=`",
148            LessThanOrEqual => "`<=`",
149            Colon => "`:`",
150            Pipe => "`|`",
151            PipeDouble => "`||`",
152            Pipeline => "`|>`",
153            Ampersand => "`&`",
154            AmpersandDouble => "`&&`",
155            Plus => "`+`",
156            Minus => "`-`",
157            Star => "`*`",
158            Slash => "`/`",
159            PlusEqual => "`+=`",
160            MinusEqual => "`-=`",
161            StarEqual => "`*=`",
162            SlashEqual => "`/=`",
163            PercentEqual => "`%=`",
164            AmpersandEqual => "`&=`",
165            PipeEqual => "`|=`",
166            CaretEqual => "`^=`",
167            ShiftLeftEqual => "`<<=`",
168            ShiftRightEqual => "`>>=`",
169            AndNotEqual => "`&^=`",
170            Caret => "`^`",
171            Percent => "`%`",
172            Bang => "`!`",
173            QuestionMark => "`?`",
174            Dot => "`.`",
175            Comma => "`,`",
176            Hash => "`#`",
177            DotDot => "`..`",
178            DotDotEqual => "`..=`",
179            Ellipsis => "`...`",
180            Backtick => "`` ` ``",
181            ShiftLeft => "`<<`",
182            ShiftRight => "`>>`",
183            AndNot => "`&^`",
184            Function => "`fn`",
185            Let => "`let`",
186            If => "`if`",
187            Else => "`else`",
188            Match => "`match`",
189            Enum => "`enum`",
190            Struct => "`struct`",
191            Type => "`type`",
192            Interface => "`interface`",
193            Impl => "`impl`",
194            Const => "`const`",
195            Var => "`var`",
196            Return => "`return`",
197            Defer => "`defer`",
198            Import => "`import`",
199            Mut => "`mut`",
200            Pub => "`pub`",
201            For => "`for`",
202            In_ => "`in`",
203            While => "`while`",
204            Loop => "`loop`",
205            Break => "`break`",
206            Continue => "`continue`",
207            Select => "`select`",
208            Task => "`task`",
209            Try => "`try`",
210            Recover => "`recover`",
211            Assert => "`assert`",
212            As => "`as`",
213            Directive => "directive",
214            EOF => "end of file",
215            Placeholder => "placeholder",
216            Error => "error",
217        };
218        write!(f, "{}", s)
219    }
220}
221
222impl TokenKind {
223    pub fn from_keyword(s: &str) -> Option<Self> {
224        use TokenKind::*;
225
226        match s {
227            "fn" => Some(Function),
228            "let" => Some(Let),
229            "if" => Some(If),
230            "else" => Some(Else),
231            "match" => Some(Match),
232            "enum" => Some(Enum),
233            "struct" => Some(Struct),
234            "type" => Some(Type),
235            "interface" => Some(Interface),
236            "impl" => Some(Impl),
237            "const" => Some(Const),
238            "var" => Some(Var),
239            "return" => Some(Return),
240            "defer" => Some(Defer),
241            "import" => Some(Import),
242            "mut" => Some(Mut),
243            "pub" => Some(Pub),
244            "for" => Some(For),
245            "in" => Some(In_),
246            "while" => Some(While),
247            "loop" => Some(Loop),
248            "break" => Some(Break),
249            "continue" => Some(Continue),
250            "select" => Some(Select),
251            "task" => Some(Task),
252            "try" => Some(Try),
253            "recover" => Some(Recover),
254            "assert" => Some(Assert),
255            "as" => Some(As),
256            _ => None,
257        }
258    }
259
260    pub fn is_keyword(&self) -> bool {
261        use TokenKind::*;
262        matches!(
263            self,
264            Function
265                | Let
266                | If
267                | Else
268                | Match
269                | Enum
270                | Struct
271                | Type
272                | Interface
273                | Impl
274                | Const
275                | Var
276                | Return
277                | Defer
278                | Import
279                | Mut
280                | Pub
281                | For
282                | In_
283                | While
284                | Loop
285                | Break
286                | Continue
287                | Select
288                | Task
289                | Try
290                | Recover
291                | Assert
292                | As
293        )
294    }
295
296    pub fn from_three_char_symbol(c1: char, c2: char, c3: char) -> Option<Self> {
297        match (c1, c2, c3) {
298            ('.', '.', '=') => Some(TokenKind::DotDotEqual),
299            ('.', '.', '.') => Some(TokenKind::Ellipsis),
300            ('<', '<', '=') => Some(TokenKind::ShiftLeftEqual),
301            ('>', '>', '=') => Some(TokenKind::ShiftRightEqual),
302            ('&', '^', '=') => Some(TokenKind::AndNotEqual),
303            _ => None,
304        }
305    }
306
307    pub fn from_two_char_symbol(c1: char, c2: char) -> Option<Self> {
308        use TokenKind::*;
309
310        match (c1, c2) {
311            ('-', '>') => Some(Arrow),
312            ('=', '>') => Some(ArrowDouble),
313            ('=', '=') => Some(EqualDouble),
314            ('!', '=') => Some(NotEqual),
315            ('>', '=') => Some(GreaterThanOrEqual),
316            ('<', '=') => Some(LessThanOrEqual),
317            ('|', '|') => Some(PipeDouble),
318            ('|', '>') => Some(Pipeline),
319            ('&', '&') => Some(AmpersandDouble),
320            ('.', '.') => Some(DotDot),
321            ('+', '=') => Some(PlusEqual),
322            ('-', '=') => Some(MinusEqual),
323            ('*', '=') => Some(StarEqual),
324            ('/', '=') => Some(SlashEqual),
325            ('%', '=') => Some(PercentEqual),
326            ('&', '=') => Some(AmpersandEqual),
327            ('|', '=') => Some(PipeEqual),
328            ('^', '=') => Some(CaretEqual),
329            ('&', '^') => Some(AndNot),
330            ('<', '<') => Some(ShiftLeft),
331            ('>', '>') => Some(ShiftRight),
332            _ => None,
333        }
334    }
335
336    pub fn from_one_char_symbol(c: char) -> Option<Self> {
337        use TokenKind::*;
338
339        match c {
340            '(' => Some(LeftParen),
341            ')' => Some(RightParen),
342            '[' => Some(LeftSquareBracket),
343            ']' => Some(RightSquareBracket),
344            '{' => Some(LeftCurlyBrace),
345            '}' => Some(RightCurlyBrace),
346            '<' => Some(LeftAngleBracket),
347            '>' => Some(RightAngleBracket),
348            '=' => Some(Equal),
349            ':' => Some(Colon),
350            '|' => Some(Pipe),
351            '&' => Some(Ampersand),
352            '+' => Some(Plus),
353            '-' => Some(Minus),
354            '*' => Some(Star),
355            '^' => Some(Caret),
356            '%' => Some(Percent),
357            '!' => Some(Bang),
358            '?' => Some(QuestionMark),
359            '.' => Some(Dot),
360            ',' => Some(Comma),
361            '#' => Some(Hash),
362            _ => None,
363        }
364    }
365}