fallback.rs 34 KB

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