Skip to content

Commit

Permalink
Support Literal as result of paste
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Dec 12, 2022
1 parent 5814fa7 commit 8c15baf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
17 changes: 16 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,13 @@ mod segment;
use crate::attr::expand_attr;
use crate::error::{Error, Result};
use crate::segment::Segment;
use proc_macro::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree};
use proc_macro::{
Delimiter, Group, Ident, LexError, Literal, Punct, Spacing, Span, TokenStream, TokenTree,
};
use std::char;
use std::iter;
use std::panic;
use std::str::FromStr;

#[proc_macro]
pub fn paste(input: TokenStream) -> TokenStream {
Expand Down Expand Up @@ -416,6 +419,18 @@ fn pasted_to_tokens(mut pasted: String, span: Span) -> Result<TokenStream> {
apostrophe.set_span(span);
tokens.extend(iter::once(apostrophe));
pasted.remove(0);
} else if pasted.starts_with(|ch: char| ch.is_ascii_digit()) {
let literal = match panic::catch_unwind(|| Literal::from_str(&pasted)) {
Ok(Ok(literal)) => TokenTree::Literal(literal),
Ok(Err(LexError { .. })) | Err(_) => {
return Err(Error::new(
span,
&format!("`{:?}` is not a valid literal", pasted),
));
}
};
tokens.extend(iter::once(literal));
return Ok(tokens);
}

let ident = match panic::catch_unwind(|| Ident::new(&pasted, span)) {
Expand Down
12 changes: 8 additions & 4 deletions tests/ui/invalid-ident.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
error: `"0f"` is not a valid identifier
--> tests/ui/invalid-ident.rs:4:8
error: expected identifier, found `0f`
--> tests/ui/invalid-ident.rs:3:1
|
4 | fn [<0 f>]() {}
| ^^^^^^^
3 | / paste! {
4 | | fn [<0 f>]() {}
5 | | }
| |_^ expected identifier
|
= note: this error originates in the macro `paste` (in Nightly builds, run with -Z macro-backtrace for more info)

error: `"f\""` is not a valid identifier
--> tests/ui/invalid-ident.rs:8:8
Expand Down

0 comments on commit 8c15baf

Please sign in to comment.