Skip to content

Improved compiler errors when feature flags are missing #123

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 6 additions & 4 deletions garde/Cargo.toml
Original file line number Diff line number Diff line change
@@ -23,13 +23,15 @@ full = [
"unicode",
]

# NOTE: When adding new feature flags for validation rules you will likely want to add the corresponding
# feature flag in garde_derive to give better compiler error messages.
serde = ["dep:serde", "compact_str/serde", "smallvec/serde"]
derive = ["dep:garde_derive"]
url = ["dep:url"]
url = ["dep:url", "garde_derive?/url"]
unicode = ["dep:unicode-segmentation"]
credit-card = ["dep:card-validate"]
phone-number = ["dep:phonenumber"]
email = ["regex"]
credit-card = ["dep:card-validate", "garde_derive?/credit-card"]
phone-number = ["dep:phonenumber", "garde_derive?/phone-number"]
email = ["regex", "garde_derive?/email"]
email-idna = ["dep:idna"]
regex = ["dep:regex", "dep:once_cell", "garde_derive?/regex"]
pattern = ["regex"] # for backward compatibility with <0.14.0
5 changes: 5 additions & 0 deletions garde_derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -13,7 +13,12 @@ readme = "../README.md"
proc-macro = true

[features]
# NOTE: When adding new validation rule feature flags, don't forget to add checking to `src/syntax.rs`
regex = ["dep:regex"]
email = []
url = []
credit-card = []
phone-number = []

[dependencies]
syn = { version = "2", features = ["full", "derive"] }
35 changes: 35 additions & 0 deletions garde_derive/src/syntax.rs
Original file line number Diff line number Diff line change
@@ -271,6 +271,41 @@ impl Parse for model::RawRule {
};
}

macro_rules! error_if_missing_feature {
($rule:expr, $feature:expr) => {
#[cfg(not(feature = $feature))]
return Err(syn::Error::new(
ident.span(),
concat!(
"Validation rule `",
$rule,
"` not found. Did you forget to add the `",
$feature,
"` feature flag?"
),
));
};
}

match ident.to_string().as_str() {
"email" => {
error_if_missing_feature!("email", "email");
}
"url" => {
error_if_missing_feature!("url", "url");
}
"credit_card" => {
error_if_missing_feature!("credit_card", "credit-card");
}
"phone_number" => {
error_if_missing_feature!("phone_number", "phone-number");
}
"regex" => {
error_if_missing_feature!("regex", "regex");
}
_ => {}
}

rules! {
(input, ident) {
"skip" => Skip,