| 1 |
use once_cell::sync::Lazy; |
| 2 |
|
| 3 |
use darling::util::Override; |
| 4 |
use darling::{FromField, FromMeta}; |
| 5 |
|
| 6 |
use proc_macro_error2::abort; |
| 7 |
use quote::quote; |
| 8 |
use syn::spanned::Spanned; |
| 9 |
use syn::{Expr, Field, Ident, Path}; |
| 10 |
|
| 11 |
use crate::utils::{get_attr, CrateName}; |
| 12 |
|
| 13 |
static OPTIONS_TYPE: [&str; 3] = ["Option|", "std|option|Option|", "core|option|Option|"]; |
| 14 |
|
| 15 |
pub(crate) static NUMBER_TYPES: Lazy<Vec<String>> = Lazy::new(|| { |
| 16 |
let number_types = [ |
| 17 |
quote!(usize), |
| 18 |
quote!(u8), |
| 19 |
quote!(u16), |
| 20 |
quote!(u32), |
| 21 |
quote!(u64), |
| 22 |
quote!(u128), |
| 23 |
quote!(isize), |
| 24 |
quote!(i8), |
| 25 |
quote!(i16), |
| 26 |
quote!(i32), |
| 27 |
quote!(i64), |
| 28 |
quote!(i128), |
| 29 |
quote!(f32), |
| 30 |
quote!(f64), |
| 31 |
]; |
| 32 |
let mut tys = Vec::with_capacity(number_types.len() * 3); |
| 33 |
for ty in number_types { |
| 34 |
tys.push(ty.to_string()); |
| 35 |
tys.push(quote!(Option<#ty>).to_string()); |
| 36 |
tys.push(quote!(Option<Option<#ty> >).to_string()); |
| 37 |
} |
| 38 |
tys |
| 39 |
}); |
| 40 |
|
| 41 |
// This struct holds all the validation information on a field |
| 42 |
// The "ident" and "ty" fields are populated by `darling` |
| 43 |
// The others are our attributes for example: |
| 44 |
// #[validate(email(message = "asdfg"))] |
| 45 |
// ^^^^^ |
| 46 |
// |
| 47 |
|
| 48 |
#[derive(Debug, FromField, Clone)] |
| 49 |
#[darling(attributes(validate))] |
| 50 |
pub struct ValidateField { |
| 51 |
pub ident: Option<syn::Ident>, |
| 52 |
pub ty: syn::Type, |
| 53 |
// pub attrs: Vec<syn::Attribute>, |
| 54 |
pub credit_card: Option<Override<Card>>, |
| 55 |
pub contains: Option<Contains>, |
| 56 |
pub does_not_contain: Option<DoesNotContain>, |
| 57 |
pub email: Option<Override<Email>>, |
| 58 |
pub ip: Option<Override<Ip>>, |
| 59 |
pub length: Option<Length>, |
| 60 |
pub must_match: Option<MustMatch>, |
| 61 |
pub non_control_character: Option<Override<NonControlCharacter>>, |
| 62 |
pub range: Option<Range>, |
| 63 |
pub required: Option<Override<Required>>, |
| 64 |
pub url: Option<Override<Url>>, |
| 65 |
pub regex: Option<Regex>, |
| 66 |
#[darling(multiple)] |
| 67 |
pub custom: Vec<Custom>, |
| 68 |
pub skip: Option<bool>, |
| 69 |
pub nested: Option<bool>, |
| 70 |
/// Placeholder for the crate name, filled in by the [`ValidationData`](crate::ValidationData) value. |
| 71 |
#[darling(skip)] |
| 72 |
pub crate_name: CrateName, |
| 73 |
} |
| 74 |
|
| 75 |
impl ValidateField { |
| 76 |
pub fn validate(&self, struct_ident: &Ident, all_fields: &[&Field], current_field: &Field) { |
| 77 |
let field_name = self.ident.clone().expect("Field is not a named field").to_string(); |
| 78 |
let field_attrs = ¤t_field.attrs; |
| 79 |
for attr in field_attrs { |
| 80 |
if attr.path().is_ident("validate") && matches!(attr.meta, syn::Meta::Path(_)) { |
| 81 |
abort!( |
| 82 |
current_field.span(), "You need to set at least one validator on field `{}`", field_name; |
| 83 |
note = "If you want nested validation, use `#[validate(nested)]`" |
| 84 |
) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
for c in &self.custom { |
| 89 |
// If function is not a path |
| 90 |
if let Err(e) = &c.function { |
| 91 |
abort!( |
| 92 |
e.span(), "Invalid attribute #[validate(custom(...))] on field `{}`:", field_name; |
| 93 |
note = "Invalid argument for `custom` validator, only paths are allowed"; |
| 94 |
help = "Try formating the argument like `path::to::function` or `\"path::to::function\"`" |
| 95 |
); |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
if let Some(length) = &self.length { |
| 100 |
// If length has both `equal` and `min` or `max` argument |
| 101 |
if length.equal.is_some() && (length.min.is_some() || length.max.is_some()) { |
| 102 |
abort! { |
| 103 |
length.equal.clone().unwrap().span(), "Invalid attribute #[validate(length(...))] on field `{}`:", field_name; |
| 104 |
note = "Both `equal` and `min` or `max` have been set"; |
| 105 |
help = "Exclusively use either the `equal` or `min` and `max` attributes" |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
// Check if validator has no arguments |
| 110 |
if length.equal.is_none() && length.min.is_none() && length.max.is_none() { |
| 111 |
abort!( |
| 112 |
get_attr(field_attrs, "length").unwrap(), "Invalid attribute #[validate(length(...))] on field `{}`:", field_name; |
| 113 |
note = "Validator `length` requires at least 1 argument"; |
| 114 |
help = "Add the argument `equal`, `min` or `max`" |
| 115 |
) |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
if let Some(must_match) = &self.must_match { |
| 120 |
let other_field = must_match |
| 121 |
.other |
| 122 |
.get_ident() |
| 123 |
.expect("Cannot get ident from `other` field value") |
| 124 |
.to_string(); |
| 125 |
|
| 126 |
// Check if the other field exists |
| 127 |
if !all_fields.iter().any(|f| f.ident.clone().unwrap() == other_field) { |
| 128 |
abort!( |
| 129 |
must_match.other.span(), "Invalid attribute for #[validate(must_match(...))] on field `{}`:", field_name; |
| 130 |
note = "The `other` field doesn't exist in the struct `{}`", struct_ident; |
| 131 |
help = "Add the field `{}` to the struct", other_field |
| 132 |
) |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
if let Some(range) = &self.range { |
| 137 |
// Check if validator has no arguments |
| 138 |
if range.min.is_none() |
| 139 |
&& range.max.is_none() |
| 140 |
&& range.exclusive_min.is_none() |
| 141 |
&& range.exclusive_max.is_none() |
| 142 |
{ |
| 143 |
abort!( |
| 144 |
get_attr(field_attrs, "range").unwrap(), "Invalid attribute #[validate(range(...))] on field `{}`:", field_name; |
| 145 |
note = "Validator `range` requires at least 1 argument"; |
| 146 |
help = "Add the argument `min` or `max`, `exclusive_min` or `exclusive_max`" |
| 147 |
) |
| 148 |
} |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
/// How many Option<Option< are there before the actual field |
| 153 |
pub fn number_options(&self) -> u8 { |
| 154 |
fn find_option(mut count: u8, ty: &syn::Type) -> u8 { |
| 155 |
if let syn::Type::Path(p) = ty { |
| 156 |
let idents_of_path = |
| 157 |
p.path.segments.iter().into_iter().fold(String::new(), |mut acc, v| { |
| 158 |
acc.push_str(&v.ident.to_string()); |
| 159 |
acc.push('|'); |
| 160 |
acc |
| 161 |
}); |
| 162 |
|
| 163 |
if OPTIONS_TYPE.contains(&idents_of_path.as_str()) { |
| 164 |
count += 1; |
| 165 |
if let Some(p) = p.path.segments.first() { |
| 166 |
if let syn::PathArguments::AngleBracketed(ref params) = p.arguments { |
| 167 |
if let syn::GenericArgument::Type(ref ty) = params.args.first().unwrap() |
| 168 |
{ |
| 169 |
count = find_option(count, ty); |
| 170 |
} |
| 171 |
} |
| 172 |
} |
| 173 |
} |
| 174 |
} |
| 175 |
count |
| 176 |
} |
| 177 |
|
| 178 |
find_option(0, &self.ty) |
| 179 |
} |
| 180 |
|
| 181 |
pub fn if_let_option_wrapper( |
| 182 |
&self, |
| 183 |
field_name: &Ident, |
| 184 |
is_number_type: bool, |
| 185 |
) -> (proc_macro2::TokenStream, Box<dyn Fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream>) |
| 186 |
{ |
| 187 |
let number_options = self.number_options(); |
| 188 |
let field_name = field_name.clone(); |
| 189 |
let actual_field = |
| 190 |
if number_options > 0 { quote!(#field_name) } else { quote!(self.#field_name) }; |
| 191 |
let binding_pattern = |
| 192 |
if is_number_type { quote!(#field_name) } else { quote!(ref #field_name) }; |
| 193 |
|
| 194 |
match number_options { |
| 195 |
0 => (actual_field.clone(), Box::new(move |tokens| tokens)), |
| 196 |
1 => ( |
| 197 |
actual_field.clone(), |
| 198 |
Box::new(move |tokens| { |
| 199 |
quote!( |
| 200 |
if let Some(#binding_pattern) = self.#field_name { |
| 201 |
#tokens |
| 202 |
} |
| 203 |
) |
| 204 |
}), |
| 205 |
), |
| 206 |
2 => ( |
| 207 |
actual_field.clone(), |
| 208 |
Box::new(move |tokens| { |
| 209 |
quote!( |
| 210 |
if let Some(Some(#binding_pattern)) = self.#field_name { |
| 211 |
#tokens |
| 212 |
} |
| 213 |
) |
| 214 |
}), |
| 215 |
), |
| 216 |
_ => abort!( |
| 217 |
field_name.span(), |
| 218 |
"Validation on values nested in more than 2 Option are not supported" |
| 219 |
), |
| 220 |
} |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
// Structs to hold the validation information and to provide attributes |
| 225 |
// The name of a field here corresponds to an attribute like |
| 226 |
// #[validate(card(message = "something's wrong", code = "1234"))] |
| 227 |
// ^^^^^^^ ^^^^ |
| 228 |
// |
| 229 |
#[derive(Debug, Clone, FromMeta, Default)] |
| 230 |
pub struct Card { |
| 231 |
pub message: Option<String>, |
| 232 |
pub code: Option<String>, |
| 233 |
} |
| 234 |
|
| 235 |
#[derive(Debug, Clone, FromMeta)] |
| 236 |
pub struct Contains { |
| 237 |
pub pattern: String, |
| 238 |
pub message: Option<String>, |
| 239 |
pub code: Option<String>, |
| 240 |
} |
| 241 |
|
| 242 |
#[derive(Debug, Clone, FromMeta)] |
| 243 |
pub struct DoesNotContain { |
| 244 |
pub pattern: String, |
| 245 |
pub message: Option<String>, |
| 246 |
pub code: Option<String>, |
| 247 |
} |
| 248 |
|
| 249 |
#[derive(Debug, Clone, FromMeta, Default)] |
| 250 |
pub struct Email { |
| 251 |
pub message: Option<String>, |
| 252 |
pub code: Option<String>, |
| 253 |
} |
| 254 |
|
| 255 |
#[derive(Debug, Clone, FromMeta, Default)] |
| 256 |
pub struct Ip { |
| 257 |
pub v4: Option<bool>, |
| 258 |
pub v6: Option<bool>, |
| 259 |
pub message: Option<String>, |
| 260 |
pub code: Option<String>, |
| 261 |
} |
| 262 |
|
| 263 |
#[derive(Debug, Clone, FromMeta)] |
| 264 |
pub struct Length { |
| 265 |
pub min: Option<Expr>, |
| 266 |
pub max: Option<Expr>, |
| 267 |
pub equal: Option<Expr>, |
| 268 |
pub message: Option<String>, |
| 269 |
pub code: Option<String>, |
| 270 |
} |
| 271 |
|
| 272 |
#[derive(Debug, Clone, FromMeta)] |
| 273 |
pub struct MustMatch { |
| 274 |
pub other: Path, |
| 275 |
pub message: Option<String>, |
| 276 |
pub code: Option<String>, |
| 277 |
} |
| 278 |
|
| 279 |
#[derive(Debug, Clone, FromMeta, Default)] |
| 280 |
pub struct NonControlCharacter { |
| 281 |
pub message: Option<String>, |
| 282 |
pub code: Option<String>, |
| 283 |
} |
| 284 |
|
| 285 |
#[derive(Debug, Clone, FromMeta)] |
| 286 |
pub struct Range { |
| 287 |
pub min: Option<Expr>, |
| 288 |
pub max: Option<Expr>, |
| 289 |
pub exclusive_min: Option<Expr>, |
| 290 |
pub exclusive_max: Option<Expr>, |
| 291 |
pub message: Option<String>, |
| 292 |
pub code: Option<String>, |
| 293 |
} |
| 294 |
|
| 295 |
#[derive(Debug, Clone, FromMeta, Default)] |
| 296 |
pub struct Required { |
| 297 |
pub message: Option<String>, |
| 298 |
pub code: Option<String>, |
| 299 |
} |
| 300 |
|
| 301 |
#[derive(Debug, Clone, FromMeta, Default)] |
| 302 |
pub struct Url { |
| 303 |
pub message: Option<String>, |
| 304 |
pub code: Option<String>, |
| 305 |
} |
| 306 |
|
| 307 |
#[derive(Debug, Clone, FromMeta)] |
| 308 |
pub struct Regex { |
| 309 |
pub path: Expr, |
| 310 |
pub message: Option<String>, |
| 311 |
pub code: Option<String>, |
| 312 |
} |
| 313 |
|
| 314 |
#[derive(Debug, Clone, FromMeta)] |
| 315 |
pub struct Custom { |
| 316 |
pub function: darling::Result<Path>, |
| 317 |
pub use_context: Option<bool>, |
| 318 |
pub message: Option<String>, |
| 319 |
pub code: Option<String>, |
| 320 |
} |
| 321 |
|
| 322 |
#[derive(Debug, Clone, FromMeta)] |
| 323 |
pub struct Schema { |
| 324 |
pub function: Path, |
| 325 |
pub use_context: Option<bool>, |
| 326 |
pub skip_on_field_errors: Option<bool>, |
| 327 |
pub message: Option<String>, |
| 328 |
pub code: Option<String>, |
| 329 |
} |