1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
// Copyright (c) 2018-2022 Jeremy Davis (jeremydavis519@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (located at /LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0), or the MIT license
// (located at /LICENSE-MIT or http://opensource.org/licenses/MIT), at your
// option. The file may not be copied, modified, or distributed except
// according to those terms.
//
// Unless required by applicable law or agreed to in writing, this software
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the applicable license for the
// specific language governing permissions and limitations under that license.
//! This crate offers a way to emulate the process of procedural macro expansion at run time.
//! It is intended for use with code coverage tools like [`tarpaulin`], which can't measure
//! the code coverage of anything that happens at compile time.
//!
//! Currently, `runtime-macros` only works with `functionlike!` procedural macros. Custom
//! derive may be supported in the future if there's demand.
//!
//! [`tarpaulin`]: https://crates.io/crates/cargo-tarpaulin
//!
//! To use it, add a test case to your procedural macro crate that calls `emulate_macro_expansion`
//! on a `.rs` file that calls the macro. Most likely, all the files you'll want to use it on will
//! be in your `/tests` directory. Once you've completed this step, any code coverage tool that
//! works with your crate's test cases will be able to report on how thoroughly you've tested the
//! macro.
//!
//! See the `/examples` directory in the [repository] for working examples.
//!
//! [repository]: https://github.com/jeremydavis519/runtime-macros
extern crate proc_macro;
extern crate quote;
extern crate syn;
use {
quote::ToTokens,
std::{
fs,
io::Read,
panic::{self, AssertUnwindSafe},
},
};
/// Searches the given Rust source code file for function-like macro calls and calls the functions
/// that define how to expand them.
///
/// Each time it finds one, this function calls the corresponding procedural macro function, passing
/// it the inner `TokenStream` just as if the macro were being expanded. The only effect is to
/// verify that the macro doesn't panic, as the expansion is not actually applied to the AST or the
/// source code.
///
/// Note that this parser only handles Rust's syntax, so it cannot resolve paths to see if they
/// are equivalent to the given one. The paths used to reference the macro must be exactly equal
/// to the one given in order to be expanded by this function. For example, if `macro_path` is
/// `"foo"` and the file provided calls the macro using `bar::foo!`, this function will not know
/// to expand it, and the macro's code coverage will be underestimated.
///
/// Also, this function uses `proc_macro2::TokenStream`, not the standard `proc_macro::TokenStream`.
/// The Rust compiler disallows using the `proc_macro` API for anything except defining a procedural
/// macro (i.e. we can't use it at runtime). You can convert between the two types using their
/// `into` methods, as shown below.
///
/// # Returns
///
/// `Ok` on success, or an instance of [`Error`] indicating any error that occurred when trying to
/// read or parse the file.
///
/// [`Error`]: enum.Error.html
///
/// # Example
///
/// ```
/// # use runtime_macros::emulate_functionlike_macro_expansion;
///
/// # /*
/// #[proc_macro]
/// fn remove(ts: proc_macro::TokenStream) -> proc_macro::TokenStream {
/// // This stub just allows us to use `proc_macro2` instead of `proc_macro`.
/// remove_internal(ts.into()).into()
/// }
/// # */
///
/// fn remove_internal(_: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
/// // This macro just eats its input and replaces it with nothing.
/// proc_macro2::TokenStream::new()
/// }
///
/// # /*
/// #[test]
/// # */
/// fn macro_code_coverage() {
/// # /*
/// let file = std::fs::File::open("tests/tests.rs").unwrap();
/// # */
/// # let file = std::fs::File::open(concat!(env!("CARGO_MANIFEST_DIR"), "/src/lib.rs")).unwrap();
/// emulate_functionlike_macro_expansion(file, &[("remove", remove_internal)]).unwrap();
/// }
/// # macro_code_coverage();
/// ```
pub fn emulate_functionlike_macro_expansion<'a, F>(
mut file: fs::File,
macro_paths_and_proc_macro_fns: &[(&'a str, F)],
) -> Result<(), Error>
where
F: Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream,
{
struct MacroVisitor<'a, F: Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream> {
macro_paths_and_proc_macro_fns: AssertUnwindSafe<Vec<(syn::Path, &'a F)>>,
}
impl<'a, 'ast, F> syn::visit::Visit<'ast> for MacroVisitor<'a, F>
where
F: Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream,
{
fn visit_macro(&mut self, macro_item: &'ast syn::Macro) {
for (path, proc_macro_fn) in self.macro_paths_and_proc_macro_fns.iter() {
if macro_item.path == *path {
proc_macro_fn(macro_item.tokens.clone().into());
}
}
}
}
let mut content = String::new();
file.read_to_string(&mut content)
.map_err(|e| Error::IoError(e))?;
let ast =
AssertUnwindSafe(syn::parse_file(content.as_str()).map_err(|e| Error::ParseError(e))?);
let macro_paths_and_proc_macro_fns = AssertUnwindSafe(
macro_paths_and_proc_macro_fns
.iter()
.map(|(s, f)| Ok((syn::parse_str(s)?, f)))
.collect::<Result<Vec<(syn::Path, &F)>, _>>()
.map_err(|e| Error::ParseError(e))?,
);
panic::catch_unwind(|| {
syn::visit::visit_file(
&mut MacroVisitor::<F> {
macro_paths_and_proc_macro_fns,
},
&*ast,
);
})
.map_err(|_| {
Error::ParseError(syn::parse::Error::new(
proc_macro2::Span::call_site().into(),
"macro expansion panicked",
))
})?;
Ok(())
}
/// Searches the given Rust source code file for derive macro calls and calls the functions that
/// define how to expand them.
///
/// This function behaves just like [`emulate_functionlike_macro_expansion`], but with derive macros
/// like `#[derive(Foo)]` instead of function-like macros like `foo!()`. See that function's
/// documentation for details and an example of use.
///
/// [`emulate_functionlike_macro_expansion`]: fn.emulate_functionlike_macro_expansion.html
pub fn emulate_derive_macro_expansion<'a, F>(
mut file: fs::File,
macro_paths_and_proc_macro_fns: &[(&'a str, F)],
) -> Result<(), Error>
where
F: Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream,
{
struct MacroVisitor<'a, F: Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream> {
macro_paths_and_proc_macro_fns: AssertUnwindSafe<Vec<(syn::Path, &'a F)>>,
}
impl<'a, 'ast, F> syn::visit::Visit<'ast> for MacroVisitor<'a, F>
where
F: Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream,
{
fn visit_item(&mut self, item: &'ast syn::Item) {
macro_rules! visit {
( $($ident:ident),* ) => {
match *item {
$(syn::Item::$ident(ref item) => {
for attr in item.attrs.iter() {
let meta = match &attr.meta {
syn::Meta::List(list) => list,
_ => continue
};
match meta.path.get_ident() {
Some(x) => {
if x != "derive" {
continue;
}
},
None => continue
}
match meta.parse_nested_meta(|meta| {
for (path, proc_macro_fn) in self.macro_paths_and_proc_macro_fns.iter() {
if meta.path == *path {
proc_macro_fn(/* attributes? */ item.to_token_stream());
}
}
Ok(())
}) {
Ok(_) => {},
Err(err) => panic!("Error parsing nested meta: {}", err),
};
}
},)*
_ => {}
}
}
}
visit!(
Const,
Enum,
ExternCrate,
Fn,
ForeignMod,
Impl,
Macro,
Mod,
Static,
Struct,
Trait,
TraitAlias,
Type,
Union,
Use
);
}
}
let mut content = String::new();
file.read_to_string(&mut content)
.map_err(|e| Error::IoError(e))?;
let ast =
AssertUnwindSafe(syn::parse_file(content.as_str()).map_err(|e| Error::ParseError(e))?);
let macro_paths_and_proc_macro_fns = AssertUnwindSafe(
macro_paths_and_proc_macro_fns
.iter()
.map(|(s, f)| Ok((syn::parse_str(s)?, f)))
.collect::<Result<Vec<(syn::Path, &F)>, _>>()
.map_err(|e| Error::ParseError(e))?,
);
panic::catch_unwind(|| {
syn::visit::visit_file(
&mut MacroVisitor::<F> {
macro_paths_and_proc_macro_fns,
},
&*ast,
);
})
.map_err(|_| {
Error::ParseError(syn::parse::Error::new(
proc_macro2::Span::call_site().into(),
"macro expansion panicked",
))
})?;
Ok(())
}
/// Searches the given Rust source code file for attribute-like macro calls and calls the functions
/// that define how to expand them.
///
/// This function behaves just like [`emulate_functionlike_macro_expansion`], but with attribute-like
/// macros like `#[foo]` instead of function-like macros like `foo!()`. See that function's
/// documentation for details and an example of use.
///
/// [`emulate_functionlike_macro_expansion`]: fn.emulate_functionlike_macro_expansion.html
pub fn emulate_attributelike_macro_expansion<'a, F>(
mut file: fs::File,
macro_paths_and_proc_macro_fns: &[(&'a str, F)],
) -> Result<(), Error>
where
F: Fn(proc_macro2::TokenStream, proc_macro2::TokenStream) -> proc_macro2::TokenStream,
{
struct MacroVisitor<
'a,
F: Fn(proc_macro2::TokenStream, proc_macro2::TokenStream) -> proc_macro2::TokenStream,
> {
macro_paths_and_proc_macro_fns: AssertUnwindSafe<Vec<(syn::Path, &'a F)>>,
}
impl<'a, 'ast, F> syn::visit::Visit<'ast> for MacroVisitor<'a, F>
where
F: Fn(proc_macro2::TokenStream, proc_macro2::TokenStream) -> proc_macro2::TokenStream,
{
fn visit_item(&mut self, item: &'ast syn::Item) {
macro_rules! visit {
( $($ident:ident),* ) => {
match *item {
$(syn::Item::$ident(ref item) => {
for attr in item.attrs.iter() {
let meta = match &attr.meta {
syn::Meta::List(list) => list,
_ => continue
};
for (path, proc_macro_fn) in self.macro_paths_and_proc_macro_fns.iter() {
if meta.path == *path {
proc_macro_fn(meta.tokens.clone().into(), item.to_token_stream());
}
}
}
},)*
_ => {}
}
}
}
visit!(
Const,
Enum,
ExternCrate,
Fn,
ForeignMod,
Impl,
Macro,
Mod,
Static,
Struct,
Trait,
TraitAlias,
Type,
Union,
Use
);
}
}
let mut content = String::new();
file.read_to_string(&mut content)
.map_err(|e| Error::IoError(e))?;
let ast =
AssertUnwindSafe(syn::parse_file(content.as_str()).map_err(|e| Error::ParseError(e))?);
let macro_paths_and_proc_macro_fns = AssertUnwindSafe(
macro_paths_and_proc_macro_fns
.iter()
.map(|(s, f)| Ok((syn::parse_str(s)?, f)))
.collect::<Result<Vec<(syn::Path, &F)>, _>>()
.map_err(|e| Error::ParseError(e))?,
);
panic::catch_unwind(|| {
syn::visit::visit_file(
&mut MacroVisitor::<F> {
macro_paths_and_proc_macro_fns,
},
&*ast,
);
})
.map_err(|_| {
Error::ParseError(syn::parse::Error::new(
proc_macro2::Span::call_site().into(),
"macro expansion panicked",
))
})?;
Ok(())
}
/// The error type for `emulate_*_macro_expansion`. If anything goes wrong during the file loading
/// or macro expansion, this type describes it.
#[derive(Debug)]
pub enum Error {
IoError(std::io::Error),
ParseError(syn::parse::Error),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::IoError(e) => e.fmt(f),
Error::ParseError(e) => e.fmt(f),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::IoError(e) => e.source(),
Error::ParseError(e) => e.source(),
}
}
}
#[cfg(test)]
mod tests {
extern crate cargo_tarpaulin;
use self::cargo_tarpaulin::config::Config;
use self::cargo_tarpaulin::launch_tarpaulin;
use std::panic;
use std::{env, time};
#[test]
fn proc_macro_coverage() {
// All the tests are in this one function so they'll run sequentially. Something about how
// Tarpaulin works seems to dislike having two instances running in parallel.
{
// Function-like
let mut config = Config::default();
let test_dir = env::current_dir()
.unwrap()
.join("examples")
.join("custom_assert");
config.set_manifest(test_dir.join("Cargo.toml"));
config.test_timeout = time::Duration::from_secs(60);
let (_trace_map, return_code) = launch_tarpaulin(&config, &None).unwrap();
assert_eq!(return_code, 0);
}
{
// Attribute-like
let mut config = Config::default();
let test_dir = env::current_dir()
.unwrap()
.join("examples")
.join("reference_counting");
config.set_manifest(test_dir.join("Cargo.toml"));
config.test_timeout = time::Duration::from_secs(60);
let (_trace_map, return_code) = match launch_tarpaulin(&config, &None) {
Ok(ret) => ret,
Err(err) => panic!("{}", err),
};
assert_eq!(return_code, 0);
}
}
}