gql 0.3.0

A GraphQL reference implementation for Rust.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
//! Input coercion.
//!
//! Two entry points mirror the specification: variable values arrive as runtime [`Value`]s and
//! are coerced by [`coerce_variable_values`], while field arguments are literals in the document
//! and are coerced by [`coerce_argument_values`]. Both funnel into the same type-directed rules so
//! custom scalars, enums and nested input objects behave identically everywhere.
//!
//! Document literals can carry integers up to `i128` (see [`crate::ast::Value::Int`]), and a
//! transport such as `suku` preserves JSON integers outside the 32-bit range as
//! [`Value::BigInt`], so custom scalars can receive values beyond GraphQL's built-in `Int`.

use std::sync::Arc;

use crate::{
    Object, Value, ast,
    error::{GraphQLError, Location},
    schema::Schema,
    types::{EnumType, Field, InputObjectType, InputValue, ScalarType, Type, TypeRef},
};

use super::selection::type_ref;

/// Variable values after coercion.
#[derive(Clone, Debug, Default)]
pub struct CoercedVariables {
    /// The coerced values.
    pub values: Object,
}

/// Variable definitions compiled once for a prepared operation.
///
/// Preparing a query splits each definition into its fixed parts — the name, the schema type and
/// the coerced default — from the per-request work, which is only coercing the values the request
/// actually supplies. The compiled form reproduces [`coerce_variable_values`] exactly; compilation
/// fails whenever a definition relies on something validation should have rejected, in which case
/// the caller keeps the general path.
pub(crate) struct CompiledVariables {
    definitions: Vec<CompiledVariable>,
}

struct CompiledVariable {
    name: Arc<str>,
    ty: TypeRef,
    default: Option<Value>,
    location: Location,
}

impl CompiledVariables {
    /// Compile an operation's variable definitions.
    ///
    /// Returns `Err(())` rather than an error value: a prepared document was already validated, so
    /// a definition that cannot be compiled is a reason to fall back, not a client-facing error.
    pub(crate) fn compile(
        schema: &Schema,
        operation: &ast::OperationDefinition<'_>,
    ) -> Result<Self, ()> {
        let mut definitions = Vec::with_capacity(operation.variables.len());
        for definition in &operation.variables {
            let ty = type_ref(&definition.ty);
            if schema.get_type(ty.named_type()).is_none() {
                return Err(());
            }
            let default = match &definition.default_value {
                Some(default) => Some(coerce_literal(schema, default, &ty, None).map_err(|_| ())?),
                None => None,
            };
            definitions.push(CompiledVariable {
                name: Arc::from(definition.name),
                ty,
                default,
                location: definition.location,
            });
        }
        Ok(Self { definitions })
    }

    /// Coerce request values against the compiled definitions.
    ///
    /// # Errors
    ///
    /// Returns every coercion failure, one per invalid variable, exactly like
    /// [`coerce_variable_values`].
    pub(crate) fn coerce(
        &self,
        schema: &Schema,
        inputs: Option<&Object>,
    ) -> Result<CoercedVariables, Vec<GraphQLError>> {
        let mut values = Object::with_capacity(self.definitions.len());
        let mut errors = Vec::new();

        for definition in &self.definitions {
            match inputs.and_then(|inputs| inputs.get(definition.name.as_ref())) {
                None => {
                    if let Some(default) = &definition.default {
                        // Variable names are unique in a validated operation, so the response map
                        // needs no duplicate scan.
                        values.push_unchecked(Arc::clone(&definition.name), default.clone());
                    } else if definition.ty.is_non_null() {
                        errors.push(
                            GraphQLError::new(format!(
                                "Variable \"${}\" of required type \"{}\" was not provided.",
                                definition.name, definition.ty
                            ))
                            .at(definition.location),
                        );
                    }
                    // A nullable variable that was not provided stays undefined, not null.
                }
                Some(input) if input.is_null() => {
                    if definition.ty.is_non_null() {
                        errors.push(
                            GraphQLError::new(format!(
                                "Variable \"${}\" of non-null type \"{}\" must not be null.",
                                definition.name, definition.ty
                            ))
                            .at(definition.location),
                        );
                    } else {
                        values.push_unchecked(Arc::clone(&definition.name), Value::Null);
                    }
                }
                Some(input) => {
                    let mut path = Vec::new();
                    match coerce_input_value(schema, input, &definition.ty, &mut path) {
                        Ok(value) => {
                            values.push_unchecked(Arc::clone(&definition.name), value);
                        }
                        Err(error) => errors.push(
                            GraphQLError::new(format!(
                                "Variable \"${}\" got invalid value {}; {}",
                                definition.name,
                                render_value(input),
                                error.message()
                            ))
                            .at(definition.location),
                        ),
                    }
                }
            }
        }

        if errors.is_empty() {
            Ok(CoercedVariables { values })
        } else {
            Err(errors)
        }
    }
}

/// Coerce variable definitions against the supplied input values.
///
/// # Errors
///
/// Returns every coercion failure, one per invalid variable.
pub fn coerce_variable_values(
    schema: &Schema,
    operation: &ast::OperationDefinition<'_>,
    inputs: Option<&Object>,
) -> Result<CoercedVariables, Vec<GraphQLError>> {
    let mut values = Object::with_capacity(operation.variables.len());
    let mut errors = Vec::new();

    for definition in &operation.variables {
        let ty = type_ref(&definition.ty);
        if schema.get_type(ty.named_type()).is_none() {
            errors.push(
                GraphQLError::new(format!(
                    "Variable \"${}\" has unknown type \"{}\".",
                    definition.name, ty
                ))
                .at(definition.location),
            );
            continue;
        }

        let supplied = inputs.and_then(|inputs| inputs.get(definition.name));
        match supplied {
            None => {
                if let Some(default) = &definition.default_value {
                    match coerce_literal(schema, default, &ty, None) {
                        Ok(value) => {
                            values.insert(definition.name, value);
                        }
                        Err(error) => {
                            let message = error.message().to_owned();
                            errors.push(
                                error
                                    .with_message(format!(
                                        "Variable \"${}\" has an invalid default value: {message}",
                                        definition.name
                                    ))
                                    .at(definition.location),
                            );
                        }
                    }
                } else if ty.is_non_null() {
                    errors.push(
                        GraphQLError::new(format!(
                            "Variable \"${}\" of required type \"{}\" was not provided.",
                            definition.name, ty
                        ))
                        .at(definition.location),
                    );
                }
                // A nullable variable that was not provided stays undefined, not null.
            }
            Some(input) => {
                if input.is_null() {
                    if ty.is_non_null() {
                        errors.push(
                            GraphQLError::new(format!(
                                "Variable \"${}\" of non-null type \"{}\" must not be null.",
                                definition.name, ty
                            ))
                            .at(definition.location),
                        );
                    } else {
                        values.insert(definition.name, Value::Null);
                    }
                } else {
                    let mut path = Vec::new();
                    match coerce_input_value(schema, input, &ty, &mut path) {
                        Ok(value) => {
                            values.insert(definition.name, value);
                        }
                        Err(error) => errors.push(
                            GraphQLError::new(format!(
                                "Variable \"${}\" got invalid value {}; {}",
                                definition.name,
                                render_value(input),
                                error.message()
                            ))
                            .at(definition.location),
                        ),
                    }
                }
            }
        }
    }

    if errors.is_empty() {
        Ok(CoercedVariables { values })
    } else {
        Err(errors)
    }
}

/// Coerce a field's arguments, applying defaults.
///
/// # Errors
///
/// Returns an error for missing required arguments, unknown arguments and invalid values.
pub fn coerce_argument_values(
    schema: &Schema,
    field: &Field,
    node: &ast::Field<'_>,
    variables: &Object,
) -> Result<Object, GraphQLError> {
    let mut coerced = Object::with_capacity(field.args.len());
    coerce_argument_values_into(schema, field, node, variables, &mut coerced)?;
    Ok(coerced)
}

/// Coerce a field's arguments into an existing, empty object.
///
/// Execution coerces arguments for every field it completes, so building the result in the
/// caller's slot avoids copying an [`Object`] out of the callee for each one.
pub(crate) fn coerce_argument_values_into(
    schema: &Schema,
    field: &Field,
    node: &ast::Field<'_>,
    variables: &Object,
    coerced: &mut Object,
) -> Result<(), GraphQLError> {
    debug_assert!(coerced.is_empty(), "argument object must start empty");

    // A document that lists exactly the field's arguments, in schema order, needs no
    // unknown-argument scan and no per-definition search: the two lists already correspond.
    if node.arguments.len() == field.args.len()
        && node
            .arguments
            .iter()
            .zip(field.args.iter())
            .all(|(argument, (name, _))| crate::types::names_eq(argument.name, name))
    {
        for (argument, (name, definition)) in node.arguments.iter().zip(field.args.iter()) {
            coerce_provided_argument(
                schema, field, name, definition, argument, variables, coerced,
            )?;
        }
        return Ok(());
    }

    for argument in &node.arguments {
        if crate::types::map_get(&field.args, argument.name).is_none() {
            return Err(GraphQLError::new(format!(
                "Unknown argument \"{}\" on field \"{}\".",
                argument.name, field.name
            ))
            .at(argument.location));
        }
    }

    for (name, definition) in &field.args {
        let Some(argument) = node.argument(name) else {
            if let Some(default) = &definition.default_value {
                let mut default_path = Vec::new();
                let value = coerce_input_value(schema, default, &definition.ty, &mut default_path)
                    .map_err(|error| {
                        let message = error.message().to_owned();
                        error.with_message(format!(
                            "Field \"{}\" argument \"{}\" has an invalid default value: {message}",
                            field.name, name
                        ))
                    })?;
                coerced.insert(name.clone(), value);
            } else if definition.ty.is_non_null() {
                return Err(GraphQLError::new(format!(
                    "Field \"{}\" argument \"{}\" of type \"{}\" is required, but it was not provided.",
                    field.name, name, definition.ty
                ))
                .at(node.location));
            }
            continue;
        };

        coerce_provided_argument(
            schema, field, name, definition, argument, variables, coerced,
        )?;
    }
    Ok(())
}

/// Coerce one provided argument into the field's argument object.
#[allow(clippy::too_many_arguments)]
fn coerce_provided_argument(
    schema: &Schema,
    field: &Field,
    name: &crate::types::Name,
    definition: &InputValue,
    argument: &ast::Argument<'_>,
    variables: &Object,
    coerced: &mut Object,
) -> Result<(), GraphQLError> {
    // A top-level variable reference follows the specification's *argument* rules rather
    // than literal rules: an undefined nullable variable means the argument is omitted.
    if let ast::Value::Variable(variable_name) = &argument.value {
        match variables.get(variable_name) {
            Some(value) => {
                if value.is_null() && definition.ty.is_non_null() {
                    return Err(GraphQLError::new(format!(
                        "Field \"{}\" argument \"{}\" of non-null type \"{}\" must not be null.",
                        field.name, name, definition.ty
                    ))
                    .at(argument.location));
                }
                coerced.insert(name.clone(), value.clone());
            }
            None => {
                if let Some(default) = &definition.default_value {
                    let mut default_path = Vec::new();
                    let value =
                        coerce_input_value(schema, default, &definition.ty, &mut default_path)
                            .map_err(|error| {
                                let message = error.message().to_owned();
                                error.with_message(format!(
                            "Field \"{}\" argument \"{}\" has an invalid default value: {message}",
                            field.name, name
                        ))
                            })?;
                    coerced.insert(name.clone(), value);
                } else if definition.ty.is_non_null() {
                    return Err(GraphQLError::new(format!(
                            "Field \"{}\" argument \"{}\" of required type \"{}\" was not provided because variable \"${}\" was not provided.",
                            field.name, name, definition.ty, variable_name
                        ))
                        .at(argument.location));
                }
            }
        }
    } else {
        let mut path = Vec::new();
        match value_from_ast(
            schema,
            &argument.value,
            &definition.ty,
            Some(variables),
            &mut path,
        ) {
            Ok(Some(value)) => {
                coerced.insert(name.clone(), value);
            }
            Ok(None) => {
                return Err(GraphQLError::new(format!(
                        "Field \"{}\" argument \"{}\" is invalid: a variable used in its value was not provided.",
                        field.name, name
                    ))
                    .at(argument.location));
            }
            Err(error) => {
                let message = error.message().to_owned();
                return Err(error
                    .with_message(format!(
                        "Field \"{}\" argument \"{}\": {message}",
                        field.name, name
                    ))
                    .at(argument.location));
            }
        }
    }
    Ok(())
}

/// Coerce a literal to a runtime value for an input type.
pub(crate) fn coerce_literal(
    schema: &Schema,
    value: &ast::Value<'_>,
    ty: &TypeRef,
    variables: Option<&Object>,
) -> Result<Value, GraphQLError> {
    let mut path = Vec::new();
    match value_from_ast(schema, value, ty, variables, &mut path)? {
        Some(value) => Ok(value),
        None => Err(GraphQLError::new(format!(
            "A value of type \"{ty}\" was required, but the variable used for it was not provided."
        ))),
    }
}

fn at_path(error: GraphQLError, path: &[String]) -> GraphQLError {
    if path.is_empty() {
        error
    } else {
        let message = error.message().to_owned();
        error.with_message(format!("{message} (at \"{}\")", path.join(".")))
    }
}

fn variable_is_missing(value: &ast::Value<'_>, variables: Option<&Object>) -> bool {
    match value {
        ast::Value::Variable(name) => {
            !variables.is_some_and(|variables| variables.contains_key(name))
        }
        _ => false,
    }
}

/// Verify that a schema's default value is valid for its declared input type.
pub(crate) fn validate_default_value(
    schema: &Schema,
    value: &Value,
    ty: &TypeRef,
) -> Result<(), GraphQLError> {
    let mut path = Vec::new();
    coerce_input_value(schema, value, ty, &mut path).map(|_| ())
}

/// Coerce a runtime (already parsed) input value.
pub(crate) fn coerce_input_value(
    schema: &Schema,
    value: &Value,
    ty: &TypeRef,
    path: &mut Vec<String>,
) -> Result<Value, GraphQLError> {
    match ty {
        TypeRef::NonNull(inner) => {
            if value.is_null() {
                return Err(at_path(
                    GraphQLError::new(format!("Expected a non-null value of type \"{ty}\".")),
                    path,
                ));
            }
            coerce_input_value(schema, value, inner, path)
        }
        _ => {
            if value.is_null() {
                return Ok(Value::Null);
            }
            match ty {
                TypeRef::List(inner) => coerce_list_value(schema, value, inner, path),
                TypeRef::Named(name) => coerce_named_value(schema, value, name, path),
                TypeRef::NonNull(_) => Err(at_path(
                    GraphQLError::new(
                        "Internal input coercion error: non-null type was not unwrapped.",
                    ),
                    path,
                )),
            }
        }
    }
}

fn coerce_list_value(
    schema: &Schema,
    value: &Value,
    inner: &TypeRef,
    path: &mut Vec<String>,
) -> Result<Value, GraphQLError> {
    // A non-list value coerces to a one-element list (October 2021 3.10 "Input Coercion").
    if let Value::List(items) = value {
        let mut coerced = Vec::with_capacity(items.len());
        for (index, item) in items.iter().enumerate() {
            path.push(index.to_string());
            let result = coerce_input_value(schema, item, inner, path);
            path.pop();
            coerced.push(result?);
        }
        Ok(Value::List(coerced))
    } else {
        let result = coerce_input_value(schema, value, inner, path)?;
        Ok(Value::List(vec![result]))
    }
}

fn coerce_named_value(
    schema: &Schema,
    value: &Value,
    name: &crate::types::Name,
    path: &mut Vec<String>,
) -> Result<Value, GraphQLError> {
    let Some(definition) = schema.get_type(name) else {
        return Err(at_path(
            GraphQLError::new(format!("Unknown input type \"{name}\".")),
            path,
        ));
    };
    match definition {
        Type::Scalar(scalar) => coerce_scalar_value(scalar, value, path),
        Type::Enum(enumeration) => coerce_enum_value(enumeration, value, path),
        Type::InputObject(input) => coerce_input_object_value(schema, input, value, path),
        _ => Err(at_path(
            GraphQLError::new(format!("Type \"{name}\" is not an input type.")),
            path,
        )),
    }
}

fn coerce_scalar_value(
    scalar: &ScalarType,
    value: &Value,
    path: &mut Vec<String>,
) -> Result<Value, GraphQLError> {
    if let Some(parse) = scalar.parse_value_fn() {
        return parse(value).map_err(|message| at_path(GraphQLError::new(message), path));
    }
    match scalar.name.as_ref() {
        "String" => match value {
            Value::String(_) => Ok(value.clone()),
            _ => Err(at_path(
                GraphQLError::new(format!(
                    "String cannot represent a value of type {}.",
                    value.kind()
                )),
                path,
            )),
        },
        "Int" => match value {
            Value::Int(_) => Ok(value.clone()),
            Value::BigInt(integer) => i32::try_from(**integer).map(Value::Int).map_err(|_| {
                at_path(
                    GraphQLError::new(format!(
                        "Int cannot represent non 32-bit signed integer value {integer}."
                    )),
                    path,
                )
            }),
            _ => Err(at_path(
                GraphQLError::new(format!(
                    "Int cannot represent a value of type {}.",
                    value.kind()
                )),
                path,
            )),
        },
        "Float" => match value {
            Value::Float(_) => Ok(value.clone()),
            Value::Int(integer) => Ok(Value::Float(f64::from(*integer))),
            Value::BigInt(integer) => Ok(Value::Float(**integer as f64)),
            _ => Err(at_path(
                GraphQLError::new(format!(
                    "Float cannot represent a value of type {}.",
                    value.kind()
                )),
                path,
            )),
        },
        "Boolean" => match value {
            Value::Boolean(_) => Ok(value.clone()),
            _ => Err(at_path(
                GraphQLError::new(format!(
                    "Boolean cannot represent a value of type {}.",
                    value.kind()
                )),
                path,
            )),
        },
        "ID" => match value {
            Value::String(value) | Value::Enum(value) => Ok(Value::String(value.clone())),
            Value::Int(value) => Ok(Value::String(Arc::from(value.to_string()))),
            Value::BigInt(value) => Ok(Value::String(Arc::from(value.to_string()))),
            _ => Err(at_path(
                GraphQLError::new(format!(
                    "ID cannot represent a value of type {}.",
                    value.kind()
                )),
                path,
            )),
        },
        // A custom scalar with no registered parser is transparent.
        _ => Ok(value.clone()),
    }
}

fn coerce_enum_value(
    enumeration: &EnumType,
    value: &Value,
    path: &mut Vec<String>,
) -> Result<Value, GraphQLError> {
    match value {
        Value::Enum(name) | Value::String(name) => {
            if enumeration.has_value(name) {
                Ok(Value::Enum(name.clone()))
            } else {
                Err(at_path(
                    GraphQLError::new(format!(
                        "Value \"{name}\" does not exist in enum \"{}\".",
                        enumeration.name
                    )),
                    path,
                ))
            }
        }
        other => Err(at_path(
            GraphQLError::new(format!(
                "Enum \"{}\" cannot represent a value of type {}.",
                enumeration.name,
                other.kind()
            )),
            path,
        )),
    }
}

fn coerce_input_object_value(
    schema: &Schema,
    input: &InputObjectType,
    value: &Value,
    path: &mut Vec<String>,
) -> Result<Value, GraphQLError> {
    let Value::Object(object) = value else {
        return Err(at_path(
            GraphQLError::new(format!(
                "Expected an object value of type \"{}\", but got a {}.",
                input.name,
                value.kind()
            )),
            path,
        ));
    };

    for (key, _) in object.iter() {
        if !input.fields.contains_key(&**key) {
            return Err(at_path(
                GraphQLError::new(format!(
                    "Field \"{key}\" is not defined by input object \"{}\".",
                    input.name
                )),
                path,
            ));
        }
    }

    let mut coerced = Object::with_capacity(input.fields.len());
    let mut provided = 0usize;
    for (field_name, field) in &input.fields {
        match object.get(field_name) {
            None => apply_input_default(schema, field, &mut coerced, path)?,
            Some(field_value) => {
                provided += 1;
                path.push(field_name.to_string());
                let result = coerce_input_value(schema, field_value, &field.ty, path);
                path.pop();
                coerced.insert(field_name.clone(), result?);
            }
        }
    }

    if input.one_of {
        check_one_of(&input.name, provided, &coerced, path)?;
    }

    Ok(Value::Object(Arc::new(coerced)))
}

fn apply_input_default(
    schema: &Schema,
    field: &InputValue,
    coerced: &mut Object,
    path: &mut Vec<String>,
) -> Result<(), GraphQLError> {
    if let Some(default) = &field.default_value {
        path.push(field.name.to_string());
        let value = coerce_input_value(schema, default, &field.ty, path);
        path.pop();
        coerced.insert(field.name.clone(), value?);
        Ok(())
    } else if field.ty.is_non_null() {
        Err(at_path(
            GraphQLError::new(format!(
                "Field \"{}\" of required type \"{}\" was not provided.",
                field.name, field.ty
            )),
            path,
        ))
    } else {
        Ok(())
    }
}

fn check_one_of(
    name: &str,
    provided: usize,
    coerced: &Object,
    path: &[String],
) -> Result<(), GraphQLError> {
    if provided != 1 {
        return Err(at_path(
            GraphQLError::new(format!(
                "OneOf input object \"{name}\" must specify exactly one field, but {provided} were provided."
            )),
            path,
        ));
    }
    if coerced.values().next().is_some_and(Value::is_null) {
        return Err(at_path(
            GraphQLError::new(format!(
                "OneOf input object \"{name}\" must not have a null value."
            )),
            path,
        ));
    }
    Ok(())
}

/// Coerce a document literal, returning `None` when a nested variable reference is undefined.
fn value_from_ast(
    schema: &Schema,
    value: &ast::Value<'_>,
    ty: &TypeRef,
    variables: Option<&Object>,
    path: &mut Vec<String>,
) -> Result<Option<Value>, GraphQLError> {
    match ty {
        TypeRef::NonNull(inner) => {
            if matches!(value, ast::Value::Null) {
                return Err(at_path(
                    GraphQLError::new(format!(
                        "Expected a value of non-null type \"{ty}\", but got null."
                    )),
                    path,
                ));
            }
            match value_from_ast(schema, value, inner, variables, path)? {
                Some(Value::Null) => Err(at_path(
                    GraphQLError::new(format!(
                        "Expected a value of non-null type \"{ty}\", but got null."
                    )),
                    path,
                )),
                other => Ok(other),
            }
        }
        _ => {
            if let ast::Value::Variable(name) = value {
                return Ok(variables.and_then(|variables| variables.get(name)).cloned());
            }
            if matches!(value, ast::Value::Null) {
                return Ok(Some(Value::Null));
            }
            match ty {
                TypeRef::List(inner) => coerce_list_literal(schema, value, inner, variables, path),
                TypeRef::Named(name) => coerce_named_literal(schema, value, name, variables, path),
                TypeRef::NonNull(_) => Err(at_path(
                    GraphQLError::new(
                        "Internal input coercion error: non-null type was not unwrapped.",
                    ),
                    path,
                )),
            }
        }
    }
}

fn coerce_list_literal(
    schema: &Schema,
    value: &ast::Value<'_>,
    inner: &TypeRef,
    variables: Option<&Object>,
    path: &mut Vec<String>,
) -> Result<Option<Value>, GraphQLError> {
    let ast::Value::List(items) = value else {
        // A single value coerces to a one-element list.
        return match value_from_ast(schema, value, inner, variables, path)? {
            Some(value) => Ok(Some(Value::List(vec![value]))),
            None => Ok(None),
        };
    };

    let mut coerced = Vec::with_capacity(items.len());
    for (index, item) in items.iter().enumerate() {
        path.push(index.to_string());
        let result = value_from_ast(schema, item, inner, variables, path);
        path.pop();
        match result? {
            Some(value) => coerced.push(value),
            None => {
                if inner.is_non_null() {
                    return Ok(None);
                }
                coerced.push(Value::Null);
            }
        }
    }
    Ok(Some(Value::List(coerced)))
}

fn coerce_named_literal(
    schema: &Schema,
    value: &ast::Value<'_>,
    name: &crate::types::Name,
    variables: Option<&Object>,
    path: &mut Vec<String>,
) -> Result<Option<Value>, GraphQLError> {
    let Some(definition) = schema.get_type(name) else {
        return Err(at_path(
            GraphQLError::new(format!("Unknown input type \"{name}\".")),
            path,
        ));
    };
    match definition {
        Type::Scalar(scalar) => coerce_scalar_literal(scalar, value, variables, path),
        Type::Enum(enumeration) => match value {
            ast::Value::Enum(value) => {
                if enumeration.has_value(value) {
                    Ok(Some(Value::Enum((*value).into())))
                } else {
                    Err(at_path(
                        GraphQLError::new(format!(
                            "Value \"{value}\" does not exist in enum \"{}\".",
                            enumeration.name
                        )),
                        path,
                    ))
                }
            }
            other => Err(at_path(
                GraphQLError::new(format!(
                    "Enum \"{}\" cannot represent a {} literal.",
                    enumeration.name,
                    literal_kind(other)
                )),
                path,
            )),
        },
        Type::InputObject(input) => {
            coerce_input_object_literal(schema, input, value, variables, path)
        }
        _ => Err(at_path(
            GraphQLError::new(format!("Type \"{name}\" is not an input type.")),
            path,
        )),
    }
}

fn coerce_scalar_literal(
    scalar: &ScalarType,
    value: &ast::Value<'_>,
    variables: Option<&Object>,
    path: &mut Vec<String>,
) -> Result<Option<Value>, GraphQLError> {
    if let Some(parse) = scalar.parse_literal_fn() {
        return parse(value)
            .map(Some)
            .map_err(|message| at_path(GraphQLError::new(message), path));
    }

    // Built-in scalars always register a literal parser, so this fallback belongs to custom
    // scalars: accept any JSON-shaped literal and let the scalar interpret it.
    generic_literal(value, variables)
}

fn generic_literal(
    value: &ast::Value<'_>,
    variables: Option<&Object>,
) -> Result<Option<Value>, GraphQLError> {
    match value {
        ast::Value::Variable(name) => {
            Ok(variables.and_then(|variables| variables.get(name)).cloned())
        }
        ast::Value::Null => Ok(Some(Value::Null)),
        ast::Value::Boolean(value) => Ok(Some(Value::Boolean(*value))),
        ast::Value::Int(value) => Ok(Some(Value::integer(*value))),
        ast::Value::Float(value) => Ok(Some(Value::Float(*value))),
        ast::Value::String(value) => Ok(Some(Value::String(Arc::from(value.as_ref())))),
        ast::Value::Enum(value) => Ok(Some(Value::Enum((*value).into()))),
        ast::Value::List(items) => {
            let mut coerced = Vec::with_capacity(items.len());
            for item in items {
                coerced.push(generic_literal(item, variables)?.unwrap_or(Value::Null));
            }
            Ok(Some(Value::List(coerced)))
        }
        ast::Value::Object(fields) => {
            let mut object = Object::with_capacity(fields.len());
            for field in fields {
                let value = generic_literal(&field.value, variables)?.unwrap_or(Value::Null);
                object.insert(field.name, value);
            }
            Ok(Some(Value::Object(Arc::new(object))))
        }
    }
}

fn coerce_input_object_literal(
    schema: &Schema,
    input: &InputObjectType,
    value: &ast::Value<'_>,
    variables: Option<&Object>,
    path: &mut Vec<String>,
) -> Result<Option<Value>, GraphQLError> {
    let ast::Value::Object(fields) = value else {
        return Err(at_path(
            GraphQLError::new(format!(
                "Expected an object literal of type \"{}\", but got a {} literal.",
                input.name,
                literal_kind(value)
            )),
            path,
        ));
    };

    for field in fields {
        if !input.fields.contains_key(field.name) {
            return Err(at_path(
                GraphQLError::new(format!(
                    "Field \"{}.{}\" is not defined by input object \"{}\".",
                    input.name, field.name, input.name
                )),
                path,
            ));
        }
    }

    let mut coerced = Object::with_capacity(input.fields.len());
    let mut provided = 0usize;
    for (field_name, field) in &input.fields {
        let node = fields
            .iter()
            .find(|candidate| candidate.name == &**field_name)
            .map(|candidate| &candidate.value);
        let missing_variable = node.is_some_and(|value| variable_is_missing(value, variables));

        if node.is_none() || missing_variable {
            if let Some(default) = &field.default_value {
                path.push(field_name.to_string());
                let value = coerce_input_value(schema, default, &field.ty, path);
                path.pop();
                coerced.insert(field_name.clone(), value?);
            } else if field.ty.is_non_null() {
                if missing_variable {
                    if let Some(ast::Value::Variable(name)) = node {
                        return Err(at_path(
                            GraphQLError::new(format!(
                                "Field \"{}\" of required type \"{}\" was not provided because variable \"${name}\" was not provided.",
                                field_name, field.ty
                            )),
                            path,
                        ));
                    }
                }
                return Err(at_path(
                    GraphQLError::new(format!(
                        "Field \"{}\" of required type \"{}\" was not provided.",
                        field_name, field.ty
                    )),
                    path,
                ));
            }
            continue;
        }

        let Some(node) = node else { continue };
        provided += 1;
        path.push(field_name.to_string());
        let result = value_from_ast(schema, node, &field.ty, variables, path);
        path.pop();
        match result? {
            Some(value) => {
                coerced.insert(field_name.clone(), value);
            }
            None => return Ok(None),
        }
    }

    if input.one_of {
        check_one_of(&input.name, provided, &coerced, path)?;
    }

    Ok(Some(Value::Object(Arc::new(coerced))))
}

fn literal_kind(value: &ast::Value<'_>) -> &'static str {
    match value {
        ast::Value::Variable(_) => "variable",
        ast::Value::Int(_) => "integer",
        ast::Value::Float(_) => "float",
        ast::Value::String(_) => "string",
        ast::Value::Boolean(_) => "boolean",
        ast::Value::Null => "null",
        ast::Value::Enum(_) => "enum",
        ast::Value::List(_) => "list",
        ast::Value::Object(_) => "object",
    }
}

fn render_value(value: &Value) -> String {
    match value {
        Value::Null => "null".to_owned(),
        Value::Boolean(value) => value.to_string(),
        Value::Int(value) => value.to_string(),
        Value::BigInt(value) => value.to_string(),
        Value::Float(value) => value.to_string(),
        Value::String(value) => format!("{value:?}"),
        Value::Enum(value) => value.to_string(),
        Value::List(_) => "[list]".to_owned(),
        Value::Object(_) => "{object}".to_owned(),
        Value::External(_) => "<model>".to_owned(),
    }
}