juniper_codegen/common/field/arg.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
//! Common functions, definitions and extensions for parsing and code generation
//! of [GraphQL arguments][1]
//!
//! [1]: https://spec.graphql.org/October2021#sec-Language.Arguments.
use std::mem;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
ext::IdentExt as _,
parse::{Parse, ParseStream},
spanned::Spanned,
token,
};
use crate::common::{
default, diagnostic, filter_attrs,
parse::{
attr::{err, OptionExt as _},
ParseBufferExt as _, TypeExt as _,
},
path_eq_single, rename, scalar, Description, SpanContainer,
};
/// Available metadata (arguments) behind `#[graphql]` attribute placed on a
/// method argument, when generating code for [GraphQL argument][1].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
#[derive(Debug, Default)]
pub(crate) struct Attr {
/// Explicitly specified name of a [GraphQL argument][1] represented by this
/// method argument.
///
/// If [`None`], then `camelCased` Rust argument name is used by default.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
pub(crate) name: Option<SpanContainer<syn::LitStr>>,
/// Explicitly specified [description][2] of this [GraphQL argument][1].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
/// [2]: https://spec.graphql.org/October2021#sec-Descriptions
pub(crate) description: Option<SpanContainer<Description>>,
/// Explicitly specified [default value][2] of this [GraphQL argument][1].
///
/// If [`None`], then this [GraphQL argument][1] is considered as
/// [required][2].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
/// [2]: https://spec.graphql.org/October2021#sec-Required-Arguments
pub(crate) default: Option<SpanContainer<default::Value>>,
/// Explicitly specified marker indicating that this method argument doesn't
/// represent a [GraphQL argument][1], but is a [`Context`] being injected
/// into a [GraphQL field][2] resolving function.
///
/// If absent, then the method argument still is considered as [`Context`]
/// if it's named `context` or `ctx`.
///
/// [`Context`]: juniper::Context
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
/// [2]: https://spec.graphql.org/October2021#sec-Language.Fields
pub(crate) context: Option<SpanContainer<syn::Ident>>,
/// Explicitly specified marker indicating that this method argument doesn't
/// represent a [GraphQL argument][1], but is an [`Executor`] being injected
/// into a [GraphQL field][2] resolving function.
///
/// If absent, then the method argument still is considered as [`Executor`]
/// if it's named `executor`.
///
/// [`Executor`]: juniper::Executor
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
/// [2]: https://spec.graphql.org/October2021#sec-Language.Fields
pub(crate) executor: Option<SpanContainer<syn::Ident>>,
}
impl Parse for Attr {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let mut out = Self::default();
while !input.is_empty() {
let ident = input.parse::<syn::Ident>()?;
match ident.to_string().as_str() {
"name" => {
input.parse::<token::Eq>()?;
let name = input.parse::<syn::LitStr>()?;
out.name
.replace(SpanContainer::new(ident.span(), Some(name.span()), name))
.none_or_else(|_| err::dup_arg(&ident))?
}
"desc" | "description" => {
input.parse::<token::Eq>()?;
let desc = input.parse::<Description>()?;
out.description
.replace(SpanContainer::new(ident.span(), Some(desc.span()), desc))
.none_or_else(|_| err::dup_arg(&ident))?
}
"default" => {
let val = input.parse::<default::Value>()?;
out.default
.replace(SpanContainer::new(ident.span(), Some(val.span()), val))
.none_or_else(|_| err::dup_arg(&ident))?
}
"ctx" | "context" | "Context" => {
let span = ident.span();
out.context
.replace(SpanContainer::new(span, Some(span), ident))
.none_or_else(|_| err::dup_arg(span))?
}
"exec" | "executor" => {
let span = ident.span();
out.executor
.replace(SpanContainer::new(span, Some(span), ident))
.none_or_else(|_| err::dup_arg(span))?
}
name => {
return Err(err::unknown_arg(&ident, name));
}
}
input.try_parse::<token::Comma>()?;
}
Ok(out)
}
}
impl Attr {
/// Tries to merge two [`Attr`]s into a single one, reporting about
/// duplicates, if any.
fn try_merge(self, mut another: Self) -> syn::Result<Self> {
Ok(Self {
name: try_merge_opt!(name: self, another),
description: try_merge_opt!(description: self, another),
default: try_merge_opt!(default: self, another),
context: try_merge_opt!(context: self, another),
executor: try_merge_opt!(executor: self, another),
})
}
/// Parses [`Attr`] from the given multiple `name`d [`syn::Attribute`]s
/// placed on a function argument.
pub(crate) fn from_attrs(name: &str, attrs: &[syn::Attribute]) -> syn::Result<Self> {
let attr = filter_attrs(name, attrs)
.map(|attr| attr.parse_args())
.try_fold(Self::default(), |prev, curr| prev.try_merge(curr?))?;
if let Some(context) = &attr.context {
if attr.name.is_some()
|| attr.description.is_some()
|| attr.default.is_some()
|| attr.executor.is_some()
{
return Err(syn::Error::new(
context.span(),
"`context` attribute argument is not composable with any other arguments",
));
}
}
if let Some(executor) = &attr.executor {
if attr.name.is_some()
|| attr.description.is_some()
|| attr.default.is_some()
|| attr.context.is_some()
{
return Err(syn::Error::new(
executor.span(),
"`executor` attribute argument is not composable with any other arguments",
));
}
}
Ok(attr)
}
/// Checks whether this [`Attr`] doesn't contain arguments related to an
/// [`OnField`] argument.
fn ensure_no_regular_arguments(&self) -> syn::Result<()> {
if let Some(span) = &self.name {
return Err(Self::err_disallowed(&span, "name"));
}
if let Some(span) = &self.description {
return Err(Self::err_disallowed(&span, "description"));
}
if let Some(span) = &self.default {
return Err(Self::err_disallowed(&span, "default"));
}
Ok(())
}
/// Emits "argument is not allowed" [`syn::Error`] for the given `arg`
/// pointing to the given `span`.
#[must_use]
fn err_disallowed<S: Spanned>(span: &S, arg: &str) -> syn::Error {
syn::Error::new(
span.span(),
format!("attribute argument `#[graphql({arg} = ...)]` is not allowed here",),
)
}
}
/// Representation of a [GraphQL field argument][1] for code generation.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
#[derive(Debug)]
pub(crate) struct OnField {
/// Rust type that this [GraphQL field argument][1] is represented by.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
pub(crate) ty: syn::Type,
/// Name of this [GraphQL field argument][2] in GraphQL schema.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
pub(crate) name: String,
/// [Description][2] of this [GraphQL field argument][1] to put into GraphQL
/// schema.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
/// [2]: https://spec.graphql.org/October2021#sec-Descriptions
pub(crate) description: Option<Description>,
/// Default value of this [GraphQL field argument][1] in GraphQL schema.
///
/// If [`None`], then this [argument][1] is a [required][2] one.
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
/// [2]: https://spec.graphql.org/October2021#sec-Required-Arguments
pub(crate) default: Option<default::Value>,
}
/// Possible kinds of Rust method arguments for code generation.
#[derive(Debug)]
pub(crate) enum OnMethod {
/// Regular [GraphQL field argument][1].
///
/// [1]: https://spec.graphql.org/October2021#sec-Language.Arguments
Regular(Box<OnField>),
/// [`Context`] passed into a [GraphQL field][2] resolving method.
///
/// [`Context`]: juniper::Context
/// [2]: https://spec.graphql.org/October2021#sec-Language.Fields
Context(Box<syn::Type>),
/// [`Executor`] passed into a [GraphQL field][2] resolving method.
///
/// [`Executor`]: juniper::Executor
/// [2]: https://spec.graphql.org/October2021#sec-Language.Fields
Executor,
}
impl OnMethod {
/// Returns this argument as the one [`OnField`], if it represents the one.
#[must_use]
pub(crate) fn as_regular(&self) -> Option<&OnField> {
if let Self::Regular(arg) = self {
Some(&**arg)
} else {
None
}
}
/// Returns [`syn::Type`] of this [`OnMethod::Context`], if it represents
/// the one.
#[must_use]
pub(crate) fn context_ty(&self) -> Option<&syn::Type> {
if let Self::Context(ty) = self {
Some(&**ty)
} else {
None
}
}
/// Returns generated code for the [`marker::IsOutputType::mark`] method,
/// which performs static checks for this argument, if it represents an
/// [`OnField`] one.
///
/// [`marker::IsOutputType::mark`]: juniper::marker::IsOutputType::mark
#[must_use]
pub(crate) fn method_mark_tokens(&self, scalar: &scalar::Type) -> Option<TokenStream> {
let ty = &self.as_regular()?.ty;
Some(quote_spanned! { ty.span() =>
<#ty as ::juniper::marker::IsInputType<#scalar>>::mark();
})
}
/// Returns generated code for the [`GraphQLType::meta`] method, which
/// registers this argument in [`Registry`], if it represents an [`OnField`]
/// argument.
///
/// [`GraphQLType::meta`]: juniper::GraphQLType::meta
/// [`Registry`]: juniper::Registry
#[must_use]
pub(crate) fn method_meta_tokens(&self) -> Option<TokenStream> {
let arg = self.as_regular()?;
let (name, ty) = (&arg.name, &arg.ty);
let description = &arg.description;
let method = if let Some(val) = &arg.default {
quote_spanned! { val.span() =>
.arg_with_default::<#ty>(#name, &#val, info)
}
} else {
quote! { .arg::<#ty>(#name, info) }
};
Some(quote! { .argument(registry #method #description) })
}
/// Returns generated code for the [`GraphQLValue::resolve_field`] method,
/// which provides the value of this [`OnMethod`] argument to be passed into
/// a trait method call.
///
/// [`GraphQLValue::resolve_field`]: juniper::GraphQLValue::resolve_field
#[must_use]
pub(crate) fn method_resolve_field_tokens(
&self,
scalar: &scalar::Type,
for_async: bool,
) -> TokenStream {
match self {
Self::Regular(arg) => {
let (name, ty) = (&arg.name, &arg.ty);
let err_text = format!("Missing argument `{name}`: {{}}");
let arg = quote! {
args.get::<#ty>(#name).and_then(|opt| opt.map_or_else(|| {
<#ty as ::juniper::FromInputValue<#scalar>>::from_implicit_null()
.map_err(|e| {
::juniper::IntoFieldError::<#scalar>::into_field_error(e)
.map_message(|m| format!(#err_text, m))
})
}, ::core::result::Result::Ok))
};
if for_async {
quote! {
match #arg {
::core::result::Result::Ok(v) => v,
::core::result::Result::Err(e) => return ::std::boxed::Box::pin(async {
::core::result::Result::Err(e)
}),
}
}
} else {
quote! { #arg? }
}
}
Self::Context(_) => quote! {
::juniper::FromContext::from(executor.context())
},
Self::Executor => quote! { &executor },
}
}
/// Parses an [`OnMethod`] argument from the given Rust method argument
/// definition.
///
/// Returns [`None`] if parsing fails and emits parsing errors into the
/// given `scope`.
pub(crate) fn parse(
argument: &mut syn::PatType,
renaming: &rename::Policy,
scope: &diagnostic::Scope,
) -> Option<Self> {
let orig_attrs = argument.attrs.clone();
// Remove repeated attributes from the method, to omit incorrect expansion.
argument.attrs = mem::take(&mut argument.attrs)
.into_iter()
.filter(|attr| !path_eq_single(attr.path(), "graphql"))
.collect();
let attr = Attr::from_attrs("graphql", &orig_attrs)
.map_err(diagnostic::emit_error)
.ok()?;
if attr.context.is_some() {
return Some(Self::Context(Box::new(argument.ty.unreferenced().clone())));
}
if attr.executor.is_some() {
return Some(Self::Executor);
}
if let syn::Pat::Ident(name) = &*argument.pat {
let arg = match name.ident.unraw().to_string().as_str() {
"context" | "ctx" | "_context" | "_ctx" => {
Some(Self::Context(Box::new(argument.ty.unreferenced().clone())))
}
"executor" | "_executor" => Some(Self::Executor),
_ => None,
};
if arg.is_some() {
attr.ensure_no_regular_arguments()
.map_err(|e| scope.error(&e).emit())
.ok()?;
return arg;
}
}
let name = if let Some(name) = attr.name.as_ref() {
name.as_ref().value()
} else if let syn::Pat::Ident(name) = &*argument.pat {
renaming.apply(&name.ident.unraw().to_string())
} else {
scope
.custom(
argument.pat.span(),
"method argument should be declared as a single identifier",
)
.note(String::from(
"use `#[graphql(name = ...)]` attribute to specify custom argument's \
name without requiring it being a single identifier",
))
.emit();
return None;
};
if name.starts_with("__") {
scope.no_double_underscore(
attr.name
.as_ref()
.map(SpanContainer::span_ident)
.unwrap_or_else(|| argument.pat.span()),
);
return None;
}
Some(Self::Regular(Box::new(OnField {
name,
ty: argument.ty.as_ref().clone(),
description: attr.description.map(SpanContainer::into_inner),
default: attr.default.map(SpanContainer::into_inner),
})))
}
}