created_at
stringlengths
20
20
problem_statement
stringlengths
155
3.86k
instance_id
stringlengths
23
24
hints_text
stringclasses
9 values
issue_numbers
listlengths
1
1
base_commit
stringlengths
40
40
test_patch
stringlengths
312
4.58k
version
stringclasses
5 values
patch
stringlengths
466
15.6k
pull_number
int64
25
438
repo
stringclasses
1 value
environment_setup_commit
stringclasses
6 values
2018-01-23T19:09:15Z
Doc comment without newline does not match libproc_macro ```rust for tt in "/// doc".parse::<TokenStream>().unwrap() { println!("{:?}", tt.kind); } ``` Proc-macro sees this as a doc comment despite not ending with a newline. ``` Literal(Literal(DocComment(/// doc))) ``` Proc-macro2 sees it as a `/` joint op followed by insignificant whitespace `// doc`. ``` Op('/', Joint) ```
dtolnay__proc-macro2-63
[ "61" ]
eca28d42767412e3f8ad670e271a09aed6e05a10
diff --git a/tests/test.rs b/tests/test.rs index ff9c205a..2e481d16 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -175,5 +175,13 @@ fn tricky_doc_commaent() { let stream = "/**/".parse::<proc_macro2::TokenStream>().unwrap(); let tokens = stream.into_iter().collect::<Vec<_>>(); assert!(tokens.is_empty(), "not empty -- {:?}", tokens); + + let stream = "/// doc".parse::<proc_macro2::TokenStream>().unwrap(); + let tokens = stream.into_iter().collect::<Vec<_>>(); + assert!(tokens.len() == 1, "not length 1 -- {:?}", tokens); + match tokens[0].kind { + proc_macro2::TokenNode::Literal(_) => {} + _ => panic!("wrong token {:?}", tokens[0]), + } }
0.2
diff --git a/src/stable.rs b/src/stable.rs index ffa077a2..41a7c4b3 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -1179,7 +1179,7 @@ fn op_char(input: Cursor) -> PResult<char> { named!(doc_comment -> (), alt!( do_parse!( punct!("//!") >> - take_until!("\n") >> + take_until_newline_or_eof!() >> (()) ) | @@ -1193,7 +1193,7 @@ named!(doc_comment -> (), alt!( do_parse!( punct!("///") >> not!(tag!("/")) >> - take_until!("\n") >> + take_until_newline_or_eof!() >> (()) ) | diff --git a/src/strnom.rs b/src/strnom.rs index 33964f45..dbac5c9c 100644 --- a/src/strnom.rs +++ b/src/strnom.rs @@ -263,34 +263,14 @@ macro_rules! option { }; } -macro_rules! take_until { - ($i:expr, $substr:expr) => {{ - if $substr.len() > $i.len() { - Err(LexError) +macro_rules! take_until_newline_or_eof { + ($i:expr,) => {{ + if $i.len() == 0 { + Ok(($i, "")) } else { - let substr_vec: Vec<char> = $substr.chars().collect(); - let mut window: Vec<char> = vec![]; - let mut offset = $i.len(); - let mut parsed = false; - for (o, c) in $i.char_indices() { - window.push(c); - if window.len() > substr_vec.len() { - window.remove(0); - } - if window == substr_vec { - parsed = true; - window.pop(); - let window_len: usize = window.iter() - .map(|x| x.len_utf8()) - .fold(0, |x, y| x + y); - offset = o - window_len; - break; - } - } - if parsed { - Ok(($i.advance(offset), &$i.rest[..offset])) - } else { - Err(LexError) + match $i.find('\n') { + Some(i) => Ok(($i.advance(i), &$i.rest[..i])), + None => Ok(($i.advance($i.len()), "")) } } }};
63
dtolnay/proc-macro2
eca28d42767412e3f8ad670e271a09aed6e05a10
2018-01-22T05:05:44Z
/**/ should be insignificant whitespace Input | Expected | proc-macro2 --- | --- | --- `/* */` | whitespace | correct `/** */` | attribute | correct `/***/` | whitespace | correct `/**/` | whitespace | INCORRECT ```rust extern crate proc_macro2; use proc_macro2::TokenStream; fn main() { for tt in "/**/".parse::<TokenStream>().unwrap() { println!("{:?}", tt.kind); } } ``` ``` Literal(Literal("/**/")) ```
dtolnay__proc-macro2-58
[ "57" ]
8c03033828a614775017f078a01f2c457957975b
diff --git a/tests/test.rs b/tests/test.rs index 7c7275d6..ff9c205a 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -170,3 +170,10 @@ fn no_panic() { assert!(s.parse::<proc_macro2::TokenStream>().is_err()); } +#[test] +fn tricky_doc_commaent() { + let stream = "/**/".parse::<proc_macro2::TokenStream>().unwrap(); + let tokens = stream.into_iter().collect::<Vec<_>>(); + assert!(tokens.is_empty(), "not empty -- {:?}", tokens); +} +
0.2
diff --git a/src/strnom.rs b/src/strnom.rs index 1bf9f236..33964f45 100644 --- a/src/strnom.rs +++ b/src/strnom.rs @@ -80,6 +80,9 @@ pub fn whitespace(input: Cursor) -> PResult<()> { continue; } break; + } else if s.starts_with("/**/") { + i += 4; + continue } else if s.starts_with("/*") && (!s.starts_with("/**") || s.starts_with("/***")) && !s.starts_with("/*!") { let (_, com) = block_comment(s)?;
58
dtolnay/proc-macro2
eca28d42767412e3f8ad670e271a09aed6e05a10
2018-01-03T04:16:53Z
Rename either --cfg procmacro2_unstable or --features proc-macro2/unstable These are basically orthogonal flags so it is confusing to give them such similar names. Someone may want to use procmacro2_unstable without proc-macro2/unstable to get the emulation of line and column from #36 on the stable compiler, or may want to use proc-macro2/unstable without procmacro2_unstable to get real spans without the semver-exempt APIs.
dtolnay__proc-macro2-44
How about changing the Cargo feature to `nightly` or `rustc-nightly`? :+1: for either of those. I might go with `--cfg procmacro2_semver_exempt` and `--features proc-macro2/nightly`. Want me to do proc-macro2 0.2 with a semver-trick to bridge 0.1's `unstable` feature to 0.2's `nightly` feature? Or go to 0.2 without a semver-trick? Or just make both changes in 0.1 because :shipit:? Yeah - sorry about the bad naming. I wasn't a big fan of it at the time either :-/. I called it `procmacro2_unstable` to match the `rayon_unstable` cfg flag which rayon uses: https://github.com/rayon-rs/rayon#semver-policy-the-rayon-core-crate-and-unstable-features @dtolnay I'd personally be ok with just shipping everything in 0.1 (e.g. just commenting that a feature is disabled in `Cago.toml`), and I'd be fine to rename the `--cfg` whenever! (also the names you proposed seemed fine by me, if you're gonna send a PR feel free to decide!)
[ "42" ]
fa1864f185f7685a1e023f06dece014bf9b32d33
diff --git a/tests/test.rs b/tests/test.rs index 6442ba6b..89f7b102 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -2,11 +2,11 @@ extern crate proc_macro2; use proc_macro2::{Term, Literal, TokenStream}; -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] use proc_macro2::TokenNode; -#[cfg(procmacro2_unstable)] -#[cfg(not(feature = "unstable"))] +#[cfg(procmacro2_semver_exempt)] +#[cfg(not(feature = "nightly"))] use proc_macro2::Span; #[test] @@ -72,7 +72,7 @@ fn fail() { fail("'mut"); } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[test] fn span_test() { fn check_spans(p: &str, mut lines: &[(usize, usize, usize, usize)]) { @@ -120,8 +120,8 @@ testing 123 ]); } -#[cfg(procmacro2_unstable)] -#[cfg(not(feature = "unstable"))] +#[cfg(procmacro2_semver_exempt)] +#[cfg(not(feature = "nightly"))] #[test] fn default_span() { let start = Span::call_site().start(); @@ -135,7 +135,7 @@ fn default_span() { assert!(!source_file.is_real()); } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[test] fn span_join() { let source1 =
0.1
diff --git a/.travis.yml b/.travis.yml index e5c59af2..a524c016 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,16 +11,16 @@ matrix: - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - cargo test - - cargo build --features unstable - - RUSTFLAGS='--cfg procmacro2_unstable' cargo test - - RUSTFLAGS='--cfg procmacro2_unstable' cargo build --features unstable - - RUSTFLAGS='--cfg procmacro2_unstable' cargo doc --no-deps + - cargo build --features nightly + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo test + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build --features nightly + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo doc --no-deps after_success: - travis-cargo --only nightly doc-upload script: - cargo test - - RUSTFLAGS='--cfg procmacro2_unstable' cargo test + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo test env: global: - TRAVIS_CARGO_NIGHTLY_FEATURE="" diff --git a/Cargo.toml b/Cargo.toml index 19e860f3..ac336074 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,4 +21,13 @@ doctest = false unicode-xid = "0.1" [features] -unstable = [] + +# When enabled: act as a shim around the nightly compiler's proc_macro crate. +# This requires a nightly compiler. +# +# When disabled: emulate the same API as the nightly compiler's proc_macro crate +# but in a way that works on all stable compilers >=1.15.0. +nightly = [] + +# Deprecated; use "nightly" instead. +unstable = ["nightly"] diff --git a/README.md b/README.md index c26ec750..576da8d7 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { } ``` -If you'd like you can enable the `unstable` feature in this crate. This will +If you'd like you can enable the `nightly` feature in this crate. This will cause it to compile against the **unstable and nightly-only** features of the `proc_macro` crate. This in turn requires a nightly compiler. This should help preserve span information, however, coming in from the compiler itself. @@ -57,7 +57,7 @@ You can enable this feature via: ```toml [dependencies] -proc-macro2 = { version = "0.1", features = ["unstable"] } +proc-macro2 = { version = "0.1", features = ["nightly"] } ``` @@ -65,11 +65,19 @@ proc-macro2 = { version = "0.1", features = ["unstable"] } `proc-macro2` supports exporting some methods from `proc_macro` which are currently highly unstable, and may not be stabilized in the first pass of -`proc_macro` stabilizations. These features are not exported by default. +`proc_macro` stabilizations. These features are not exported by default. Minor +versions of `proc-macro2` may make breaking changes to them at any time. -To export these features, the `procmacro2_unstable` config flag must be passed -to rustc. To pass this flag, run `cargo` with -`RUSTFLAGS='--cfg procmacro2_unstable' cargo build`. +To enable these features, the `procmacro2_semver_exempt` config flag must be +passed to rustc. + +``` +RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build +``` + +Note that this must not only be done for your crate, but for any crate that +depends on your crate. This infectious nature is intentional, as it serves as a +reminder that you are outside of the normal semver guarantees. # License diff --git a/src/lib.rs b/src/lib.rs index 26d32446..49e3d21e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,16 +14,16 @@ //! to use this crate will be trivially able to switch to the upstream //! `proc_macro` crate once its API stabilizes. //! -//! In the meantime this crate also has an `unstable` Cargo feature which +//! In the meantime this crate also has a `nightly` Cargo feature which //! enables it to reimplement itself with the unstable API of `proc_macro`. //! This'll allow immediate usage of the beneficial upstream API, particularly //! around preserving span information. -#![cfg_attr(feature = "unstable", feature(proc_macro))] +#![cfg_attr(feature = "nightly", feature(proc_macro))] extern crate proc_macro; -#[cfg(not(feature = "unstable"))] +#[cfg(not(feature = "nightly"))] extern crate unicode_xid; use std::fmt; @@ -31,14 +31,14 @@ use std::str::FromStr; use std::iter::FromIterator; #[macro_use] -#[cfg(not(feature = "unstable"))] +#[cfg(not(feature = "nightly"))] mod strnom; #[path = "stable.rs"] -#[cfg(not(feature = "unstable"))] +#[cfg(not(feature = "nightly"))] mod imp; #[path = "unstable.rs"] -#[cfg(feature = "unstable")] +#[cfg(feature = "nightly")] mod imp; #[macro_use] @@ -104,14 +104,14 @@ impl TokenStream { } // Returned by reference, so we can't easily wrap it. -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] pub use imp::FileName; -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[derive(Clone, PartialEq, Eq)] pub struct SourceFile(imp::SourceFile); -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl SourceFile { /// Get the path to this source file as a string. pub fn path(&self) -> &FileName { @@ -123,21 +123,21 @@ impl SourceFile { } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl AsRef<FileName> for SourceFile { fn as_ref(&self) -> &FileName { self.0.path() } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl fmt::Debug for SourceFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] pub struct LineColumn { pub line: usize, pub column: usize, @@ -162,30 +162,30 @@ impl Span { Span(imp::Span::def_site()) } - /// This method is only available when the `"unstable"` feature is enabled. - #[cfg(feature = "unstable")] + /// This method is only available when the `"nightly"` feature is enabled. + #[cfg(feature = "nightly")] pub fn unstable(self) -> proc_macro::Span { self.0.unstable() } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn source_file(&self) -> SourceFile { SourceFile(self.0.source_file()) } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn start(&self) -> LineColumn { let imp::LineColumn{ line, column } = self.0.start(); LineColumn { line: line, column: column } } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn end(&self) -> LineColumn { let imp::LineColumn{ line, column } = self.0.end(); LineColumn { line: line, column: column } } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn join(&self, other: Span) -> Option<Span> { self.0.join(other.0).map(Span) } diff --git a/src/stable.rs b/src/stable.rs index d892ae52..984a1466 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -1,7 +1,7 @@ use std::ascii; use std::borrow::Borrow; use std::cell::RefCell; -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] use std::cmp; use std::collections::HashMap; use std::fmt; @@ -36,7 +36,7 @@ impl TokenStream { } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] fn get_cursor(src: &str) -> Cursor { // Create a dummy file & add it to the codemap CODEMAP.with(|cm| { @@ -50,7 +50,7 @@ fn get_cursor(src: &str) -> Cursor { }) } -#[cfg(not(procmacro2_unstable))] +#[cfg(not(procmacro2_semver_exempt))] fn get_cursor(src: &str) -> Cursor { Cursor { rest: src, @@ -163,24 +163,24 @@ impl IntoIterator for TokenStream { } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[derive(Clone, PartialEq, Eq, Debug)] pub struct FileName(String); -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl fmt::Display for FileName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[derive(Clone, PartialEq, Eq)] pub struct SourceFile { name: FileName, } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl SourceFile { /// Get the path to this source file as a string. pub fn path(&self) -> &FileName { @@ -193,14 +193,14 @@ impl SourceFile { } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl AsRef<FileName> for SourceFile { fn as_ref(&self) -> &FileName { self.path() } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl fmt::Debug for SourceFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SourceFile") @@ -210,14 +210,14 @@ impl fmt::Debug for SourceFile { } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LineColumn { pub line: usize, pub column: usize, } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] thread_local! { static CODEMAP: RefCell<Codemap> = RefCell::new(Codemap { // NOTE: We start with a single dummy file which all call_site() and @@ -230,14 +230,14 @@ thread_local! { }); } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] struct FileInfo { name: String, span: Span, lines: Vec<usize>, } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl FileInfo { fn offset_line_column(&self, offset: usize) -> LineColumn { assert!(self.span_within(Span { lo: offset as u32, hi: offset as u32 })); @@ -260,7 +260,7 @@ impl FileInfo { } /// Computes the offsets of each line in the given source string. -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] fn lines_offsets(s: &str) -> Vec<usize> { let mut lines = vec![0]; let mut prev = 0; @@ -271,12 +271,12 @@ fn lines_offsets(s: &str) -> Vec<usize> { lines } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] struct Codemap { files: Vec<FileInfo>, } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl Codemap { fn next_start_pos(&self) -> u32 { // Add 1 so there's always space between files. @@ -313,19 +313,19 @@ impl Codemap { #[derive(Clone, Copy, Debug)] pub struct Span { - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] lo: u32, - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] hi: u32, } impl Span { - #[cfg(not(procmacro2_unstable))] + #[cfg(not(procmacro2_semver_exempt))] pub fn call_site() -> Span { Span {} } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn call_site() -> Span { Span { lo: 0, hi: 0 } } @@ -334,7 +334,7 @@ impl Span { Span::call_site() } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn source_file(&self) -> SourceFile { CODEMAP.with(|cm| { let cm = cm.borrow(); @@ -345,7 +345,7 @@ impl Span { }) } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn start(&self) -> LineColumn { CODEMAP.with(|cm| { let cm = cm.borrow(); @@ -354,7 +354,7 @@ impl Span { }) } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn end(&self) -> LineColumn { CODEMAP.with(|cm| { let cm = cm.borrow(); @@ -363,7 +363,7 @@ impl Span { }) } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn join(&self, other: Span) -> Option<Span> { CODEMAP.with(|cm| { let cm = cm.borrow(); @@ -578,7 +578,7 @@ named!(token_stream -> ::TokenStream, map!( |trees| ::TokenStream(TokenStream { inner: trees }) )); -#[cfg(not(procmacro2_unstable))] +#[cfg(not(procmacro2_semver_exempt))] fn token_tree(input: Cursor) -> PResult<TokenTree> { let (input, kind) = token_kind(input)?; Ok((input, TokenTree { @@ -587,7 +587,7 @@ fn token_tree(input: Cursor) -> PResult<TokenTree> { })) } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] fn token_tree(input: Cursor) -> PResult<TokenTree> { let input = skip_whitespace(input); let lo = input.off; diff --git a/src/strnom.rs b/src/strnom.rs index 2f9e73fd..35acff72 100644 --- a/src/strnom.rs +++ b/src/strnom.rs @@ -9,18 +9,18 @@ use imp::LexError; #[derive(Copy, Clone, Eq, PartialEq)] pub struct Cursor<'a> { pub rest: &'a str, - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub off: u32, } impl<'a> Cursor<'a> { - #[cfg(not(procmacro2_unstable))] + #[cfg(not(procmacro2_semver_exempt))] pub fn advance(&self, amt: usize) -> Cursor<'a> { Cursor { rest: &self.rest[amt..], } } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn advance(&self, amt: usize) -> Cursor<'a> { Cursor { rest: &self.rest[amt..], diff --git a/src/unstable.rs b/src/unstable.rs index 56df0dd3..f8cd68c2 100644 --- a/src/unstable.rs +++ b/src/unstable.rs @@ -159,11 +159,11 @@ impl fmt::Debug for TokenTreeIter { } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[derive(Clone, PartialEq, Eq)] pub struct FileName(String); -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl fmt::Display for FileName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) @@ -172,11 +172,11 @@ impl fmt::Display for FileName { // NOTE: We have to generate our own filename object here because we can't wrap // the one provided by proc_macro. -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] #[derive(Clone, PartialEq, Eq)] pub struct SourceFile(proc_macro::SourceFile, FileName); -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl SourceFile { fn new(sf: proc_macro::SourceFile) -> Self { let filename = FileName(sf.path().to_string()); @@ -193,21 +193,21 @@ impl SourceFile { } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl AsRef<FileName> for SourceFile { fn as_ref(&self) -> &FileName { self.path() } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] impl fmt::Debug for SourceFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } -#[cfg(procmacro2_unstable)] +#[cfg(procmacro2_semver_exempt)] pub struct LineColumn { pub line: usize, pub column: usize, @@ -229,24 +229,24 @@ impl Span { self.0 } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn source_file(&self) -> SourceFile { SourceFile::new(self.0.source_file()) } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn start(&self) -> LineColumn { let proc_macro::LineColumn{ line, column } = self.0.start(); LineColumn { line, column } } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn end(&self) -> LineColumn { let proc_macro::LineColumn{ line, column } = self.0.end(); LineColumn { line, column } } - #[cfg(procmacro2_unstable)] + #[cfg(procmacro2_semver_exempt)] pub fn join(&self, other: Span) -> Option<Span> { self.0.join(other.0).map(Span) }
44
dtolnay/proc-macro2
fa1864f185f7685a1e023f06dece014bf9b32d33
2017-12-25T23:25:17Z
Fails to lex underscore in unicode escapes This test case from the compiler test suite results in a lex error: https://github.com/rust-lang/rust/blob/1.22.1/src/test/run-pass/issue-43692.rs This was implemented upstream in https://github.com/rust-lang/rust/pull/43716 and stabilized in Rust 1.22.
dtolnay__proc-macro2-38
[ "37" ]
ea71984b11eff216be73e50f1a3b8a1ad42f4259
diff --git a/tests/test.rs b/tests/test.rs index 4d6831b3..831c0cbb 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -47,6 +47,8 @@ fn roundtrip() { "); roundtrip("'a"); roundtrip("'static"); + roundtrip("'\\u{10__FFFF}'"); + roundtrip("\"\\u{10_F0FF__}foo\\u{1_0_0_0__}\""); } #[test]
0.1
diff --git a/src/stable.rs b/src/stable.rs index 8277d4c3..116635cc 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -722,28 +722,12 @@ fn backslash_u<I>(chars: &mut I) -> bool { next_ch!(chars @ '{'); next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F'); - let b = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}'); - if b == '}' { - return true - } - let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}'); - if c == '}' { - return true - } - let d = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}'); - if d == '}' { - return true - } - let e = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}'); - if e == '}' { - return true - } - let f = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '}'); - if f == '}' { - return true + loop { + let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}'); + if c == '}' { + return true; + } } - next_ch!(chars @ '}'); - true } fn float(input: &str) -> PResult<()> {
38
dtolnay/proc-macro2
fa1864f185f7685a1e023f06dece014bf9b32d33
2017-06-03T16:20:04Z
Symbol should implement neither Send nor Sync It is an index into a thread local vector. Upstream issue: https://github.com/rust-lang/rust/issues/42407
dtolnay__proc-macro2-25
[ "24" ]
a5d12d3895f9d7062edf505dea9b6feda61ba79a
diff --git a/tests/compile-fail/symbol_send.rs b/tests/compile-fail/symbol_send.rs new file mode 100644 index 00000000..64727fcc --- /dev/null +++ b/tests/compile-fail/symbol_send.rs @@ -0,0 +1,9 @@ +extern crate proc_macro2; + +use proc_macro2::Symbol; + +fn assert_send<T: Send>() {} + +fn main() { + assert_send::<Symbol>(); //~ the trait bound `*const (): std::marker::Send` is not satisfied in `proc_macro2::Symbol` +} diff --git a/tests/compile-fail/symbol_sync.rs b/tests/compile-fail/symbol_sync.rs new file mode 100644 index 00000000..ede06d1b --- /dev/null +++ b/tests/compile-fail/symbol_sync.rs @@ -0,0 +1,9 @@ +extern crate proc_macro2; + +use proc_macro2::Symbol; + +fn assert_sync<T: Sync>() {} + +fn main() { + assert_sync::<Symbol>(); //~ the trait bound `*const (): std::marker::Sync` is not satisfied in `proc_macro2::Symbol` +} diff --git a/tests/compiletest.rs b/tests/compiletest.rs new file mode 100644 index 00000000..b1055ce4 --- /dev/null +++ b/tests/compiletest.rs @@ -0,0 +1,14 @@ +extern crate compiletest_rs as compiletest; + +fn run_mode(mode: &'static str) { + let mut config = compiletest::default_config(); + config.mode = mode.parse().expect("invalid mode"); + config.target_rustcflags = Some("-L target/debug/deps".to_owned()); + config.src_base = format!("tests/{}", mode).into(); + compiletest::run_tests(&config); +} + +#[test] +fn compile_fail() { + run_mode("compile-fail"); +}
0.1
diff --git a/.travis.yml b/.travis.yml index 5877ec51..ec822078 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,13 +7,15 @@ sudo: false before_script: - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - - cargo test + - travis-cargo build + - travis-cargo --only nightly test - cargo doc --no-deps after_success: - travis-cargo --only nightly doc-upload env: global: - secure: "NAsZghAVTAksrm4WP4I66VmD2wW0eRbwB+ZKHUQfvbgUaCRvVdp4WBbWXGU/f/yHgDFWZwljWR4iPMiBwAK8nZsQFRuLFdHrOOHqbkj639LLdT9A07s1zLMB1GfR1fDttzrGhm903pbT2yxSyqqpahGYM7TaGDYYmKYIk4XyVNA5F5Sk7RI+rCecKraoYDeUEFbjWWYtU2FkEXsELEKj0emX5reWkR+wja3QokFcRZ25+Zd2dRC0K8W5QcY2UokLzKncBMCTC5q70H616S3r/9qW67Si1njsJ7RzP0NlZQUNQ/VCvwr4LCr9w+AD9i1SZtXxuux77tWEWSJvBzUc82dDMUv/floJuF7HTulSxxQoRm+fbzpXj9mgaJNiUHXru6ZRTCRVRUSXpcAco94bVoy/jnjrTe3jgAIZK5w14zA8yLw1Jxof31DlbcWORxgF+6fnY2nKPRN2oiQ50+jm1AuGDZX59/wMiu1QlkjOBHtikHp+u+7mp3SkkM04DvuQ/tWODQQnOOtrA0EB3i5H1zeTSnUcmbJufUljWWOvF1QYII08MccqwfG1KWbpobvdu+cV2iVhkq/lNCEL3Ai101CnmSCnMz+9oK/XxYOrx2TnaD9ootOKgnk7XWxF19GZecQx6O2hHTouxvB/0KcRPGWmMWl0H88f3T/Obql8bG8=" + - TRAVIS_CARGO_NIGHTLY_FEATURE="" + - secure: "NAsZghAVTAksrm4WP4I66VmD2wW0eRbwB+ZKHUQfvbgUaCRvVdp4WBbWXGU/f/yHgDFWZwljWR4iPMiBwAK8nZsQFRuLFdHrOOHqbkj639LLdT9A07s1zLMB1GfR1fDttzrGhm903pbT2yxSyqqpahGYM7TaGDYYmKYIk4XyVNA5F5Sk7RI+rCecKraoYDeUEFbjWWYtU2FkEXsELEKj0emX5reWkR+wja3QokFcRZ25+Zd2dRC0K8W5QcY2UokLzKncBMCTC5q70H616S3r/9qW67Si1njsJ7RzP0NlZQUNQ/VCvwr4LCr9w+AD9i1SZtXxuux77tWEWSJvBzUc82dDMUv/floJuF7HTulSxxQoRm+fbzpXj9mgaJNiUHXru6ZRTCRVRUSXpcAco94bVoy/jnjrTe3jgAIZK5w14zA8yLw1Jxof31DlbcWORxgF+6fnY2nKPRN2oiQ50+jm1AuGDZX59/wMiu1QlkjOBHtikHp+u+7mp3SkkM04DvuQ/tWODQQnOOtrA0EB3i5H1zeTSnUcmbJufUljWWOvF1QYII08MccqwfG1KWbpobvdu+cV2iVhkq/lNCEL3Ai101CnmSCnMz+9oK/XxYOrx2TnaD9ootOKgnk7XWxF19GZecQx6O2hHTouxvB/0KcRPGWmMWl0H88f3T/Obql8bG8=" notifications: email: diff --git a/Cargo.toml b/Cargo.toml index 127d20dc..9cf5c056 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,5 +9,8 @@ doctest = false [dependencies] unicode-xid = "0.0.4" +[dev-dependencies] +compiletest_rs = "0.2" + [features] unstable = [] diff --git a/src/stable.rs b/src/stable.rs index 0c0607af..26b2686b 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -4,6 +4,7 @@ use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::iter; +use std::marker::PhantomData; use std::ops; use std::rc::Rc; use std::str::FromStr; @@ -146,13 +147,19 @@ impl Span { } #[derive(Copy, Clone, Debug)] -pub struct Symbol(usize); +pub struct Symbol { + intern: usize, + not_send_sync: PhantomData<*const ()>, +} thread_local!(static SYMBOLS: RefCell<Interner> = RefCell::new(Interner::new())); impl<'a> From<&'a str> for Symbol { fn from(string: &'a str) -> Symbol { - Symbol(SYMBOLS.with(|s| s.borrow_mut().intern(string))) + Symbol { + intern: SYMBOLS.with(|s| s.borrow_mut().intern(string)), + not_send_sync: PhantomData, + } } } @@ -162,7 +169,7 @@ impl ops::Deref for Symbol { fn deref(&self) -> &str { SYMBOLS.with(|interner| { let interner = interner.borrow(); - let s = interner.get(self.0); + let s = interner.get(self.intern); unsafe { &*(s as *const str) }
25
dtolnay/proc-macro2
fa1864f185f7685a1e023f06dece014bf9b32d33
2018-11-12T00:37:18Z
SourceFile needs to opt out of Send and Sync `proc_macro2::SourceFile` currently has both those traits. We need to opt out to match the one in the compiler: https://github.com/rust-lang/rust/blob/1.30.0/src/libproc_macro/lib.rs#L419-L422
dtolnay__proc-macro2-150
In general, none of the types in the `proc_macro` public API that has any private state should be `Send`/`Sync`.
[ "141" ]
102ee29e36c15ca68a6f6ec7d37b04571997a8f4
diff --git a/tests/marker.rs b/tests/marker.rs new file mode 100644 index 00000000..7bb50276 --- /dev/null +++ b/tests/marker.rs @@ -0,0 +1,61 @@ +extern crate proc_macro2; + +use proc_macro2::*; + +macro_rules! assert_impl { + ($ty:ident is $($marker:ident) and +) => { + #[test] + #[allow(non_snake_case)] + fn $ty() { + fn assert_implemented<T: $($marker +)+>() {} + assert_implemented::<$ty>(); + } + }; + + ($ty:ident is not $($marker:ident) or +) => { + #[test] + #[allow(non_snake_case)] + fn $ty() { + $( + { + // Implemented for types that implement $marker. + trait IsNotImplemented { + fn assert_not_implemented() {} + } + impl<T: $marker> IsNotImplemented for T {} + + // Implemented for the type being tested. + trait IsImplemented { + fn assert_not_implemented() {} + } + impl IsImplemented for $ty {} + + // If $ty does not implement $marker, there is no ambiguity + // in the following trait method call. + <$ty>::assert_not_implemented(); + } + )+ + } + }; +} + +assert_impl!(Delimiter is Send and Sync); +assert_impl!(Spacing is Send and Sync); + +assert_impl!(Group is not Send or Sync); +assert_impl!(Ident is not Send or Sync); +assert_impl!(LexError is not Send or Sync); +assert_impl!(Literal is not Send or Sync); +assert_impl!(Punct is not Send or Sync); +assert_impl!(Span is not Send or Sync); +assert_impl!(TokenStream is not Send or Sync); +assert_impl!(TokenTree is not Send or Sync); + +#[cfg(procmacro2_semver_exempt)] +mod semver_exempt { + use super::*; + + assert_impl!(LineColumn is Send and Sync); + + assert_impl!(SourceFile is not Send or Sync); +}
0.4
diff --git a/src/lib.rs b/src/lib.rs index 2f632f6e..784e456a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -220,10 +220,20 @@ pub use imp::FileName; /// This type is semver exempt and not exposed by default. #[cfg(procmacro2_semver_exempt)] #[derive(Clone, PartialEq, Eq)] -pub struct SourceFile(imp::SourceFile); +pub struct SourceFile { + inner: imp::SourceFile, + _marker: marker::PhantomData<Rc<()>>, +} #[cfg(procmacro2_semver_exempt)] impl SourceFile { + fn _new(inner: imp::SourceFile) -> Self { + SourceFile { + inner: inner, + _marker: marker::PhantomData, + } + } + /// Get the path to this source file. /// /// ### Note @@ -238,27 +248,27 @@ impl SourceFile { /// /// [`is_real`]: #method.is_real pub fn path(&self) -> &FileName { - self.0.path() + self.inner.path() } /// Returns `true` if this source file is a real source file, and not /// generated by an external macro's expansion. pub fn is_real(&self) -> bool { - self.0.is_real() + self.inner.is_real() } } #[cfg(procmacro2_semver_exempt)] impl AsRef<FileName> for SourceFile { fn as_ref(&self) -> &FileName { - self.0.path() + self.inner.path() } } #[cfg(procmacro2_semver_exempt)] impl fmt::Debug for SourceFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.0.fmt(f) + self.inner.fmt(f) } } @@ -344,7 +354,7 @@ impl Span { /// This method is semver exempt and not exposed by default. #[cfg(procmacro2_semver_exempt)] pub fn source_file(&self) -> SourceFile { - SourceFile(self.inner.source_file()) + SourceFile::_new(self.inner.source_file()) } /// Get the starting line/column in the source file for this span.
150
dtolnay/proc-macro2
219b1d3d4d73fc645e4dcd8a01e387ee157a6a35
2018-07-13T22:49:06Z
`Tokens` previously implemented `Default` but `TokenStream` no longer does It made perfect sense for it to create an empty token stream. In my specific use case, I have a 3-tuple of `TokenStream`s that I could previously default-initialize using `Default::default()`, but now I have to write `(TokenStream::new(), TokenStream::new(), TokenStream::new())`.
dtolnay__proc-macro2-106
Sounds reasonable to me to add! Awesome, btw I'm already working on the PR :)
[ "105" ]
b761e47aad488c96baa834641d471b86bbf8829f
diff --git a/tests/test.rs b/tests/test.rs index 6a060928..5d2fb854 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -381,3 +381,10 @@ TokenStream [ assert_eq!(expected, format!("{:#?}", tts)); } + +#[test] +fn default_tokenstream_is_empty() { + let default_token_stream: TokenStream = Default::default(); + + assert!(default_token_stream.is_empty()); +}
0.4
diff --git a/src/lib.rs b/src/lib.rs index 67f80339..9930c3c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -118,6 +118,14 @@ impl TokenStream { } } +/// `TokenStream::default()` returns an empty stream, +/// i.e. this is equivalent with `TokenStream::new()`. +impl Default for TokenStream { + fn default() -> Self { + TokenStream::new() + } +} + /// Attempts to break the string into tokens and parse those tokens into a token /// stream. ///
106
dtolnay/proc-macro2
219b1d3d4d73fc645e4dcd8a01e387ee157a6a35
2018-05-17T17:57:00Z
Parse underscore as Term Nightly currently treats `_` as: ``` TokenStream [Term { sym: _, span: #0 bytes(75..76) }] ``` whereas in proc-macro2 it is: ``` TokenStream [Op { op: \'_\', spacing: Alone }] ```
dtolnay__proc-macro2-91
[ "87" ]
ca3dcad2f575e9106f1f0459845d0b8aa489bc58
diff --git a/tests/test.rs b/tests/test.rs index a3c53ec9..673a35f9 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -113,6 +113,7 @@ fn roundtrip() { ", ); roundtrip("'a"); + roundtrip("'_"); roundtrip("'static"); roundtrip("'\\u{10__FFFF}'"); roundtrip("\"\\u{10_F0FF__}foo\\u{1_0_0_0__}\"");
0.4
diff --git a/src/stable.rs b/src/stable.rs index a718db23..801a1df1 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -787,8 +787,6 @@ fn symbol(input: Cursor) -> PResult<TokenTree> { let a = &input.rest[..end]; if a == "r#_" { Err(LexError) - } else if a == "_" { - Ok((input.advance(end), Punct::new('_', Spacing::Alone).into())) } else { let ident = if raw { ::Ident::_new_raw(&a[2..], ::Span::call_site())
91
dtolnay/proc-macro2
219b1d3d4d73fc645e4dcd8a01e387ee157a6a35
2018-04-23T04:21:02Z
Op followed by comment should not be considered joint ```rust for tt in "~// comment".parse::<TokenStream>().unwrap() { println!("{:?}", tt); } ``` Proc-macro: ``` Op(Op { op: '~', spacing: Alone, span: Span(...) }) ``` Proc-macro2: ``` Op(Op { op: '~', spacing: Joint, span: Span }) ``` The comment should be considered whitespace, making the preceding op alone rather than joint.
dtolnay__proc-macro2-80
Still incorrect as of proc-macro2 0.3.5.
[ "62" ]
11437353d289246664673b43be7c608a37cc4e3f
diff --git a/tests/test.rs b/tests/test.rs index caed47ce..5ed21a4f 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -2,7 +2,7 @@ extern crate proc_macro2; use std::str::{self, FromStr}; -use proc_macro2::{Literal, Span, Term, TokenStream, TokenTree}; +use proc_macro2::{Literal, Spacing, Span, Term, TokenStream, TokenTree}; #[test] fn terms() { @@ -293,6 +293,18 @@ fn tricky_doc_comment() { assert!(tokens.len() == 3, "not length 3 -- {:?}", tokens); } +#[test] +fn op_before_comment() { + let mut tts = TokenStream::from_str("~// comment").unwrap().into_iter(); + match tts.next().unwrap() { + TokenTree::Op(tt) => { + assert_eq!(tt.op(), '~'); + assert_eq!(tt.spacing(), Spacing::Alone); + } + wrong => panic!("wrong token {:?}", wrong), + } +} + #[test] fn raw_identifier() { let mut tts = TokenStream::from_str("r#dyn").unwrap().into_iter();
0.3
diff --git a/src/stable.rs b/src/stable.rs index ad9870ce..7bcdaad9 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -1198,6 +1198,11 @@ fn op(input: Cursor) -> PResult<Op> { } fn op_char(input: Cursor) -> PResult<char> { + if input.starts_with("//") || input.starts_with("/*") { + // Do not accept `/` of a comment as an op. + return Err(LexError); + } + let mut chars = input.chars(); let first = match chars.next() { Some(ch) => ch,
80
dtolnay/proc-macro2
11437353d289246664673b43be7c608a37cc4e3f
2018-04-04T20:08:27Z
Do not parse doc comment as Literal As of 0.3.2: ```rust extern crate proc_macro2; use proc_macro2::TokenStream; fn main() { println!("{:?}", "/// doc\n".parse::<TokenStream>().unwrap()); } ``` ``` TokenStream { inner: [Literal(Literal { text: "/// doc", span: Span })] } ``` This should be the tokens <kbd>#</kbd> <kbd>[ doc = " doc" ]</kbd>.
dtolnay__proc-macro2-74
[ "73" ]
99d9630273a9c102b80f902e85aed076e241ece6
diff --git a/tests/test.rs b/tests/test.rs index 50322a1c..7699d53d 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -29,12 +29,6 @@ fn roundtrip() { roundtrip("a"); roundtrip("<<"); roundtrip("<<="); - roundtrip( - " - /// a - wut - ", - ); roundtrip( " 1 @@ -115,12 +109,16 @@ testing 123 testing 234 }", &[ - (1, 0, 1, 30), - (2, 0, 2, 7), - (2, 8, 2, 11), - (3, 0, 5, 1), - (4, 2, 4, 9), - (4, 10, 4, 13), + (1, 0, 1, 30), // # + (1, 0, 1, 30), // [ ... ] + (1, 0, 1, 30), // doc + (1, 0, 1, 30), // = + (1, 0, 1, 30), // "This is..." + (2, 0, 2, 7), // testing + (2, 8, 2, 11), // 123 + (3, 0, 5, 1), // { ... } + (4, 2, 4, 9), // testing + (4, 10, 4, 13), // 234 ], ); } @@ -192,11 +190,38 @@ fn tricky_doc_comment() { let stream = "/// doc".parse::<proc_macro2::TokenStream>().unwrap(); let tokens = stream.into_iter().collect::<Vec<_>>(); - assert!(tokens.len() == 1, "not length 1 -- {:?}", tokens); + assert!(tokens.len() == 2, "not length 2 -- {:?}", tokens); match tokens[0] { - proc_macro2::TokenTree::Literal(_) => {} + proc_macro2::TokenTree::Op(ref tt) => assert_eq!(tt.op(), '#'), _ => panic!("wrong token {:?}", tokens[0]), } + let mut tokens = match tokens[1] { + proc_macro2::TokenTree::Group(ref tt) => { + assert_eq!(tt.delimiter(), proc_macro2::Delimiter::Bracket); + tt.stream().into_iter() + } + _ => panic!("wrong token {:?}", tokens[0]), + }; + + match tokens.next().unwrap() { + proc_macro2::TokenTree::Term(ref tt) => assert_eq!(tt.as_str(), "doc"), + t => panic!("wrong token {:?}", t), + } + match tokens.next().unwrap() { + proc_macro2::TokenTree::Op(ref tt) => assert_eq!(tt.op(), '='), + t => panic!("wrong token {:?}", t), + } + match tokens.next().unwrap() { + proc_macro2::TokenTree::Literal(ref tt) => { + assert_eq!(tt.to_string(), "\" doc\""); + } + t => panic!("wrong token {:?}", t), + } + assert!(tokens.next().is_none()); + + let stream = "//! doc".parse::<proc_macro2::TokenStream>().unwrap(); + let tokens = stream.into_iter().collect::<Vec<_>>(); + assert!(tokens.len() == 3, "not length 3 -- {:?}", tokens); } #[test]
0.3
diff --git a/src/stable.rs b/src/stable.rs index 3e2f28cd..abfeab36 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -591,24 +591,55 @@ impl fmt::Display for Literal { } } -named!(token_stream -> ::TokenStream, map!( - many0!(token_tree), - |trees| ::TokenStream::_new(TokenStream { inner: trees }) -)); +fn token_stream(mut input: Cursor) -> PResult<::TokenStream> { + let mut trees = Vec::new(); + loop { + let input_no_ws = skip_whitespace(input); + if input_no_ws.rest.len() == 0 { + break + } + if let Ok((a, tokens)) = doc_comment(input_no_ws) { + input = a; + trees.extend(tokens); + continue + } + + let (a, tt) = match token_tree(input_no_ws) { + Ok(p) => p, + Err(_) => break, + }; + trees.push(tt); + input = a; + } + Ok((input, ::TokenStream::_new(TokenStream { inner: trees }))) +} #[cfg(not(procmacro2_semver_exempt))] -fn token_tree(input: Cursor) -> PResult<TokenTree> { - token_kind(input) +fn spanned<'a, T>( + input: Cursor<'a>, + f: fn(Cursor<'a>) -> PResult<'a, T>, +) -> PResult<'a, (T, ::Span)> { + let (a, b) = f(skip_whitespace(input))?; + Ok((a, ((b, ::Span::_new(Span { }))))) } #[cfg(procmacro2_semver_exempt)] -fn token_tree(input: Cursor) -> PResult<TokenTree> { +fn spanned<'a, T>( + input: Cursor<'a>, + f: fn(Cursor<'a>) -> PResult<'a, T>, +) -> PResult<'a, (T, ::Span)> { let input = skip_whitespace(input); let lo = input.off; - let (input, mut token) = token_kind(input)?; - let hi = input.off; - token.set_span(::Span::_new(Span { lo: lo, hi: hi })); - Ok((input, token)) + let (a, b) = f(input)?; + let hi = a.off; + let span = ::Span::_new(Span { lo: lo, hi: hi }); + Ok((a, (b, span))) +} + +fn token_tree(input: Cursor) -> PResult<TokenTree> { + let (rest, (mut tt, span)) = spanned(input, token_kind)?; + tt.set_span(span); + Ok((rest, tt)) } named!(token_kind -> TokenTree, alt!( @@ -721,8 +752,6 @@ named!(literal_nocapture -> (), alt!( float | int - | - doc_comment )); named!(string -> (), alt!( @@ -1146,31 +1175,53 @@ fn op_char(input: Cursor) -> PResult<char> { } } -named!(doc_comment -> (), alt!( +fn doc_comment(input: Cursor) -> PResult<Vec<TokenTree>> { + let mut trees = Vec::new(); + let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?; + trees.push(TokenTree::Op(Op::new('#', Spacing::Alone))); + if inner { + trees.push(Op::new('!', Spacing::Alone).into()); + } + let mut stream = vec![ + TokenTree::Term(::Term::new("doc", span)), + TokenTree::Op(Op::new('=', Spacing::Alone)), + TokenTree::Literal(::Literal::string(comment)), + ]; + for tt in stream.iter_mut() { + tt.set_span(span); + } + trees.push(Group::new(Delimiter::Bracket, stream.into_iter().collect()).into()); + for tt in trees.iter_mut() { + tt.set_span(span); + } + Ok((rest, trees)) +} + +named!(doc_comment_contents -> (&str, bool), alt!( do_parse!( punct!("//!") >> - take_until_newline_or_eof!() >> - (()) + s: take_until_newline_or_eof!() >> + ((s, true)) ) | do_parse!( option!(whitespace) >> peek!(tag!("/*!")) >> - block_comment >> - (()) + s: block_comment >> + ((s, true)) ) | do_parse!( punct!("///") >> not!(tag!("/")) >> - take_until_newline_or_eof!() >> - (()) + s: take_until_newline_or_eof!() >> + ((s, false)) ) | do_parse!( option!(whitespace) >> peek!(tuple!(tag!("/**"), not!(tag!("*")))) >> - block_comment >> - (()) + s: block_comment >> + ((s, false)) ) )); diff --git a/src/strnom.rs b/src/strnom.rs index 1fddcd02..f5dd1456 100644 --- a/src/strnom.rs +++ b/src/strnom.rs @@ -268,7 +268,7 @@ macro_rules! take_until_newline_or_eof { } else { match $i.find('\n') { Some(i) => Ok(($i.advance(i), &$i.rest[..i])), - None => Ok(($i.advance($i.len()), "")), + None => Ok(($i.advance($i.len()), &$i.rest[..$i.len()])), } } }}; @@ -389,37 +389,3 @@ macro_rules! map { map!($i, call!($f), $g) }; } - -macro_rules! many0 { - ($i:expr, $f:expr) => {{ - let ret; - let mut res = ::std::vec::Vec::new(); - let mut input = $i; - - loop { - if input.is_empty() { - ret = Ok((input, res)); - break; - } - - match $f(input) { - Err(LexError) => { - ret = Ok((input, res)); - break; - } - Ok((i, o)) => { - // loop trip must always consume (otherwise infinite loops) - if i.len() == input.len() { - ret = Err(LexError); - break; - } - - res.push(o); - input = i; - } - } - } - - ret - }}; -}
74
dtolnay/proc-macro2
11437353d289246664673b43be7c608a37cc4e3f
2020-05-31T06:56:23Z
Fallback handling of negative integer literals is different to proc_macro This crate's fallback implementation of `From<TokenTree>` for `TokenStream` treats negative integer literals as one token, however `rustc`'s implementation treats negative integer literals as an alone `-` followed by the positive integer literal. ### How to Reproduce 1. Make a simple proc-macro crate, with this code: ```rust use std::iter; use proc_macro2::{TokenStream, TokenTree, Literal}; #[proc_macro] pub fn proc_macro_test(input: proc_macro::TokenStream) -> proc_macro::TokenStream { //proc_macro2::fallback::force(); let int: i32 = -3; let mut tokens = TokenStream::new(); tokens.extend(iter::once(TokenTree::Literal(Literal::i32_suffixed(int)))); dbg!(&tokens); input } ``` 2. Run that proc macro in another crate. With the commented line commented it will output two separate tokens, but with it uncommented it will output one negative literal token.
dtolnay__proc-macro2-236
[ "235" ]
ee2554d3fa4214164a0b23006008dcbf9e82769f
diff --git a/tests/test.rs b/tests/test.rs index a0133f60..39e0c789 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -117,6 +117,27 @@ fn literal_suffix() { assert_eq!(token_count("b'b'b"), 1); } +#[test] +fn literal_iter_negative() { + let negative_literal = Literal::i32_suffixed(-3); + let tokens = TokenStream::from(TokenTree::Literal(negative_literal)); + let mut iter = tokens.into_iter(); + match iter.next().unwrap() { + TokenTree::Punct(punct) => { + assert_eq!(punct.as_char(), '-'); + assert_eq!(punct.spacing(), Spacing::Alone); + } + unexpected => panic!("unexpected token {:?}", unexpected), + } + match iter.next().unwrap() { + TokenTree::Literal(literal) => { + assert_eq!(literal.to_string(), "3i32"); + } + unexpected => panic!("unexpected token {:?}", unexpected), + } + assert!(iter.next().is_none()); +} + #[test] fn roundtrip() { fn roundtrip(p: &str) {
1.0
diff --git a/build.rs b/build.rs index 89e2ab39..153e13f5 100644 --- a/build.rs +++ b/build.rs @@ -61,6 +61,10 @@ fn main() { println!("cargo:rustc-cfg=span_locations"); } + if version.minor < 39 { + println!("cargo:rustc-cfg=no_bind_by_move_pattern_guard"); + } + if version.minor >= 45 { println!("cargo:rustc-cfg=hygiene"); } diff --git a/src/fallback.rs b/src/fallback.rs index 4d102efe..2a064307 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -49,6 +49,49 @@ impl TokenStream { fn take_inner(&mut self) -> Vec<TokenTree> { mem::replace(&mut self.inner, Vec::new()) } + + fn push_token(&mut self, token: TokenTree) { + // https://github.com/alexcrichton/proc-macro2/issues/235 + match token { + #[cfg(not(no_bind_by_move_pattern_guard))] + TokenTree::Literal(crate::Literal { + #[cfg(wrap_proc_macro)] + inner: crate::imp::Literal::Fallback(literal), + #[cfg(not(wrap_proc_macro))] + inner: literal, + .. + }) if literal.text.starts_with('-') => { + push_negative_literal(self, literal); + } + #[cfg(no_bind_by_move_pattern_guard)] + TokenTree::Literal(crate::Literal { + #[cfg(wrap_proc_macro)] + inner: crate::imp::Literal::Fallback(literal), + #[cfg(not(wrap_proc_macro))] + inner: literal, + .. + }) => { + if literal.text.starts_with('-') { + push_negative_literal(self, literal); + } else { + self.inner + .push(TokenTree::Literal(crate::Literal::_new_stable(literal))); + } + } + _ => self.inner.push(token), + } + + #[cold] + fn push_negative_literal(stream: &mut TokenStream, mut literal: Literal) { + literal.text.remove(0); + let mut punct = crate::Punct::new('-', Spacing::Alone); + punct.set_span(crate::Span::_new_stable(literal.span)); + stream.inner.push(TokenTree::Punct(punct)); + stream + .inner + .push(TokenTree::Literal(crate::Literal::_new_stable(literal))); + } + } } // Nonrecursive to prevent stack overflow. @@ -172,19 +215,17 @@ impl From<TokenStream> for proc_macro::TokenStream { impl From<TokenTree> for TokenStream { fn from(tree: TokenTree) -> TokenStream { - TokenStream { inner: vec![tree] } + let mut stream = TokenStream::new(); + stream.push_token(tree); + stream } } impl FromIterator<TokenTree> for TokenStream { - fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self { - let mut v = Vec::new(); - - for token in streams { - v.push(token); - } - - TokenStream { inner: v } + fn from_iter<I: IntoIterator<Item = TokenTree>>(tokens: I) -> Self { + let mut stream = TokenStream::new(); + stream.extend(tokens); + stream } } @@ -201,8 +242,8 @@ impl FromIterator<TokenStream> for TokenStream { } impl Extend<TokenTree> for TokenStream { - fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) { - self.inner.extend(streams); + fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, tokens: I) { + tokens.into_iter().for_each(|token| self.push_token(token)); } }
236
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8
2020-05-19T17:08:06Z
Non-ascii characters in doc comments offsets are miscounted ```rust let stream: TokenStream = FromStr::from_str("//! a").unwrap(); for tree in stream { eprintln!("{:?}", tree.span().end()); } let stream: TokenStream = FromStr::from_str("//! Ø").unwrap(); for tree in stream { eprintln!("{:?}", tree.span().end()); } ``` prints: ``` LineColumn { line: 1, column: 5 } LineColumn { line: 1, column: 5 } LineColumn { line: 1, column: 5 } LineColumn { line: 1, column: 6 } LineColumn { line: 1, column: 6 } LineColumn { line: 1, column: 6 } ``` I suspect the problem is [here](https://github.com/alexcrichton/proc-macro2/blob/3f9b24d63611b82d9378c6d794dd93ef6007a79d/src/parse.rs#L760), where the cursor is advanced using byte positions instead of character positions.
dtolnay__proc-macro2-229
`Span` counts bytes not characters, since if you counted characters you wouldn't know how many bytes you have. https://es.wikipedia.org/wiki/UTF-8 I was under the impression that `LineColumn.column` is character-based, not byte-based: https://docs.rs/proc-macro2/1.0.13/proc_macro2/struct.LineColumn.html IIRC, the mismatch does not occur if you change the doc comments with explicit doc attributes. if we count in characters, in which byte is the "a" in this text? `"ØØaØ"` `LineColumn { line: 1, column: 2 }` How do we mark the snippets in each line? With an oracle? I would accept a PR to fix this to match libproc_macro's behavior, which is character based. I'll give it a try https://github.com/botika/proc-macro2/blob/master/src/fallback.rs#L407-L422 If all I have are the byte of the lines, and a range. @dtolnay I ask the same thing again, are you going to implement an oracle, or realloc the text, or past text as argument? I honestly don't understand. I will learn a lot with the solution. @botika you need the text anyway in order to turn line+column into a byte offset in the file. Once you have source text, adding up the byte size of the first N characters on a line to get a byte offset is not hard. https://github.com/alexcrichton/proc-macro2/blob/master/src/fallback.rs#L325-L346 When you create the cursor, then there is no text to look at this on. https://github.com/alexcrichton/proc-macro2/blob/master/src/fallback.rs#L305 The only thing it keeps is the line number. Do you want to convert that line number to utf-8 first and then measure utf-8 in the parser. It is quite expensive and it does not affect the `compile_error!`, in addition to not being able to know the byte with the `LineColumn` output, the only output there is. Come on you break me `yarte`. > When you create the cursor, then there is no text to look at this on. Your link is to private implementation code inside proc-macro2. Yes, fixing the bug means changing code, possibly including that code. Ok, the implementation of `Span` in utf-8 characters, I'll find a solution to frame it with the bytes. Thank you. See you.
[ "227" ]
c26e99cb41e69669ae15e8f4e630fd2409f583fd
diff --git a/tests/test.rs b/tests/test.rs index 6d69d9a3..ff96633a 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -171,34 +171,6 @@ fn fail() { #[cfg(span_locations)] #[test] fn span_test() { - fn check_spans(p: &str, mut lines: &[(usize, usize, usize, usize)]) { - let ts = p.parse::<TokenStream>().unwrap(); - check_spans_internal(ts, &mut lines); - } - - fn check_spans_internal(ts: TokenStream, lines: &mut &[(usize, usize, usize, usize)]) { - for i in ts { - if let Some((&(sline, scol, eline, ecol), rest)) = lines.split_first() { - *lines = rest; - - let start = i.span().start(); - assert_eq!(start.line, sline, "sline did not match for {}", i); - assert_eq!(start.column, scol, "scol did not match for {}", i); - - let end = i.span().end(); - assert_eq!(end.line, eline, "eline did not match for {}", i); - assert_eq!(end.column, ecol, "ecol did not match for {}", i); - - match i { - TokenTree::Group(g) => { - check_spans_internal(g.stream().clone(), lines); - } - _ => {} - } - } - } - } - check_spans( "\ /// This is a document comment @@ -477,3 +449,78 @@ fn tuple_indexing() { assert_eq!("0.0", tokens.next().unwrap().to_string()); assert!(tokens.next().is_none()); } + +#[cfg(span_locations)] +#[test] +fn non_ascii_tokens() { + check_spans("// abc", &[]); + check_spans("// Ñbc", &[]); + check_spans("// abc x", &[(1, 7, 1, 8)]); + check_spans("// Ñbc x", &[(1, 7, 1, 8)]); + check_spans("/* abc */ x", &[(1, 10, 1, 11)]); + check_spans("/* Ñbc */ x", &[(1, 10, 1, 11)]); + check_spans("/* ab\nc */ x", &[(2, 5, 2, 6)]); + check_spans("/* Ñb\nc */ x", &[(2, 5, 2, 6)]); + check_spans("/*** abc */ x", &[(1, 12, 1, 13)]); + check_spans("/*** Ñbc */ x", &[(1, 12, 1, 13)]); + check_spans(r#""abc""#, &[(1, 0, 1, 5)]); + check_spans(r#""Ñbc""#, &[(1, 0, 1, 5)]); + check_spans(r###"r#"abc"#"###, &[(1, 0, 1, 8)]); + check_spans(r###"r#"Ñbc"#"###, &[(1, 0, 1, 8)]); + check_spans("r#\"a\nc\"#", &[(1, 0, 2, 3)]); + check_spans("r#\"Ñ\nc\"#", &[(1, 0, 2, 3)]); + check_spans("'a'", &[(1, 0, 1, 3)]); + check_spans("'Ñ'", &[(1, 0, 1, 3)]); + check_spans("//! abc", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("//! Ñbc", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("//! abc\n", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("//! Ñbc\n", &[(1, 0, 1, 7), (1, 0, 1, 7), (1, 0, 1, 7)]); + check_spans("/*! abc */", &[(1, 0, 1, 10), (1, 0, 1, 10), (1, 0, 1, 10)]); + check_spans("/*! Ñbc */", &[(1, 0, 1, 10), (1, 0, 1, 10), (1, 0, 1, 10)]); + check_spans("/*! a\nc */", &[(1, 0, 2, 4), (1, 0, 2, 4), (1, 0, 2, 4)]); + check_spans("/*! Ñ\nc */", &[(1, 0, 2, 4), (1, 0, 2, 4), (1, 0, 2, 4)]); + check_spans("abc", &[(1, 0, 1, 3)]); + check_spans("Ñbc", &[(1, 0, 1, 3)]); + check_spans("Ñbć", &[(1, 0, 1, 3)]); + check_spans("abc// foo", &[(1, 0, 1, 3)]); + check_spans("Ñbc// foo", &[(1, 0, 1, 3)]); + check_spans("Ñbć// foo", &[(1, 0, 1, 3)]); + check_spans("b\"a\\\n c\"", &[(1, 0, 2, 3)]); + check_spans("b\"a\\\n\u{00a0}c\"", &[(1, 0, 2, 3)]); +} + +#[test] +fn incomplete_comment_no_panic() { + let s = "/*/"; + assert!(s.parse::<TokenStream>().is_err()); +} + +#[cfg(span_locations)] +fn check_spans(p: &str, mut lines: &[(usize, usize, usize, usize)]) { + let ts = p.parse::<TokenStream>().unwrap(); + check_spans_internal(ts, &mut lines); +} + +#[cfg(span_locations)] +fn check_spans_internal(ts: TokenStream, lines: &mut &[(usize, usize, usize, usize)]) { + for i in ts { + if let Some((&(sline, scol, eline, ecol), rest)) = lines.split_first() { + *lines = rest; + + let start = i.span().start(); + assert_eq!(start.line, sline, "sline did not match for {}", i); + assert_eq!(start.column, scol, "scol did not match for {}", i); + + let end = i.span().end(); + assert_eq!(end.line, eline, "eline did not match for {}", i); + assert_eq!(end.column, ecol, "ecol did not match for {}", i); + + match i { + TokenTree::Group(g) => { + check_spans_internal(g.stream().clone(), lines); + } + _ => {} + } + } + } +}
1.0
diff --git a/src/fallback.rs b/src/fallback.rs index fffea68f..50c6d6b4 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -295,16 +295,21 @@ impl FileInfo { } } -/// Computesthe offsets of each line in the given source string. +/// Computes the offsets of each line in the given source string +/// and the total number of characters #[cfg(span_locations)] -fn lines_offsets(s: &str) -> Vec<usize> { +fn lines_offsets(s: &str) -> (usize, Vec<usize>) { let mut lines = vec![0]; - let mut prev = 0; - while let Some(len) = s[prev..].find('\n') { - prev += len + 1; - lines.push(prev); + let mut total = 0; + + for ch in s.chars() { + total += 1; + if ch == '\n' { + lines.push(total); + } } - lines + + (total, lines) } #[cfg(span_locations)] @@ -323,12 +328,12 @@ impl SourceMap { } fn add_file(&mut self, name: &str, src: &str) -> Span { - let lines = lines_offsets(src); + let (len, lines) = lines_offsets(src); let lo = self.next_start_pos(); // XXX(nika): Shouild we bother doing a checked cast or checked add here? let span = Span { lo, - hi: lo + (src.len() as u32), + hi: lo + (len as u32), }; #[cfg(procmacro2_semver_exempt)] diff --git a/src/parse.rs b/src/parse.rs index 208c0fb7..b0783cc4 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -14,12 +14,14 @@ pub(crate) struct Cursor<'a> { impl<'a> Cursor<'a> { #[cfg(not(span_locations))] + /// Advance `amt` bytes, without regards for non-ascii text fn advance(&self, amt: usize) -> Cursor<'a> { Cursor { rest: &self.rest[amt..], } } #[cfg(span_locations)] + /// Advance `amt` bytes, without regards for non-ascii text fn advance(&self, amt: usize) -> Cursor<'a> { Cursor { rest: &self.rest[amt..], @@ -27,8 +29,18 @@ impl<'a> Cursor<'a> { } } - fn find(&self, p: char) -> Option<usize> { - self.rest.find(p) + #[cfg(not(span_locations))] + fn advance_chars(&self, _chars: usize, bytes: usize) -> Cursor<'a> { + Cursor { + rest: &self.rest[bytes..], + } + } + #[cfg(span_locations)] + fn advance_chars(&self, chars: usize, bytes: usize) -> Cursor<'a> { + Cursor { + rest: &self.rest[bytes..], + off: self.off + (chars as u32), + } } fn starts_with(&self, s: &str) -> bool { @@ -59,6 +71,13 @@ impl<'a> Cursor<'a> { self.rest.char_indices() } + fn char_offsets(&self) -> impl Iterator<Item = (usize, usize, char)> + 'a { + self.rest + .char_indices() + .enumerate() + .map(|(char_idx, (byte_offset, ch))| (char_idx, byte_offset, ch)) + } + fn parse(&self, tag: &str) -> Result<Cursor<'a>, LexError> { if self.starts_with(tag) { Ok(self.advance(tag.len())) @@ -71,53 +90,51 @@ impl<'a> Cursor<'a> { type PResult<'a, O> = Result<(Cursor<'a>, O), LexError>; fn skip_whitespace(input: Cursor) -> Cursor { - let bytes = input.as_bytes(); - let mut i = 0; - while i < bytes.len() { - let s = input.advance(i); - if bytes[i] == b'/' { + let mut s = input; + + while !s.is_empty() { + let byte = s.as_bytes()[0]; + if byte == b'/' { if s.starts_with("//") && (!s.starts_with("///") || s.starts_with("////")) && !s.starts_with("//!") { - if let Some(len) = s.find('\n') { - i += len + 1; - continue; - } - break; + let (cursor, _) = take_until_newline_or_eof(s); + s = cursor; + continue; } else if s.starts_with("/**/") { - i += 4; + s = s.advance(4); continue; } else if s.starts_with("/*") && (!s.starts_with("/**") || s.starts_with("/***")) && !s.starts_with("/*!") { match block_comment(s) { - Ok((_, com)) => { - i += com.len(); + Ok((rest, _)) => { + s = rest; continue; } Err(LexError) => return input, } } } - match bytes[i] { + match byte { b' ' | 0x09..=0x0d => { - i += 1; + s = s.advance(1); continue; } b if b <= 0x7f => {} _ => { let ch = s.chars().next().unwrap(); if is_whitespace(ch) { - i += ch.len_utf8(); + s = s.advance_chars(1, ch.len_utf8()); continue; } } } return s; } - input.advance(input.len()) + s } fn block_comment(input: Cursor) -> PResult<&str> { @@ -127,21 +144,27 @@ fn block_comment(input: Cursor) -> PResult<&str> { let mut depth = 0; let bytes = input.as_bytes(); - let mut i = 0; + let mut iter = input.char_offsets(); let upper = bytes.len() - 1; - while i < upper { + + while let Some((ch_i, i, _)) = iter.next() { + if i == upper { + break; + } if bytes[i] == b'/' && bytes[i + 1] == b'*' { depth += 1; - i += 1; // eat '*' + // eat '*' + let _ = iter.next(); } else if bytes[i] == b'*' && bytes[i + 1] == b'/' { depth -= 1; if depth == 0 { - return Ok((input.advance(i + 2), &input.rest[..i + 2])); + return Ok((input.advance_chars(ch_i + 2, i + 2), &input.rest[..i + 2])); } - i += 1; // eat '/' + // eat '/' + let _ = iter.next(); } - i += 1; } + Err(LexError) } @@ -264,14 +287,16 @@ fn symbol_not_raw(input: Cursor) -> PResult<&str> { } let mut end = input.len(); + let mut chars_end = 1; for (i, ch) in chars { if !is_ident_continue(ch) { end = i; break; } + chars_end += 1; } - Ok((input.advance(end), &input.rest[..end])) + Ok((input.advance_chars(chars_end, end), &input.rest[..end])) } fn literal(input: Cursor) -> PResult<Literal> { @@ -320,35 +345,42 @@ fn string(input: Cursor) -> Result<Cursor, LexError> { } fn cooked_string(input: Cursor) -> Result<Cursor, LexError> { - let mut chars = input.char_indices().peekable(); - while let Some((byte_offset, ch)) = chars.next() { + let mut chars = input.char_offsets().peekable(); + + macro_rules! char_indices { + ($iter:expr) => { + &mut ((&mut $iter).map(|(_, byte_offset, ch)| (byte_offset, ch))) + }; + } + + while let Some((char_offset, byte_offset, ch)) = chars.next() { match ch { '"' => { - let input = input.advance(byte_offset + 1); + let input = input.advance_chars(char_offset + 1, byte_offset + 1); return Ok(literal_suffix(input)); } '\r' => { - if let Some((_, '\n')) = chars.next() { + if let Some((_, _, '\n')) = chars.next() { // ... } else { break; } } '\\' => match chars.next() { - Some((_, 'x')) => { - if !backslash_x_char(&mut chars) { + Some((_, _, 'x')) => { + if !backslash_x_char(char_indices!(chars)) { break; } } - Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\')) - | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {} - Some((_, 'u')) => { - if !backslash_u(&mut chars) { + Some((_, _, 'n')) | Some((_, _, 'r')) | Some((_, _, 't')) | Some((_, _, '\\')) + | Some((_, _, '\'')) | Some((_, _, '"')) | Some((_, _, '0')) => {} + Some((_, _, 'u')) => { + if !backslash_u(char_indices!(chars)) { break; } } - Some((_, '\n')) | Some((_, '\r')) => { - while let Some(&(_, ch)) = chars.peek() { + Some((_, _, '\n')) | Some((_, _, '\r')) => { + while let Some(&(_, _, ch)) = chars.peek() { if ch.is_whitespace() { chars.next(); } else { @@ -399,9 +431,9 @@ fn cooked_byte_string(mut input: Cursor) -> Result<Cursor, LexError> { | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {} Some((newline, b'\n')) | Some((newline, b'\r')) => { let rest = input.advance(newline + 1); - for (offset, ch) in rest.char_indices() { + for (char_offset, offset, ch) in rest.char_offsets() { if !ch.is_whitespace() { - input = rest.advance(offset); + input = rest.advance_chars(char_offset, offset); bytes = input.bytes().enumerate(); continue 'outer; } @@ -418,9 +450,9 @@ fn cooked_byte_string(mut input: Cursor) -> Result<Cursor, LexError> { } fn raw_string(input: Cursor) -> Result<Cursor, LexError> { - let mut chars = input.char_indices(); + let mut chars = input.char_offsets(); let mut n = 0; - while let Some((byte_offset, ch)) = chars.next() { + while let Some((_, byte_offset, ch)) = chars.next() { match ch { '"' => { n = byte_offset; @@ -430,10 +462,10 @@ fn raw_string(input: Cursor) -> Result<Cursor, LexError> { _ => return Err(LexError), } } - for (byte_offset, ch) in chars { + for (char_offset, byte_offset, ch) in chars { match ch { - '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => { - let rest = input.advance(byte_offset + 1 + n); + '"' if input.rest[(byte_offset + 1)..].starts_with(&input.rest[..n]) => { + let rest = input.advance_chars(char_offset + 1 + n, byte_offset + 1 + n); return Ok(literal_suffix(rest)); } '\r' => {} @@ -469,6 +501,7 @@ fn byte(input: Cursor) -> Result<Cursor, LexError> { fn character(input: Cursor) -> Result<Cursor, LexError> { let input = input.parse("'")?; let mut chars = input.char_indices(); + let escaped = input.as_bytes().get(0) == Some(&b'\\'); let ok = match chars.next().map(|(_, ch)| ch) { Some('\\') => match chars.next().map(|(_, ch)| ch) { Some('x') => backslash_x_char(&mut chars), @@ -484,7 +517,9 @@ fn character(input: Cursor) -> Result<Cursor, LexError> { return Err(LexError); } let (idx, _) = chars.next().ok_or(LexError)?; - let input = input.advance(idx).parse("'")?; + let input = input + .advance_chars(if escaped { idx } else { 1 }, idx) + .parse("'")?; Ok(literal_suffix(input)) } @@ -757,8 +792,18 @@ fn doc_comment_contents(input: Cursor) -> PResult<(&str, bool)> { } fn take_until_newline_or_eof(input: Cursor) -> (Cursor, &str) { - match input.find('\n') { - Some(i) => (input.advance(i), &input.rest[..i]), - None => (input.advance(input.len()), input.rest), + let mut chars = input.char_offsets(); + let mut char_len = 0; + + while let Some((char_off, byte_off, ch)) = chars.next() { + if ch == '\n' { + return ( + input.advance_chars(char_len, byte_off), + &input.rest[..byte_off], + ); + } + char_len = char_off + 1; } + + (input.advance_chars(char_len, input.len()), input.rest) }
229
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8
2019-08-11T17:55:28Z
Fails to tokenize `1x` in stable mode ```rust fn main() { "1x".parse::<proc_macro2::TokenStream>().unwrap(); } ``` This fails with a LexError. The compiler's proc_macro parses this input successfully, and it is allowed in macro inputs. ```rust fn main() { println!(stringify!(1x)); } ```
dtolnay__proc-macro2-189
[ "155" ]
7d277e0b8bd566294f0e2187444a36b350636748
diff --git a/tests/test.rs b/tests/test.rs index 8ab975c2..75283881 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -96,6 +96,22 @@ fn literal_float() { assert_eq!(Literal::f32_unsuffixed(10.0).to_string(), "10.0"); } +#[test] +fn literal_suffix() { + fn token_count(p: &str) -> usize { + p.parse::<TokenStream>().unwrap().into_iter().count() + } + + assert_eq!(token_count("999u256"), 1); + assert_eq!(token_count("999r#u256"), 3); + assert_eq!(token_count("1."), 1); + assert_eq!(token_count("1.f32"), 3); + assert_eq!(token_count("1.0_0"), 1); + assert_eq!(token_count("1._0"), 3); + assert_eq!(token_count("1._m"), 3); + assert_eq!(token_count("\"\"s"), 1); +} + #[test] fn roundtrip() { fn roundtrip(p: &str) { @@ -123,6 +139,9 @@ fn roundtrip() { 9 0 0xffffffffffffffffffffffffffffffff + 1x + 1u80 + 1f320 ", ); roundtrip("'a"); @@ -139,9 +158,6 @@ fn fail() { panic!("should have failed to parse: {}\n{:#?}", p, s); } } - fail("1x"); - fail("1u80"); - fail("1f320"); fail("' static"); fail("r#1"); fail("r#_");
null
diff --git a/src/fallback.rs b/src/fallback.rs index 5590480c..1bd58483 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -881,14 +881,27 @@ fn symbol_leading_ws(input: Cursor) -> PResult<TokenTree> { } fn symbol(input: Cursor) -> PResult<TokenTree> { - let mut chars = input.char_indices(); - let raw = input.starts_with("r#"); - if raw { - chars.next(); - chars.next(); + let rest = input.advance((raw as usize) << 1); + + let (rest, sym) = symbol_not_raw(rest)?; + + if !raw { + let ident = crate::Ident::new(sym, crate::Span::call_site()); + return Ok((rest, ident.into())); } + if sym == "_" { + return Err(LexError) + } + + let ident = crate::Ident::_new_raw(sym, crate::Span::call_site()); + Ok((rest, ident.into())) +} + +fn symbol_not_raw(input: Cursor) -> PResult<&str> { + let mut chars = input.char_indices(); + match chars.next() { Some((_, ch)) if is_ident_start(ch) => {} _ => return Err(LexError), @@ -902,17 +915,7 @@ fn symbol(input: Cursor) -> PResult<TokenTree> { } } - let a = &input.rest[..end]; - if a == "r#_" { - Err(LexError) - } else { - let ident = if raw { - crate::Ident::_new_raw(&a[2..], crate::Span::call_site()) - } else { - crate::Ident::new(a, crate::Span::call_site()) - }; - Ok((input.advance(end), ident.into())) - } + Ok((input.advance(end), &input.rest[..end])) } fn literal(input: Cursor) -> PResult<Literal> { @@ -952,10 +955,12 @@ named!(string -> (), alt!( ) => { |_| () } )); -named!(quoted_string -> (), delimited!( - punct!("\""), - cooked_string, - tag!("\"") +named!(quoted_string -> (), do_parse!( + punct!("\"") >> + cooked_string >> + tag!("\"") >> + option!(symbol_not_raw) >> + (()) )); fn cooked_string(input: Cursor) -> PResult<()> { @@ -1193,10 +1198,10 @@ where } fn float(input: Cursor) -> PResult<()> { - let (rest, ()) = float_digits(input)?; - for suffix in &["f32", "f64"] { - if rest.starts_with(suffix) { - return word_break(rest.advance(suffix.len())); + let (mut rest, ()) = float_digits(input)?; + if let Some(ch) = rest.chars().next() { + if is_ident_start(ch) { + rest = symbol_not_raw(rest)?.0; } } word_break(rest) @@ -1225,7 +1230,7 @@ fn float_digits(input: Cursor) -> PResult<()> { chars.next(); if chars .peek() - .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch)) + .map(|&ch| ch == '.' || is_ident_start(ch)) .unwrap_or(false) { return Err(LexError); @@ -1280,12 +1285,10 @@ fn float_digits(input: Cursor) -> PResult<()> { } fn int(input: Cursor) -> PResult<()> { - let (rest, ()) = digits(input)?; - for suffix in &[ - "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128", - ] { - if rest.starts_with(suffix) { - return word_break(rest.advance(suffix.len())); + let (mut rest, ()) = digits(input)?; + if let Some(ch) = rest.chars().next() { + if is_ident_start(ch) { + rest = symbol_not_raw(rest)?.0; } } word_break(rest)
189
dtolnay/proc-macro2
7d277e0b8bd566294f0e2187444a36b350636748
2019-04-22T23:15:38Z
Be smarter about string escaping Something like ```rust proc_macro2::Literal::string(&format!("Couldn't find {}", class_name)); ``` will end up as `"Couldn\'t find SomeProtocol"` when used in `quote!` Since we're in a string surrounded by double quotes, the escaping there is useless.
dtolnay__proc-macro2-171
Thanks! I would accept a PR to fix this.
[ "60" ]
219b1d3d4d73fc645e4dcd8a01e387ee157a6a35
diff --git a/tests/test.rs b/tests/test.rs index f5660c00..370392b6 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -80,9 +80,21 @@ fn lifetime_invalid() { } #[test] -fn literals() { +fn literal_string() { assert_eq!(Literal::string("foo").to_string(), "\"foo\""); assert_eq!(Literal::string("\"").to_string(), "\"\\\"\""); + assert_eq!(Literal::string("didn't").to_string(), "\"didn't\""); +} + +#[test] +fn literal_character() { + assert_eq!(Literal::character('x').to_string(), "'x'"); + assert_eq!(Literal::character('\'').to_string(), "'\\''"); + assert_eq!(Literal::character('"').to_string(), "'\"'"); +} + +#[test] +fn literal_float() { assert_eq!(Literal::f32_unsuffixed(10.0).to_string(), "10.0"); }
0.4
diff --git a/src/fallback.rs b/src/fallback.rs index 05fe8ed5..2ce32f13 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -734,17 +734,31 @@ impl Literal { } pub fn string(t: &str) -> Literal { - let mut s = t - .chars() - .flat_map(|c| c.escape_default()) - .collect::<String>(); - s.push('"'); - s.insert(0, '"'); - Literal::_new(s) + let mut text = String::with_capacity(t.len() + 2); + text.push('"'); + for c in t.chars() { + if c == '\'' { + // escape_default turns this into "\'" which is unnecessary. + text.push(c); + } else { + text.extend(c.escape_default()); + } + } + text.push('"'); + Literal::_new(text) } pub fn character(t: char) -> Literal { - Literal::_new(format!("'{}'", t.escape_default().collect::<String>())) + let mut text = String::new(); + text.push('\''); + if t == '"' { + // escape_default turns this into '\"' which is unnecessary. + text.push(t); + } else { + text.extend(t.escape_default()); + } + text.push('\''); + Literal::_new(text) } pub fn byte_string(bytes: &[u8]) -> Literal {
171
dtolnay/proc-macro2
219b1d3d4d73fc645e4dcd8a01e387ee157a6a35
2018-11-12T00:48:51Z
Remove proc_macro2::FileName This type was removed upstream by https://github.com/rust-lang/rust/commit/e5e29d1a1976ff7d0b39ade8706ca0e3ddebe7a9 in favor of PathBuf.
dtolnay__proc-macro2-151
[ "149" ]
7c8bf4bf0f0d7a509aa006e4b6325ddd79705ec0
diff --git a/tests/test.rs b/tests/test.rs index 5d2fb854..9d37cf37 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -203,7 +203,7 @@ fn default_span() { assert_eq!(end.line, 1); assert_eq!(end.column, 0); let source_file = Span::call_site().source_file(); - assert_eq!(source_file.path().to_string(), "<unspecified>"); + assert_eq!(source_file.path().to_string_lossy(), "<unspecified>"); assert!(!source_file.is_real()); }
0.4
diff --git a/src/lib.rs b/src/lib.rs index 784e456a..1204c6c2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,6 +58,8 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::iter::FromIterator; use std::marker; +#[cfg(procmacro2_semver_exempt)] +use std::path::PathBuf; use std::rc::Rc; use std::str::FromStr; @@ -211,10 +213,6 @@ impl fmt::Debug for LexError { } } -// Returned by reference, so we can't easily wrap it. -#[cfg(procmacro2_semver_exempt)] -pub use imp::FileName; - /// The source file of a given `Span`. /// /// This type is semver exempt and not exposed by default. @@ -247,7 +245,7 @@ impl SourceFile { /// may not actually be valid. /// /// [`is_real`]: #method.is_real - pub fn path(&self) -> &FileName { + pub fn path(&self) -> PathBuf { self.inner.path() } @@ -258,13 +256,6 @@ impl SourceFile { } } -#[cfg(procmacro2_semver_exempt)] -impl AsRef<FileName> for SourceFile { - fn as_ref(&self) -> &FileName { - self.inner.path() - } -} - #[cfg(procmacro2_semver_exempt)] impl fmt::Debug for SourceFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/src/stable.rs b/src/stable.rs index 0d8aac9d..baeed69a 100644 --- a/src/stable.rs +++ b/src/stable.rs @@ -6,6 +6,9 @@ use std::cell::RefCell; use std::cmp; use std::fmt; use std::iter; +#[cfg(procmacro2_semver_exempt)] +use std::path::Path; +use std::path::PathBuf; use std::str::FromStr; use std::vec; @@ -190,29 +193,15 @@ impl IntoIterator for TokenStream { } } -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct FileName(String); - -#[allow(dead_code)] -pub fn file_name(s: String) -> FileName { - FileName(s) -} - -impl fmt::Display for FileName { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.0.fmt(f) - } -} - #[derive(Clone, PartialEq, Eq)] pub struct SourceFile { - name: FileName, + path: PathBuf, } impl SourceFile { /// Get the path to this source file as a string. - pub fn path(&self) -> &FileName { - &self.name + pub fn path(&self) -> PathBuf { + self.path.clone() } pub fn is_real(&self) -> bool { @@ -221,12 +210,6 @@ impl SourceFile { } } -impl AsRef<FileName> for SourceFile { - fn as_ref(&self) -> &FileName { - self.path() - } -} - impl fmt::Debug for SourceFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("SourceFile") @@ -382,7 +365,7 @@ impl Span { let cm = cm.borrow(); let fi = cm.fileinfo(*self); SourceFile { - name: FileName(fi.name.clone()), + path: Path::new(&fi.name).to_owned(), } }) } diff --git a/src/unstable.rs b/src/unstable.rs index d15b9da6..c4cf11a8 100644 --- a/src/unstable.rs +++ b/src/unstable.rs @@ -3,6 +3,8 @@ use std::fmt; use std::iter; use std::panic::{self, PanicInfo}; +#[cfg(super_unstable)] +use std::path::PathBuf; use std::str::FromStr; use proc_macro; @@ -382,52 +384,40 @@ impl fmt::Debug for TokenTreeIter { } } -pub use stable::FileName; - -// NOTE: We have to generate our own filename object here because we can't wrap -// the one provided by proc_macro. #[derive(Clone, PartialEq, Eq)] #[cfg(super_unstable)] pub enum SourceFile { - Nightly(proc_macro::SourceFile, FileName), + Nightly(proc_macro::SourceFile), Stable(stable::SourceFile), } #[cfg(super_unstable)] impl SourceFile { fn nightly(sf: proc_macro::SourceFile) -> Self { - let filename = stable::file_name(sf.path().display().to_string()); - SourceFile::Nightly(sf, filename) + SourceFile::Nightly(sf) } /// Get the path to this source file as a string. - pub fn path(&self) -> &FileName { + pub fn path(&self) -> PathBuf { match self { - SourceFile::Nightly(_, f) => f, + SourceFile::Nightly(a) => a.path(), SourceFile::Stable(a) => a.path(), } } pub fn is_real(&self) -> bool { match self { - SourceFile::Nightly(a, _) => a.is_real(), + SourceFile::Nightly(a) => a.is_real(), SourceFile::Stable(a) => a.is_real(), } } } -#[cfg(super_unstable)] -impl AsRef<FileName> for SourceFile { - fn as_ref(&self) -> &FileName { - self.path() - } -} - #[cfg(super_unstable)] impl fmt::Debug for SourceFile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - SourceFile::Nightly(a, _) => a.fmt(f), + SourceFile::Nightly(a) => a.fmt(f), SourceFile::Stable(a) => a.fmt(f), } }
151
dtolnay/proc-macro2
219b1d3d4d73fc645e4dcd8a01e387ee157a6a35
2024-01-18T12:23:20Z
Consider an API to reset thread-local Span data Basically truncate this thing: https://github.com/dtolnay/proc-macro2/blob/fecb02df0e2966c7eb39e020dbf650fa8bafd0c5/src/fallback.rs#L323-L325 Resetting would be a claim that all currently existing non-call-site spans on the current thread are no longer in use, or it's okay if methods like `line`/`column` and `source_text` crash or produce wrong results. A workload that involves parsing all versions of all crates on a thread pool of 64 threads would need this, because otherwise our 32-bit positions would overflow. See https://github.com/dtolnay/proc-macro2/issues/413#issuecomment-1754216797.
dtolnay__proc-macro2-438
Adding such an API would be much appreciated. My workload is similar to what you described in your comment. David, did you already have an API in mind? I'd be happy to file a PR. Also for my understanding: The idea behind the thread-local source map is to avoid a ref on Span to safe bytes? Something like `proc_macro2::invalidate_current_thread_spans()` with a realistic code example. > The idea behind the thread-local source map is to avoid a ref on Span to safe bytes? `Span` needs to be Copy and 'static. I don't know any other way to implement that, regardless of how many bytes big Span is.
[ "414" ]
1edd1b993b79d16f60a85f32a320d9430dfde8a8
diff --git a/tests/test.rs b/tests/test.rs index b75cd55..e80cd19 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -757,3 +757,40 @@ fn byte_order_mark() { let string = "foo\u{feff}"; string.parse::<TokenStream>().unwrap_err(); } + +// Creates a new Span from a TokenStream +#[cfg(all(test, span_locations))] +fn create_span() -> proc_macro2::Span { + let tts: TokenStream = "1".parse().unwrap(); + match tts.into_iter().next().unwrap() { + TokenTree::Literal(literal) => literal.span(), + _ => unreachable!(), + } +} + +#[cfg(span_locations)] +#[test] +fn test_invalidate_current_thread_spans() { + let actual = format!("{:#?}", create_span()); + assert_eq!(actual, "bytes(1..2)"); + let actual = format!("{:#?}", create_span()); + assert_eq!(actual, "bytes(3..4)"); + + proc_macro2::invalidate_current_thread_spans(); + + let actual = format!("{:#?}", create_span()); + // Test that span offsets have been reset after the call + // to invalidate_current_thread_spans() + assert_eq!(actual, "bytes(1..2)"); +} + +#[cfg(span_locations)] +#[test] +#[should_panic] +fn test_use_span_after_invalidation() { + let span = create_span(); + + proc_macro2::invalidate_current_thread_spans(); + + span.source_text(); +}
1.0
diff --git a/src/fallback.rs b/src/fallback.rs index 7b40427..590717e 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -320,17 +320,30 @@ impl Debug for SourceFile { } } +#[cfg(all(span_locations, not(fuzzing)))] +fn dummy_file() -> FileInfo { + FileInfo { + source_text: String::new(), + span: Span { lo: 0, hi: 0 }, + lines: vec![0], + char_index_to_byte_offset: BTreeMap::new(), + } +} + #[cfg(all(span_locations, not(fuzzing)))] thread_local! { static SOURCE_MAP: RefCell<SourceMap> = RefCell::new(SourceMap { // Start with a single dummy file which all call_site() and def_site() // spans reference. - files: vec![FileInfo { - source_text: String::new(), - span: Span { lo: 0, hi: 0 }, - lines: vec![0], - char_index_to_byte_offset: BTreeMap::new(), - }], + files: vec![dummy_file()], + }); +} + +#[cfg(all(span_locations, not(fuzzing)))] +pub fn invalidate_current_thread_spans() { + SOURCE_MAP.with(|sm| { + let mut sm = sm.borrow_mut(); + sm.files = vec![dummy_file()]; }); } diff --git a/src/lib.rs b/src/lib.rs index 233082e..d1d5807 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -170,6 +170,10 @@ use std::error::Error; #[cfg(procmacro2_semver_exempt)] use std::path::PathBuf; +#[cfg(span_locations)] +#[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))] +pub use crate::imp::invalidate_current_thread_spans; + #[cfg(span_locations)] #[cfg_attr(doc_cfg, doc(cfg(feature = "span-locations")))] pub use crate::location::LineColumn; @@ -1325,4 +1329,4 @@ pub mod token_stream { } } } -} +} \ No newline at end of file diff --git a/src/wrapper.rs b/src/wrapper.rs index f5eb826..7598239 100644 --- a/src/wrapper.rs +++ b/src/wrapper.rs @@ -928,3 +928,30 @@ impl Debug for Literal { } } } + +/// Invalidates any `proc_macro2::Span` on the current thread +/// +/// The implementation of the `proc_macro2::Span` type relies on thread-local +/// memory and this function clears it. Calling any method on a +/// `proc_macro2::Span` on the current thread and that was created before this +/// function was called will either lead to incorrect results or abort your +/// program. +/// +/// This function is useful for programs that process more than 2^32 bytes of +/// text on a single thread. The internal representation of `proc_macro2::Span` +/// uses 32-bit integers to represent offsets and those will overflow when +/// processing more than 2^32 bytes. This function resets all offsets +/// and thereby also invalidates any previously created `proc_macro2::Span`. +/// +/// This function requires the `span-locations` feature to be enabled. This +/// function is not applicable to and will panic if called from a procedural macro. +#[cfg(span_locations)] +pub fn invalidate_current_thread_spans() { + if inside_proc_macro() { + panic!( + "proc_macro2::invalidate_current_thread_spans is not available in procedural macros" + ); + } else { + crate::fallback::invalidate_current_thread_spans() + } +}
438
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8
2023-10-09T00:56:29Z
Issue with multibyte chars in source_text() computation It treats `lo` as a byte index, while it is actually a character index: https://github.com/dtolnay/proc-macro2/blob/7f5533d6cc9ff783d174aec4e3be2caa202b62ca/src/fallback.rs#L367 I expect this test to pass, but it does not: ```rust #[cfg(span_locations)] #[test] fn source_text() { let input = " 𓀕 c "; let mut tokens = input .parse::<proc_macro2::TokenStream>() .unwrap() .into_iter(); let ident1 = tokens.next().unwrap(); assert_eq!("𓀕", ident1.span().source_text().unwrap()); let ident2 = tokens.next().unwrap(); assert_eq!("𓀕", ident2.span().source_text().unwrap()); } ``` Panics with (as character `𓀕` occupies byte 5 and 6) ``` ---- source_text stdout ---- thread 'source_text' panicked at 'byte index 6 is not a char boundary; it is inside '𓀕' (bytes 4..8) of ` 𓀕 c `', src/fallback.rs:367:25 ```
dtolnay__proc-macro2-411
[ "410" ]
12eddc03a40e8393e82f7ef1dadbaaabdcb00a08
diff --git a/tests/test.rs b/tests/test.rs index 4a6ca75..1916a85 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -328,10 +328,17 @@ fn literal_span() { #[cfg(span_locations)] #[test] fn source_text() { - let input = " 𓀕 "; - let tokens = input.parse::<proc_macro2::TokenStream>().unwrap(); - let ident = tokens.into_iter().next().unwrap(); + let input = " 𓀕 c "; + let mut tokens = input + .parse::<proc_macro2::TokenStream>() + .unwrap() + .into_iter(); + + let ident = tokens.next().unwrap(); assert_eq!("𓀕", ident.span().source_text().unwrap()); + + let ident = tokens.next().unwrap(); + assert_eq!("c", ident.span().source_text().unwrap()); } #[test]
1.0
diff --git a/src/fallback.rs b/src/fallback.rs index 281b7b2..70deb4b 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -364,7 +364,10 @@ impl FileInfo { fn source_text(&self, span: Span) -> String { let lo = (span.lo - self.span.lo) as usize; - let trunc_lo = &self.source_text[lo..]; + let trunc_lo = match self.source_text.char_indices().nth(lo) { + Some((offset, _ch)) => &self.source_text[offset..], + None => return String::new(), + }; let char_len = (span.hi - span.lo) as usize; let source_text = match trunc_lo.char_indices().nth(char_len) { Some((offset, _ch)) => &trunc_lo[..offset],
411
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8
2023-10-06T04:04:55Z
`Span::source_text` panics with multibyte source ```rust #[test] fn proc_macro2_source_text_is_correct_for_single_byte() { let source_code = "const FOO: () = ();"; let ast = syn::parse_str::<syn::ItemConst>(source_code).unwrap(); assert_eq!("FOO", ast.ident.span().source_text().unwrap()) } #[test] #[should_panic = "is not a char boundary"] fn proc_macro2_source_text_is_incorrect_for_multibyte() { let source_code = "const 𓀕: () = ();"; let ast = syn::parse_str::<syn::ItemConst>(source_code).unwrap(); let reported = ast.ident.span().source_text(); // boom assert_eq!("𓀕", reported.unwrap()) } ``` Note this is just _calling the method_, not unwrapping the `Option`: ``` thread 'tests::proc_macro2_source_text_is_incorrect_for_multibyte' panicked at 'byte index 7 is not a char boundary; it is inside '𓀕' (bytes 6..10) of `const 𓀕: () = ();`', /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:369:9 ... 6: <alloc::string::String as core::ops::index::Index<core::ops::range::Range<usize>>>::index at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/alloc/src/string.rs:2350:10 7: proc_macro2::fallback::FileInfo::source_text at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:369:9 8: proc_macro2::fallback::Span::source_text::{{closure}} at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:569:43 9: std::thread::local::LocalKey<T>::try_with at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/std/src/thread/local.rs:270:16 10: std::thread::local::LocalKey<T>::with at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/std/src/thread/local.rs:246:9 11: proc_macro2::fallback::Span::source_text at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/fallback.rs:569:22 12: proc_macro2::Span::source_text at /home/aatif/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.67/src/lib.rs:522:9 13: synsert::tests::proc_macro2_source_text_is_incorrect_for_multibyte at ./src/lib.rs:165:24 14: synsert::tests::proc_macro2_source_text_is_incorrect_for_multibyte::{{closure}} at ./src/lib.rs:162:61 ... ``` `proc-macro2 1.0.67` (latest) Not called from a `proc-macro` context
dtolnay__proc-macro2-409
[ "408" ]
07bb590e9706c65f4c850f0163ec05333ab636c9
diff --git a/tests/test.rs b/tests/test.rs index 8e47b46..4a6ca75 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -325,6 +325,15 @@ fn literal_span() { assert!(positive.subspan(1..4).is_none()); } +#[cfg(span_locations)] +#[test] +fn source_text() { + let input = " 𓀕 "; + let tokens = input.parse::<proc_macro2::TokenStream>().unwrap(); + let ident = tokens.into_iter().next().unwrap(); + assert_eq!("𓀕", ident.span().source_text().unwrap()); +} + #[test] fn roundtrip() { fn roundtrip(p: &str) {
1.0
diff --git a/src/fallback.rs b/src/fallback.rs index db52959..352b459 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -364,8 +364,13 @@ impl FileInfo { fn source_text(&self, span: Span) -> String { let lo = (span.lo - self.span.lo) as usize; - let hi = (span.hi - self.span.lo) as usize; - self.source_text[lo..hi].to_owned() + let trunc_lo = &self.source_text[lo..]; + let char_len = (span.hi - span.lo) as usize; + let source_text = match trunc_lo.char_indices().nth(char_len) { + Some((offset, _ch)) => &trunc_lo[..offset], + None => trunc_lo, + }; + source_text.to_owned() } }
409
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8
2023-04-03T06:04:06Z
`LitByteStr` produces tokens that trigger `clippy::octal-escapes` Not sure whether to file this here or in `quote`. `LitByteStr::new(&[65, 0], ...)` quotes as `b"a\0"`, which triggers [this default clippy lint](https://rust-lang.github.io/rust-clippy/master/#octal_escapes). Whether that lint should be default is a different question, but it'd be nice if syn output would be clippy clean. This would mean representing `0u8` by `\x00` instead of `\0`.
dtolnay__proc-macro2-380
https://github.com/dtolnay/proc-macro2/blob/master/src/fallback.rs#L932 Actually this only triggers if the `\0` is followed by a digit.
[ "363" ]
c4a3e197f086b9f21880c979f7c87a04808660ac
diff --git a/tests/test.rs b/tests/test.rs index 3f0bfd3c..2bd93e0b 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -1,7 +1,8 @@ #![allow( clippy::assertions_on_result_states, clippy::items_after_statements, - clippy::non_ascii_literal + clippy::non_ascii_literal, + clippy::octal_escapes )] use proc_macro2::{Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; @@ -114,6 +115,11 @@ fn literal_string() { assert_eq!(Literal::string("foo").to_string(), "\"foo\""); assert_eq!(Literal::string("\"").to_string(), "\"\\\"\""); assert_eq!(Literal::string("didn't").to_string(), "\"didn't\""); + + let repr = Literal::string("a\00b\07c\08d\0e\0").to_string(); + if repr != "\"a\\x000b\\x007c\\u{0}8d\\u{0}e\\u{0}\"" { + assert_eq!(repr, "\"a\\x000b\\x007c\\08d\\0e\\0\""); + } } #[test] @@ -147,6 +153,10 @@ fn literal_byte_string() { Literal::byte_string(b"\0\t\n\r\"\\2\x10").to_string(), "b\"\\0\\t\\n\\r\\\"\\\\2\\x10\"", ); + assert_eq!( + Literal::byte_string(b"a\00b\07c\08d\0e\0").to_string(), + "b\"a\\x000b\\x007c\\08d\\0e\\0\"", + ); } #[test]
1.0
diff --git a/src/fallback.rs b/src/fallback.rs index 214843ae..bd5d9dad 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -958,12 +958,20 @@ impl Literal { pub fn string(t: &str) -> Literal { let mut repr = String::with_capacity(t.len() + 2); repr.push('"'); - for c in t.chars() { - if c == '\'' { + let mut chars = t.chars(); + while let Some(ch) = chars.next() { + if ch == '\0' + && chars + .as_str() + .starts_with(|next| '0' <= next && next <= '7') + { + // circumvent clippy::octal_escapes lint + repr.push_str("\\x00"); + } else if ch == '\'' { // escape_debug turns this into "\'" which is unnecessary. - repr.push(c); + repr.push(ch); } else { - repr.extend(c.escape_debug()); + repr.extend(ch.escape_debug()); } } repr.push('"'); @@ -985,16 +993,21 @@ impl Literal { pub fn byte_string(bytes: &[u8]) -> Literal { let mut escaped = "b\"".to_string(); - for b in bytes { + let mut bytes = bytes.iter(); + while let Some(&b) = bytes.next() { #[allow(clippy::match_overlapping_arm)] - match *b { - b'\0' => escaped.push_str(r"\0"), + match b { + b'\0' => escaped.push_str(match bytes.as_slice().first() { + // circumvent clippy::octal_escapes lint + Some(b'0'..=b'7') => r"\x00", + _ => r"\0", + }), b'\t' => escaped.push_str(r"\t"), b'\n' => escaped.push_str(r"\n"), b'\r' => escaped.push_str(r"\r"), b'"' => escaped.push_str("\\\""), b'\\' => escaped.push_str("\\\\"), - b'\x20'..=b'\x7E' => escaped.push(*b as char), + b'\x20'..=b'\x7E' => escaped.push(b as char), _ => { let _ = write!(escaped, "\\x{:02X}", b); }
380
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8
2022-09-29T01:55:02Z
Fails to parse string starting with byte order mark ```rust let string = "\u{feff}foo"; eprintln!("{:?}", string.parse::<TokenStream>()); ``` proc_macro::TokenStream: ```console Ok(TokenStream [Ident { ident: "foo", span: #6 bytes(31..42) }]) ``` proc_macro2::TokenStream: ```console Err(LexError { span: Span }) ```
dtolnay__proc-macro2-354
[ "353" ]
f26128d5d6c94c62ce70683f6f4363766963a256
diff --git a/tests/test.rs b/tests/test.rs index 16f775ed..8f5624db 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -630,3 +630,16 @@ fn check_spans_internal(ts: TokenStream, lines: &mut &[(usize, usize, usize, usi } } } + +#[test] +fn byte_order_mark() { + let string = "\u{feff}foo"; + let tokens = string.parse::<TokenStream>().unwrap(); + match tokens.into_iter().next().unwrap() { + TokenTree::Ident(ident) => assert_eq!(ident, "foo"), + _ => unreachable!(), + } + + let string = "foo\u{feff}"; + string.parse::<TokenStream>().unwrap_err(); +}
1.0
diff --git a/src/fallback.rs b/src/fallback.rs index 4c476e5d..fe4f248d 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -182,7 +182,13 @@ impl FromStr for TokenStream { fn from_str(src: &str) -> Result<TokenStream, LexError> { // Create a dummy file & add it to the source map - let cursor = get_cursor(src); + let mut cursor = get_cursor(src); + + // Strip a byte order mark if present + const BYTE_ORDER_MARK: &str = "\u{feff}"; + if cursor.starts_with(BYTE_ORDER_MARK) { + cursor = cursor.advance(BYTE_ORDER_MARK.len()); + } parse::token_stream(cursor) } diff --git a/src/parse.rs b/src/parse.rs index d2b86a41..04c48336 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -14,7 +14,7 @@ pub(crate) struct Cursor<'a> { } impl<'a> Cursor<'a> { - fn advance(&self, bytes: usize) -> Cursor<'a> { + pub fn advance(&self, bytes: usize) -> Cursor<'a> { let (_front, rest) = self.rest.split_at(bytes); Cursor { rest, @@ -23,7 +23,7 @@ impl<'a> Cursor<'a> { } } - fn starts_with(&self, s: &str) -> bool { + pub fn starts_with(&self, s: &str) -> bool { self.rest.starts_with(s) }
354
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8
2020-09-09T19:39:40Z
proc_macro2::TokenStream doesn't implement UnwindSafe While writing tests for a procedural macro I learned that `proc_macro2::TokenStream` isn't `UnwindSafe`. Since I suspect it is not intentional, I am reporting it here. In my tests I have a function that executes a thunk and asserts that it panicked, something like this: ```rust fn assert_panic(f: impl FnOnce() + std::panic::UnwindSafe) { if std::panic::catch_unwind(f).is_ok() { panic!("panic didn't happen"); } // in real code this also asserts that the panic that occurred matches an // expected message substring } ``` I'd like to test my proc macro with a range of inputs that should all fail, as in this test: ```rust fn macro_impl(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream { todo!() } fn main() { for unsupported_type in &[quote!(i8), quote!(u128), quote!(())] { assert_panic(|| { macro_impl(quote! { struct X { field: #unsupported_type } }); }); } } ``` But the above code fails to compile with the following error ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=42a8b1b8c76936999713cc0baed7610a)): ``` error[E0277]: the type `std::cell::UnsafeCell<usize>` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary --> src/main.rs:18:9 | 4 | fn assert_panic(f: impl FnOnce() + std::panic::UnwindSafe) { | ---------------------- required by this bound in `assert_panic` ... 18 | assert_panic(|| { | ^^^^^^^^^^^^ `std::cell::UnsafeCell<usize>` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary | = help: within `&proc_macro2::TokenStream`, the trait `std::panic::RefUnwindSafe` is not implemented for `std::cell::UnsafeCell<usize>` = note: required because it appears within the type `std::cell::Cell<usize>` = note: required because it appears within the type `std::rc::RcBox<()>` = note: required because it appears within the type `std::marker::PhantomData<std::rc::RcBox<()>>` = note: required because it appears within the type `std::rc::Rc<()>` = note: required because it appears within the type `std::marker::PhantomData<std::rc::Rc<()>>` = note: required because it appears within the type `proc_macro2::TokenStream` = note: required because it appears within the type `&proc_macro2::TokenStream` = note: required because of the requirements on the impl of `std::panic::UnwindSafe` for `&&proc_macro2::TokenStream` = note: required because it appears within the type `[closure@src/main.rs:18:22: 24:10 unsupported_type:&&proc_macro2::TokenStream]` ``` I don't know if this is intentional, but I suspect it might not be. Perhaps `UnsafeCell` is used for efficiency and the type is actually `UnwindSafe`, it just needs the appropriate explicit marker. I worked around the issue by avoiding the capture of `TokenStream`s produced by `quote!` and capturing strings instead ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=51d46dea9a596bd9863a603afb90fb47)): ```rust fn main() { for unsupported_type in &["i8", "u128", "()"] { assert_panic(|| { let unsupported_type: proc_macro2::TokenStream = syn::parse_str(unsupported_type).unwrap(); macro_impl(quote! { struct X { field: #unsupported_type } }); }); } } ``` That works, but the explicit parsing is less readable than `quote!`. If `TokenStream` can be `UnwindSafe`, it would be nice for it to implement the trait.
dtolnay__proc-macro2-251
[ "250" ]
24a41c94ed3096534633d29e21a920b797a012a0
diff --git a/tests/marker.rs b/tests/marker.rs index 7af2539c..70e57677 100644 --- a/tests/marker.rs +++ b/tests/marker.rs @@ -57,3 +57,36 @@ mod semver_exempt { assert_impl!(SourceFile is not Send or Sync); } + +#[cfg(not(no_libprocmacro_unwind_safe))] +mod unwind_safe { + use super::*; + use std::panic::{RefUnwindSafe, UnwindSafe}; + + macro_rules! assert_unwind_safe { + ($($types:ident)*) => { + $( + assert_impl!($types is UnwindSafe and RefUnwindSafe); + )* + }; + } + + assert_unwind_safe! { + Delimiter + Group + Ident + LexError + Literal + Punct + Spacing + Span + TokenStream + TokenTree + } + + #[cfg(procmacro2_semver_exempt)] + assert_unwind_safe! { + LineColumn + SourceFile + } +} diff --git a/tests/ui/test-not-send.stderr b/tests/ui/test-not-send.stderr index 9253c1bf..f1487dd9 100644 --- a/tests/ui/test-not-send.stderr +++ b/tests/ui/test-not-send.stderr @@ -19,5 +19,6 @@ error[E0277]: `Rc<()>` cannot be sent between threads safely | ^^^^^^^^^^^^^^^^^^^^^ `Rc<()>` cannot be sent between threads safely | = help: within `Span`, the trait `Send` is not implemented for `Rc<()>` - = note: required because it appears within the type `PhantomData<Rc<()>>` + = note: required because it appears within the type `proc_macro2::marker::ProcMacroAutoTraits` + = note: required because it appears within the type `PhantomData<proc_macro2::marker::ProcMacroAutoTraits>` = note: required because it appears within the type `Span`
1.0
diff --git a/build.rs b/build.rs index 153e13f5..edc0db7a 100644 --- a/build.rs +++ b/build.rs @@ -61,6 +61,10 @@ fn main() { println!("cargo:rustc-cfg=span_locations"); } + if version.minor < 32 { + println!("cargo:rustc-cfg=no_libprocmacro_unwind_safe"); + } + if version.minor < 39 { println!("cargo:rustc-cfg=no_bind_by_move_pattern_guard"); } diff --git a/src/lib.rs b/src/lib.rs index 5eecdcf1..9abf515f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -86,6 +86,7 @@ #[cfg(use_proc_macro)] extern crate proc_macro; +mod marker; mod parse; #[cfg(wrap_proc_macro)] @@ -102,15 +103,14 @@ use crate::fallback as imp; #[cfg(wrap_proc_macro)] mod imp; +use crate::marker::Marker; use std::cmp::Ordering; use std::fmt::{self, Debug, Display}; use std::hash::{Hash, Hasher}; use std::iter::FromIterator; -use std::marker::PhantomData; use std::ops::RangeBounds; #[cfg(procmacro2_semver_exempt)] use std::path::PathBuf; -use std::rc::Rc; use std::str::FromStr; /// An abstract stream of tokens, or more concretely a sequence of token trees. @@ -123,27 +123,27 @@ use std::str::FromStr; #[derive(Clone)] pub struct TokenStream { inner: imp::TokenStream, - _marker: PhantomData<Rc<()>>, + _marker: Marker, } /// Error returned from `TokenStream::from_str`. pub struct LexError { inner: imp::LexError, - _marker: PhantomData<Rc<()>>, + _marker: Marker, } impl TokenStream { fn _new(inner: imp::TokenStream) -> TokenStream { TokenStream { inner, - _marker: PhantomData, + _marker: Marker, } } fn _new_stable(inner: fallback::TokenStream) -> TokenStream { TokenStream { inner: inner.into(), - _marker: PhantomData, + _marker: Marker, } } @@ -180,7 +180,7 @@ impl FromStr for TokenStream { fn from_str(src: &str) -> Result<TokenStream, LexError> { let e = src.parse().map_err(|e| LexError { inner: e, - _marker: PhantomData, + _marker: Marker, })?; Ok(TokenStream::_new(e)) } @@ -261,7 +261,7 @@ impl Debug for LexError { #[derive(Clone, PartialEq, Eq)] pub struct SourceFile { inner: imp::SourceFile, - _marker: PhantomData<Rc<()>>, + _marker: Marker, } #[cfg(procmacro2_semver_exempt)] @@ -269,7 +269,7 @@ impl SourceFile { fn _new(inner: imp::SourceFile) -> Self { SourceFile { inner, - _marker: PhantomData, + _marker: Marker, } } @@ -338,21 +338,21 @@ impl PartialOrd for LineColumn { #[derive(Copy, Clone)] pub struct Span { inner: imp::Span, - _marker: PhantomData<Rc<()>>, + _marker: Marker, } impl Span { fn _new(inner: imp::Span) -> Span { Span { inner, - _marker: PhantomData, + _marker: Marker, } } fn _new_stable(inner: fallback::Span) -> Span { Span { inner: inner.into(), - _marker: PhantomData, + _marker: Marker, } } @@ -840,14 +840,14 @@ impl Debug for Punct { #[derive(Clone)] pub struct Ident { inner: imp::Ident, - _marker: PhantomData<Rc<()>>, + _marker: Marker, } impl Ident { fn _new(inner: imp::Ident) -> Ident { Ident { inner, - _marker: PhantomData, + _marker: Marker, } } @@ -968,7 +968,7 @@ impl Debug for Ident { #[derive(Clone)] pub struct Literal { inner: imp::Literal, - _marker: PhantomData<Rc<()>>, + _marker: Marker, } macro_rules! suffixed_int_literals { @@ -1015,14 +1015,14 @@ impl Literal { fn _new(inner: imp::Literal) -> Literal { Literal { inner, - _marker: PhantomData, + _marker: Marker, } } fn _new_stable(inner: fallback::Literal) -> Literal { Literal { inner: inner.into(), - _marker: PhantomData, + _marker: Marker, } } @@ -1181,10 +1181,9 @@ impl Display for Literal { /// Public implementation details for the `TokenStream` type, such as iterators. pub mod token_stream { + use crate::marker::Marker; use crate::{imp, TokenTree}; use std::fmt::{self, Debug}; - use std::marker::PhantomData; - use std::rc::Rc; pub use crate::TokenStream; @@ -1195,7 +1194,7 @@ pub mod token_stream { #[derive(Clone)] pub struct IntoIter { inner: imp::TokenTreeIter, - _marker: PhantomData<Rc<()>>, + _marker: Marker, } impl Iterator for IntoIter { @@ -1219,7 +1218,7 @@ pub mod token_stream { fn into_iter(self) -> IntoIter { IntoIter { inner: self.inner.into_iter(), - _marker: PhantomData, + _marker: Marker, } } } diff --git a/src/marker.rs b/src/marker.rs new file mode 100644 index 00000000..58729baf --- /dev/null +++ b/src/marker.rs @@ -0,0 +1,18 @@ +use std::marker::PhantomData; +use std::panic::{RefUnwindSafe, UnwindSafe}; +use std::rc::Rc; + +// Zero sized marker with the correct set of autotrait impls we want all proc +// macro types to have. +pub(crate) type Marker = PhantomData<ProcMacroAutoTraits>; + +pub(crate) use self::value::*; + +mod value { + pub(crate) use std::marker::PhantomData as Marker; +} + +pub(crate) struct ProcMacroAutoTraits(Rc<()>); + +impl UnwindSafe for ProcMacroAutoTraits {} +impl RefUnwindSafe for ProcMacroAutoTraits {}
251
dtolnay/proc-macro2
1edd1b993b79d16f60a85f32a320d9430dfde8a8