wrapper.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. use crate::detection::inside_proc_macro;
  3. use crate::fallback::{self, FromStr2 as _};
  4. #[cfg(span_locations)]
  5. use crate::location::LineColumn;
  6. #[cfg(proc_macro_span)]
  7. use crate::probe::proc_macro_span;
  8. #[cfg(all(span_locations, proc_macro_span_file))]
  9. use crate::probe::proc_macro_span_file;
  10. #[cfg(all(span_locations, proc_macro_span_location))]
  11. use crate::probe::proc_macro_span_location;
  12. use crate::{Delimiter, Punct, Spacing, TokenTree};
  13. use core::fmt::{self, Debug, Display};
  14. #[cfg(span_locations)]
  15. use core::ops::Range;
  16. use core::ops::RangeBounds;
  17. use std::ffi::CStr;
  18. #[cfg(span_locations)]
  19. use std::path::PathBuf;
  20. #[derive(Clone)]
  21. pub(crate) enum TokenStream {
  22. Compiler(DeferredTokenStream),
  23. Fallback(fallback::TokenStream),
  24. }
  25. // Work around https://github.com/rust-lang/rust/issues/65080.
  26. // In `impl Extend<TokenTree> for TokenStream` which is used heavily by quote,
  27. // we hold on to the appended tokens and do proc_macro::TokenStream::extend as
  28. // late as possible to batch together consecutive uses of the Extend impl.
  29. #[derive(Clone)]
  30. pub(crate) struct DeferredTokenStream {
  31. stream: proc_macro::TokenStream,
  32. extra: Vec<proc_macro::TokenTree>,
  33. }
  34. pub(crate) enum LexError {
  35. Compiler(proc_macro::LexError),
  36. Fallback(fallback::LexError),
  37. // Rustc was supposed to return a LexError, but it panicked instead.
  38. // https://github.com/rust-lang/rust/issues/58736
  39. CompilerPanic,
  40. }
  41. #[cold]
  42. fn mismatch(line: u32) -> ! {
  43. #[cfg(procmacro2_backtrace)]
  44. {
  45. let backtrace = std::backtrace::Backtrace::force_capture();
  46. panic!("compiler/fallback mismatch L{}\n\n{}", line, backtrace)
  47. }
  48. #[cfg(not(procmacro2_backtrace))]
  49. {
  50. panic!("compiler/fallback mismatch L{}", line)
  51. }
  52. }
  53. impl DeferredTokenStream {
  54. fn new(stream: proc_macro::TokenStream) -> Self {
  55. DeferredTokenStream {
  56. stream,
  57. extra: Vec::new(),
  58. }
  59. }
  60. fn is_empty(&self) -> bool {
  61. self.stream.is_empty() && self.extra.is_empty()
  62. }
  63. fn evaluate_now(&mut self) {
  64. // If-check provides a fast short circuit for the common case of `extra`
  65. // being empty, which saves a round trip over the proc macro bridge.
  66. // Improves macro expansion time in winrt by 6% in debug mode.
  67. if !self.extra.is_empty() {
  68. self.stream.extend(self.extra.drain(..));
  69. }
  70. }
  71. fn into_token_stream(mut self) -> proc_macro::TokenStream {
  72. self.evaluate_now();
  73. self.stream
  74. }
  75. }
  76. impl TokenStream {
  77. pub(crate) fn new() -> Self {
  78. if inside_proc_macro() {
  79. TokenStream::Compiler(DeferredTokenStream::new(proc_macro::TokenStream::new()))
  80. } else {
  81. TokenStream::Fallback(fallback::TokenStream::new())
  82. }
  83. }
  84. pub(crate) fn from_str_checked(src: &str) -> Result<Self, LexError> {
  85. if inside_proc_macro() {
  86. Ok(TokenStream::Compiler(DeferredTokenStream::new(
  87. proc_macro::TokenStream::from_str_checked(src)?,
  88. )))
  89. } else {
  90. Ok(TokenStream::Fallback(
  91. fallback::TokenStream::from_str_checked(src)?,
  92. ))
  93. }
  94. }
  95. pub(crate) fn is_empty(&self) -> bool {
  96. match self {
  97. TokenStream::Compiler(tts) => tts.is_empty(),
  98. TokenStream::Fallback(tts) => tts.is_empty(),
  99. }
  100. }
  101. fn unwrap_nightly(self) -> proc_macro::TokenStream {
  102. match self {
  103. TokenStream::Compiler(s) => s.into_token_stream(),
  104. TokenStream::Fallback(_) => mismatch(line!()),
  105. }
  106. }
  107. fn unwrap_stable(self) -> fallback::TokenStream {
  108. match self {
  109. TokenStream::Compiler(_) => mismatch(line!()),
  110. TokenStream::Fallback(s) => s,
  111. }
  112. }
  113. }
  114. impl Display for TokenStream {
  115. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  116. match self {
  117. TokenStream::Compiler(tts) => Display::fmt(&tts.clone().into_token_stream(), f),
  118. TokenStream::Fallback(tts) => Display::fmt(tts, f),
  119. }
  120. }
  121. }
  122. impl From<proc_macro::TokenStream> for TokenStream {
  123. fn from(inner: proc_macro::TokenStream) -> Self {
  124. TokenStream::Compiler(DeferredTokenStream::new(inner))
  125. }
  126. }
  127. impl From<TokenStream> for proc_macro::TokenStream {
  128. fn from(inner: TokenStream) -> Self {
  129. match inner {
  130. TokenStream::Compiler(inner) => inner.into_token_stream(),
  131. TokenStream::Fallback(inner) => {
  132. proc_macro::TokenStream::from_str_unchecked(&inner.to_string())
  133. }
  134. }
  135. }
  136. }
  137. impl From<fallback::TokenStream> for TokenStream {
  138. fn from(inner: fallback::TokenStream) -> Self {
  139. TokenStream::Fallback(inner)
  140. }
  141. }
  142. // Assumes inside_proc_macro().
  143. fn into_compiler_token(token: TokenTree) -> proc_macro::TokenTree {
  144. match token {
  145. TokenTree::Group(tt) => proc_macro::TokenTree::Group(tt.inner.unwrap_nightly()),
  146. TokenTree::Punct(tt) => {
  147. let spacing = match tt.spacing() {
  148. Spacing::Joint => proc_macro::Spacing::Joint,
  149. Spacing::Alone => proc_macro::Spacing::Alone,
  150. };
  151. let mut punct = proc_macro::Punct::new(tt.as_char(), spacing);
  152. punct.set_span(tt.span().inner.unwrap_nightly());
  153. proc_macro::TokenTree::Punct(punct)
  154. }
  155. TokenTree::Ident(tt) => proc_macro::TokenTree::Ident(tt.inner.unwrap_nightly()),
  156. TokenTree::Literal(tt) => proc_macro::TokenTree::Literal(tt.inner.unwrap_nightly()),
  157. }
  158. }
  159. impl From<TokenTree> for TokenStream {
  160. fn from(token: TokenTree) -> Self {
  161. if inside_proc_macro() {
  162. TokenStream::Compiler(DeferredTokenStream::new(proc_macro::TokenStream::from(
  163. into_compiler_token(token),
  164. )))
  165. } else {
  166. TokenStream::Fallback(fallback::TokenStream::from(token))
  167. }
  168. }
  169. }
  170. impl FromIterator<TokenTree> for TokenStream {
  171. fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
  172. if inside_proc_macro() {
  173. TokenStream::Compiler(DeferredTokenStream::new(
  174. trees.into_iter().map(into_compiler_token).collect(),
  175. ))
  176. } else {
  177. TokenStream::Fallback(trees.into_iter().collect())
  178. }
  179. }
  180. }
  181. impl FromIterator<TokenStream> for TokenStream {
  182. fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
  183. let mut streams = streams.into_iter();
  184. match streams.next() {
  185. Some(TokenStream::Compiler(mut first)) => {
  186. first.evaluate_now();
  187. first.stream.extend(streams.map(|s| match s {
  188. TokenStream::Compiler(s) => s.into_token_stream(),
  189. TokenStream::Fallback(_) => mismatch(line!()),
  190. }));
  191. TokenStream::Compiler(first)
  192. }
  193. Some(TokenStream::Fallback(mut first)) => {
  194. first.extend(streams.map(|s| match s {
  195. TokenStream::Fallback(s) => s,
  196. TokenStream::Compiler(_) => mismatch(line!()),
  197. }));
  198. TokenStream::Fallback(first)
  199. }
  200. None => TokenStream::new(),
  201. }
  202. }
  203. }
  204. impl Extend<TokenTree> for TokenStream {
  205. fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, stream: I) {
  206. match self {
  207. TokenStream::Compiler(tts) => {
  208. // Here is the reason for DeferredTokenStream.
  209. for token in stream {
  210. tts.extra.push(into_compiler_token(token));
  211. }
  212. }
  213. TokenStream::Fallback(tts) => tts.extend(stream),
  214. }
  215. }
  216. }
  217. impl Extend<TokenStream> for TokenStream {
  218. fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
  219. match self {
  220. TokenStream::Compiler(tts) => {
  221. tts.evaluate_now();
  222. tts.stream
  223. .extend(streams.into_iter().map(TokenStream::unwrap_nightly));
  224. }
  225. TokenStream::Fallback(tts) => {
  226. tts.extend(streams.into_iter().map(TokenStream::unwrap_stable));
  227. }
  228. }
  229. }
  230. }
  231. impl Debug for TokenStream {
  232. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  233. match self {
  234. TokenStream::Compiler(tts) => Debug::fmt(&tts.clone().into_token_stream(), f),
  235. TokenStream::Fallback(tts) => Debug::fmt(tts, f),
  236. }
  237. }
  238. }
  239. impl LexError {
  240. pub(crate) fn span(&self) -> Span {
  241. match self {
  242. LexError::Compiler(_) | LexError::CompilerPanic => Span::call_site(),
  243. LexError::Fallback(e) => Span::Fallback(e.span()),
  244. }
  245. }
  246. }
  247. impl From<proc_macro::LexError> for LexError {
  248. fn from(e: proc_macro::LexError) -> Self {
  249. LexError::Compiler(e)
  250. }
  251. }
  252. impl From<fallback::LexError> for LexError {
  253. fn from(e: fallback::LexError) -> Self {
  254. LexError::Fallback(e)
  255. }
  256. }
  257. impl Debug for LexError {
  258. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  259. match self {
  260. LexError::Compiler(e) => Debug::fmt(e, f),
  261. LexError::Fallback(e) => Debug::fmt(e, f),
  262. LexError::CompilerPanic => {
  263. let fallback = fallback::LexError::call_site();
  264. Debug::fmt(&fallback, f)
  265. }
  266. }
  267. }
  268. }
  269. impl Display for LexError {
  270. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  271. match self {
  272. LexError::Compiler(e) => Display::fmt(e, f),
  273. LexError::Fallback(e) => Display::fmt(e, f),
  274. LexError::CompilerPanic => {
  275. let fallback = fallback::LexError::call_site();
  276. Display::fmt(&fallback, f)
  277. }
  278. }
  279. }
  280. }
  281. #[derive(Clone)]
  282. pub(crate) enum TokenTreeIter {
  283. Compiler(proc_macro::token_stream::IntoIter),
  284. Fallback(fallback::TokenTreeIter),
  285. }
  286. impl IntoIterator for TokenStream {
  287. type Item = TokenTree;
  288. type IntoIter = TokenTreeIter;
  289. fn into_iter(self) -> TokenTreeIter {
  290. match self {
  291. TokenStream::Compiler(tts) => {
  292. TokenTreeIter::Compiler(tts.into_token_stream().into_iter())
  293. }
  294. TokenStream::Fallback(tts) => TokenTreeIter::Fallback(tts.into_iter()),
  295. }
  296. }
  297. }
  298. impl Iterator for TokenTreeIter {
  299. type Item = TokenTree;
  300. fn next(&mut self) -> Option<TokenTree> {
  301. let token = match self {
  302. TokenTreeIter::Compiler(iter) => iter.next()?,
  303. TokenTreeIter::Fallback(iter) => return iter.next(),
  304. };
  305. Some(match token {
  306. proc_macro::TokenTree::Group(tt) => {
  307. TokenTree::Group(crate::Group::_new(Group::Compiler(tt)))
  308. }
  309. proc_macro::TokenTree::Punct(tt) => {
  310. let spacing = match tt.spacing() {
  311. proc_macro::Spacing::Joint => Spacing::Joint,
  312. proc_macro::Spacing::Alone => Spacing::Alone,
  313. };
  314. let mut o = Punct::new(tt.as_char(), spacing);
  315. o.set_span(crate::Span::_new(Span::Compiler(tt.span())));
  316. TokenTree::Punct(o)
  317. }
  318. proc_macro::TokenTree::Ident(s) => {
  319. TokenTree::Ident(crate::Ident::_new(Ident::Compiler(s)))
  320. }
  321. proc_macro::TokenTree::Literal(l) => {
  322. TokenTree::Literal(crate::Literal::_new(Literal::Compiler(l)))
  323. }
  324. })
  325. }
  326. fn size_hint(&self) -> (usize, Option<usize>) {
  327. match self {
  328. TokenTreeIter::Compiler(tts) => tts.size_hint(),
  329. TokenTreeIter::Fallback(tts) => tts.size_hint(),
  330. }
  331. }
  332. }
  333. #[derive(Copy, Clone)]
  334. pub(crate) enum Span {
  335. Compiler(proc_macro::Span),
  336. Fallback(fallback::Span),
  337. }
  338. impl Span {
  339. pub(crate) fn call_site() -> Self {
  340. if inside_proc_macro() {
  341. Span::Compiler(proc_macro::Span::call_site())
  342. } else {
  343. Span::Fallback(fallback::Span::call_site())
  344. }
  345. }
  346. pub(crate) fn mixed_site() -> Self {
  347. if inside_proc_macro() {
  348. Span::Compiler(proc_macro::Span::mixed_site())
  349. } else {
  350. Span::Fallback(fallback::Span::mixed_site())
  351. }
  352. }
  353. #[cfg(super_unstable)]
  354. pub(crate) fn def_site() -> Self {
  355. if inside_proc_macro() {
  356. Span::Compiler(proc_macro::Span::def_site())
  357. } else {
  358. Span::Fallback(fallback::Span::def_site())
  359. }
  360. }
  361. pub(crate) fn resolved_at(&self, other: Span) -> Span {
  362. match (self, other) {
  363. (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.resolved_at(b)),
  364. (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.resolved_at(b)),
  365. (Span::Compiler(_), Span::Fallback(_)) => mismatch(line!()),
  366. (Span::Fallback(_), Span::Compiler(_)) => mismatch(line!()),
  367. }
  368. }
  369. pub(crate) fn located_at(&self, other: Span) -> Span {
  370. match (self, other) {
  371. (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.located_at(b)),
  372. (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.located_at(b)),
  373. (Span::Compiler(_), Span::Fallback(_)) => mismatch(line!()),
  374. (Span::Fallback(_), Span::Compiler(_)) => mismatch(line!()),
  375. }
  376. }
  377. pub(crate) fn unwrap(self) -> proc_macro::Span {
  378. match self {
  379. Span::Compiler(s) => s,
  380. Span::Fallback(_) => panic!("proc_macro::Span is only available in procedural macros"),
  381. }
  382. }
  383. #[cfg(span_locations)]
  384. pub(crate) fn byte_range(&self) -> Range<usize> {
  385. match self {
  386. #[cfg(proc_macro_span)]
  387. Span::Compiler(s) => proc_macro_span::byte_range(s),
  388. #[cfg(not(proc_macro_span))]
  389. Span::Compiler(_) => 0..0,
  390. Span::Fallback(s) => s.byte_range(),
  391. }
  392. }
  393. #[cfg(span_locations)]
  394. pub(crate) fn start(&self) -> LineColumn {
  395. match self {
  396. #[cfg(proc_macro_span_location)]
  397. Span::Compiler(s) => LineColumn {
  398. line: proc_macro_span_location::line(s),
  399. column: proc_macro_span_location::column(s).saturating_sub(1),
  400. },
  401. #[cfg(not(proc_macro_span_location))]
  402. Span::Compiler(_) => LineColumn { line: 0, column: 0 },
  403. Span::Fallback(s) => s.start(),
  404. }
  405. }
  406. #[cfg(span_locations)]
  407. pub(crate) fn end(&self) -> LineColumn {
  408. match self {
  409. #[cfg(proc_macro_span_location)]
  410. Span::Compiler(s) => {
  411. let end = proc_macro_span_location::end(s);
  412. LineColumn {
  413. line: proc_macro_span_location::line(&end),
  414. column: proc_macro_span_location::column(&end).saturating_sub(1),
  415. }
  416. }
  417. #[cfg(not(proc_macro_span_location))]
  418. Span::Compiler(_) => LineColumn { line: 0, column: 0 },
  419. Span::Fallback(s) => s.end(),
  420. }
  421. }
  422. #[cfg(span_locations)]
  423. pub(crate) fn file(&self) -> String {
  424. match self {
  425. #[cfg(proc_macro_span_file)]
  426. Span::Compiler(s) => proc_macro_span_file::file(s),
  427. #[cfg(not(proc_macro_span_file))]
  428. Span::Compiler(_) => "<token stream>".to_owned(),
  429. Span::Fallback(s) => s.file(),
  430. }
  431. }
  432. #[cfg(span_locations)]
  433. pub(crate) fn local_file(&self) -> Option<PathBuf> {
  434. match self {
  435. #[cfg(proc_macro_span_file)]
  436. Span::Compiler(s) => proc_macro_span_file::local_file(s),
  437. #[cfg(not(proc_macro_span_file))]
  438. Span::Compiler(_) => None,
  439. Span::Fallback(s) => s.local_file(),
  440. }
  441. }
  442. pub(crate) fn join(&self, other: Span) -> Option<Span> {
  443. let ret = match (self, other) {
  444. #[cfg(proc_macro_span)]
  445. (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(proc_macro_span::join(a, b)?),
  446. (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.join(b)?),
  447. _ => return None,
  448. };
  449. Some(ret)
  450. }
  451. #[cfg(super_unstable)]
  452. pub(crate) fn eq(&self, other: &Span) -> bool {
  453. match (self, other) {
  454. (Span::Compiler(a), Span::Compiler(b)) => a.eq(b),
  455. (Span::Fallback(a), Span::Fallback(b)) => a.eq(b),
  456. _ => false,
  457. }
  458. }
  459. pub(crate) fn source_text(&self) -> Option<String> {
  460. match self {
  461. #[cfg(not(no_source_text))]
  462. Span::Compiler(s) => s.source_text(),
  463. #[cfg(no_source_text)]
  464. Span::Compiler(_) => None,
  465. Span::Fallback(s) => s.source_text(),
  466. }
  467. }
  468. fn unwrap_nightly(self) -> proc_macro::Span {
  469. match self {
  470. Span::Compiler(s) => s,
  471. Span::Fallback(_) => mismatch(line!()),
  472. }
  473. }
  474. }
  475. impl From<proc_macro::Span> for crate::Span {
  476. fn from(proc_span: proc_macro::Span) -> Self {
  477. crate::Span::_new(Span::Compiler(proc_span))
  478. }
  479. }
  480. impl From<fallback::Span> for Span {
  481. fn from(inner: fallback::Span) -> Self {
  482. Span::Fallback(inner)
  483. }
  484. }
  485. impl Debug for Span {
  486. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  487. match self {
  488. Span::Compiler(s) => Debug::fmt(s, f),
  489. Span::Fallback(s) => Debug::fmt(s, f),
  490. }
  491. }
  492. }
  493. pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) {
  494. match span {
  495. Span::Compiler(s) => {
  496. debug.field("span", &s);
  497. }
  498. Span::Fallback(s) => fallback::debug_span_field_if_nontrivial(debug, s),
  499. }
  500. }
  501. #[derive(Clone)]
  502. pub(crate) enum Group {
  503. Compiler(proc_macro::Group),
  504. Fallback(fallback::Group),
  505. }
  506. impl Group {
  507. pub(crate) fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
  508. match stream {
  509. TokenStream::Compiler(tts) => {
  510. let delimiter = match delimiter {
  511. Delimiter::Parenthesis => proc_macro::Delimiter::Parenthesis,
  512. Delimiter::Bracket => proc_macro::Delimiter::Bracket,
  513. Delimiter::Brace => proc_macro::Delimiter::Brace,
  514. Delimiter::None => proc_macro::Delimiter::None,
  515. };
  516. Group::Compiler(proc_macro::Group::new(delimiter, tts.into_token_stream()))
  517. }
  518. TokenStream::Fallback(stream) => {
  519. Group::Fallback(fallback::Group::new(delimiter, stream))
  520. }
  521. }
  522. }
  523. pub(crate) fn delimiter(&self) -> Delimiter {
  524. match self {
  525. Group::Compiler(g) => match g.delimiter() {
  526. proc_macro::Delimiter::Parenthesis => Delimiter::Parenthesis,
  527. proc_macro::Delimiter::Bracket => Delimiter::Bracket,
  528. proc_macro::Delimiter::Brace => Delimiter::Brace,
  529. proc_macro::Delimiter::None => Delimiter::None,
  530. },
  531. Group::Fallback(g) => g.delimiter(),
  532. }
  533. }
  534. pub(crate) fn stream(&self) -> TokenStream {
  535. match self {
  536. Group::Compiler(g) => TokenStream::Compiler(DeferredTokenStream::new(g.stream())),
  537. Group::Fallback(g) => TokenStream::Fallback(g.stream()),
  538. }
  539. }
  540. pub(crate) fn span(&self) -> Span {
  541. match self {
  542. Group::Compiler(g) => Span::Compiler(g.span()),
  543. Group::Fallback(g) => Span::Fallback(g.span()),
  544. }
  545. }
  546. pub(crate) fn span_open(&self) -> Span {
  547. match self {
  548. Group::Compiler(g) => Span::Compiler(g.span_open()),
  549. Group::Fallback(g) => Span::Fallback(g.span_open()),
  550. }
  551. }
  552. pub(crate) fn span_close(&self) -> Span {
  553. match self {
  554. Group::Compiler(g) => Span::Compiler(g.span_close()),
  555. Group::Fallback(g) => Span::Fallback(g.span_close()),
  556. }
  557. }
  558. pub(crate) fn set_span(&mut self, span: Span) {
  559. match (self, span) {
  560. (Group::Compiler(g), Span::Compiler(s)) => g.set_span(s),
  561. (Group::Fallback(g), Span::Fallback(s)) => g.set_span(s),
  562. (Group::Compiler(_), Span::Fallback(_)) => mismatch(line!()),
  563. (Group::Fallback(_), Span::Compiler(_)) => mismatch(line!()),
  564. }
  565. }
  566. fn unwrap_nightly(self) -> proc_macro::Group {
  567. match self {
  568. Group::Compiler(g) => g,
  569. Group::Fallback(_) => mismatch(line!()),
  570. }
  571. }
  572. }
  573. impl From<fallback::Group> for Group {
  574. fn from(g: fallback::Group) -> Self {
  575. Group::Fallback(g)
  576. }
  577. }
  578. impl Display for Group {
  579. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  580. match self {
  581. Group::Compiler(group) => Display::fmt(group, formatter),
  582. Group::Fallback(group) => Display::fmt(group, formatter),
  583. }
  584. }
  585. }
  586. impl Debug for Group {
  587. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  588. match self {
  589. Group::Compiler(group) => Debug::fmt(group, formatter),
  590. Group::Fallback(group) => Debug::fmt(group, formatter),
  591. }
  592. }
  593. }
  594. #[derive(Clone)]
  595. pub(crate) enum Ident {
  596. Compiler(proc_macro::Ident),
  597. Fallback(fallback::Ident),
  598. }
  599. impl Ident {
  600. #[track_caller]
  601. pub(crate) fn new_checked(string: &str, span: Span) -> Self {
  602. match span {
  603. Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new(string, s)),
  604. Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_checked(string, s)),
  605. }
  606. }
  607. #[track_caller]
  608. pub(crate) fn new_raw_checked(string: &str, span: Span) -> Self {
  609. match span {
  610. Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new_raw(string, s)),
  611. Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_raw_checked(string, s)),
  612. }
  613. }
  614. pub(crate) fn span(&self) -> Span {
  615. match self {
  616. Ident::Compiler(t) => Span::Compiler(t.span()),
  617. Ident::Fallback(t) => Span::Fallback(t.span()),
  618. }
  619. }
  620. pub(crate) fn set_span(&mut self, span: Span) {
  621. match (self, span) {
  622. (Ident::Compiler(t), Span::Compiler(s)) => t.set_span(s),
  623. (Ident::Fallback(t), Span::Fallback(s)) => t.set_span(s),
  624. (Ident::Compiler(_), Span::Fallback(_)) => mismatch(line!()),
  625. (Ident::Fallback(_), Span::Compiler(_)) => mismatch(line!()),
  626. }
  627. }
  628. fn unwrap_nightly(self) -> proc_macro::Ident {
  629. match self {
  630. Ident::Compiler(s) => s,
  631. Ident::Fallback(_) => mismatch(line!()),
  632. }
  633. }
  634. }
  635. impl From<fallback::Ident> for Ident {
  636. fn from(inner: fallback::Ident) -> Self {
  637. Ident::Fallback(inner)
  638. }
  639. }
  640. impl PartialEq for Ident {
  641. fn eq(&self, other: &Ident) -> bool {
  642. match (self, other) {
  643. (Ident::Compiler(t), Ident::Compiler(o)) => t.to_string() == o.to_string(),
  644. (Ident::Fallback(t), Ident::Fallback(o)) => t == o,
  645. (Ident::Compiler(_), Ident::Fallback(_)) => mismatch(line!()),
  646. (Ident::Fallback(_), Ident::Compiler(_)) => mismatch(line!()),
  647. }
  648. }
  649. }
  650. impl<T> PartialEq<T> for Ident
  651. where
  652. T: ?Sized + AsRef<str>,
  653. {
  654. fn eq(&self, other: &T) -> bool {
  655. let other = other.as_ref();
  656. match self {
  657. Ident::Compiler(t) => t.to_string() == other,
  658. Ident::Fallback(t) => t == other,
  659. }
  660. }
  661. }
  662. impl Display for Ident {
  663. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  664. match self {
  665. Ident::Compiler(t) => Display::fmt(t, f),
  666. Ident::Fallback(t) => Display::fmt(t, f),
  667. }
  668. }
  669. }
  670. impl Debug for Ident {
  671. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  672. match self {
  673. Ident::Compiler(t) => Debug::fmt(t, f),
  674. Ident::Fallback(t) => Debug::fmt(t, f),
  675. }
  676. }
  677. }
  678. #[derive(Clone)]
  679. pub(crate) enum Literal {
  680. Compiler(proc_macro::Literal),
  681. Fallback(fallback::Literal),
  682. }
  683. macro_rules! suffixed_numbers {
  684. ($($name:ident => $kind:ident,)*) => ($(
  685. pub(crate) fn $name(n: $kind) -> Literal {
  686. if inside_proc_macro() {
  687. Literal::Compiler(proc_macro::Literal::$name(n))
  688. } else {
  689. Literal::Fallback(fallback::Literal::$name(n))
  690. }
  691. }
  692. )*)
  693. }
  694. macro_rules! unsuffixed_integers {
  695. ($($name:ident => $kind:ident,)*) => ($(
  696. pub(crate) fn $name(n: $kind) -> Literal {
  697. if inside_proc_macro() {
  698. Literal::Compiler(proc_macro::Literal::$name(n))
  699. } else {
  700. Literal::Fallback(fallback::Literal::$name(n))
  701. }
  702. }
  703. )*)
  704. }
  705. impl Literal {
  706. pub(crate) fn from_str_checked(repr: &str) -> Result<Self, LexError> {
  707. if inside_proc_macro() {
  708. let literal = proc_macro::Literal::from_str_checked(repr)?;
  709. Ok(Literal::Compiler(literal))
  710. } else {
  711. let literal = fallback::Literal::from_str_checked(repr)?;
  712. Ok(Literal::Fallback(literal))
  713. }
  714. }
  715. pub(crate) unsafe fn from_str_unchecked(repr: &str) -> Self {
  716. if inside_proc_macro() {
  717. Literal::Compiler(proc_macro::Literal::from_str_unchecked(repr))
  718. } else {
  719. Literal::Fallback(unsafe { fallback::Literal::from_str_unchecked(repr) })
  720. }
  721. }
  722. suffixed_numbers! {
  723. u8_suffixed => u8,
  724. u16_suffixed => u16,
  725. u32_suffixed => u32,
  726. u64_suffixed => u64,
  727. u128_suffixed => u128,
  728. usize_suffixed => usize,
  729. i8_suffixed => i8,
  730. i16_suffixed => i16,
  731. i32_suffixed => i32,
  732. i64_suffixed => i64,
  733. i128_suffixed => i128,
  734. isize_suffixed => isize,
  735. f32_suffixed => f32,
  736. f64_suffixed => f64,
  737. }
  738. unsuffixed_integers! {
  739. u8_unsuffixed => u8,
  740. u16_unsuffixed => u16,
  741. u32_unsuffixed => u32,
  742. u64_unsuffixed => u64,
  743. u128_unsuffixed => u128,
  744. usize_unsuffixed => usize,
  745. i8_unsuffixed => i8,
  746. i16_unsuffixed => i16,
  747. i32_unsuffixed => i32,
  748. i64_unsuffixed => i64,
  749. i128_unsuffixed => i128,
  750. isize_unsuffixed => isize,
  751. }
  752. pub(crate) fn f32_unsuffixed(f: f32) -> Literal {
  753. if inside_proc_macro() {
  754. Literal::Compiler(proc_macro::Literal::f32_unsuffixed(f))
  755. } else {
  756. Literal::Fallback(fallback::Literal::f32_unsuffixed(f))
  757. }
  758. }
  759. pub(crate) fn f64_unsuffixed(f: f64) -> Literal {
  760. if inside_proc_macro() {
  761. Literal::Compiler(proc_macro::Literal::f64_unsuffixed(f))
  762. } else {
  763. Literal::Fallback(fallback::Literal::f64_unsuffixed(f))
  764. }
  765. }
  766. pub(crate) fn string(string: &str) -> Literal {
  767. if inside_proc_macro() {
  768. Literal::Compiler(proc_macro::Literal::string(string))
  769. } else {
  770. Literal::Fallback(fallback::Literal::string(string))
  771. }
  772. }
  773. pub(crate) fn character(ch: char) -> Literal {
  774. if inside_proc_macro() {
  775. Literal::Compiler(proc_macro::Literal::character(ch))
  776. } else {
  777. Literal::Fallback(fallback::Literal::character(ch))
  778. }
  779. }
  780. pub(crate) fn byte_character(byte: u8) -> Literal {
  781. if inside_proc_macro() {
  782. Literal::Compiler({
  783. #[cfg(not(no_literal_byte_character))]
  784. {
  785. proc_macro::Literal::byte_character(byte)
  786. }
  787. #[cfg(no_literal_byte_character)]
  788. {
  789. let fallback = fallback::Literal::byte_character(byte);
  790. proc_macro::Literal::from_str_unchecked(&fallback.repr)
  791. }
  792. })
  793. } else {
  794. Literal::Fallback(fallback::Literal::byte_character(byte))
  795. }
  796. }
  797. pub(crate) fn byte_string(bytes: &[u8]) -> Literal {
  798. if inside_proc_macro() {
  799. Literal::Compiler(proc_macro::Literal::byte_string(bytes))
  800. } else {
  801. Literal::Fallback(fallback::Literal::byte_string(bytes))
  802. }
  803. }
  804. pub(crate) fn c_string(string: &CStr) -> Literal {
  805. if inside_proc_macro() {
  806. Literal::Compiler({
  807. #[cfg(not(no_literal_c_string))]
  808. {
  809. proc_macro::Literal::c_string(string)
  810. }
  811. #[cfg(no_literal_c_string)]
  812. {
  813. let fallback = fallback::Literal::c_string(string);
  814. proc_macro::Literal::from_str_unchecked(&fallback.repr)
  815. }
  816. })
  817. } else {
  818. Literal::Fallback(fallback::Literal::c_string(string))
  819. }
  820. }
  821. pub(crate) fn span(&self) -> Span {
  822. match self {
  823. Literal::Compiler(lit) => Span::Compiler(lit.span()),
  824. Literal::Fallback(lit) => Span::Fallback(lit.span()),
  825. }
  826. }
  827. pub(crate) fn set_span(&mut self, span: Span) {
  828. match (self, span) {
  829. (Literal::Compiler(lit), Span::Compiler(s)) => lit.set_span(s),
  830. (Literal::Fallback(lit), Span::Fallback(s)) => lit.set_span(s),
  831. (Literal::Compiler(_), Span::Fallback(_)) => mismatch(line!()),
  832. (Literal::Fallback(_), Span::Compiler(_)) => mismatch(line!()),
  833. }
  834. }
  835. pub(crate) fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
  836. match self {
  837. #[cfg(proc_macro_span)]
  838. Literal::Compiler(lit) => proc_macro_span::subspan(lit, range).map(Span::Compiler),
  839. #[cfg(not(proc_macro_span))]
  840. Literal::Compiler(_lit) => None,
  841. Literal::Fallback(lit) => lit.subspan(range).map(Span::Fallback),
  842. }
  843. }
  844. fn unwrap_nightly(self) -> proc_macro::Literal {
  845. match self {
  846. Literal::Compiler(s) => s,
  847. Literal::Fallback(_) => mismatch(line!()),
  848. }
  849. }
  850. }
  851. impl From<fallback::Literal> for Literal {
  852. fn from(s: fallback::Literal) -> Self {
  853. Literal::Fallback(s)
  854. }
  855. }
  856. impl Display for Literal {
  857. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  858. match self {
  859. Literal::Compiler(t) => Display::fmt(t, f),
  860. Literal::Fallback(t) => Display::fmt(t, f),
  861. }
  862. }
  863. }
  864. impl Debug for Literal {
  865. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  866. match self {
  867. Literal::Compiler(t) => Debug::fmt(t, f),
  868. Literal::Fallback(t) => Debug::fmt(t, f),
  869. }
  870. }
  871. }
  872. #[cfg(span_locations)]
  873. pub(crate) fn invalidate_current_thread_spans() {
  874. if inside_proc_macro() {
  875. panic!(
  876. "proc_macro2::extra::invalidate_current_thread_spans is not available in procedural macros"
  877. );
  878. } else {
  879. crate::fallback::invalidate_current_thread_spans();
  880. }
  881. }