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