apollo-compiler 1.31.1

A compiler for the GraphQL query language.
Documentation
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
use crate::ast;
use crate::ast::NamedType;
use crate::collections::HashMap;
use crate::collections::HashSet;
use crate::collections::IndexSet;
use crate::executable;
use crate::schema;
use crate::schema::Implementers;
use crate::validation::diagnostics::DiagnosticData;
use crate::validation::variable::walk_selections_with_deduped_fragments;
use crate::validation::CycleError;
use crate::validation::DiagnosticList;
use crate::validation::OperationValidationContext;
use crate::validation::RecursionGuard;
use crate::validation::RecursionLimitError;
use crate::validation::RecursionStack;
use crate::validation::SourceSpan;
use crate::ExecutableDocument;
use crate::Name;
use crate::Node;
use std::borrow::Cow;

/// Given a type definition, find all the type names that can be used for fragment spreading.
///
/// Spec: https://spec.graphql.org/October2021/#GetPossibleTypes()
fn get_possible_types<'a>(
    type_definition: &schema::ExtendedType,
    implementers_map: &'a HashMap<Name, Implementers>,
) -> Cow<'a, IndexSet<NamedType>> {
    match type_definition {
        // 1. If `type` is an object type, return a set containing `type`.
        schema::ExtendedType::Object(object) => {
            let mut set = IndexSet::default();
            set.insert(object.name.clone());
            Cow::Owned(set)
        }
        // 2. If `type` is an interface type, return the set of object types implementing `type`.
        schema::ExtendedType::Interface(interface) => implementers_map
            .get(&interface.name)
            .map(|implementers| Cow::Borrowed(&implementers.objects))
            .unwrap_or_default(),
        // 3. If `type` is a union type, return the set of possible types of `type`.
        schema::ExtendedType::Union(union_) => Cow::Owned(
            union_
                .members
                .iter()
                .map(|component| component.name.clone())
                .collect(),
        ),
        _ => Default::default(),
    }
}

fn validate_fragment_spread_type(
    diagnostics: &mut DiagnosticList,
    schema: &crate::Schema,
    document: &ExecutableDocument,
    against_type: &NamedType,
    type_condition: &NamedType,
    selection: &executable::Selection,
    context: &mut OperationValidationContext<'_>,
) {
    // Treat a spread that's just literally on the parent type as always valid:
    // by spec text, it shouldn't be, but graphql-{js,java,go} and others all do this.
    // See https://github.com/graphql/graphql-spec/issues/1109
    if type_condition == against_type {
        return;
    }

    // Another diagnostic will be raised if the type condition was wrong.
    // We reduce noise by silencing other issues with the fragment.
    let Some(type_condition_definition) = schema.types.get(type_condition) else {
        return;
    };

    let Some(against_type_definition) = schema.types.get(against_type) else {
        // We cannot check anything if the parent type is unknown.
        return;
    };

    let implementers_map = context.implementers_map();
    let concrete_parent_types = get_possible_types(against_type_definition, implementers_map);
    let concrete_condition_types = get_possible_types(type_condition_definition, implementers_map);

    let mut applicable_types = concrete_parent_types.intersection(&concrete_condition_types);
    if applicable_types.next().is_none() {
        // Report specific errors for the different kinds of fragments.
        match selection {
            executable::Selection::Field(_) => unreachable!(),
            executable::Selection::FragmentSpread(spread) => {
                // TODO(@goto-bus-stop) Can we guarantee this unwrap()?
                let fragment_definition = document.fragments.get(&spread.fragment_name).unwrap();

                diagnostics.push(
                    spread.location(),
                    DiagnosticData::InvalidFragmentSpread {
                        name: Some(spread.fragment_name.clone()),
                        type_name: against_type.clone(),
                        type_condition: type_condition.clone(),
                        fragment_location: fragment_definition.location(),
                        type_location: against_type_definition.location(),
                    },
                )
            }
            executable::Selection::InlineFragment(inline) => diagnostics.push(
                inline.location(),
                DiagnosticData::InvalidFragmentSpread {
                    name: None,
                    type_name: against_type.clone(),
                    type_condition: type_condition.clone(),
                    fragment_location: inline.location(),
                    type_location: against_type_definition.location(),
                },
            ),
        };
    }
}

pub(crate) fn validate_inline_fragment(
    diagnostics: &mut DiagnosticList,
    document: &ExecutableDocument,
    against_type: Option<(&crate::Schema, &ast::NamedType)>,
    inline: &Node<executable::InlineFragment>,
    context: &mut OperationValidationContext<'_>,
) {
    super::directive::validate_directives(
        diagnostics,
        context.schema(),
        inline.directives.iter(),
        ast::DirectiveLocation::InlineFragment,
        context.variables,
    );

    let previous = diagnostics.len();
    if let Some(schema) = context.schema() {
        if let Some(t) = &inline.type_condition {
            validate_fragment_type_condition(diagnostics, schema, None, t, inline.location())
        }
    }
    let has_type_error = diagnostics.len() > previous;

    // If there was an error with the type condition, it makes no sense to validate the selection,
    // as every field would be an error.
    if !has_type_error {
        if let (Some((schema, against_type)), Some(type_condition)) =
            (against_type, &inline.type_condition)
        {
            validate_fragment_spread_type(
                diagnostics,
                schema,
                document,
                against_type,
                type_condition,
                &executable::Selection::InlineFragment(inline.clone()),
                context,
            );
        }
        super::selection::validate_selection_set(
            diagnostics,
            document,
            if let (Some(schema), Some(ty)) = (&context.schema(), &inline.type_condition) {
                Some((schema, ty))
            } else {
                against_type
            },
            &inline.selection_set,
            context,
        );
    }
}

pub(crate) fn validate_fragment_spread(
    diagnostics: &mut DiagnosticList,
    document: &ExecutableDocument,
    against_type: Option<(&crate::Schema, &NamedType)>,
    spread: &Node<executable::FragmentSpread>,
    context: &mut OperationValidationContext<'_>,
) {
    super::directive::validate_directives(
        diagnostics,
        context.schema(),
        spread.directives.iter(),
        ast::DirectiveLocation::FragmentSpread,
        context.variables,
    );

    match document.fragments.get(&spread.fragment_name) {
        Some(def) => {
            if let Some((schema, against_type)) = against_type {
                validate_fragment_spread_type(
                    diagnostics,
                    schema,
                    document,
                    against_type,
                    def.type_condition(),
                    &executable::Selection::FragmentSpread(spread.clone()),
                    context,
                );
            }
            let new = context
                .validated_fragments
                .insert(spread.fragment_name.clone());
            if new {
                validate_fragment_definition(diagnostics, document, def, context);
            }
        }
        None => {
            diagnostics.push(
                spread.location(),
                DiagnosticData::UndefinedFragment {
                    name: spread.fragment_name.clone(),
                },
            );
        }
    }
}

pub(crate) fn validate_fragment_definition(
    diagnostics: &mut DiagnosticList,
    document: &ExecutableDocument,
    fragment: &Node<executable::Fragment>,
    context: &mut OperationValidationContext<'_>,
) {
    super::directive::validate_directives(
        diagnostics,
        context.schema(),
        fragment.directives.iter(),
        ast::DirectiveLocation::FragmentDefinition,
        context.variables,
    );

    let previous = diagnostics.len();
    if let Some(schema) = context.schema() {
        validate_fragment_type_condition(
            diagnostics,
            schema,
            Some(fragment.name.clone()),
            fragment.type_condition(),
            fragment.location(),
        );
    }
    let has_type_error = diagnostics.len() > previous;

    let previous = diagnostics.len();
    validate_fragment_cycles(diagnostics, document, fragment);
    let has_cycles = diagnostics.len() > previous;

    if !has_type_error && !has_cycles {
        // If the type does not exist, do not attempt to validate the selections against it;
        // it has either already raised an error, or we are validating an executable without
        // a schema.
        let type_condition = context.schema().and_then(|schema| {
            schema
                .types
                .contains_key(fragment.type_condition())
                .then_some((schema, fragment.type_condition()))
        });

        super::selection::validate_selection_set(
            diagnostics,
            document,
            type_condition,
            &fragment.selection_set,
            context,
        );
    }
}

pub(crate) fn validate_fragment_cycles(
    diagnostics: &mut DiagnosticList,
    document: &ExecutableDocument,
    def: &Node<executable::Fragment>,
) {
    /// If a fragment spread is recursive, returns a vec containing the spread that refers back to
    /// the original fragment, and a trace of each fragment spread back to the original fragment.
    fn detect_fragment_cycles<'doc>(
        document: &'doc ExecutableDocument,
        selection_set: &'doc executable::SelectionSet,
        path_from_root: &mut RecursionGuard<'_>,
        seen: &mut HashSet<&'doc Name>,
    ) -> Result<(), CycleError<executable::FragmentSpread>> {
        for selection in &selection_set.selections {
            match selection {
                executable::Selection::FragmentSpread(spread) => {
                    if path_from_root.contains(&spread.fragment_name) {
                        if path_from_root.first() == Some(&spread.fragment_name) {
                            return Err(CycleError::Recursed(vec![spread.clone()]));
                        }
                        continue;
                    }

                    let new = seen.insert(&spread.fragment_name);
                    if !new {
                        // We already recursively traversed that fragment and didn’t find a cycle then
                        continue;
                    }

                    if let Some(fragment) = document.fragments.get(&spread.fragment_name) {
                        detect_fragment_cycles(
                            document,
                            &fragment.selection_set,
                            &mut path_from_root.push(&fragment.name)?,
                            seen,
                        )
                        .map_err(|error| error.trace(spread))?;
                    }
                }
                executable::Selection::InlineFragment(inline) => {
                    detect_fragment_cycles(document, &inline.selection_set, path_from_root, seen)?;
                }
                executable::Selection::Field(field) => {
                    detect_fragment_cycles(document, &field.selection_set, path_from_root, seen)?;
                }
            }
        }

        Ok(())
    }

    let mut visited = RecursionStack::with_root(def.name.clone()).with_limit(100);

    match detect_fragment_cycles(
        document,
        &def.selection_set,
        &mut visited.guard(),
        &mut HashSet::default(),
    ) {
        Ok(_) => {}
        Err(CycleError::Recursed(trace)) => {
            let head_location = SourceSpan::recompose(def.location(), def.name.location());

            diagnostics.push(
                def.location(),
                DiagnosticData::RecursiveFragmentDefinition {
                    head_location,
                    name: def.name.clone(),
                    trace,
                },
            );
        }
        Err(CycleError::Limit(_)) => {
            let head_location = SourceSpan::recompose(def.location(), def.name.location());

            diagnostics.push(
                head_location,
                DiagnosticData::DeeplyNestedType {
                    name: def.name.clone(),
                    describe_type: "fragment",
                },
            );
        }
    };
}

pub(crate) fn validate_fragment_type_condition(
    diagnostics: &mut DiagnosticList,
    schema: &crate::Schema,
    fragment_name: Option<Name>,
    type_cond: &NamedType,
    fragment_location: Option<SourceSpan>,
) {
    let type_def = schema.types.get(type_cond);
    let is_composite = matches!(
        type_def,
        Some(schema::ExtendedType::Object(_))
            | Some(schema::ExtendedType::Interface(_))
            | Some(schema::ExtendedType::Union(_))
    );

    if !is_composite {
        diagnostics.push(
            fragment_location,
            DiagnosticData::InvalidFragmentTarget {
                name: fragment_name,
                ty: type_cond.clone(),
            },
        );
    }
}

fn collect_used_fragments(
    document: &ExecutableDocument,
) -> Result<HashSet<&Name>, RecursionLimitError> {
    let mut names = HashSet::default();
    for operation in document.operations.iter() {
        walk_selections_with_deduped_fragments(document, &operation.selection_set, |selection| {
            if let executable::Selection::FragmentSpread(spread) = selection {
                names.insert(&spread.fragment_name);
            }
        })?;
    }
    Ok(names)
}

pub(crate) fn validate_fragments_used(
    diagnostics: &mut DiagnosticList,
    document: &ExecutableDocument,
) {
    let Ok(used_fragments) = collect_used_fragments(document) else {
        diagnostics.push(None, super::Details::RecursionLimitError);
        return;
    };

    for fragment in document.fragments.values() {
        // Fragments must be used within the schema
        //
        // Returns Unused Fragment error.
        if !used_fragments.contains(&fragment.name) {
            diagnostics.push(
                fragment.location(),
                DiagnosticData::UnusedFragment {
                    name: fragment.name.clone(),
                },
            )
        }
    }
}