Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert usize into Exprs, add option to rename context #65

Merged
merged 3 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion garde/tests/rules/byte_length.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use super::util;

const UWU: usize = 101;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pain

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HEY we need some tests and I'm not good with naming stuff


#[derive(Debug, garde::Validate)]
struct Test<'a> {
#[garde(byte_length(min = 10, max = 100))]
#[garde(byte_length(min = 10, max = UWU - 1))]
field: &'a str,

#[garde(inner(length(min = 10, max = 100)))]
Expand Down
75 changes: 66 additions & 9 deletions garde_derive/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use syn::parse_quote;
use syn::spanned::Spanned;

use crate::model;
use crate::util::MaybeFoldError;
use crate::util::{default_ctx_name, MaybeFoldError};

pub fn check(input: model::Input) -> syn::Result<model::Validate> {
let model::Input {
Expand All @@ -25,7 +25,7 @@ pub fn check(input: model::Input) -> syn::Result<model::Validate> {
Ok(v) => v,
Err(e) => {
error.maybe_fold(e);
parse_quote!(())
(parse_quote!(()), default_ctx_name())
}
};

Expand Down Expand Up @@ -92,15 +92,15 @@ fn check_attrs(attrs: &[(Span, model::Attr)]) -> syn::Result<()> {
}
}

fn get_context(attrs: &[(Span, model::Attr)]) -> syn::Result<syn::Type> {
fn get_context(attrs: &[(Span, model::Attr)]) -> syn::Result<(syn::Type, syn::Ident)> {
#![allow(clippy::single_match)]

let error = None;
let mut context = None;

for (_, attr) in attrs {
match attr {
model::Attr::Context(ty) => context = Some(ty),
model::Attr::Context(ty, ident) => context = Some((ty, ident)),
_ => {}
}
}
Expand All @@ -110,8 +110,8 @@ fn get_context(attrs: &[(Span, model::Attr)]) -> syn::Result<syn::Type> {
}

match context {
Some(v) => Ok((**v).clone()),
None => Ok(parse_quote!(())),
Some((ty, id)) => Ok(((**ty).clone(), (*id).clone())),
None => Ok((parse_quote!(()), default_ctx_name())),
}
}

Expand All @@ -122,7 +122,7 @@ fn get_options(attrs: &[(Span, model::Attr)]) -> model::Options {

for (_, attr) in attrs {
match attr {
model::Attr::Context(_) => {}
model::Attr::Context(..) => {}
model::Attr::AllowUnvalidated => options.allow_unvalidated = true,
}
}
Expand Down Expand Up @@ -307,8 +307,8 @@ fn check_rule(
IpV6 => apply!(rule_set, IpV6(), span),
CreditCard => apply!(rule_set, CreditCard(), span),
PhoneNumber => apply!(rule_set, PhoneNumber(), span),
Length(v) => apply!(rule_set, Length(check_range(v)?), span),
ByteLength(v) => apply!(rule_set, ByteLength(check_range(v)?), span),
Length(v) => apply!(rule_set, Length(check_range_generic(v)?), span),
ByteLength(v) => apply!(rule_set, ByteLength(check_range_generic(v)?), span),
Range(v) => apply!(rule_set, Range(check_range_not_ord(v)?), span),
Contains(v) => apply!(rule_set, Contains(v), span),
Prefix(v) => apply!(rule_set, Prefix(v), span),
Expand Down Expand Up @@ -339,6 +339,63 @@ trait CheckRange: Sized {
fn check_range(self) -> syn::Result<model::ValidateRange<Self>>;
}

fn check_range_generic<L, R>(
range: model::Range<model::Either<L, R>>,
) -> syn::Result<model::ValidateRange<model::Either<L, R>>>
where
L: PartialOrd,
{
macro_rules! map_validate_range {
($value:expr, $wrapper:expr) => {{
match $value {
model::ValidateRange::GreaterThan(v) => {
model::ValidateRange::GreaterThan($wrapper(v))
}
model::ValidateRange::LowerThan(v) => model::ValidateRange::LowerThan($wrapper(v)),
model::ValidateRange::Between(v1, v2) => {
model::ValidateRange::Between($wrapper(v1), $wrapper(v2))
}
}
}};
}

let range = match (range.span, range.min, range.max) {
(span, Some(model::Either::Left(min)), Some(model::Either::Left(max))) => {
map_validate_range!(
check_range(model::Range {
span,
min: Some(min),
max: Some(max)
})?,
model::Either::Left
)
}
(span, Some(model::Either::Left(min)), None) => {
map_validate_range!(
check_range(model::Range {
span,
min: Some(min),
max: None,
})?,
model::Either::Left
)
}
(span, None, Some(model::Either::Left(max))) => {
map_validate_range!(
check_range(model::Range {
span,
min: None,
max: Some(max),
})?,
model::Either::Left
)
}
(span, min, max) => check_range_not_ord(model::Range { span, min, max })?,
};

Ok(range)
}

fn check_range<T>(range: model::Range<T>) -> syn::Result<model::ValidateRange<T>>
where
T: PartialOrd,
Expand Down
6 changes: 4 additions & 2 deletions garde_derive/src/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn emit(input: model::Validate) -> TokenStream2 {
impl ToTokens for model::Validate {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let ident = &self.ident;
let context_ty = &self.context;
let (context_ty, context_ident) = &self.context;
let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
let kind = &self.kind;

Expand All @@ -22,7 +22,9 @@ impl ToTokens for model::Validate {
type Context = #context_ty ;

#[allow(clippy::needless_borrow)]
fn validate(&self, __garde_user_ctx: &Self::Context) -> ::core::result::Result<(), ::garde::error::Errors> {
fn validate(&self, #context_ident: &Self::Context) -> ::core::result::Result<(), ::garde::error::Errors> {
let __garde_user_ctx = &#context_ident;

(
#kind
)
Expand Down
32 changes: 25 additions & 7 deletions garde_derive/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct Input {

#[repr(u8)]
pub enum Attr {
Context(Box<Type>),
Context(Box<Type>, Ident),
AllowUnvalidated,
}

Expand All @@ -27,7 +27,7 @@ impl Attr {

pub fn name(&self) -> &'static str {
match self {
Attr::Context(_) => "context",
Attr::Context(..) => "context",
Attr::AllowUnvalidated => "allow_unvalidated",
}
}
Expand Down Expand Up @@ -100,8 +100,8 @@ pub enum RawRuleKind {
IpV6,
CreditCard,
PhoneNumber,
Length(Range<usize>),
ByteLength(Range<usize>),
Length(Range<Either<usize, Expr>>),
ByteLength(Range<Either<usize, Expr>>),
Range(Range<Expr>),
Contains(Expr),
Prefix(Expr),
Expand All @@ -111,6 +111,24 @@ pub enum RawRuleKind {
Inner(List<RawRule>),
}

pub enum Either<L, R> {
Left(L),
Right(R),
}

impl<L, R> quote::ToTokens for Either<L, R>
where
L: quote::ToTokens,
R: quote::ToTokens,
{
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
match self {
Self::Left(left) => left.to_tokens(tokens),
Self::Right(right) => right.to_tokens(tokens),
}
}
}

pub enum Pattern {
Lit(Str),
Expr(Expr),
Expand All @@ -135,7 +153,7 @@ pub struct List<T> {
pub struct Validate {
pub ident: Ident,
pub generics: Generics,
pub context: Type,
pub context: (Type, Ident),
pub kind: ValidateKind,
pub options: Options,
}
Expand Down Expand Up @@ -211,8 +229,8 @@ pub enum ValidateRule {
IpV6,
CreditCard,
PhoneNumber,
Length(ValidateRange<usize>),
ByteLength(ValidateRange<usize>),
Length(ValidateRange<Either<usize, Expr>>),
ByteLength(ValidateRange<Either<usize, Expr>>),
Range(ValidateRange<Expr>),
Contains(Expr),
Prefix(Expr),
Expand Down
29 changes: 26 additions & 3 deletions garde_derive/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ use syn::ext::IdentExt;
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::As;
use syn::{DeriveInput, Token, Type};

use crate::model;
use crate::model::List;
use crate::util::MaybeFoldError;
use crate::util::{default_ctx_name, MaybeFoldError};

pub fn parse(input: DeriveInput) -> syn::Result<model::Input> {
let mut error = None;
Expand Down Expand Up @@ -90,7 +91,13 @@ impl Parse for model::Attr {
let content;
syn::parenthesized!(content in input);
let ty = content.parse::<Type>()?;
Ok(model::Attr::Context(Box::new(ty)))
let ident = if content.parse::<As>().is_ok() {
content.parse()?
} else {
default_ctx_name()
};

Ok(model::Attr::Context(Box::new(ty), ident))
}
"allow_unvalidated" => Ok(model::Attr::AllowUnvalidated),
_ => Err(syn::Error::new(ident.span(), "unrecognized attribute")),
Expand Down Expand Up @@ -383,7 +390,11 @@ where
}
}

Ok(model::Range { span, min, max })
if let Some(error) = error {
Err(error)
} else {
Ok(model::Range { span, min, max })
}
}
}

Expand All @@ -404,6 +415,18 @@ trait FromExpr: Sized {
fn from_expr(v: syn::Expr) -> syn::Result<Self>;
}

impl<L, R> FromExpr for model::Either<L, R>
where
L: FromExpr,
R: FromExpr,
{
fn from_expr(v: syn::Expr) -> syn::Result<Self> {
L::from_expr(v.clone())
.map(model::Either::Left)
.or_else(|_| R::from_expr(v).map(model::Either::Right))
}
}

impl FromExpr for syn::Expr {
fn from_expr(v: syn::Expr) -> syn::Result<Self> {
Ok(v)
Expand Down
4 changes: 4 additions & 0 deletions garde_derive/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@ impl MaybeFoldError for Option<syn::Error> {
}
}
}

pub fn default_ctx_name() -> syn::Ident {
syn::Ident::new("__garde_user_ctx", proc_macro2::Span::call_site())
}