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
use crate::context::QueryPathNode;
use crate::{registry, Pos, QueryPathSegment, Value};
use graphql_parser::query::OperationDefinition;
use std::collections::HashSet;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Scope<'a> {
    Operation(Option<&'a str>),
    Fragment(&'a str),
}

fn valid_error(path_node: &QueryPathNode, msg: String) -> String {
    format!("\"{}\", {}", path_node, msg)
}

pub fn referenced_variables(value: &Value) -> Vec<&str> {
    let mut vars = Vec::new();
    referenced_variables_to_vec(value, &mut vars);
    vars
}

fn referenced_variables_to_vec<'a>(value: &'a Value, vars: &mut Vec<&'a str>) {
    match value {
        Value::Variable(name) => {
            vars.push(name.as_str());
        }
        Value::List(values) => values
            .iter()
            .for_each(|value| referenced_variables_to_vec(value, vars)),
        Value::Object(obj) => obj
            .values()
            .for_each(|value| referenced_variables_to_vec(value, vars)),
        _ => {}
    }
}

pub fn operation_name(operation_definition: &OperationDefinition) -> (Option<&str>, Pos) {
    match operation_definition {
        OperationDefinition::SelectionSet(selection_set) => (None, selection_set.span.0),
        OperationDefinition::Query(query) => (query.name.as_deref(), query.position),
        OperationDefinition::Mutation(mutation) => (mutation.name.as_deref(), mutation.position),
        OperationDefinition::Subscription(subscription) => {
            (subscription.name.as_deref(), subscription.position)
        }
    }
}

pub fn is_valid_input_value(
    registry: &registry::Registry,
    type_name: &str,
    value: &Value,
    path_node: QueryPathNode,
) -> Option<String> {
    if let Value::Variable(_) = value {
        return None;
    }

    match registry::TypeName::create(type_name) {
        registry::TypeName::NonNull(type_name) => match value {
            Value::Null => Some(valid_error(
                &path_node,
                format!("expected type \"{}\"", type_name),
            )),
            _ => is_valid_input_value(registry, type_name, value, path_node),
        },
        registry::TypeName::List(type_name) => match value {
            Value::List(elems) => {
                for (idx, elem) in elems.iter().enumerate() {
                    if let Some(reason) = is_valid_input_value(
                        registry,
                        type_name,
                        elem,
                        QueryPathNode {
                            parent: Some(&path_node),
                            segment: QueryPathSegment::Index(idx),
                        },
                    ) {
                        return Some(reason);
                    }
                }
                None
            }
            _ => is_valid_input_value(registry, type_name, value, path_node),
        },
        registry::TypeName::Named(type_name) => {
            if let Value::Null = value {
                return None;
            }

            if let Some(ty) = registry.types.get(type_name) {
                match ty {
                    registry::Type::Scalar { is_valid, .. } => {
                        if !is_valid(value) {
                            Some(valid_error(
                                &path_node,
                                format!("expected type \"{}\"", type_name),
                            ))
                        } else {
                            None
                        }
                    }
                    registry::Type::Enum { enum_values, .. } => match value {
                        Value::Enum(name) => {
                            if !enum_values.contains_key(name.as_str()) {
                                Some(valid_error(
                                    &path_node,
                                    format!(
                                        "enumeration type \"{}\" does not contain the value \"{}\"",
                                        ty.name(),
                                        name
                                    ),
                                ))
                            } else {
                                None
                            }
                        }
                        _ => Some(valid_error(
                            &path_node,
                            format!("expected type \"{}\"", type_name),
                        )),
                    },
                    registry::Type::InputObject { input_fields, .. } => match value {
                        Value::Object(values) => {
                            let mut input_names = values
                                .keys()
                                .map(|name| name.as_str())
                                .collect::<HashSet<_>>();

                            for field in input_fields.values() {
                                input_names.remove(field.name);
                                if let Some(value) = values.get(field.name) {
                                    if let Some(validator) = &field.validator {
                                        if let Some(reason) = validator.is_valid(value) {
                                            return Some(valid_error(
                                                &QueryPathNode {
                                                    parent: Some(&path_node),
                                                    segment: QueryPathSegment::Name(field.name),
                                                },
                                                reason,
                                            ));
                                        }
                                    }

                                    if let Some(reason) = is_valid_input_value(
                                        registry,
                                        &field.ty,
                                        value,
                                        QueryPathNode {
                                            parent: Some(&path_node),
                                            segment: QueryPathSegment::Name(field.name),
                                        },
                                    ) {
                                        return Some(reason);
                                    }
                                } else if registry::TypeName::create(&field.ty).is_non_null()
                                    && field.default_value.is_none()
                                {
                                    return Some(valid_error(
                                            &path_node,
                                            format!(
                                                "field \"{}\" of type \"{}\" is required but not provided",
                                                field.name,
                                                ty.name(),
                                            ),
                                        ));
                                }
                            }

                            if let Some(name) = input_names.iter().next() {
                                return Some(valid_error(
                                    &path_node,
                                    format!("unknown field \"{}\" of type \"{}\"", name, ty.name()),
                                ));
                            }

                            None
                        }
                        _ => None,
                    },
                    _ => None,
                }
            } else {
                unreachable!()
            }
        }
    }
}