Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/syn/src/buffer.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / syn / src / buffer.rs` 462 lines ยท 16945 bytes Raw Blame History 1 //! A stably addressed token buffer supporting efficient traversal based on a 2 //! cheaply copyable cursor. 3 4 // This module is heavily commented as it contains most of the unsafe code in 5 // Syn, and caution should be used when editing it. The public-facing interface 6 // is 100% safe but the implementation is fragile internally. 7 8 use crate::ext::TokenStreamExt as _; 9 use crate::Lifetime; 10 use alloc::boxed::Box; 11 use alloc::vec::Vec; 12 use core::cmp::Ordering; 13 use core::marker::PhantomData; 14 use core::ptr; 15 use proc_macro2::extra::DelimSpan; 16 use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; 17 18 /// Internal type which is used instead of `TokenTree` to represent a token tree 19 /// within a `TokenBuffer`. 20 enum Entry { 21 // Mimicking types from proc-macro. 22 // Group entries contain the offset to the matching End entry. 23 Group(Group, usize), 24 Ident(Ident), 25 Punct(Punct), 26 Literal(Literal), 27 // End entries contain the offset (negative) to the start of the buffer, and 28 // offset (negative) to the matching Group entry. 29 End(isize, isize), 30 } 31 32 /// A buffer that can be efficiently traversed multiple times, unlike 33 /// `TokenStream` which requires a deep copy in order to traverse more than 34 /// once. 35 pub struct TokenBuffer { 36 // NOTE: Do not implement clone on this - while the current design could be 37 // cloned, other designs which could be desirable may not be cloneable. 38 entries: Box<[Entry]>, 39 } 40 41 impl TokenBuffer { 42 fn recursive_new(entries: &mut Vec, stream: TokenStream) { 43 for tt in stream { 44 match tt { 45 TokenTree::Ident(ident) => entries.push(Entry::Ident(ident)), 46 TokenTree::Punct(punct) => entries.push(Entry::Punct(punct)), 47 TokenTree::Literal(literal) => entries.push(Entry::Literal(literal)), 48 TokenTree::Group(group) => { 49 let group_start_index = entries.len(); 50 entries.push(Entry::End(0, 0)); // we replace this below 51 Self::recursive_new(entries, group.stream()); 52 let group_end_index = entries.len(); 53 let group_offset = group_end_index - group_start_index; 54 entries.push(Entry::End( 55 -(group_end_index as isize), 56 -(group_offset as isize), 57 )); 58 entries[group_start_index] = Entry::Group(group, group_offset); 59 } 60 } 61 } 62 } 63 64 /// Creates a `TokenBuffer` containing all the tokens from the input 65 /// `proc_macro::TokenStream`. 66 #[cfg(feature = "proc-macro")] 67 #[cfg_attr(docsrs, doc(cfg(feature = "proc-macro")))] 68 pub fn new(stream: proc_macro::TokenStream) -> Self { 69 Self::new2(stream.into()) 70 } 71 72 /// Creates a `TokenBuffer` containing all the tokens from the input 73 /// `proc_macro2::TokenStream`. 74 pub fn new2(stream: TokenStream) -> Self { 75 let mut entries = Vec::new(); 76 Self::recursive_new(&mut entries, stream); 77 entries.push(Entry::End(-(entries.len() as isize), 0)); 78 Self { 79 entries: entries.into_boxed_slice(), 80 } 81 } 82 83 /// Creates a cursor referencing the first token in the buffer and able to 84 /// traverse until the end of the buffer. 85 pub fn begin(&self) -> Cursor { 86 let ptr = self.entries.as_ptr(); 87 unsafe { Cursor::create(ptr, ptr.add(self.entries.len() - 1)) } 88 } 89 } 90 91 /// A cheaply copyable cursor into a `TokenBuffer`. 92 /// 93 /// This cursor holds a shared reference into the immutable data which is used 94 /// internally to represent a `TokenStream`, and can be efficiently manipulated 95 /// and copied around. 96 /// 97 /// An empty `Cursor` can be created directly, or one may create a `TokenBuffer` 98 /// object and get a cursor to its first token with `begin()`. 99 pub struct Cursor<'a> { 100 // The current entry which the `Cursor` is pointing at. 101 ptr: *const Entry, 102 // This is the only `Entry::End` object which this cursor is allowed to 103 // point at. All other `End` objects are skipped over in `Cursor::create`. 104 scope: *const Entry, 105 // Cursor is covariant in 'a. This field ensures that our pointers are still 106 // valid. 107 marker: PhantomData<&'a Entry>, 108 } 109 110 impl<'a> Cursor<'a> { 111 /// Creates a cursor referencing a static empty TokenStream. 112 pub fn empty() -> Self { 113 // It's safe in this situation for us to put an `Entry` object in global 114 // storage, despite it not actually being safe to send across threads 115 // (`Ident` is a reference into a thread-local table). This is because 116 // this entry never includes a `Ident` object. 117 // 118 // This wrapper struct allows us to break the rules and put a `Sync` 119 // object in global storage. 120 struct UnsafeSyncEntry(Entry); 121 unsafe impl Sync for UnsafeSyncEntry {} 122 static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0, 0)); 123 124 Cursor { 125 ptr: &EMPTY_ENTRY.0, 126 scope: &EMPTY_ENTRY.0, 127 marker: PhantomData, 128 } 129 } 130 131 /// This create method intelligently exits non-explicitly-entered 132 /// `None`-delimited scopes when the cursor reaches the end of them, 133 /// allowing for them to be treated transparently. 134 unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self { 135 // NOTE: If we're looking at a `End`, we want to advance the cursor 136 // past it, unless `ptr == scope`, which means that we're at the edge of 137 // our cursor's scope. We should only have `ptr != scope` at the exit 138 // from None-delimited groups entered with `ignore_none`. 139 while let Entry::End(..) = unsafe { &*ptr } { 140 if ptr::eq(ptr, scope) { 141 break; 142 } 143 ptr = unsafe { ptr.add(1) }; 144 } 145 146 Cursor { 147 ptr, 148 scope, 149 marker: PhantomData, 150 } 151 } 152 153 /// Get the current entry. 154 fn entry(self) -> &'a Entry { 155 unsafe { &*self.ptr } 156 } 157 158 /// Bump the cursor to point at the next token after the current one. This 159 /// is undefined behavior if the cursor is currently looking at an 160 /// `Entry::End`. 161 /// 162 /// If the cursor is looking at an `Entry::Group`, the bumped cursor will 163 /// point at the first token in the group (with the same scope end). 164 unsafe fn bump_ignore_group(self) -> Cursor<'a> { 165 unsafe { Cursor::create(self.ptr.add(1), self.scope) } 166 } 167 168 /// While the cursor is looking at a `None`-delimited group, move it to look 169 /// at the first token inside instead. If the group is empty, this will move 170 /// the cursor past the `None`-delimited group. 171 /// 172 /// WARNING: This mutates its argument. 173 fn ignore_none(&mut self) { 174 while let Entry::Group(group, _) = self.entry() { 175 if group.delimiter() == Delimiter::None { 176 unsafe { *self = self.bump_ignore_group() }; 177 } else { 178 break; 179 } 180 } 181 } 182 183 /// Checks whether the cursor is currently pointing at the end of its valid 184 /// scope. 185 pub fn eof(self) -> bool { 186 // We're at eof if we're at the end of our scope. 187 ptr::eq(self.ptr, self.scope) 188 } 189 190 /// If the cursor is pointing at a `Ident`, returns it along with a cursor 191 /// pointing at the next `TokenTree`. 192 pub fn ident(mut self) -> Option<(Ident, Cursor<'a>)> { 193 self.ignore_none(); 194 match self.entry() { 195 Entry::Ident(ident) => Some((ident.clone(), unsafe { self.bump_ignore_group() })), 196 _ => None, 197 } 198 } 199 200 pub(crate) fn peek_keyword(mut self, token: &str) -> bool { 201 self.ignore_none(); 202 match self.entry() { 203 Entry::Ident(ident) => ident == token, 204 _ => false, 205 } 206 } 207 208 /// If the cursor is pointing at a `Punct`, returns it along with a cursor 209 /// pointing at the next `TokenTree`. 210 pub fn punct(mut self) -> Option<(Punct, Cursor<'a>)> { 211 self.ignore_none(); 212 match self.entry() { 213 Entry::Punct(punct) if punct.as_char() != '\'' => { 214 Some((punct.clone(), unsafe { self.bump_ignore_group() })) 215 } 216 _ => None, 217 } 218 } 219 220 pub(crate) fn peek_punct(mut self, token: &str) -> bool { 221 for (i, ch) in token.chars().enumerate() { 222 self.ignore_none(); 223 match self.entry() { 224 Entry::Punct(punct) if punct.as_char() == ch => { 225 if i == token.len() - 1 { 226 return true; 227 } else if punct.spacing() != Spacing::Joint { 228 break; 229 } 230 self = unsafe { self.bump_ignore_group() }; 231 } 232 _ => break, 233 } 234 } 235 false 236 } 237 238 /// If the cursor is pointing at a `Literal`, return it along with a cursor 239 /// pointing at the next `TokenTree`. 240 pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> { 241 self.ignore_none(); 242 match self.entry() { 243 Entry::Literal(literal) => Some((literal.clone(), unsafe { self.bump_ignore_group() })), 244 _ => None, 245 } 246 } 247 248 /// If the cursor is pointing at a `Lifetime`, returns it along with a 249 /// cursor pointing at the next `TokenTree`. 250 pub fn lifetime(mut self) -> Option<(Lifetime, Cursor<'a>)> { 251 self.ignore_none(); 252 match self.entry() { 253 Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => { 254 let next = unsafe { self.bump_ignore_group() }; 255 let (ident, rest) = next.ident()?; 256 let lifetime = Lifetime { 257 apostrophe: punct.span(), 258 ident, 259 }; 260 Some((lifetime, rest)) 261 } 262 _ => None, 263 } 264 } 265 266 /// If the cursor is pointing at a `Group` with the given delimiter, returns 267 /// a cursor into that group and one pointing to the next `TokenTree`. 268 pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, DelimSpan, Cursor<'a>)> { 269 // If we're not trying to enter a none-delimited group, we want to 270 // ignore them. We have to make sure to _not_ ignore them when we want 271 // to enter them, of course. For obvious reasons. 272 if delim != Delimiter::None { 273 self.ignore_none(); 274 } 275 276 if let Entry::Group(group, end_offset) = self.entry() { 277 if group.delimiter() == delim { 278 let span = group.delim_span(); 279 let end_of_group = unsafe { self.ptr.add(*end_offset) }; 280 let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; 281 let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; 282 return Some((inside_of_group, span, after_group)); 283 } 284 } 285 286 None 287 } 288 289 /// If the cursor is pointing at a `Group`, returns a cursor into the group 290 /// and one pointing to the next `TokenTree`. 291 pub fn any_group(self) -> Option<(Cursor<'a>, Delimiter, DelimSpan, Cursor<'a>)> { 292 if let Entry::Group(group, end_offset) = self.entry() { 293 let delimiter = group.delimiter(); 294 let span = group.delim_span(); 295 let end_of_group = unsafe { self.ptr.add(*end_offset) }; 296 let inside_of_group = unsafe { Cursor::create(self.ptr.add(1), end_of_group) }; 297 let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; 298 return Some((inside_of_group, delimiter, span, after_group)); 299 } 300 301 None 302 } 303 304 pub(crate) fn any_group_token(self) -> Option<(Group, Cursor<'a>)> { 305 if let Entry::Group(group, end_offset) = self.entry() { 306 let end_of_group = unsafe { self.ptr.add(*end_offset) }; 307 let after_group = unsafe { Cursor::create(end_of_group, self.scope) }; 308 return Some((group.clone(), after_group)); 309 } 310 311 None 312 } 313 314 /// Copies all remaining tokens visible from this cursor into a 315 /// `TokenStream`. 316 pub fn token_stream(self) -> TokenStream { 317 let mut tokens = TokenStream::new(); 318 let mut cursor = self; 319 while let Some((tt, rest)) = cursor.token_tree() { 320 tokens.append(tt); 321 cursor = rest; 322 } 323 tokens 324 } 325 326 /// If the cursor is pointing at a `TokenTree`, returns it along with a 327 /// cursor pointing at the next `TokenTree`. 328 /// 329 /// Returns `None` if the cursor has reached the end of its stream. 330 /// 331 /// This method does not treat `None`-delimited groups as transparent, and 332 /// will return a `Group(None, ..)` if the cursor is looking at one. 333 pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> { 334 let (tree, len) = match self.entry() { 335 Entry::Group(group, end_offset) => (group.clone().into(), *end_offset), 336 Entry::Literal(literal) => (literal.clone().into(), 1), 337 Entry::Ident(ident) => (ident.clone().into(), 1), 338 Entry::Punct(punct) => (punct.clone().into(), 1), 339 Entry::End(..) => return None, 340 }; 341 342 let rest = unsafe { Cursor::create(self.ptr.add(len), self.scope) }; 343 Some((tree, rest)) 344 } 345 346 /// Returns the `Span` of the current token, or `Span::call_site()` if this 347 /// cursor points to eof. 348 pub fn span(mut self) -> Span { 349 match self.entry() { 350 Entry::Group(group, _) => group.span(), 351 Entry::Literal(literal) => literal.span(), 352 Entry::Ident(ident) => ident.span(), 353 Entry::Punct(punct) => punct.span(), 354 Entry::End(_, offset) => { 355 self.ptr = unsafe { self.ptr.offset(*offset) }; 356 if let Entry::Group(group, _) = self.entry() { 357 group.span_close() 358 } else { 359 Span::call_site() 360 } 361 } 362 } 363 } 364 365 /// Returns the `Span` of the token immediately prior to the position of 366 /// this cursor, or of the current token if there is no previous one. 367 pub fn prev_span(mut self) -> Span { 368 if start_of_buffer(self) < self.ptr { 369 self.ptr = unsafe { self.ptr.sub(1) }; 370 } 371 self.span() 372 } 373 374 /// Skip over the next token that is not a None-delimited group, without 375 /// cloning it. Returns `None` if this cursor points to eof. 376 /// 377 /// This method treats `'lifetimes` as a single token. 378 pub(crate) fn skip(mut self) -> Option> { 379 self.ignore_none(); 380 381 let len = match self.entry() { 382 Entry::End(..) => return None, 383 384 // Treat lifetimes as a single tt for the purposes of 'skip'. 385 Entry::Punct(punct) if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint => { 386 match unsafe { &*self.ptr.add(1) } { 387 Entry::Ident(_) => 2, 388 _ => 1, 389 } 390 } 391 392 Entry::Group(_, end_offset) => *end_offset, 393 _ => 1, 394 }; 395 396 Some(unsafe { Cursor::create(self.ptr.add(len), self.scope) }) 397 } 398 399 pub(crate) fn scope_delimiter(self) -> Delimiter { 400 match unsafe { &*self.scope } { 401 Entry::End(_, offset) => match unsafe { &*self.scope.offset(*offset) } { 402 Entry::Group(group, _) => group.delimiter(), 403 _ => Delimiter::None, 404 }, 405 _ => unreachable!(), 406 } 407 } 408 } 409 410 impl<'a> Copy for Cursor<'a> {} 411 412 impl<'a> Clone for Cursor<'a> { 413 fn clone(&self) -> Self { 414 *self 415 } 416 } 417 418 impl<'a> Eq for Cursor<'a> {} 419 420 impl<'a> PartialEq for Cursor<'a> { 421 fn eq(&self, other: &Self) -> bool { 422 ptr::eq(self.ptr, other.ptr) 423 } 424 } 425 426 impl<'a> PartialOrd for Cursor<'a> { 427 fn partial_cmp(&self, other: &Self) -> Option { 428 if same_buffer(*self, *other) { 429 Some(cmp_assuming_same_buffer(*self, *other)) 430 } else { 431 None 432 } 433 } 434 } 435 436 pub(crate) fn same_scope(a: Cursor, b: Cursor) -> bool { 437 ptr::eq(a.scope, b.scope) 438 } 439 440 pub(crate) fn same_buffer(a: Cursor, b: Cursor) -> bool { 441 ptr::eq(start_of_buffer(a), start_of_buffer(b)) 442 } 443 444 fn start_of_buffer(cursor: Cursor) -> *const Entry { 445 unsafe { 446 match &*cursor.scope { 447 Entry::End(offset, _) => cursor.scope.offset(*offset), 448 _ => unreachable!(), 449 } 450 } 451 } 452 453 pub(crate) fn cmp_assuming_same_buffer(a: Cursor, b: Cursor) -> Ordering { 454 a.ptr.cmp(&b.ptr) 455 } 456 457 pub(crate) fn open_span_of_group(cursor: Cursor) -> Span { 458 match cursor.entry() { 459 Entry::Group(group, _) => group.span_open(), 460 _ => cursor.span(), 461 } 462 }