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