apollo_smith/
variable.rs

1use crate::directive::Directive;
2use crate::directive::DirectiveLocation;
3use crate::input_value::Constness;
4use crate::input_value::InputValue;
5use crate::name::Name;
6use crate::ty::Ty;
7use crate::DocumentBuilder;
8use apollo_compiler::ast;
9use apollo_compiler::Node;
10use arbitrary::Result as ArbitraryResult;
11use indexmap::IndexMap;
12
13/// The __variableDef type represents a variable definition
14///
15/// *VariableDefinition*:
16///     VariableName : Type DefaultValue? Directives?
17///
18/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/October2021/#sec-Language.Variables).
19#[derive(Debug, Clone)]
20pub struct VariableDef {
21    name: Name,
22    ty: Ty,
23    default_value: Option<InputValue>,
24    directives: IndexMap<Name, Directive>,
25}
26
27impl From<VariableDef> for ast::VariableDefinition {
28    fn from(x: VariableDef) -> Self {
29        Self {
30            name: x.name.into(),
31            ty: Node::new(x.ty.into()),
32            default_value: x.default_value.map(|x| Node::new(x.into())),
33            directives: Directive::to_ast(x.directives),
34        }
35    }
36}
37
38impl DocumentBuilder<'_> {
39    /// Create an arbitrary list of `VariableDef`
40    pub fn variable_definitions(&mut self) -> ArbitraryResult<Vec<VariableDef>> {
41        (0..self.u.int_in_range(0..=7usize)?)
42            .map(|_| self.variable_definition()) // TODO do not generate duplication variable name
43            .collect()
44    }
45
46    /// Create an arbitrary `VariableDef`
47    pub fn variable_definition(&mut self) -> ArbitraryResult<VariableDef> {
48        let name = self.type_name()?;
49        let ty = self.choose_ty(&self.list_existing_types())?;
50        let default_value = self
51            .u
52            .arbitrary()
53            .unwrap_or(false)
54            .then(|| self.input_value(Constness::Const))
55            .transpose()?;
56        let directives = self.directives(DirectiveLocation::VariableDefinition)?;
57
58        Ok(VariableDef {
59            name,
60            ty,
61            default_value,
62            directives,
63        })
64    }
65}