| 1 |
/// Module for error rendering stuff |
| 2 |
use std::collections::HashMap; |
| 3 |
|
| 4 |
use proc_macro2::TokenStream; |
| 5 |
use syn::{visit, ItemFn, Pat}; |
| 6 |
use syn::{spanned::Spanned, visit::Visit}; |
| 7 |
|
| 8 |
use crate::parse::{ |
| 9 |
fixture::FixtureInfo, |
| 10 |
rstest::{RsTestData, RsTestInfo}, |
| 11 |
}; |
| 12 |
use crate::parse::arguments::ArgumentsInfo; |
| 13 |
use crate::refident::{MaybeIdent, MaybePat}; |
| 14 |
use crate::utils::attr_is; |
| 15 |
|
| 16 |
use super::utils::fn_args_has_pat; |
| 17 |
|
| 18 |
pub mod messages { |
| 19 |
pub const DESTRUCT_WITHOUT_FROM : &str = "To destruct a fixture you should provide a path to resolve it by '#[from(...)]' attribute."; |
| 20 |
pub fn use_more_than_once(name: &str) -> String { |
| 21 |
format!("You cannot use '{name}' attribute more than once for the same argument") |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
pub(crate) fn rstest(test: &ItemFn, info: &RsTestInfo) -> TokenStream { |
| 26 |
missed_arguments(test, info.data.items.iter()) |
| 27 |
.chain(duplicate_arguments(info.data.items.iter())) |
| 28 |
.chain(invalid_cases(&info.data)) |
| 29 |
.chain(case_args_without_cases(&info.data)) |
| 30 |
.chain(destruct_fixture_without_from(test, info)) |
| 31 |
.chain(test_attributes(test, &info.arguments)) |
| 32 |
.map(|e| e.to_compile_error()) |
| 33 |
.collect() |
| 34 |
} |
| 35 |
|
| 36 |
pub(crate) fn fixture(test: &ItemFn, info: &FixtureInfo) -> TokenStream { |
| 37 |
missed_arguments(test, info.data.items.iter()) |
| 38 |
.chain(duplicate_arguments(info.data.items.iter())) |
| 39 |
.chain(async_once(test, info)) |
| 40 |
.chain(generics_once(test, info)) |
| 41 |
.chain(destruct_fixture_without_from(test, info)) |
| 42 |
.map(|e| e.to_compile_error()) |
| 43 |
.collect() |
| 44 |
} |
| 45 |
|
| 46 |
fn async_once<'a>(test: &'a ItemFn, info: &FixtureInfo) -> Errors<'a> { |
| 47 |
match (test.sig.asyncness, info.arguments.get_once()) { |
| 48 |
(Some(_asyncness), Some(once)) => Box::new(std::iter::once(syn::Error::new_spanned( |
| 49 |
once, |
| 50 |
"Cannot apply #[once] to async fixture.", |
| 51 |
))), |
| 52 |
_ => Box::new(std::iter::empty()), |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
#[derive(Default)] |
| 57 |
struct SearchImpl(bool); |
| 58 |
|
| 59 |
impl<'ast> Visit<'ast> for SearchImpl { |
| 60 |
fn visit_type(&mut self, i: &'ast syn::Type) { |
| 61 |
if self.0 { |
| 62 |
return; |
| 63 |
} |
| 64 |
if let syn::Type::ImplTrait(_) = i { |
| 65 |
self.0 = true |
| 66 |
} |
| 67 |
visit::visit_type(self, i); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
impl SearchImpl { |
| 72 |
fn function_has_some_impl(f: &ItemFn) -> bool { |
| 73 |
let mut s = SearchImpl::default(); |
| 74 |
visit::visit_item_fn(&mut s, f); |
| 75 |
s.0 |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
fn has_some_generics(test: &ItemFn) -> bool { |
| 80 |
!test.sig.generics.params.is_empty() || SearchImpl::function_has_some_impl(test) |
| 81 |
} |
| 82 |
|
| 83 |
fn generics_once<'a>(test: &'a ItemFn, info: &FixtureInfo) -> Errors<'a> { |
| 84 |
match (has_some_generics(test), info.arguments.get_once()) { |
| 85 |
(true, Some(once)) => Box::new(std::iter::once(syn::Error::new_spanned( |
| 86 |
once, |
| 87 |
"Cannot apply #[once] on generic fixture.", |
| 88 |
))), |
| 89 |
_ => Box::new(std::iter::empty()), |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
trait IsImplicitFixture { |
| 94 |
fn is_implicit_fixture(&self, pat: &Pat) -> bool; |
| 95 |
} |
| 96 |
|
| 97 |
impl IsImplicitFixture for FixtureInfo { |
| 98 |
fn is_implicit_fixture(&self, pat: &Pat) -> bool { |
| 99 |
!self.data.fixtures().any(|f| &f.arg == pat) |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
impl IsImplicitFixture for RsTestInfo { |
| 104 |
fn is_implicit_fixture(&self, pat: &Pat) -> bool { |
| 105 |
!self.data.case_args().any(|a| a == pat) |
| 106 |
&& !self.data.list_values().any(|a| &a.arg == pat) |
| 107 |
&& !self.data.fixtures().any(|f| &f.arg == pat) |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
fn destruct_fixture_without_from<'a>( |
| 112 |
function: &'a ItemFn, |
| 113 |
info: &'a impl IsImplicitFixture, |
| 114 |
) -> Errors<'a> { |
| 115 |
Box::new( |
| 116 |
function |
| 117 |
.sig |
| 118 |
.inputs |
| 119 |
.iter() |
| 120 |
.filter_map(|a| a.maybe_pat().map(|p| (a, p))) |
| 121 |
.filter(|&(_, p)| p.maybe_ident().is_none()) |
| 122 |
.filter(|&(_, p)| info.is_implicit_fixture(p)) |
| 123 |
.map(|(a, _)| syn::Error::new_spanned(a, messages::DESTRUCT_WITHOUT_FROM)), |
| 124 |
) |
| 125 |
} |
| 126 |
|
| 127 |
#[derive(Debug, Default)] |
| 128 |
pub struct ErrorsVec(Vec<syn::Error>); |
| 129 |
|
| 130 |
pub(crate) fn _merge_errors<R1, R2>( |
| 131 |
r1: Result<R1, ErrorsVec>, |
| 132 |
r2: Result<R2, ErrorsVec>, |
| 133 |
) -> Result<(R1, R2), ErrorsVec> { |
| 134 |
match (r1, r2) { |
| 135 |
(Ok(r1), Ok(r2)) => Ok((r1, r2)), |
| 136 |
(Ok(_), Err(e)) | (Err(e), Ok(_)) => Err(e), |
| 137 |
(Err(mut e1), Err(mut e2)) => { |
| 138 |
e1.append(&mut e2); |
| 139 |
Err(e1) |
| 140 |
} |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
macro_rules! merge_errors { |
| 145 |
($e:expr) => { |
| 146 |
$e |
| 147 |
}; |
| 148 |
($e:expr, $($es:expr), + $(,)?) => { |
| 149 |
crate::error::_merge_errors($e, merge_errors!($($es),*)) |
| 150 |
}; |
| 151 |
} |
| 152 |
|
| 153 |
macro_rules! composed_tuple { |
| 154 |
($i:ident) => { |
| 155 |
$i |
| 156 |
}; |
| 157 |
($i:ident, $($is:ident), +) => { |
| 158 |
($i, composed_tuple!($($is),*)) |
| 159 |
}; |
| 160 |
} |
| 161 |
|
| 162 |
impl std::ops::Deref for ErrorsVec { |
| 163 |
type Target = Vec<syn::Error>; |
| 164 |
fn deref(&self) -> &Self::Target { |
| 165 |
&self.0 |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
impl std::ops::DerefMut for ErrorsVec { |
| 170 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 171 |
&mut self.0 |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
impl From<syn::Error> for ErrorsVec { |
| 176 |
fn from(errors: syn::Error) -> Self { |
| 177 |
vec![errors].into() |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
impl From<Vec<syn::Error>> for ErrorsVec { |
| 182 |
fn from(errors: Vec<syn::Error>) -> Self { |
| 183 |
Self(errors) |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
impl From<ErrorsVec> for Vec<syn::Error> { |
| 188 |
fn from(v: ErrorsVec) -> Self { |
| 189 |
v.0 |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
impl quote::ToTokens for ErrorsVec { |
| 194 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 195 |
tokens.extend(self.0.iter().map(|e| e.to_compile_error())) |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
impl From<ErrorsVec> for proc_macro::TokenStream { |
| 200 |
fn from(v: ErrorsVec) -> Self { |
| 201 |
use quote::ToTokens; |
| 202 |
v.into_token_stream().into() |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
type Errors<'a> = Box<dyn Iterator<Item = syn::Error> + 'a>; |
| 207 |
|
| 208 |
fn missed_arguments<'a, I: MaybePat + Spanned + 'a>( |
| 209 |
test: &'a ItemFn, |
| 210 |
args: impl Iterator<Item = &'a I> + 'a, |
| 211 |
) -> Errors<'a> { |
| 212 |
Box::new( |
| 213 |
args.filter_map(|it| it.maybe_pat().map(|pat| (it, pat))) |
| 214 |
.filter(move |(_, pat)| !fn_args_has_pat(test, pat)) |
| 215 |
.map(|(missed, pat)| { |
| 216 |
syn::Error::new( |
| 217 |
missed.span(), |
| 218 |
format!( |
| 219 |
"Missed argument: '{}' should be a test function argument.", |
| 220 |
pat.render_type() |
| 221 |
), |
| 222 |
) |
| 223 |
}), |
| 224 |
) |
| 225 |
} |
| 226 |
|
| 227 |
fn duplicate_arguments<'a, I: MaybePat + Spanned + 'a>( |
| 228 |
args: impl Iterator<Item = &'a I> + 'a, |
| 229 |
) -> Errors<'a> { |
| 230 |
let mut used = HashMap::new(); |
| 231 |
Box::new( |
| 232 |
args.filter_map(|it| it.maybe_pat().map(|pat| (it, pat))) |
| 233 |
.filter_map(move |(it, pat)| { |
| 234 |
let is_duplicate = used.contains_key(&pat); |
| 235 |
used.insert(pat, it); |
| 236 |
match is_duplicate { |
| 237 |
true => Some((it, pat)), |
| 238 |
false => None, |
| 239 |
} |
| 240 |
}) |
| 241 |
.map(|(duplicate, pat)| { |
| 242 |
syn::Error::new( |
| 243 |
duplicate.span(), |
| 244 |
format!( |
| 245 |
"Duplicate argument: '{}' is already defined.", |
| 246 |
pat.render_type() |
| 247 |
), |
| 248 |
) |
| 249 |
}), |
| 250 |
) |
| 251 |
} |
| 252 |
|
| 253 |
fn invalid_cases(params: &RsTestData) -> Errors<'_> { |
| 254 |
let n_args = params.case_args().count(); |
| 255 |
Box::new( |
| 256 |
params |
| 257 |
.cases() |
| 258 |
.filter(move |case| case.args.len() != n_args) |
| 259 |
.map(|case| { |
| 260 |
syn::Error::new_spanned( |
| 261 |
case, |
| 262 |
"Wrong case signature: should match the given parameters list.", |
| 263 |
) |
| 264 |
}), |
| 265 |
) |
| 266 |
} |
| 267 |
|
| 268 |
fn case_args_without_cases(params: &RsTestData) -> Errors<'_> { |
| 269 |
if !params.has_cases() { |
| 270 |
return Box::new( |
| 271 |
params |
| 272 |
.case_args() |
| 273 |
.map(|a| syn::Error::new(a.span(), "No cases for this argument.")), |
| 274 |
); |
| 275 |
} |
| 276 |
Box::new(std::iter::empty()) |
| 277 |
} |
| 278 |
|
| 279 |
trait RenderType { |
| 280 |
fn render_type(&self) -> String; |
| 281 |
} |
| 282 |
|
| 283 |
impl RenderType for syn::Pat { |
| 284 |
fn render_type(&self) -> String { |
| 285 |
match self { |
| 286 |
syn::Pat::Ident(ref i) => i.ident.to_string(), |
| 287 |
other => format!("{other:?}"), |
| 288 |
} |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
fn test_attributes<'a>(test: &'a ItemFn, arguments: &'a ArgumentsInfo) -> Errors<'a> { |
| 293 |
Box::new(async_test_without_test_attribute(test, arguments).chain(malformed_explicit_test_attr(test))) |
| 294 |
} |
| 295 |
|
| 296 |
fn async_test_without_test_attribute<'a>(test: &'a ItemFn, arguments: &'a ArgumentsInfo) -> Errors<'a> { |
| 297 |
if test.sig.asyncness.is_some() && arguments.test_attr().is_none() { |
| 298 |
let span = test.sig.ident.span(); |
| 299 |
Box::new(std::iter::once(syn::Error::new(span, "async test requires either explicit `test_attr` or implicit (attribute path ends with `test`)"))) |
| 300 |
} else { |
| 301 |
Box::new(std::iter::empty()) |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
fn malformed_explicit_test_attr(test: &ItemFn) -> Errors<'_> { |
| 306 |
let Some(explicit_test_attr) = test.attrs.iter().find(|attr| attr_is(attr, "test_attr")) else { |
| 307 |
return Box::new(std::iter::empty()); |
| 308 |
}; |
| 309 |
match explicit_test_attr.meta { |
| 310 |
syn::Meta::List(_) => Box::new(std::iter::empty()), |
| 311 |
syn::Meta::Path(_) | syn::Meta::NameValue(_) => { |
| 312 |
Box::new(std::iter::once(syn::Error::new_spanned( |
| 313 |
explicit_test_attr.path(), |
| 314 |
"invalid `test_attr` syntax; should be `#[test_attr(<test attribute>)]`", |
| 315 |
))) |
| 316 |
} |
| 317 |
} |
| 318 |
} |
| 319 |
|
| 320 |
#[cfg(test)] |
| 321 |
mod test { |
| 322 |
use crate::{ |
| 323 |
parse::ExtendWithFunctionAttrs, |
| 324 |
test::{assert_eq, *}, |
| 325 |
}; |
| 326 |
use rstest_test::assert_in; |
| 327 |
|
| 328 |
use super::*; |
| 329 |
|
| 330 |
#[rstest] |
| 331 |
#[case::generics("fn f<G: SomeTrait>(){}")] |
| 332 |
#[case::const_generics("fn f<const N: usize>(){}")] |
| 333 |
#[case::lifetimes("fn f<'a>(){}")] |
| 334 |
#[case::use_impl_in_answer("fn f() -> impl Iterator<Item=u32>{}")] |
| 335 |
#[case::use_impl_in_arguments("fn f(it: impl Iterator<Item=u32>){}")] |
| 336 |
#[should_panic] |
| 337 |
#[case::sanity_check_with_no_generics("fn f() {}")] |
| 338 |
fn generics_once_should_return_error(#[case] f: &str) { |
| 339 |
let f: ItemFn = f.ast(); |
| 340 |
let info = FixtureInfo::default().with_once(); |
| 341 |
|
| 342 |
let errors = generics_once(&f, &info); |
| 343 |
|
| 344 |
let out = errors |
| 345 |
.map(|e| format!("{:?}", e)) |
| 346 |
.collect::<Vec<_>>() |
| 347 |
.join("-----------------------\n"); |
| 348 |
|
| 349 |
assert_in!(out, "Cannot apply #[once] on generic fixture."); |
| 350 |
} |
| 351 |
|
| 352 |
#[rstest] |
| 353 |
#[case::generics("fn f<G: SomeTrait>(){}")] |
| 354 |
#[case::const_generics("fn f<const N: usize>(){}")] |
| 355 |
#[case::lifetimes("fn f<'a>(){}")] |
| 356 |
#[case::use_impl_in_answer("fn f() -> impl Iterator<Item=u32>{}")] |
| 357 |
#[case::use_impl_in_arguments("fn f(it: impl Iterator<Item=u32>){}")] |
| 358 |
fn generics_once_should_not_return_if_no_once(#[case] f: &str) { |
| 359 |
let f: ItemFn = f.ast(); |
| 360 |
let info = FixtureInfo::default(); |
| 361 |
|
| 362 |
let errors = generics_once(&f, &info); |
| 363 |
|
| 364 |
assert_eq!(0, errors.count()); |
| 365 |
} |
| 366 |
|
| 367 |
#[rstest] |
| 368 |
#[case::base_in_fixture("fn f(T{a}: T){}", FixtureInfo::default(), 1)] |
| 369 |
#[case::one_of_two("fn f(T{a}: T, #[from(f)] T{a: c}: T){}", FixtureInfo::default(), 1)] |
| 370 |
#[case::find_all( |
| 371 |
"fn f(T{a}: T, z: u32, S(a,b): S, x: u32, (f , g, h): (u32, String, f32)){}", |
| 372 |
FixtureInfo::default(), |
| 373 |
3 |
| 374 |
)] |
| 375 |
#[case::base_in_test("fn f(T{a}: T){}", RsTestInfo::default(), 1)] |
| 376 |
#[case::not_case_or_values( |
| 377 |
"fn f(#[case] T{a}: T, #[values(T::a(),T::b())] T{v}: T, S{e}: S){}", |
| 378 |
RsTestInfo::default(), |
| 379 |
1 |
| 380 |
)] |
| 381 |
#[case::mixed_more( |
| 382 |
r#"fn wrong_destruct_fixture( |
| 383 |
T(a, b): T, |
| 384 |
#[case] T(e, f): T, |
| 385 |
#[values(T(1, 2))] T(g, h): T, |
| 386 |
) {}"#, |
| 387 |
RsTestInfo::default(), |
| 388 |
1 |
| 389 |
)] |
| 390 |
fn destruct_implicit_from_should_return_error( |
| 391 |
#[case] f: &str, |
| 392 |
#[case] mut info: impl ExtendWithFunctionAttrs + IsImplicitFixture, |
| 393 |
#[case] n: usize, |
| 394 |
) { |
| 395 |
let mut f: ItemFn = f.ast(); |
| 396 |
|
| 397 |
info.extend_with_function_attrs(&mut f).unwrap(); |
| 398 |
|
| 399 |
let errors = destruct_fixture_without_from(&f, &info); |
| 400 |
|
| 401 |
let out = errors |
| 402 |
.map(|e| format!("{:?}", e)) |
| 403 |
.collect::<Vec<_>>() |
| 404 |
.join("\n"); |
| 405 |
|
| 406 |
assert_in!(out, messages::DESTRUCT_WITHOUT_FROM); |
| 407 |
assert_eq!(n, out.lines().count()) |
| 408 |
} |
| 409 |
|
| 410 |
#[rstest] |
| 411 |
#[case::happy_fixture("fn f(#[from(b)] T{a}: T){}", FixtureInfo::default())] |
| 412 |
#[case::happy_test("fn f(#[from(b)] T{a}: T){}", RsTestInfo::default())] |
| 413 |
#[case::some_cases_or_values( |
| 414 |
"fn f(#[case] T{a}: T, #[values(T::a(),T::b())] T{v}: T){}", |
| 415 |
RsTestInfo::default() |
| 416 |
)] |
| 417 |
fn destruct_not_implicit_should_not_return_error( |
| 418 |
#[case] f: &str, |
| 419 |
#[case] mut info: impl ExtendWithFunctionAttrs + IsImplicitFixture, |
| 420 |
) { |
| 421 |
let mut f: ItemFn = f.ast(); |
| 422 |
|
| 423 |
info.extend_with_function_attrs(&mut f).unwrap(); |
| 424 |
|
| 425 |
let errors = destruct_fixture_without_from(&f, &info); |
| 426 |
|
| 427 |
assert_eq!(0, errors.count()); |
| 428 |
} |
| 429 |
} |