| 1 |
//! Implementations of [`fmt`]-like derive macros. |
| 2 |
//! |
| 3 |
//! [`fmt`]: std::fmt |
| 4 |
|
| 5 |
#[cfg(feature = "debug")] |
| 6 |
pub(crate) mod debug; |
| 7 |
#[cfg(feature = "display")] |
| 8 |
pub(crate) mod display; |
| 9 |
mod parsing; |
| 10 |
|
| 11 |
use proc_macro2::TokenStream; |
| 12 |
use quote::ToTokens; |
| 13 |
use syn::{ |
| 14 |
parse::{Parse, ParseStream}, |
| 15 |
punctuated::Punctuated, |
| 16 |
spanned::Spanned as _, |
| 17 |
token, Ident, |
| 18 |
}; |
| 19 |
|
| 20 |
use crate::parsing::Expr; |
| 21 |
|
| 22 |
/// Representation of a macro attribute expressing additional trait bounds. |
| 23 |
#[derive(Debug, Default)] |
| 24 |
struct BoundsAttribute(Punctuated<syn::WherePredicate, syn::token::Comma>); |
| 25 |
|
| 26 |
impl BoundsAttribute { |
| 27 |
/// Errors in case legacy syntax is encountered: `bound = "..."`. |
| 28 |
fn check_legacy_fmt(input: ParseStream<'_>) -> syn::Result<()> { |
| 29 |
let fork = input.fork(); |
| 30 |
|
| 31 |
let path = fork |
| 32 |
.parse::<syn::Path>() |
| 33 |
.and_then(|path| fork.parse::<syn::token::Eq>().map(|_| path)); |
| 34 |
match path { |
| 35 |
Ok(path) if path.is_ident("bound") => fork |
| 36 |
.parse::<syn::Lit>() |
| 37 |
.ok() |
| 38 |
.and_then(|lit| match lit { |
| 39 |
syn::Lit::Str(s) => Some(s.value()), |
| 40 |
_ => None, |
| 41 |
}) |
| 42 |
.map_or(Ok(()), |bound| { |
| 43 |
Err(syn::Error::new( |
| 44 |
input.span(), |
| 45 |
format!("legacy syntax, use `bound({bound})` instead"), |
| 46 |
)) |
| 47 |
}), |
| 48 |
Ok(_) | Err(_) => Ok(()), |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
impl Parse for BoundsAttribute { |
| 54 |
fn parse(input: ParseStream<'_>) -> syn::Result<Self> { |
| 55 |
let _ = input.parse::<syn::Path>().and_then(|p| { |
| 56 |
if ["bound", "bounds", "where"] |
| 57 |
.into_iter() |
| 58 |
.any(|i| p.is_ident(i)) |
| 59 |
{ |
| 60 |
Ok(p) |
| 61 |
} else { |
| 62 |
Err(syn::Error::new( |
| 63 |
p.span(), |
| 64 |
"unknown attribute, expected `bound(...)`", |
| 65 |
)) |
| 66 |
} |
| 67 |
})?; |
| 68 |
|
| 69 |
let content; |
| 70 |
syn::parenthesized!(content in input); |
| 71 |
|
| 72 |
content |
| 73 |
.parse_terminated(syn::WherePredicate::parse, token::Comma) |
| 74 |
.map(Self) |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
/// Representation of a [`fmt`]-like attribute. |
| 79 |
/// |
| 80 |
/// [`fmt`]: std::fmt |
| 81 |
#[derive(Debug)] |
| 82 |
struct FmtAttribute { |
| 83 |
/// Interpolation [`syn::LitStr`]. |
| 84 |
/// |
| 85 |
/// [`syn::LitStr`]: struct@syn::LitStr |
| 86 |
lit: syn::LitStr, |
| 87 |
|
| 88 |
/// Optional [`token::Comma`]. |
| 89 |
comma: Option<token::Comma>, |
| 90 |
|
| 91 |
/// Interpolation arguments. |
| 92 |
args: Punctuated<FmtArgument, token::Comma>, |
| 93 |
} |
| 94 |
|
| 95 |
impl FmtAttribute { |
| 96 |
/// Returns an [`Iterator`] over bounded [`syn::Type`]s and trait names. |
| 97 |
fn bounded_types<'a>( |
| 98 |
&'a self, |
| 99 |
fields: &'a syn::Fields, |
| 100 |
) -> impl Iterator<Item = (&'a syn::Type, &'static str)> { |
| 101 |
let placeholders = Placeholder::parse_fmt_string(&self.lit.value()); |
| 102 |
|
| 103 |
// We ignore unknown fields, as compiler will produce better error messages. |
| 104 |
placeholders.into_iter().filter_map(move |placeholder| { |
| 105 |
let name = match placeholder.arg { |
| 106 |
Parameter::Named(name) => self |
| 107 |
.args |
| 108 |
.iter() |
| 109 |
.find_map(|a| (a.alias()? == &name).then_some(&a.expr)) |
| 110 |
.map_or(Some(name), |expr| expr.ident().map(ToString::to_string))?, |
| 111 |
Parameter::Positional(i) => self |
| 112 |
.args |
| 113 |
.iter() |
| 114 |
.nth(i) |
| 115 |
.and_then(|a| a.expr.ident().filter(|_| a.alias.is_none()))? |
| 116 |
.to_string(), |
| 117 |
}; |
| 118 |
|
| 119 |
let unnamed = name.strip_prefix('_').and_then(|s| s.parse().ok()); |
| 120 |
let ty = match (&fields, unnamed) { |
| 121 |
(syn::Fields::Unnamed(f), Some(i)) => { |
| 122 |
f.unnamed.iter().nth(i).map(|f| &f.ty) |
| 123 |
} |
| 124 |
(syn::Fields::Named(f), None) => f.named.iter().find_map(|f| { |
| 125 |
f.ident.as_ref().filter(|s| **s == name).map(|_| &f.ty) |
| 126 |
}), |
| 127 |
_ => None, |
| 128 |
}?; |
| 129 |
|
| 130 |
Some((ty, placeholder.trait_name)) |
| 131 |
}) |
| 132 |
} |
| 133 |
|
| 134 |
/// Errors in case legacy syntax is encountered: `fmt = "...", (arg),*`. |
| 135 |
fn check_legacy_fmt(input: ParseStream<'_>) -> syn::Result<()> { |
| 136 |
let fork = input.fork(); |
| 137 |
|
| 138 |
let path = fork |
| 139 |
.parse::<syn::Path>() |
| 140 |
.and_then(|path| fork.parse::<syn::token::Eq>().map(|_| path)); |
| 141 |
match path { |
| 142 |
Ok(path) if path.is_ident("fmt") => (|| { |
| 143 |
let args = fork |
| 144 |
.parse_terminated(syn::Lit::parse, token::Comma) |
| 145 |
.ok()? |
| 146 |
.into_iter() |
| 147 |
.enumerate() |
| 148 |
.filter_map(|(i, lit)| match lit { |
| 149 |
syn::Lit::Str(str) => Some(if i == 0 { |
| 150 |
format!("\"{}\"", str.value()) |
| 151 |
} else { |
| 152 |
str.value() |
| 153 |
}), |
| 154 |
_ => None, |
| 155 |
}) |
| 156 |
.collect::<Vec<_>>(); |
| 157 |
(!args.is_empty()).then_some(args) |
| 158 |
})() |
| 159 |
.map_or(Ok(()), |fmt| { |
| 160 |
Err(syn::Error::new( |
| 161 |
input.span(), |
| 162 |
format!( |
| 163 |
"legacy syntax, remove `fmt =` and use `{}` instead", |
| 164 |
fmt.join(", "), |
| 165 |
), |
| 166 |
)) |
| 167 |
}), |
| 168 |
Ok(_) | Err(_) => Ok(()), |
| 169 |
} |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
impl Parse for FmtAttribute { |
| 174 |
fn parse(input: ParseStream) -> syn::Result<Self> { |
| 175 |
Ok(Self { |
| 176 |
lit: input.parse()?, |
| 177 |
comma: input |
| 178 |
.peek(syn::token::Comma) |
| 179 |
.then(|| input.parse()) |
| 180 |
.transpose()?, |
| 181 |
args: input.parse_terminated(FmtArgument::parse, token::Comma)?, |
| 182 |
}) |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
impl ToTokens for FmtAttribute { |
| 187 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 188 |
self.lit.to_tokens(tokens); |
| 189 |
self.comma.to_tokens(tokens); |
| 190 |
self.args.to_tokens(tokens); |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
/// Representation of a [named parameter][1] (`identifier '=' expression`) in |
| 195 |
/// in a [`FmtAttribute`]. |
| 196 |
/// |
| 197 |
/// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#named-parameters |
| 198 |
#[derive(Debug)] |
| 199 |
struct FmtArgument { |
| 200 |
/// `identifier =` [`Ident`]. |
| 201 |
alias: Option<(Ident, token::Eq)>, |
| 202 |
|
| 203 |
/// `expression` [`Expr`]. |
| 204 |
expr: Expr, |
| 205 |
} |
| 206 |
|
| 207 |
impl FmtArgument { |
| 208 |
/// Returns an `identifier` of the [named parameter][1]. |
| 209 |
/// |
| 210 |
/// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#named-parameters |
| 211 |
fn alias(&self) -> Option<&Ident> { |
| 212 |
self.alias.as_ref().map(|(ident, _)| ident) |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
impl Parse for FmtArgument { |
| 217 |
fn parse(input: ParseStream) -> syn::Result<Self> { |
| 218 |
Ok(Self { |
| 219 |
alias: (input.peek(Ident) && input.peek2(token::Eq)) |
| 220 |
.then(|| Ok::<_, syn::Error>((input.parse()?, input.parse()?))) |
| 221 |
.transpose()?, |
| 222 |
expr: input.parse()?, |
| 223 |
}) |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
impl ToTokens for FmtArgument { |
| 228 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 229 |
if let Some((ident, eq)) = &self.alias { |
| 230 |
ident.to_tokens(tokens); |
| 231 |
eq.to_tokens(tokens); |
| 232 |
} |
| 233 |
self.expr.to_tokens(tokens); |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
/// Representation of a [parameter][1] used in a [`Placeholder`]. |
| 238 |
/// |
| 239 |
/// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-parameters |
| 240 |
#[derive(Debug, Eq, PartialEq)] |
| 241 |
enum Parameter { |
| 242 |
/// [Positional parameter][1]. |
| 243 |
/// |
| 244 |
/// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#positional-parameters |
| 245 |
Positional(usize), |
| 246 |
|
| 247 |
/// [Named parameter][1]. |
| 248 |
/// |
| 249 |
/// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#named-parameters |
| 250 |
Named(String), |
| 251 |
} |
| 252 |
|
| 253 |
impl<'a> From<parsing::Argument<'a>> for Parameter { |
| 254 |
fn from(arg: parsing::Argument<'a>) -> Self { |
| 255 |
match arg { |
| 256 |
parsing::Argument::Integer(i) => Self::Positional(i), |
| 257 |
parsing::Argument::Identifier(i) => Self::Named(i.to_owned()), |
| 258 |
} |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
/// Representation of a formatting placeholder. |
| 263 |
#[derive(Debug, PartialEq, Eq)] |
| 264 |
struct Placeholder { |
| 265 |
/// Formatting argument (either named or positional) to be used by this placeholder. |
| 266 |
arg: Parameter, |
| 267 |
|
| 268 |
/// [Width parameter][1], if present. |
| 269 |
/// |
| 270 |
/// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#width |
| 271 |
width: Option<Parameter>, |
| 272 |
|
| 273 |
/// [Precision parameter][1], if present. |
| 274 |
/// |
| 275 |
/// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#precision |
| 276 |
precision: Option<Parameter>, |
| 277 |
|
| 278 |
/// Name of [`std::fmt`] trait to be used for rendering this placeholder. |
| 279 |
trait_name: &'static str, |
| 280 |
} |
| 281 |
|
| 282 |
impl Placeholder { |
| 283 |
/// Parses [`Placeholder`]s from the provided formatting string. |
| 284 |
fn parse_fmt_string(s: &str) -> Vec<Self> { |
| 285 |
let mut n = 0; |
| 286 |
parsing::format_string(s) |
| 287 |
.into_iter() |
| 288 |
.flat_map(|f| f.formats) |
| 289 |
.map(|format| { |
| 290 |
let (maybe_arg, ty) = ( |
| 291 |
format.arg, |
| 292 |
format.spec.map(|s| s.ty).unwrap_or(parsing::Type::Display), |
| 293 |
); |
| 294 |
let position = maybe_arg.map(Into::into).unwrap_or_else(|| { |
| 295 |
// Assign "the next argument". |
| 296 |
// https://doc.rust-lang.org/stable/std/fmt/index.html#positional-parameters |
| 297 |
n += 1; |
| 298 |
Parameter::Positional(n - 1) |
| 299 |
}); |
| 300 |
|
| 301 |
Self { |
| 302 |
arg: position, |
| 303 |
width: format.spec.and_then(|s| match s.width { |
| 304 |
Some(parsing::Count::Parameter(arg)) => Some(arg.into()), |
| 305 |
_ => None, |
| 306 |
}), |
| 307 |
precision: format.spec.and_then(|s| match s.precision { |
| 308 |
Some(parsing::Precision::Count(parsing::Count::Parameter( |
| 309 |
arg, |
| 310 |
))) => Some(arg.into()), |
| 311 |
_ => None, |
| 312 |
}), |
| 313 |
trait_name: ty.trait_name(), |
| 314 |
} |
| 315 |
}) |
| 316 |
.collect() |
| 317 |
} |
| 318 |
} |
| 319 |
|
| 320 |
#[cfg(test)] |
| 321 |
mod fmt_attribute_spec { |
| 322 |
use itertools::Itertools as _; |
| 323 |
use quote::ToTokens; |
| 324 |
use syn; |
| 325 |
|
| 326 |
use super::FmtAttribute; |
| 327 |
|
| 328 |
fn assert<'a>(input: &'a str, parsed: impl AsRef<[&'a str]>) { |
| 329 |
let parsed = parsed.as_ref(); |
| 330 |
let attr = syn::parse_str::<FmtAttribute>(&format!("\"\", {}", input)).unwrap(); |
| 331 |
let fmt_args = attr |
| 332 |
.args |
| 333 |
.into_iter() |
| 334 |
.map(|arg| arg.into_token_stream().to_string()) |
| 335 |
.collect::<Vec<String>>(); |
| 336 |
fmt_args.iter().zip_eq(parsed).enumerate().for_each( |
| 337 |
|(i, (found, expected))| { |
| 338 |
assert_eq!( |
| 339 |
*expected, found, |
| 340 |
"Mismatch at index {i}\n\ |
| 341 |
Expected: {parsed:?}\n\ |
| 342 |
Found: {fmt_args:?}", |
| 343 |
); |
| 344 |
}, |
| 345 |
); |
| 346 |
} |
| 347 |
|
| 348 |
#[test] |
| 349 |
fn cases() { |
| 350 |
let cases = [ |
| 351 |
"ident", |
| 352 |
"alias = ident", |
| 353 |
"[a , b , c , d]", |
| 354 |
"counter += 1", |
| 355 |
"async { fut . await }", |
| 356 |
"a < b", |
| 357 |
"a > b", |
| 358 |
"{ let x = (a , b) ; }", |
| 359 |
"invoke (a , b)", |
| 360 |
"foo as f64", |
| 361 |
"| a , b | a + b", |
| 362 |
"obj . k", |
| 363 |
"for pat in expr { break pat ; }", |
| 364 |
"if expr { true } else { false }", |
| 365 |
"vector [2]", |
| 366 |
"1", |
| 367 |
"\"foo\"", |
| 368 |
"loop { break i ; }", |
| 369 |
"format ! (\"{}\" , q)", |
| 370 |
"match n { Some (n) => { } , None => { } }", |
| 371 |
"x . foo ::< T > (a , b)", |
| 372 |
"x . foo ::< T < [T < T >; if a < b { 1 } else { 2 }] >, { a < b } > (a , b)", |
| 373 |
"(a + b)", |
| 374 |
"i32 :: MAX", |
| 375 |
"1 .. 2", |
| 376 |
"& a", |
| 377 |
"[0u8 ; N]", |
| 378 |
"(a , b , c , d)", |
| 379 |
"< Ty as Trait > :: T", |
| 380 |
"< Ty < Ty < T >, { a < b } > as Trait < T > > :: T", |
| 381 |
]; |
| 382 |
|
| 383 |
assert("", []); |
| 384 |
for i in 1..4 { |
| 385 |
for permutations in cases.into_iter().permutations(i) { |
| 386 |
let mut input = permutations.clone().join(","); |
| 387 |
assert(&input, &permutations); |
| 388 |
input.push(','); |
| 389 |
assert(&input, &permutations); |
| 390 |
} |
| 391 |
} |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
#[cfg(test)] |
| 396 |
mod placeholder_parse_fmt_string_spec { |
| 397 |
use super::{Parameter, Placeholder}; |
| 398 |
|
| 399 |
#[test] |
| 400 |
fn indicates_position_and_trait_name_for_each_fmt_placeholder() { |
| 401 |
let fmt_string = "{},{:?},{{}},{{{1:0$}}}-{2:.1$x}{par:#?}{:width$}"; |
| 402 |
assert_eq!( |
| 403 |
Placeholder::parse_fmt_string(&fmt_string), |
| 404 |
vec![ |
| 405 |
Placeholder { |
| 406 |
arg: Parameter::Positional(0), |
| 407 |
width: None, |
| 408 |
precision: None, |
| 409 |
trait_name: "Display", |
| 410 |
}, |
| 411 |
Placeholder { |
| 412 |
arg: Parameter::Positional(1), |
| 413 |
width: None, |
| 414 |
precision: None, |
| 415 |
trait_name: "Debug", |
| 416 |
}, |
| 417 |
Placeholder { |
| 418 |
arg: Parameter::Positional(1), |
| 419 |
width: Some(Parameter::Positional(0)), |
| 420 |
precision: None, |
| 421 |
trait_name: "Display", |
| 422 |
}, |
| 423 |
Placeholder { |
| 424 |
arg: Parameter::Positional(2), |
| 425 |
width: None, |
| 426 |
precision: Some(Parameter::Positional(1)), |
| 427 |
trait_name: "LowerHex", |
| 428 |
}, |
| 429 |
Placeholder { |
| 430 |
arg: Parameter::Named("par".to_owned()), |
| 431 |
width: None, |
| 432 |
precision: None, |
| 433 |
trait_name: "Debug", |
| 434 |
}, |
| 435 |
Placeholder { |
| 436 |
arg: Parameter::Positional(2), |
| 437 |
width: Some(Parameter::Named("width".to_owned())), |
| 438 |
precision: None, |
| 439 |
trait_name: "Display", |
| 440 |
}, |
| 441 |
], |
| 442 |
); |
| 443 |
} |
| 444 |
} |