Skip to main content

ridx_syntax/
token.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! Token representation, kinds, flags, and binary-search offset lookup.
12
13use core::ops::Range;
14
15/// Flag set on a single-character punctuation [`Token`] when the immediately following
16/// token is also a single-character punctuation token with zero intervening trivia
17/// (`self.end == next.start`).
18pub const JOINT_NEXT: u8 = 1 << 0;
19
20/// Flag set on a [`Token`] when lexical recovery occurred (e.g. unclosed literal or
21/// block comment, empty/overlong char literal, missing digits after base/exponent prefix,
22/// invalid raw identifier, or unrecognized source character).
23pub const HAS_ERROR: u8 = 1 << 1;
24
25/// Compact 12-byte lossless lexical token referencing a byte span `[start, end)` in `src`.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub struct Token {
28    pub kind: TokenKind,
29    pub flags: u8,
30    pub start: u32,
31    pub end: u32,
32}
33
34const _: () = assert!(core::mem::size_of::<Token>() == 12);
35
36impl Token {
37    #[inline]
38    pub const fn new(kind: TokenKind, flags: u8, start: u32, end: u32) -> Self {
39        Self { kind, flags, start, end }
40    }
41
42    #[inline]
43    pub const fn len(self) -> u32 {
44        self.end - self.start
45    }
46
47    #[inline]
48    pub const fn is_empty(self) -> bool {
49        self.start == self.end
50    }
51
52    #[inline]
53    pub const fn is_trivia(self) -> bool {
54        self.kind.is_trivia()
55    }
56
57    #[inline]
58    pub const fn is_joint(self) -> bool {
59        (self.flags & JOINT_NEXT) != 0
60    }
61
62    #[inline]
63    pub const fn has_error(self) -> bool {
64        (self.flags & HAS_ERROR) != 0
65    }
66
67    #[inline]
68    pub const fn range(self) -> Range<usize> {
69        (self.start as usize)..(self.end as usize)
70    }
71
72    #[inline]
73    pub fn text(self, src: &str) -> &str {
74        &src[self.range()]
75    }
76}
77
78/// Finds the index of the token covering `byte` (`token.start <= byte < token.end`)
79/// using `O(log N)` binary search over a contiguous or monotonic slice of tokens.
80#[inline]
81pub fn token_at(tokens: &[Token], byte: u32) -> Option<usize> {
82    let idx = tokens.partition_point(|t| t.end <= byte);
83    if idx < tokens.len() && tokens[idx].start <= byte {
84        Some(idx)
85    } else {
86        None
87    }
88}
89
90/// Lexical kind of a Rust source token (edition-independent, context-free).
91#[repr(u8)]
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
93pub enum TokenKind {
94    // Trivia
95    Whitespace,
96    LineComment,
97    BlockComment,
98    Shebang,
99
100    // Identifiers & lifetimes
101    Ident,
102    RawIdent,
103    Lifetime,
104
105    // Literals
106    Int,
107    Float,
108    Char,
109    Byte,
110    Str,
111    RawStr,
112    ByteStr,
113    RawByteStr,
114    CStr,
115    RawCStr,
116
117    // Strict keywords (Rust 2018 / 2021) + underscore
118    As,
119    Async,
120    Await,
121    Break,
122    Const,
123    Continue,
124    Crate,
125    Dyn,
126    Else,
127    Enum,
128    Extern,
129    False,
130    Fn,
131    For,
132    If,
133    Impl,
134    In,
135    Let,
136    Loop,
137    Match,
138    Mod,
139    Move,
140    Mut,
141    Pub,
142    Ref,
143    Return,
144    SelfKw,
145    SelfType,
146    Static,
147    Struct,
148    Super,
149    Trait,
150    True,
151    Type,
152    Unsafe,
153    Use,
154    Where,
155    While,
156    Underscore,
157
158    // Delimiters
159    LParen,
160    RParen,
161    LBrace,
162    RBrace,
163    LBracket,
164    RBracket,
165
166    // Atomic single-character punctuation
167    Bang,
168    Hash,
169    Dollar,
170    Percent,
171    Amp,
172    Star,
173    Plus,
174    Comma,
175    Minus,
176    Dot,
177    Slash,
178    Colon,
179    Semi,
180    Lt,
181    Eq,
182    Gt,
183    Question,
184    At,
185    Caret,
186    Pipe,
187    Tilde,
188
189    // Unrecognized character or stray byte sequence
190    Unknown,
191}
192
193impl TokenKind {
194    /// Returns `true` for whitespace, comments (including doc comments), and file shebangs.
195    #[inline]
196    pub const fn is_trivia(self) -> bool {
197        (self as u8) <= (Self::Shebang as u8)
198    }
199
200    /// Returns `true` for non-delimiter atomic punctuation characters eligible for [`JOINT_NEXT`].
201    #[inline]
202    pub const fn is_punct(self) -> bool {
203        let v = self as u8;
204        v >= (Self::Bang as u8) && v <= (Self::Tilde as u8)
205    }
206
207    /// Returns `true` for `(`, `)`, `{`, `}`, `[`, `]`.
208    #[inline]
209    pub const fn is_delimiter(self) -> bool {
210        let v = self as u8;
211        v >= (Self::LParen as u8) && v <= (Self::RBracket as u8)
212    }
213
214    /// Returns `true` for strict keywords (excluding [`Self::Underscore`]).
215    #[inline]
216    pub const fn is_keyword(self) -> bool {
217        let v = self as u8;
218        v >= (Self::As as u8) && v <= (Self::While as u8)
219    }
220
221    /// Returns `true` for numeric, character, byte, string, and C-string literals.
222    #[inline]
223    pub const fn is_literal(self) -> bool {
224        let v = self as u8;
225        v >= (Self::Int as u8) && v <= (Self::RawCStr as u8)
226    }
227
228    /// Maps an atomic punctuation [`TokenKind`] back to its ASCII byte, enabling fast
229    /// multi-character operator checks (`at_op("::")`, `eat_op("->")`, `at_op(">>")`) in the parser.
230    #[inline]
231    pub const fn punct_byte(self) -> Option<u8> {
232        const BYTES: [u8; 21] = *b"!#$%&*+,-./:;<=>?@^|~";
233        let idx = (self as u8).wrapping_sub(Self::Bang as u8) as usize;
234        if idx < BYTES.len() {
235            Some(BYTES[idx])
236        } else {
237            None
238        }
239    }
240}