/rust/registry/src/index.crates.io-1949cf8c6b5b557f/proc-macro2-1.0.103/src/fallback.rs
Line | Count | Source |
1 | | #[cfg(wrap_proc_macro)] |
2 | | use crate::imp; |
3 | | #[cfg(span_locations)] |
4 | | use crate::location::LineColumn; |
5 | | use crate::parse::{self, Cursor}; |
6 | | use crate::rcvec::{RcVec, RcVecBuilder, RcVecIntoIter, RcVecMut}; |
7 | | use crate::{Delimiter, Spacing, TokenTree}; |
8 | | #[cfg(all(span_locations, not(fuzzing)))] |
9 | | use alloc::collections::BTreeMap; |
10 | | #[cfg(all(span_locations, not(fuzzing)))] |
11 | | use core::cell::RefCell; |
12 | | #[cfg(span_locations)] |
13 | | use core::cmp; |
14 | | #[cfg(all(span_locations, not(fuzzing)))] |
15 | | use core::cmp::Ordering; |
16 | | use core::fmt::{self, Debug, Display, Write}; |
17 | | use core::mem::ManuallyDrop; |
18 | | #[cfg(span_locations)] |
19 | | use core::ops::Range; |
20 | | use core::ops::RangeBounds; |
21 | | use core::ptr; |
22 | | use core::str; |
23 | | #[cfg(feature = "proc-macro")] |
24 | | use core::str::FromStr; |
25 | | use std::ffi::CStr; |
26 | | #[cfg(wrap_proc_macro)] |
27 | | use std::panic; |
28 | | #[cfg(span_locations)] |
29 | | use std::path::PathBuf; |
30 | | |
31 | | /// Force use of proc-macro2's fallback implementation of the API for now, even |
32 | | /// if the compiler's implementation is available. |
33 | 0 | pub fn force() { |
34 | | #[cfg(wrap_proc_macro)] |
35 | 0 | crate::detection::force_fallback(); |
36 | 0 | } |
37 | | |
38 | | /// Resume using the compiler's implementation of the proc macro API if it is |
39 | | /// available. |
40 | 0 | pub fn unforce() { |
41 | | #[cfg(wrap_proc_macro)] |
42 | 0 | crate::detection::unforce_fallback(); |
43 | 0 | } |
44 | | |
45 | | #[derive(Clone)] |
46 | | pub(crate) struct TokenStream { |
47 | | inner: RcVec<TokenTree>, |
48 | | } |
49 | | |
50 | | #[derive(Debug)] |
51 | | pub(crate) struct LexError { |
52 | | pub(crate) span: Span, |
53 | | } |
54 | | |
55 | | impl LexError { |
56 | 0 | pub(crate) fn span(&self) -> Span { |
57 | 0 | self.span |
58 | 0 | } |
59 | | |
60 | 0 | pub(crate) fn call_site() -> Self { |
61 | 0 | LexError { |
62 | 0 | span: Span::call_site(), |
63 | 0 | } |
64 | 0 | } |
65 | | } |
66 | | |
67 | | impl TokenStream { |
68 | 0 | pub(crate) fn new() -> Self { |
69 | 0 | TokenStream { |
70 | 0 | inner: RcVecBuilder::new().build(), |
71 | 0 | } |
72 | 0 | } |
73 | | |
74 | 420 | pub(crate) fn from_str_checked(src: &str) -> Result<Self, LexError> { |
75 | | // Create a dummy file & add it to the source map |
76 | 420 | let mut cursor = get_cursor(src); |
77 | | |
78 | | // Strip a byte order mark if present |
79 | | const BYTE_ORDER_MARK: &str = "\u{feff}"; |
80 | 420 | if cursor.starts_with(BYTE_ORDER_MARK) { |
81 | 0 | cursor = cursor.advance(BYTE_ORDER_MARK.len()); |
82 | 420 | } |
83 | | |
84 | 420 | parse::token_stream(cursor) |
85 | 420 | } |
86 | | |
87 | | #[cfg(feature = "proc-macro")] |
88 | 0 | pub(crate) fn from_str_unchecked(src: &str) -> Self { |
89 | 0 | Self::from_str_checked(src).unwrap() |
90 | 0 | } |
91 | | |
92 | 0 | pub(crate) fn is_empty(&self) -> bool { |
93 | 0 | self.inner.len() == 0 |
94 | 0 | } |
95 | | |
96 | 0 | fn take_inner(self) -> RcVecBuilder<TokenTree> { |
97 | 0 | let nodrop = ManuallyDrop::new(self); |
98 | 0 | unsafe { ptr::read(&nodrop.inner) }.make_owned() |
99 | 0 | } |
100 | | } |
101 | | |
102 | 0 | fn push_token_from_proc_macro(mut vec: RcVecMut<TokenTree>, token: TokenTree) { |
103 | | // https://github.com/dtolnay/proc-macro2/issues/235 |
104 | 0 | match token { |
105 | | TokenTree::Literal(crate::Literal { |
106 | | #[cfg(wrap_proc_macro)] |
107 | 0 | inner: crate::imp::Literal::Fallback(literal), |
108 | | #[cfg(not(wrap_proc_macro))] |
109 | | inner: literal, |
110 | | .. |
111 | 0 | }) if literal.repr.starts_with('-') => { |
112 | 0 | push_negative_literal(vec, literal); |
113 | 0 | } |
114 | 0 | _ => vec.push(token), |
115 | | } |
116 | | |
117 | | #[cold] |
118 | 0 | fn push_negative_literal(mut vec: RcVecMut<TokenTree>, mut literal: Literal) { |
119 | 0 | literal.repr.remove(0); |
120 | 0 | let mut punct = crate::Punct::new('-', Spacing::Alone); |
121 | 0 | punct.set_span(crate::Span::_new_fallback(literal.span)); |
122 | 0 | vec.push(TokenTree::Punct(punct)); |
123 | 0 | vec.push(TokenTree::Literal(crate::Literal::_new_fallback(literal))); |
124 | 0 | } |
125 | 0 | } |
126 | | |
127 | | // Nonrecursive to prevent stack overflow. |
128 | | impl Drop for TokenStream { |
129 | 516k | fn drop(&mut self) { |
130 | 516k | let mut stack = Vec::new(); |
131 | 516k | let mut current = match self.inner.get_mut() { |
132 | 516k | Some(inner) => inner.take().into_iter(), |
133 | 0 | None => return, |
134 | | }; |
135 | | loop { |
136 | 8.67M | while let Some(token) = current.next() { |
137 | 7.66M | let group = match token { |
138 | 502k | TokenTree::Group(group) => group.inner, |
139 | 7.15M | _ => continue, |
140 | | }; |
141 | | #[cfg(wrap_proc_macro)] |
142 | 502k | let group = match group { |
143 | 502k | crate::imp::Group::Fallback(group) => group, |
144 | 0 | crate::imp::Group::Compiler(_) => continue, |
145 | | }; |
146 | 502k | let mut group = group; |
147 | 502k | if let Some(inner) = group.stream.inner.get_mut() { |
148 | 502k | stack.push(current); |
149 | 502k | current = inner.take().into_iter(); |
150 | 502k | } |
151 | | } |
152 | 1.01M | match stack.pop() { |
153 | 502k | Some(next) => current = next, |
154 | 516k | None => return, |
155 | | } |
156 | | } |
157 | 516k | } |
158 | | } |
159 | | |
160 | | pub(crate) struct TokenStreamBuilder { |
161 | | inner: RcVecBuilder<TokenTree>, |
162 | | } |
163 | | |
164 | | impl TokenStreamBuilder { |
165 | 8.98M | pub(crate) fn new() -> Self { |
166 | 8.98M | TokenStreamBuilder { |
167 | 8.98M | inner: RcVecBuilder::new(), |
168 | 8.98M | } |
169 | 8.98M | } |
170 | | |
171 | 11.1k | pub(crate) fn with_capacity(cap: usize) -> Self { |
172 | 11.1k | TokenStreamBuilder { |
173 | 11.1k | inner: RcVecBuilder::with_capacity(cap), |
174 | 11.1k | } |
175 | 11.1k | } |
176 | | |
177 | 11.1M | pub(crate) fn push_token_from_parser(&mut self, tt: TokenTree) { |
178 | 11.1M | self.inner.push(tt); |
179 | 11.1M | } |
180 | | |
181 | 516k | pub(crate) fn build(self) -> TokenStream { |
182 | 516k | TokenStream { |
183 | 516k | inner: self.inner.build(), |
184 | 516k | } |
185 | 516k | } |
186 | | } |
187 | | |
188 | | #[cfg(span_locations)] |
189 | | fn get_cursor(src: &str) -> Cursor { |
190 | | #[cfg(fuzzing)] |
191 | | return Cursor { rest: src, off: 1 }; |
192 | | |
193 | | // Create a dummy file & add it to the source map |
194 | | #[cfg(not(fuzzing))] |
195 | | SOURCE_MAP.with(|sm| { |
196 | | let mut sm = sm.borrow_mut(); |
197 | | let span = sm.add_file(src); |
198 | | Cursor { |
199 | | rest: src, |
200 | | off: span.lo, |
201 | | } |
202 | | }) |
203 | | } |
204 | | |
205 | | #[cfg(not(span_locations))] |
206 | 420 | fn get_cursor(src: &str) -> Cursor { |
207 | 420 | Cursor { rest: src } |
208 | 420 | } |
209 | | |
210 | | impl Display for LexError { |
211 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
212 | 0 | f.write_str("cannot parse string into token stream") |
213 | 0 | } |
214 | | } |
215 | | |
216 | | impl Display for TokenStream { |
217 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
218 | 0 | let mut joint = false; |
219 | 0 | for (i, tt) in self.inner.iter().enumerate() { |
220 | 0 | if i != 0 && !joint { |
221 | 0 | write!(f, " ")?; |
222 | 0 | } |
223 | 0 | joint = false; |
224 | 0 | match tt { |
225 | 0 | TokenTree::Group(tt) => write!(f, "{}", tt), |
226 | 0 | TokenTree::Ident(tt) => write!(f, "{}", tt), |
227 | 0 | TokenTree::Punct(tt) => { |
228 | 0 | joint = tt.spacing() == Spacing::Joint; |
229 | 0 | write!(f, "{}", tt) |
230 | | } |
231 | 0 | TokenTree::Literal(tt) => write!(f, "{}", tt), |
232 | 0 | }?; |
233 | | } |
234 | | |
235 | 0 | Ok(()) |
236 | 0 | } |
237 | | } |
238 | | |
239 | | impl Debug for TokenStream { |
240 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
241 | 0 | f.write_str("TokenStream ")?; |
242 | 0 | f.debug_list().entries(self.clone()).finish() |
243 | 0 | } |
244 | | } |
245 | | |
246 | | #[cfg(feature = "proc-macro")] |
247 | | impl From<proc_macro::TokenStream> for TokenStream { |
248 | 0 | fn from(inner: proc_macro::TokenStream) -> Self { |
249 | 0 | TokenStream::from_str_unchecked(&inner.to_string()) |
250 | 0 | } |
251 | | } |
252 | | |
253 | | #[cfg(feature = "proc-macro")] |
254 | | impl From<TokenStream> for proc_macro::TokenStream { |
255 | 0 | fn from(inner: TokenStream) -> Self { |
256 | 0 | proc_macro::TokenStream::from_str_unchecked(&inner.to_string()) |
257 | 0 | } |
258 | | } |
259 | | |
260 | | impl From<TokenTree> for TokenStream { |
261 | 0 | fn from(tree: TokenTree) -> Self { |
262 | 0 | let mut stream = RcVecBuilder::new(); |
263 | 0 | push_token_from_proc_macro(stream.as_mut(), tree); |
264 | 0 | TokenStream { |
265 | 0 | inner: stream.build(), |
266 | 0 | } |
267 | 0 | } |
268 | | } |
269 | | |
270 | | impl FromIterator<TokenTree> for TokenStream { |
271 | 0 | fn from_iter<I: IntoIterator<Item = TokenTree>>(tokens: I) -> Self { |
272 | 0 | let mut stream = TokenStream::new(); |
273 | 0 | stream.extend(tokens); |
274 | 0 | stream |
275 | 0 | } |
276 | | } |
277 | | |
278 | | impl FromIterator<TokenStream> for TokenStream { |
279 | 0 | fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self { |
280 | 0 | let mut v = RcVecBuilder::new(); |
281 | | |
282 | 0 | for stream in streams { |
283 | 0 | v.extend(stream.take_inner()); |
284 | 0 | } |
285 | | |
286 | 0 | TokenStream { inner: v.build() } |
287 | 0 | } |
288 | | } |
289 | | |
290 | | impl Extend<TokenTree> for TokenStream { |
291 | 0 | fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, tokens: I) { |
292 | 0 | let mut vec = self.inner.make_mut(); |
293 | 0 | tokens |
294 | 0 | .into_iter() |
295 | 0 | .for_each(|token| push_token_from_proc_macro(vec.as_mut(), token)); |
296 | 0 | } |
297 | | } |
298 | | |
299 | | impl Extend<TokenStream> for TokenStream { |
300 | 0 | fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) { |
301 | 0 | self.inner.make_mut().extend(streams.into_iter().flatten()); |
302 | 0 | } |
303 | | } |
304 | | |
305 | | pub(crate) type TokenTreeIter = RcVecIntoIter<TokenTree>; |
306 | | |
307 | | impl IntoIterator for TokenStream { |
308 | | type Item = TokenTree; |
309 | | type IntoIter = TokenTreeIter; |
310 | | |
311 | 0 | fn into_iter(self) -> TokenTreeIter { |
312 | 0 | self.take_inner().into_iter() |
313 | 0 | } |
314 | | } |
315 | | |
316 | | #[cfg(all(span_locations, not(fuzzing)))] |
317 | | thread_local! { |
318 | | static SOURCE_MAP: RefCell<SourceMap> = RefCell::new(SourceMap { |
319 | | // Start with a single dummy file which all call_site() and def_site() |
320 | | // spans reference. |
321 | | files: vec![FileInfo { |
322 | | source_text: String::new(), |
323 | | span: Span { lo: 0, hi: 0 }, |
324 | | lines: vec![0], |
325 | | char_index_to_byte_offset: BTreeMap::new(), |
326 | | }], |
327 | | }); |
328 | | } |
329 | | |
330 | | #[cfg(span_locations)] |
331 | | pub(crate) fn invalidate_current_thread_spans() { |
332 | | #[cfg(not(fuzzing))] |
333 | | SOURCE_MAP.with(|sm| sm.borrow_mut().files.truncate(1)); |
334 | | } |
335 | | |
336 | | #[cfg(all(span_locations, not(fuzzing)))] |
337 | | struct FileInfo { |
338 | | source_text: String, |
339 | | span: Span, |
340 | | lines: Vec<usize>, |
341 | | char_index_to_byte_offset: BTreeMap<usize, usize>, |
342 | | } |
343 | | |
344 | | #[cfg(all(span_locations, not(fuzzing)))] |
345 | | impl FileInfo { |
346 | | fn offset_line_column(&self, offset: usize) -> LineColumn { |
347 | | assert!(self.span_within(Span { |
348 | | lo: offset as u32, |
349 | | hi: offset as u32, |
350 | | })); |
351 | | let offset = offset - self.span.lo as usize; |
352 | | match self.lines.binary_search(&offset) { |
353 | | Ok(found) => LineColumn { |
354 | | line: found + 1, |
355 | | column: 0, |
356 | | }, |
357 | | Err(idx) => LineColumn { |
358 | | line: idx, |
359 | | column: offset - self.lines[idx - 1], |
360 | | }, |
361 | | } |
362 | | } |
363 | | |
364 | | fn span_within(&self, span: Span) -> bool { |
365 | | span.lo >= self.span.lo && span.hi <= self.span.hi |
366 | | } |
367 | | |
368 | | fn byte_range(&mut self, span: Span) -> Range<usize> { |
369 | | let lo_char = (span.lo - self.span.lo) as usize; |
370 | | |
371 | | // Look up offset of the largest already-computed char index that is |
372 | | // less than or equal to the current requested one. We resume counting |
373 | | // chars from that point. |
374 | | let (&last_char_index, &last_byte_offset) = self |
375 | | .char_index_to_byte_offset |
376 | | .range(..=lo_char) |
377 | | .next_back() |
378 | | .unwrap_or((&0, &0)); |
379 | | |
380 | | let lo_byte = if last_char_index == lo_char { |
381 | | last_byte_offset |
382 | | } else { |
383 | | let total_byte_offset = match self.source_text[last_byte_offset..] |
384 | | .char_indices() |
385 | | .nth(lo_char - last_char_index) |
386 | | { |
387 | | Some((additional_offset, _ch)) => last_byte_offset + additional_offset, |
388 | | None => self.source_text.len(), |
389 | | }; |
390 | | self.char_index_to_byte_offset |
391 | | .insert(lo_char, total_byte_offset); |
392 | | total_byte_offset |
393 | | }; |
394 | | |
395 | | let trunc_lo = &self.source_text[lo_byte..]; |
396 | | let char_len = (span.hi - span.lo) as usize; |
397 | | lo_byte..match trunc_lo.char_indices().nth(char_len) { |
398 | | Some((offset, _ch)) => lo_byte + offset, |
399 | | None => self.source_text.len(), |
400 | | } |
401 | | } |
402 | | |
403 | | fn source_text(&mut self, span: Span) -> String { |
404 | | let byte_range = self.byte_range(span); |
405 | | self.source_text[byte_range].to_owned() |
406 | | } |
407 | | } |
408 | | |
409 | | /// Computes the offsets of each line in the given source string |
410 | | /// and the total number of characters |
411 | | #[cfg(all(span_locations, not(fuzzing)))] |
412 | | fn lines_offsets(s: &str) -> (usize, Vec<usize>) { |
413 | | let mut lines = vec![0]; |
414 | | let mut total = 0; |
415 | | |
416 | | for ch in s.chars() { |
417 | | total += 1; |
418 | | if ch == '\n' { |
419 | | lines.push(total); |
420 | | } |
421 | | } |
422 | | |
423 | | (total, lines) |
424 | | } |
425 | | |
426 | | #[cfg(all(span_locations, not(fuzzing)))] |
427 | | struct SourceMap { |
428 | | files: Vec<FileInfo>, |
429 | | } |
430 | | |
431 | | #[cfg(all(span_locations, not(fuzzing)))] |
432 | | impl SourceMap { |
433 | | fn next_start_pos(&self) -> u32 { |
434 | | // Add 1 so there's always space between files. |
435 | | // |
436 | | // We'll always have at least 1 file, as we initialize our files list |
437 | | // with a dummy file. |
438 | | self.files.last().unwrap().span.hi + 1 |
439 | | } |
440 | | |
441 | | fn add_file(&mut self, src: &str) -> Span { |
442 | | let (len, lines) = lines_offsets(src); |
443 | | let lo = self.next_start_pos(); |
444 | | let span = Span { |
445 | | lo, |
446 | | hi: lo + (len as u32), |
447 | | }; |
448 | | |
449 | | self.files.push(FileInfo { |
450 | | source_text: src.to_owned(), |
451 | | span, |
452 | | lines, |
453 | | // Populated lazily by source_text(). |
454 | | char_index_to_byte_offset: BTreeMap::new(), |
455 | | }); |
456 | | |
457 | | span |
458 | | } |
459 | | |
460 | | fn find(&self, span: Span) -> usize { |
461 | | match self.files.binary_search_by(|file| { |
462 | | if file.span.hi < span.lo { |
463 | | Ordering::Less |
464 | | } else if file.span.lo > span.hi { |
465 | | Ordering::Greater |
466 | | } else { |
467 | | assert!(file.span_within(span)); |
468 | | Ordering::Equal |
469 | | } |
470 | | }) { |
471 | | Ok(i) => i, |
472 | | Err(_) => unreachable!("Invalid span with no related FileInfo!"), |
473 | | } |
474 | | } |
475 | | |
476 | | fn filepath(&self, span: Span) -> String { |
477 | | let i = self.find(span); |
478 | | if i == 0 { |
479 | | "<unspecified>".to_owned() |
480 | | } else { |
481 | | format!("<parsed string {}>", i) |
482 | | } |
483 | | } |
484 | | |
485 | | fn fileinfo(&self, span: Span) -> &FileInfo { |
486 | | let i = self.find(span); |
487 | | &self.files[i] |
488 | | } |
489 | | |
490 | | fn fileinfo_mut(&mut self, span: Span) -> &mut FileInfo { |
491 | | let i = self.find(span); |
492 | | &mut self.files[i] |
493 | | } |
494 | | } |
495 | | |
496 | | #[derive(Clone, Copy, PartialEq, Eq)] |
497 | | pub(crate) struct Span { |
498 | | #[cfg(span_locations)] |
499 | | pub(crate) lo: u32, |
500 | | #[cfg(span_locations)] |
501 | | pub(crate) hi: u32, |
502 | | } |
503 | | |
504 | | impl Span { |
505 | | #[cfg(not(span_locations))] |
506 | 11.1M | pub(crate) fn call_site() -> Self { |
507 | 11.1M | Span {} |
508 | 11.1M | } |
509 | | |
510 | | #[cfg(span_locations)] |
511 | | pub(crate) fn call_site() -> Self { |
512 | | Span { lo: 0, hi: 0 } |
513 | | } |
514 | | |
515 | 0 | pub(crate) fn mixed_site() -> Self { |
516 | 0 | Span::call_site() |
517 | 0 | } |
518 | | |
519 | | #[cfg(procmacro2_semver_exempt)] |
520 | | pub(crate) fn def_site() -> Self { |
521 | | Span::call_site() |
522 | | } |
523 | | |
524 | 0 | pub(crate) fn resolved_at(&self, _other: Span) -> Span { |
525 | | // Stable spans consist only of line/column information, so |
526 | | // `resolved_at` and `located_at` only select which span the |
527 | | // caller wants line/column information from. |
528 | 0 | *self |
529 | 0 | } |
530 | | |
531 | 0 | pub(crate) fn located_at(&self, other: Span) -> Span { |
532 | 0 | other |
533 | 0 | } |
534 | | |
535 | | #[cfg(span_locations)] |
536 | | pub(crate) fn byte_range(&self) -> Range<usize> { |
537 | | #[cfg(fuzzing)] |
538 | | return 0..0; |
539 | | |
540 | | #[cfg(not(fuzzing))] |
541 | | { |
542 | | if self.is_call_site() { |
543 | | 0..0 |
544 | | } else { |
545 | | SOURCE_MAP.with(|sm| sm.borrow_mut().fileinfo_mut(*self).byte_range(*self)) |
546 | | } |
547 | | } |
548 | | } |
549 | | |
550 | | #[cfg(span_locations)] |
551 | | pub(crate) fn start(&self) -> LineColumn { |
552 | | #[cfg(fuzzing)] |
553 | | return LineColumn { line: 0, column: 0 }; |
554 | | |
555 | | #[cfg(not(fuzzing))] |
556 | | SOURCE_MAP.with(|sm| { |
557 | | let sm = sm.borrow(); |
558 | | let fi = sm.fileinfo(*self); |
559 | | fi.offset_line_column(self.lo as usize) |
560 | | }) |
561 | | } |
562 | | |
563 | | #[cfg(span_locations)] |
564 | | pub(crate) fn end(&self) -> LineColumn { |
565 | | #[cfg(fuzzing)] |
566 | | return LineColumn { line: 0, column: 0 }; |
567 | | |
568 | | #[cfg(not(fuzzing))] |
569 | | SOURCE_MAP.with(|sm| { |
570 | | let sm = sm.borrow(); |
571 | | let fi = sm.fileinfo(*self); |
572 | | fi.offset_line_column(self.hi as usize) |
573 | | }) |
574 | | } |
575 | | |
576 | | #[cfg(span_locations)] |
577 | | pub(crate) fn file(&self) -> String { |
578 | | #[cfg(fuzzing)] |
579 | | return "<unspecified>".to_owned(); |
580 | | |
581 | | #[cfg(not(fuzzing))] |
582 | | SOURCE_MAP.with(|sm| { |
583 | | let sm = sm.borrow(); |
584 | | sm.filepath(*self) |
585 | | }) |
586 | | } |
587 | | |
588 | | #[cfg(span_locations)] |
589 | | pub(crate) fn local_file(&self) -> Option<PathBuf> { |
590 | | None |
591 | | } |
592 | | |
593 | | #[cfg(not(span_locations))] |
594 | 0 | pub(crate) fn join(&self, _other: Span) -> Option<Span> { |
595 | 0 | Some(Span {}) |
596 | 0 | } |
597 | | |
598 | | #[cfg(span_locations)] |
599 | | pub(crate) fn join(&self, other: Span) -> Option<Span> { |
600 | | #[cfg(fuzzing)] |
601 | | return { |
602 | | let _ = other; |
603 | | None |
604 | | }; |
605 | | |
606 | | #[cfg(not(fuzzing))] |
607 | | SOURCE_MAP.with(|sm| { |
608 | | let sm = sm.borrow(); |
609 | | // If `other` is not within the same FileInfo as us, return None. |
610 | | if !sm.fileinfo(*self).span_within(other) { |
611 | | return None; |
612 | | } |
613 | | Some(Span { |
614 | | lo: cmp::min(self.lo, other.lo), |
615 | | hi: cmp::max(self.hi, other.hi), |
616 | | }) |
617 | | }) |
618 | | } |
619 | | |
620 | | #[cfg(not(span_locations))] |
621 | 0 | pub(crate) fn source_text(&self) -> Option<String> { |
622 | 0 | None |
623 | 0 | } |
624 | | |
625 | | #[cfg(span_locations)] |
626 | | pub(crate) fn source_text(&self) -> Option<String> { |
627 | | #[cfg(fuzzing)] |
628 | | return None; |
629 | | |
630 | | #[cfg(not(fuzzing))] |
631 | | { |
632 | | if self.is_call_site() { |
633 | | None |
634 | | } else { |
635 | | Some(SOURCE_MAP.with(|sm| sm.borrow_mut().fileinfo_mut(*self).source_text(*self))) |
636 | | } |
637 | | } |
638 | | } |
639 | | |
640 | | #[cfg(not(span_locations))] |
641 | 0 | pub(crate) fn first_byte(self) -> Self { |
642 | 0 | self |
643 | 0 | } |
644 | | |
645 | | #[cfg(span_locations)] |
646 | | pub(crate) fn first_byte(self) -> Self { |
647 | | Span { |
648 | | lo: self.lo, |
649 | | hi: cmp::min(self.lo.saturating_add(1), self.hi), |
650 | | } |
651 | | } |
652 | | |
653 | | #[cfg(not(span_locations))] |
654 | 0 | pub(crate) fn last_byte(self) -> Self { |
655 | 0 | self |
656 | 0 | } |
657 | | |
658 | | #[cfg(span_locations)] |
659 | | pub(crate) fn last_byte(self) -> Self { |
660 | | Span { |
661 | | lo: cmp::max(self.hi.saturating_sub(1), self.lo), |
662 | | hi: self.hi, |
663 | | } |
664 | | } |
665 | | |
666 | | #[cfg(span_locations)] |
667 | | fn is_call_site(&self) -> bool { |
668 | | self.lo == 0 && self.hi == 0 |
669 | | } |
670 | | } |
671 | | |
672 | | impl Debug for Span { |
673 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
674 | | #[cfg(span_locations)] |
675 | | return write!(f, "bytes({}..{})", self.lo, self.hi); |
676 | | |
677 | | #[cfg(not(span_locations))] |
678 | 0 | write!(f, "Span") |
679 | 0 | } |
680 | | } |
681 | | |
682 | 0 | pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) { |
683 | | #[cfg(span_locations)] |
684 | | { |
685 | | if span.is_call_site() { |
686 | | return; |
687 | | } |
688 | | } |
689 | | |
690 | 0 | if cfg!(span_locations) { |
691 | 0 | debug.field("span", &span); |
692 | 0 | } |
693 | 0 | } |
694 | | |
695 | | #[derive(Clone)] |
696 | | pub(crate) struct Group { |
697 | | delimiter: Delimiter, |
698 | | stream: TokenStream, |
699 | | span: Span, |
700 | | } |
701 | | |
702 | | impl Group { |
703 | 516k | pub(crate) fn new(delimiter: Delimiter, stream: TokenStream) -> Self { |
704 | 516k | Group { |
705 | 516k | delimiter, |
706 | 516k | stream, |
707 | 516k | span: Span::call_site(), |
708 | 516k | } |
709 | 516k | } |
710 | | |
711 | 0 | pub(crate) fn delimiter(&self) -> Delimiter { |
712 | 0 | self.delimiter |
713 | 0 | } |
714 | | |
715 | 0 | pub(crate) fn stream(&self) -> TokenStream { |
716 | 0 | self.stream.clone() |
717 | 0 | } |
718 | | |
719 | 0 | pub(crate) fn span(&self) -> Span { |
720 | 0 | self.span |
721 | 0 | } |
722 | | |
723 | 0 | pub(crate) fn span_open(&self) -> Span { |
724 | 0 | self.span.first_byte() |
725 | 0 | } |
726 | | |
727 | 0 | pub(crate) fn span_close(&self) -> Span { |
728 | 0 | self.span.last_byte() |
729 | 0 | } |
730 | | |
731 | 516k | pub(crate) fn set_span(&mut self, span: Span) { |
732 | 516k | self.span = span; |
733 | 516k | } |
734 | | } |
735 | | |
736 | | impl Display for Group { |
737 | | // We attempt to match libproc_macro's formatting. |
738 | | // Empty parens: () |
739 | | // Nonempty parens: (...) |
740 | | // Empty brackets: [] |
741 | | // Nonempty brackets: [...] |
742 | | // Empty braces: { } |
743 | | // Nonempty braces: { ... } |
744 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
745 | 0 | let (open, close) = match self.delimiter { |
746 | 0 | Delimiter::Parenthesis => ("(", ")"), |
747 | 0 | Delimiter::Brace => ("{ ", "}"), |
748 | 0 | Delimiter::Bracket => ("[", "]"), |
749 | 0 | Delimiter::None => ("", ""), |
750 | | }; |
751 | | |
752 | 0 | f.write_str(open)?; |
753 | 0 | Display::fmt(&self.stream, f)?; |
754 | 0 | if self.delimiter == Delimiter::Brace && !self.stream.inner.is_empty() { |
755 | 0 | f.write_str(" ")?; |
756 | 0 | } |
757 | 0 | f.write_str(close)?; |
758 | | |
759 | 0 | Ok(()) |
760 | 0 | } |
761 | | } |
762 | | |
763 | | impl Debug for Group { |
764 | 0 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
765 | 0 | let mut debug = fmt.debug_struct("Group"); |
766 | 0 | debug.field("delimiter", &self.delimiter); |
767 | 0 | debug.field("stream", &self.stream); |
768 | 0 | debug_span_field_if_nontrivial(&mut debug, self.span); |
769 | 0 | debug.finish() |
770 | 0 | } |
771 | | } |
772 | | |
773 | | #[derive(Clone)] |
774 | | pub(crate) struct Ident { |
775 | | sym: Box<str>, |
776 | | span: Span, |
777 | | raw: bool, |
778 | | } |
779 | | |
780 | | impl Ident { |
781 | | #[track_caller] |
782 | 0 | pub(crate) fn new_checked(string: &str, span: Span) -> Self { |
783 | 0 | validate_ident(string); |
784 | 0 | Ident::new_unchecked(string, span) |
785 | 0 | } |
786 | | |
787 | 1.23M | pub(crate) fn new_unchecked(string: &str, span: Span) -> Self { |
788 | 1.23M | Ident { |
789 | 1.23M | sym: Box::from(string), |
790 | 1.23M | span, |
791 | 1.23M | raw: false, |
792 | 1.23M | } |
793 | 1.23M | } |
794 | | |
795 | | #[track_caller] |
796 | 0 | pub(crate) fn new_raw_checked(string: &str, span: Span) -> Self { |
797 | 0 | validate_ident_raw(string); |
798 | 0 | Ident::new_raw_unchecked(string, span) |
799 | 0 | } |
800 | | |
801 | 2.63k | pub(crate) fn new_raw_unchecked(string: &str, span: Span) -> Self { |
802 | 2.63k | Ident { |
803 | 2.63k | sym: Box::from(string), |
804 | 2.63k | span, |
805 | 2.63k | raw: true, |
806 | 2.63k | } |
807 | 2.63k | } |
808 | | |
809 | 0 | pub(crate) fn span(&self) -> Span { |
810 | 0 | self.span |
811 | 0 | } |
812 | | |
813 | 1.22M | pub(crate) fn set_span(&mut self, span: Span) { |
814 | 1.22M | self.span = span; |
815 | 1.22M | } |
816 | | } |
817 | | |
818 | 4.08M | pub(crate) fn is_ident_start(c: char) -> bool { |
819 | 4.08M | c == '_' || unicode_ident::is_xid_start(c) |
820 | 4.08M | } |
821 | | |
822 | 20.5M | pub(crate) fn is_ident_continue(c: char) -> bool { |
823 | 20.5M | unicode_ident::is_xid_continue(c) |
824 | 20.5M | } |
825 | | |
826 | | #[track_caller] |
827 | 0 | fn validate_ident(string: &str) { |
828 | 0 | if string.is_empty() { |
829 | 0 | panic!("Ident is not allowed to be empty; use Option<Ident>"); |
830 | 0 | } |
831 | | |
832 | 0 | if string.bytes().all(|digit| b'0' <= digit && digit <= b'9') { |
833 | 0 | panic!("Ident cannot be a number; use Literal instead"); |
834 | 0 | } |
835 | | |
836 | 0 | fn ident_ok(string: &str) -> bool { |
837 | 0 | let mut chars = string.chars(); |
838 | 0 | let first = chars.next().unwrap(); |
839 | 0 | if !is_ident_start(first) { |
840 | 0 | return false; |
841 | 0 | } |
842 | 0 | for ch in chars { |
843 | 0 | if !is_ident_continue(ch) { |
844 | 0 | return false; |
845 | 0 | } |
846 | | } |
847 | 0 | true |
848 | 0 | } |
849 | | |
850 | 0 | if !ident_ok(string) { |
851 | 0 | panic!("{:?} is not a valid Ident", string); |
852 | 0 | } |
853 | 0 | } |
854 | | |
855 | | #[track_caller] |
856 | 0 | fn validate_ident_raw(string: &str) { |
857 | 0 | validate_ident(string); |
858 | | |
859 | 0 | match string { |
860 | 0 | "_" | "super" | "self" | "Self" | "crate" => { |
861 | 0 | panic!("`r#{}` cannot be a raw identifier", string); |
862 | | } |
863 | 0 | _ => {} |
864 | | } |
865 | 0 | } |
866 | | |
867 | | impl PartialEq for Ident { |
868 | 0 | fn eq(&self, other: &Ident) -> bool { |
869 | 0 | self.sym == other.sym && self.raw == other.raw |
870 | 0 | } |
871 | | } |
872 | | |
873 | | impl<T> PartialEq<T> for Ident |
874 | | where |
875 | | T: ?Sized + AsRef<str>, |
876 | | { |
877 | 0 | fn eq(&self, other: &T) -> bool { |
878 | 0 | let other = other.as_ref(); |
879 | 0 | if self.raw { |
880 | 0 | other.starts_with("r#") && *self.sym == other[2..] |
881 | | } else { |
882 | 0 | *self.sym == *other |
883 | | } |
884 | 0 | } |
885 | | } |
886 | | |
887 | | impl Display for Ident { |
888 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
889 | 0 | if self.raw { |
890 | 0 | f.write_str("r#")?; |
891 | 0 | } |
892 | 0 | f.write_str(&self.sym) |
893 | 0 | } |
894 | | } |
895 | | |
896 | | #[allow(clippy::missing_fields_in_debug)] |
897 | | impl Debug for Ident { |
898 | | // Ident(proc_macro), Ident(r#union) |
899 | | #[cfg(not(span_locations))] |
900 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
901 | 0 | let mut debug = f.debug_tuple("Ident"); |
902 | 0 | debug.field(&format_args!("{}", self)); |
903 | 0 | debug.finish() |
904 | 0 | } |
905 | | |
906 | | // Ident { |
907 | | // sym: proc_macro, |
908 | | // span: bytes(128..138) |
909 | | // } |
910 | | #[cfg(span_locations)] |
911 | | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
912 | | let mut debug = f.debug_struct("Ident"); |
913 | | debug.field("sym", &format_args!("{}", self)); |
914 | | debug_span_field_if_nontrivial(&mut debug, self.span); |
915 | | debug.finish() |
916 | | } |
917 | | } |
918 | | |
919 | | #[derive(Clone)] |
920 | | pub(crate) struct Literal { |
921 | | pub(crate) repr: String, |
922 | | span: Span, |
923 | | } |
924 | | |
925 | | macro_rules! suffixed_numbers { |
926 | | ($($name:ident => $kind:ident,)*) => ($( |
927 | 0 | pub(crate) fn $name(n: $kind) -> Literal { |
928 | 0 | Literal::_new(format!(concat!("{}", stringify!($kind)), n)) |
929 | 0 | } Unexecuted instantiation: <proc_macro2::fallback::Literal>::i8_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u8_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::f32_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::f64_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i16_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i32_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i64_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u16_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u32_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u64_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i128_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u128_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::isize_suffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::usize_suffixed |
930 | | )*) |
931 | | } |
932 | | |
933 | | macro_rules! unsuffixed_numbers { |
934 | | ($($name:ident => $kind:ident,)*) => ($( |
935 | 0 | pub(crate) fn $name(n: $kind) -> Literal { |
936 | 0 | Literal::_new(n.to_string()) |
937 | 0 | } Unexecuted instantiation: <proc_macro2::fallback::Literal>::i8_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u8_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i16_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i32_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i64_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u16_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u32_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u64_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::i128_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::u128_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::isize_unsuffixed Unexecuted instantiation: <proc_macro2::fallback::Literal>::usize_unsuffixed |
938 | | )*) |
939 | | } |
940 | | |
941 | | impl Literal { |
942 | 2.11M | pub(crate) fn _new(repr: String) -> Self { |
943 | 2.11M | Literal { |
944 | 2.11M | repr, |
945 | 2.11M | span: Span::call_site(), |
946 | 2.11M | } |
947 | 2.11M | } |
948 | | |
949 | 0 | pub(crate) fn from_str_checked(repr: &str) -> Result<Self, LexError> { |
950 | 0 | let mut cursor = get_cursor(repr); |
951 | | #[cfg(span_locations)] |
952 | | let lo = cursor.off; |
953 | | |
954 | 0 | let negative = cursor.starts_with_char('-'); |
955 | 0 | if negative { |
956 | 0 | cursor = cursor.advance(1); |
957 | 0 | if !cursor.starts_with_fn(|ch| ch.is_ascii_digit()) { |
958 | 0 | return Err(LexError::call_site()); |
959 | 0 | } |
960 | 0 | } |
961 | | |
962 | 0 | if let Ok((rest, mut literal)) = parse::literal(cursor) { |
963 | 0 | if rest.is_empty() { |
964 | 0 | if negative { |
965 | 0 | literal.repr.insert(0, '-'); |
966 | 0 | } |
967 | 0 | literal.span = Span { |
968 | 0 | #[cfg(span_locations)] |
969 | 0 | lo, |
970 | 0 | #[cfg(span_locations)] |
971 | 0 | hi: rest.off, |
972 | 0 | }; |
973 | 0 | return Ok(literal); |
974 | 0 | } |
975 | 0 | } |
976 | 0 | Err(LexError::call_site()) |
977 | 0 | } |
978 | | |
979 | 0 | pub(crate) unsafe fn from_str_unchecked(repr: &str) -> Self { |
980 | 0 | Literal::_new(repr.to_owned()) |
981 | 0 | } |
982 | | |
983 | | suffixed_numbers! { |
984 | | u8_suffixed => u8, |
985 | | u16_suffixed => u16, |
986 | | u32_suffixed => u32, |
987 | | u64_suffixed => u64, |
988 | | u128_suffixed => u128, |
989 | | usize_suffixed => usize, |
990 | | i8_suffixed => i8, |
991 | | i16_suffixed => i16, |
992 | | i32_suffixed => i32, |
993 | | i64_suffixed => i64, |
994 | | i128_suffixed => i128, |
995 | | isize_suffixed => isize, |
996 | | |
997 | | f32_suffixed => f32, |
998 | | f64_suffixed => f64, |
999 | | } |
1000 | | |
1001 | | unsuffixed_numbers! { |
1002 | | u8_unsuffixed => u8, |
1003 | | u16_unsuffixed => u16, |
1004 | | u32_unsuffixed => u32, |
1005 | | u64_unsuffixed => u64, |
1006 | | u128_unsuffixed => u128, |
1007 | | usize_unsuffixed => usize, |
1008 | | i8_unsuffixed => i8, |
1009 | | i16_unsuffixed => i16, |
1010 | | i32_unsuffixed => i32, |
1011 | | i64_unsuffixed => i64, |
1012 | | i128_unsuffixed => i128, |
1013 | | isize_unsuffixed => isize, |
1014 | | } |
1015 | | |
1016 | 0 | pub(crate) fn f32_unsuffixed(f: f32) -> Literal { |
1017 | 0 | let mut s = f.to_string(); |
1018 | 0 | if !s.contains('.') { |
1019 | 0 | s.push_str(".0"); |
1020 | 0 | } |
1021 | 0 | Literal::_new(s) |
1022 | 0 | } |
1023 | | |
1024 | 0 | pub(crate) fn f64_unsuffixed(f: f64) -> Literal { |
1025 | 0 | let mut s = f.to_string(); |
1026 | 0 | if !s.contains('.') { |
1027 | 0 | s.push_str(".0"); |
1028 | 0 | } |
1029 | 0 | Literal::_new(s) |
1030 | 0 | } |
1031 | | |
1032 | 11.1k | pub(crate) fn string(string: &str) -> Literal { |
1033 | 11.1k | let mut repr = String::with_capacity(string.len() + 2); |
1034 | 11.1k | repr.push('"'); |
1035 | 11.1k | escape_utf8(string, &mut repr); |
1036 | 11.1k | repr.push('"'); |
1037 | 11.1k | Literal::_new(repr) |
1038 | 11.1k | } |
1039 | | |
1040 | 0 | pub(crate) fn character(ch: char) -> Literal { |
1041 | 0 | let mut repr = String::new(); |
1042 | 0 | repr.push('\''); |
1043 | 0 | if ch == '"' { |
1044 | 0 | // escape_debug turns this into '\"' which is unnecessary. |
1045 | 0 | repr.push(ch); |
1046 | 0 | } else { |
1047 | 0 | repr.extend(ch.escape_debug()); |
1048 | 0 | } |
1049 | 0 | repr.push('\''); |
1050 | 0 | Literal::_new(repr) |
1051 | 0 | } |
1052 | | |
1053 | 0 | pub(crate) fn byte_character(byte: u8) -> Literal { |
1054 | 0 | let mut repr = "b'".to_string(); |
1055 | | #[allow(clippy::match_overlapping_arm)] |
1056 | 0 | match byte { |
1057 | 0 | b'\0' => repr.push_str(r"\0"), |
1058 | 0 | b'\t' => repr.push_str(r"\t"), |
1059 | 0 | b'\n' => repr.push_str(r"\n"), |
1060 | 0 | b'\r' => repr.push_str(r"\r"), |
1061 | 0 | b'\'' => repr.push_str(r"\'"), |
1062 | 0 | b'\\' => repr.push_str(r"\\"), |
1063 | 0 | b'\x20'..=b'\x7E' => repr.push(byte as char), |
1064 | 0 | _ => { |
1065 | 0 | let _ = write!(repr, r"\x{:02X}", byte); |
1066 | 0 | } |
1067 | | } |
1068 | 0 | repr.push('\''); |
1069 | 0 | Literal::_new(repr) |
1070 | 0 | } |
1071 | | |
1072 | 0 | pub(crate) fn byte_string(bytes: &[u8]) -> Literal { |
1073 | 0 | let mut repr = "b\"".to_string(); |
1074 | 0 | let mut bytes = bytes.iter(); |
1075 | 0 | while let Some(&b) = bytes.next() { |
1076 | | #[allow(clippy::match_overlapping_arm)] |
1077 | 0 | match b { |
1078 | 0 | b'\0' => repr.push_str(match bytes.as_slice().first() { |
1079 | | // circumvent clippy::octal_escapes lint |
1080 | 0 | Some(b'0'..=b'7') => r"\x00", |
1081 | 0 | _ => r"\0", |
1082 | | }), |
1083 | 0 | b'\t' => repr.push_str(r"\t"), |
1084 | 0 | b'\n' => repr.push_str(r"\n"), |
1085 | 0 | b'\r' => repr.push_str(r"\r"), |
1086 | 0 | b'"' => repr.push_str("\\\""), |
1087 | 0 | b'\\' => repr.push_str(r"\\"), |
1088 | 0 | b'\x20'..=b'\x7E' => repr.push(b as char), |
1089 | 0 | _ => { |
1090 | 0 | let _ = write!(repr, r"\x{:02X}", b); |
1091 | 0 | } |
1092 | | } |
1093 | | } |
1094 | 0 | repr.push('"'); |
1095 | 0 | Literal::_new(repr) |
1096 | 0 | } |
1097 | | |
1098 | 0 | pub(crate) fn c_string(string: &CStr) -> Literal { |
1099 | 0 | let mut repr = "c\"".to_string(); |
1100 | 0 | let mut bytes = string.to_bytes(); |
1101 | 0 | while !bytes.is_empty() { |
1102 | 0 | let (valid, invalid) = match str::from_utf8(bytes) { |
1103 | 0 | Ok(all_valid) => { |
1104 | 0 | bytes = b""; |
1105 | 0 | (all_valid, bytes) |
1106 | | } |
1107 | 0 | Err(utf8_error) => { |
1108 | 0 | let (valid, rest) = bytes.split_at(utf8_error.valid_up_to()); |
1109 | 0 | let valid = str::from_utf8(valid).unwrap(); |
1110 | 0 | let invalid = utf8_error |
1111 | 0 | .error_len() |
1112 | 0 | .map_or(rest, |error_len| &rest[..error_len]); |
1113 | 0 | bytes = &bytes[valid.len() + invalid.len()..]; |
1114 | 0 | (valid, invalid) |
1115 | | } |
1116 | | }; |
1117 | 0 | escape_utf8(valid, &mut repr); |
1118 | 0 | for &byte in invalid { |
1119 | 0 | let _ = write!(repr, r"\x{:02X}", byte); |
1120 | 0 | } |
1121 | | } |
1122 | 0 | repr.push('"'); |
1123 | 0 | Literal::_new(repr) |
1124 | 0 | } |
1125 | | |
1126 | 0 | pub(crate) fn span(&self) -> Span { |
1127 | 0 | self.span |
1128 | 0 | } |
1129 | | |
1130 | 2.11M | pub(crate) fn set_span(&mut self, span: Span) { |
1131 | 2.11M | self.span = span; |
1132 | 2.11M | } |
1133 | | |
1134 | 0 | pub(crate) fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> { |
1135 | | #[cfg(not(span_locations))] |
1136 | | { |
1137 | 0 | let _ = range; |
1138 | 0 | None |
1139 | | } |
1140 | | |
1141 | | #[cfg(span_locations)] |
1142 | | { |
1143 | | use core::ops::Bound; |
1144 | | |
1145 | | let lo = match range.start_bound() { |
1146 | | Bound::Included(start) => { |
1147 | | let start = u32::try_from(*start).ok()?; |
1148 | | self.span.lo.checked_add(start)? |
1149 | | } |
1150 | | Bound::Excluded(start) => { |
1151 | | let start = u32::try_from(*start).ok()?; |
1152 | | self.span.lo.checked_add(start)?.checked_add(1)? |
1153 | | } |
1154 | | Bound::Unbounded => self.span.lo, |
1155 | | }; |
1156 | | let hi = match range.end_bound() { |
1157 | | Bound::Included(end) => { |
1158 | | let end = u32::try_from(*end).ok()?; |
1159 | | self.span.lo.checked_add(end)?.checked_add(1)? |
1160 | | } |
1161 | | Bound::Excluded(end) => { |
1162 | | let end = u32::try_from(*end).ok()?; |
1163 | | self.span.lo.checked_add(end)? |
1164 | | } |
1165 | | Bound::Unbounded => self.span.hi, |
1166 | | }; |
1167 | | if lo <= hi && hi <= self.span.hi { |
1168 | | Some(Span { lo, hi }) |
1169 | | } else { |
1170 | | None |
1171 | | } |
1172 | | } |
1173 | 0 | } |
1174 | | } |
1175 | | |
1176 | | impl Display for Literal { |
1177 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
1178 | 0 | Display::fmt(&self.repr, f) |
1179 | 0 | } |
1180 | | } |
1181 | | |
1182 | | impl Debug for Literal { |
1183 | 0 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
1184 | 0 | let mut debug = fmt.debug_struct("Literal"); |
1185 | 0 | debug.field("lit", &format_args!("{}", self.repr)); |
1186 | 0 | debug_span_field_if_nontrivial(&mut debug, self.span); |
1187 | 0 | debug.finish() |
1188 | 0 | } |
1189 | | } |
1190 | | |
1191 | 11.1k | fn escape_utf8(string: &str, repr: &mut String) { |
1192 | 11.1k | let mut chars = string.chars(); |
1193 | 23.8M | while let Some(ch) = chars.next() { |
1194 | 23.8M | if ch == '\0' { |
1195 | 1.32M | repr.push_str( |
1196 | 1.32M | if chars |
1197 | 1.32M | .as_str() |
1198 | 1.32M | .starts_with(|next| '0' <= next && next <= '7') |
1199 | | { |
1200 | | // circumvent clippy::octal_escapes lint |
1201 | 567 | r"\x00" |
1202 | | } else { |
1203 | 1.32M | r"\0" |
1204 | | }, |
1205 | | ); |
1206 | 22.5M | } else if ch == '\'' { |
1207 | 2.75k | // escape_debug turns this into "\'" which is unnecessary. |
1208 | 2.75k | repr.push(ch); |
1209 | 22.5M | } else { |
1210 | 22.5M | repr.extend(ch.escape_debug()); |
1211 | 22.5M | } |
1212 | | } |
1213 | 11.1k | } |
1214 | | |
1215 | | #[cfg(feature = "proc-macro")] |
1216 | | pub(crate) trait FromStr2: FromStr<Err = proc_macro::LexError> { |
1217 | | #[cfg(wrap_proc_macro)] |
1218 | | fn valid(src: &str) -> bool; |
1219 | | |
1220 | | #[cfg(wrap_proc_macro)] |
1221 | 0 | fn from_str_checked(src: &str) -> Result<Self, imp::LexError> { |
1222 | | // Validate using fallback parser, because rustc is incapable of |
1223 | | // returning a recoverable Err for certain invalid token streams, and |
1224 | | // will instead permanently poison the compilation. |
1225 | 0 | if !Self::valid(src) { |
1226 | 0 | return Err(imp::LexError::CompilerPanic); |
1227 | 0 | } |
1228 | | |
1229 | | // Catch panic to work around https://github.com/rust-lang/rust/issues/58736. |
1230 | 0 | match panic::catch_unwind(|| Self::from_str(src)) {Unexecuted instantiation: <proc_macro::TokenStream as proc_macro2::fallback::FromStr2>::from_str_checked::{closure#0}Unexecuted instantiation: <proc_macro::Literal as proc_macro2::fallback::FromStr2>::from_str_checked::{closure#0} |
1231 | 0 | Ok(Ok(ok)) => Ok(ok), |
1232 | 0 | Ok(Err(lex)) => Err(imp::LexError::Compiler(lex)), |
1233 | 0 | Err(_panic) => Err(imp::LexError::CompilerPanic), |
1234 | | } |
1235 | 0 | } Unexecuted instantiation: <proc_macro::TokenStream as proc_macro2::fallback::FromStr2>::from_str_checked Unexecuted instantiation: <proc_macro::Literal as proc_macro2::fallback::FromStr2>::from_str_checked |
1236 | | |
1237 | 0 | fn from_str_unchecked(src: &str) -> Self { |
1238 | 0 | Self::from_str(src).unwrap() |
1239 | 0 | } Unexecuted instantiation: <proc_macro::TokenStream as proc_macro2::fallback::FromStr2>::from_str_unchecked Unexecuted instantiation: <proc_macro::Literal as proc_macro2::fallback::FromStr2>::from_str_unchecked |
1240 | | } |
1241 | | |
1242 | | #[cfg(feature = "proc-macro")] |
1243 | | impl FromStr2 for proc_macro::TokenStream { |
1244 | | #[cfg(wrap_proc_macro)] |
1245 | 0 | fn valid(src: &str) -> bool { |
1246 | 0 | TokenStream::from_str_checked(src).is_ok() |
1247 | 0 | } |
1248 | | } |
1249 | | |
1250 | | #[cfg(feature = "proc-macro")] |
1251 | | impl FromStr2 for proc_macro::Literal { |
1252 | | #[cfg(wrap_proc_macro)] |
1253 | 0 | fn valid(src: &str) -> bool { |
1254 | 0 | Literal::from_str_checked(src).is_ok() |
1255 | 0 | } |
1256 | | } |