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
//! Parsing and printing for schema coordinates as described in [the RFC].
//!
//! Schema coordinates uniquely point to an item defined in a schema.
//!
//! [the RFC]: https://github.com/graphql/graphql-wg/blob/main/rfcs/SchemaCoordinates.md

use crate::ast::InvalidNameError;
use crate::ast::Name;
use crate::schema::Component;
use crate::schema::DirectiveDefinition;
use crate::schema::EnumValueDefinition;
use crate::schema::ExtendedType;
use crate::schema::FieldDefinition;
use crate::schema::InputValueDefinition;
use crate::schema::NamedType;
use crate::schema::Schema;
use crate::Node;
use std::fmt;
use std::str::FromStr;

/// Create a static schema coordinate at compile time.
///
/// ```rust
/// use apollo_compiler::coord;
///
/// assert_eq!(coord!(@directive).to_string(), "@directive");
/// assert_eq!(coord!(@directive(arg:)).to_string(), "@directive(arg:)");
/// assert_eq!(coord!(Type).to_string(), "Type");
/// assert_eq!(coord!(Type.field).to_string(), "Type.field");
/// assert_eq!(coord!(Type.field(arg:)).to_string(), "Type.field(arg:)");
/// assert_eq!(coord!(EnumType.ENUM_VALUE).to_string(), "EnumType.ENUM_VALUE");
/// ```
#[macro_export]
macro_rules! coord {
    ( @ $name:ident ) => {
        $crate::coordinate::DirectiveCoordinate {
            directive: $crate::name!($name),
        }
    };
    ( @ $name:ident ( $arg:ident : ) ) => {
        $crate::coordinate::DirectiveArgumentCoordinate {
            directive: $crate::name!($name),
            argument: $crate::name!($arg),
        }
    };
    ( $name:ident ) => {
        $crate::coordinate::TypeCoordinate {
            ty: $crate::name!($name),
        }
    };
    ( $name:ident . $attribute:ident ) => {
        $crate::coordinate::TypeAttributeCoordinate {
            ty: $crate::name!($name),
            attribute: $crate::name!($attribute),
        }
    };
    ( $name:ident . $field:ident ( $arg:ident : ) ) => {
        $crate::coordinate::FieldArgumentCoordinate {
            ty: $crate::name!($name),
            field: $crate::name!($field),
            argument: $crate::name!($arg),
        }
    };
}

/// A schema coordinate targeting a type definition: `Type`.
///
/// # Example
/// ```
/// use apollo_compiler::name;
/// use apollo_compiler::coordinate::TypeCoordinate;
///
/// assert_eq!(TypeCoordinate { ty: name!("Type") }.to_string(), "Type");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TypeCoordinate {
    pub ty: NamedType,
}

/// A schema coordinate targeting a field definition or an enum value: `Type.field`, `Enum.VALUE`.
///
/// Type attribute coordinate syntax can refer to object or interface field definitions, input
/// field definitions, and enum values. [`TypeAttributeCoordinate::lookup`] returns an enum to
/// account for those possibilities. To look up a specific kind of type attribute, there are
/// convenience methods:
/// - [`TypeAttributeCoordinate::lookup_field`] for object or interface fields
/// - [`TypeAttributeCoordinate::lookup_input_field`] for input fields
/// - [`TypeAttributeCoordinate::lookup_enum_value`] for enum values
///
/// # Example
/// ```
/// use apollo_compiler::name;
/// use apollo_compiler::coordinate::TypeAttributeCoordinate;
///
/// assert_eq!(TypeAttributeCoordinate {
///     ty: name!("Type"),
///     attribute: name!("field"),
/// }.to_string(), "Type.field");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TypeAttributeCoordinate {
    pub ty: NamedType,
    pub attribute: Name,
}

/// A schema coordinate targeting a field argument definition: `Type.field(argument:)`.
///
/// # Example
/// ```
/// use apollo_compiler::name;
/// use apollo_compiler::coordinate::FieldArgumentCoordinate;
///
/// assert_eq!(FieldArgumentCoordinate {
///     ty: name!("Type"),
///     field: name!("field"),
///     argument: name!("argument"),
/// }.to_string(), "Type.field(argument:)");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldArgumentCoordinate {
    pub ty: NamedType,
    pub field: Name,
    pub argument: Name,
}

/// A schema coordinate targeting a directive definition: `@directive`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DirectiveCoordinate {
    pub directive: Name,
}

/// A schema coordinate targeting a directive argument definition: `@directive(argument:)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DirectiveArgumentCoordinate {
    pub directive: Name,
    pub argument: Name,
}

/// Any schema coordinate.
///
/// # Example
/// ```
/// use apollo_compiler::name;
/// use apollo_compiler::coordinate::{SchemaCoordinate, FieldArgumentCoordinate};
///
/// let coord: SchemaCoordinate = "Type.field(argument:)".parse().unwrap();
/// assert_eq!(coord, SchemaCoordinate::FieldArgument(
///     FieldArgumentCoordinate {
///         ty: name!("Type"),
///         field: name!("field"),
///         argument: name!("argument"),
///     },
/// ));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SchemaCoordinate {
    Type(TypeCoordinate),
    TypeAttribute(TypeAttributeCoordinate),
    FieldArgument(FieldArgumentCoordinate),
    Directive(DirectiveCoordinate),
    DirectiveArgument(DirectiveArgumentCoordinate),
}

/// Errors that can occur while parsing a schema coordinate.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum SchemaCoordinateParseError {
    /// Invalid format, eg. unexpected characters
    #[error("invalid schema coordinate")]
    InvalidFormat,
    /// A name part contains invalid characters
    #[error(transparent)]
    InvalidName(#[from] InvalidNameError),
}

/// Errors that can occur while looking up a schema coordinate.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SchemaLookupError<'coord, 'schema> {
    /// The requested type does not exist in the schema.
    #[error("type `{0}` does not exist")]
    MissingType(&'coord NamedType),
    /// The requested field or enum value does not exist on its type.
    #[error("type does not have attribute `{0}`")]
    MissingAttribute(&'coord Name),
    /// The requested argument can not be looked up because its type does not support arguments.
    #[error("type attribute `{0}` is not a field and can not have arguments")]
    InvalidArgumentAttribute(&'coord Name),
    /// The requested argument does not exist on its field or directive.
    #[error("field or directive does not have argument `{0}`")]
    MissingArgument(&'coord Name),
    /// The requested field or enum value can not be looked up because its type does not support
    /// fields.
    #[error("type does not have attributes")]
    InvalidType(&'schema ExtendedType),
}

/// Possible types selected by a type attribute coordinate, of the form `Type.field`.
#[derive(Debug, Clone, PartialEq, Eq)]
// Should this be non-exhaustive? Allows for future extension should unions ever be added.
#[non_exhaustive]
pub enum TypeAttributeLookup<'schema> {
    Field(&'schema Component<FieldDefinition>),
    InputField(&'schema Component<InputValueDefinition>),
    EnumValue(&'schema Component<EnumValueDefinition>),
}

/// Possible types selected by a schema coordinate.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SchemaCoordinateLookup<'schema> {
    Type(&'schema ExtendedType),
    Directive(&'schema Node<DirectiveDefinition>),
    Field(&'schema Component<FieldDefinition>),
    InputField(&'schema Component<InputValueDefinition>),
    EnumValue(&'schema Component<EnumValueDefinition>),
    Argument(&'schema Node<InputValueDefinition>),
}

impl TypeCoordinate {
    /// Create a schema coordinate that points to an attribute on this type.
    ///
    /// For object types and interfaces, the resulting coordinate points to a field. For enums, the
    /// resulting coordinate points to a value.
    pub fn with_attribute(&self, attribute: Name) -> TypeAttributeCoordinate {
        TypeAttributeCoordinate {
            ty: self.ty.clone(),
            attribute,
        }
    }

    fn lookup_ref<'coord, 'schema>(
        ty: &'coord NamedType,
        schema: &'schema Schema,
    ) -> Result<&'schema ExtendedType, SchemaLookupError<'coord, 'schema>> {
        schema
            .types
            .get(ty)
            .ok_or(SchemaLookupError::MissingType(ty))
    }

    /// Look up this type coordinate in a schema.
    pub fn lookup<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<&'schema ExtendedType, SchemaLookupError<'coord, 'schema>> {
        Self::lookup_ref(&self.ty, schema)
    }
}

impl FromStr for TypeCoordinate {
    type Err = SchemaCoordinateParseError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Ok(Self {
            ty: NamedType::try_from(input)?,
        })
    }
}

impl TypeAttributeCoordinate {
    /// Create a schema coordinate that points to the type this attribute is part of.
    pub fn type_coordinate(&self) -> TypeCoordinate {
        TypeCoordinate {
            ty: self.ty.clone(),
        }
    }

    /// Assume this attribute is a field, and create a schema coordinate that points to an argument on this field.
    pub fn with_argument(&self, argument: Name) -> FieldArgumentCoordinate {
        FieldArgumentCoordinate {
            ty: self.ty.clone(),
            field: self.attribute.clone(),
            argument,
        }
    }

    fn lookup_ref<'coord, 'schema>(
        ty: &'coord NamedType,
        attribute: &'coord Name,
        schema: &'schema Schema,
    ) -> Result<TypeAttributeLookup<'schema>, SchemaLookupError<'coord, 'schema>> {
        let ty = TypeCoordinate::lookup_ref(ty, schema)?;
        match ty {
            ExtendedType::Enum(enum_) => enum_
                .values
                .get(attribute)
                .ok_or(SchemaLookupError::MissingAttribute(attribute))
                .map(TypeAttributeLookup::EnumValue),
            ExtendedType::InputObject(input_object) => input_object
                .fields
                .get(attribute)
                .ok_or(SchemaLookupError::MissingAttribute(attribute))
                .map(TypeAttributeLookup::InputField),
            ExtendedType::Object(object) => object
                .fields
                .get(attribute)
                .ok_or(SchemaLookupError::MissingAttribute(attribute))
                .map(TypeAttributeLookup::Field),
            ExtendedType::Interface(interface) => interface
                .fields
                .get(attribute)
                .ok_or(SchemaLookupError::MissingAttribute(attribute))
                .map(TypeAttributeLookup::Field),
            ExtendedType::Union(_) | ExtendedType::Scalar(_) => {
                Err(SchemaLookupError::InvalidType(ty))
            }
        }
    }

    /// Look up this type attribute in a schema.
    pub fn lookup<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<TypeAttributeLookup<'schema>, SchemaLookupError<'coord, 'schema>> {
        Self::lookup_ref(&self.ty, &self.attribute, schema)
    }

    /// Look up this field definition in a schema. If the attribute does not refer to an object or
    /// interface field, returns `SchemaLookupError::InvalidType`.
    pub fn lookup_field<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<&'schema Component<FieldDefinition>, SchemaLookupError<'coord, 'schema>> {
        let ty = TypeCoordinate::lookup_ref(&self.ty, schema)?;
        match ty {
            ExtendedType::Object(object) => object
                .fields
                .get(&self.attribute)
                .ok_or(SchemaLookupError::MissingAttribute(&self.attribute)),
            ExtendedType::Interface(interface) => interface
                .fields
                .get(&self.attribute)
                .ok_or(SchemaLookupError::MissingAttribute(&self.attribute)),
            _ => Err(SchemaLookupError::InvalidType(ty)),
        }
    }

    /// Look up this input field definition in a schema. If the attribute does not refer to an
    /// input field, returns `SchemaLookupError::InvalidType`.
    pub fn lookup_input_field<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<&'schema Component<InputValueDefinition>, SchemaLookupError<'coord, 'schema>> {
        let ty = TypeCoordinate::lookup_ref(&self.ty, schema)?;
        match ty {
            ExtendedType::InputObject(object) => object
                .fields
                .get(&self.attribute)
                .ok_or(SchemaLookupError::MissingAttribute(&self.attribute)),
            _ => Err(SchemaLookupError::InvalidType(ty)),
        }
    }

    /// Look up this enum value definition in a schema. If the attribute does not refer to an
    /// enum, returns `SchemaLookupError::InvalidType`.
    pub fn lookup_enum_value<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<&'schema Component<EnumValueDefinition>, SchemaLookupError<'coord, 'schema>> {
        let ty = TypeCoordinate::lookup_ref(&self.ty, schema)?;
        match ty {
            ExtendedType::Enum(enum_) => enum_
                .values
                .get(&self.attribute)
                .ok_or(SchemaLookupError::MissingAttribute(&self.attribute)),
            _ => Err(SchemaLookupError::InvalidType(ty)),
        }
    }
}

impl FromStr for TypeAttributeCoordinate {
    type Err = SchemaCoordinateParseError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let Some((type_name, field)) = input.split_once('.') else {
            return Err(SchemaCoordinateParseError::InvalidFormat);
        };
        Ok(Self {
            ty: NamedType::try_from(type_name)?,
            attribute: Name::try_from(field)?,
        })
    }
}

impl FieldArgumentCoordinate {
    /// Create a schema coordinate that points to the type this argument is defined in.
    pub fn type_coordinate(&self) -> TypeCoordinate {
        TypeCoordinate {
            ty: self.ty.clone(),
        }
    }

    /// Create a schema coordinate that points to the field this argument is defined in.
    pub fn field_coordinate(&self) -> TypeAttributeCoordinate {
        TypeAttributeCoordinate {
            ty: self.ty.clone(),
            attribute: self.field.clone(),
        }
    }

    fn lookup_ref<'coord, 'schema>(
        ty: &'coord NamedType,
        field: &'coord Name,
        argument: &'coord Name,
        schema: &'schema Schema,
    ) -> Result<&'schema Node<InputValueDefinition>, SchemaLookupError<'coord, 'schema>> {
        match TypeAttributeCoordinate::lookup_ref(ty, field, schema)? {
            TypeAttributeLookup::Field(field) => field
                .argument_by_name(argument)
                .ok_or(SchemaLookupError::MissingArgument(argument)),
            _ => Err(SchemaLookupError::InvalidArgumentAttribute(field)),
        }
    }

    /// Look up this argument definition in a schema.
    pub fn lookup<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<&'schema Node<InputValueDefinition>, SchemaLookupError<'coord, 'schema>> {
        Self::lookup_ref(&self.ty, &self.field, &self.argument, schema)
    }
}

impl FromStr for FieldArgumentCoordinate {
    type Err = SchemaCoordinateParseError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let Some((field, rest)) = input.split_once('(') else {
            return Err(SchemaCoordinateParseError::InvalidFormat);
        };
        let field = TypeAttributeCoordinate::from_str(field)?;

        let Some((argument, ")")) = rest.split_once(':') else {
            return Err(SchemaCoordinateParseError::InvalidFormat);
        };
        Ok(Self {
            ty: field.ty,
            field: field.attribute,
            argument: Name::try_from(argument)?,
        })
    }
}

impl DirectiveCoordinate {
    /// Create a schema coordinate that points to an argument of this directive.
    pub fn with_argument(&self, argument: Name) -> DirectiveArgumentCoordinate {
        DirectiveArgumentCoordinate {
            directive: self.directive.clone(),
            argument,
        }
    }

    fn lookup_ref<'coord, 'schema>(
        directive: &'coord Name,
        schema: &'schema Schema,
    ) -> Result<&'schema Node<DirectiveDefinition>, SchemaLookupError<'coord, 'schema>> {
        schema
            .directive_definitions
            .get(directive)
            .ok_or(SchemaLookupError::MissingType(directive))
    }

    /// Look up this directive in a schema.
    pub fn lookup<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<&'schema Node<DirectiveDefinition>, SchemaLookupError<'coord, 'schema>> {
        Self::lookup_ref(&self.directive, schema)
    }
}

impl From<Name> for DirectiveCoordinate {
    fn from(directive: Name) -> Self {
        Self { directive }
    }
}

impl FromStr for DirectiveCoordinate {
    type Err = SchemaCoordinateParseError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        if let Some(directive) = input.strip_prefix('@') {
            Ok(Self {
                directive: Name::try_from(directive)?,
            })
        } else {
            Err(SchemaCoordinateParseError::InvalidFormat)
        }
    }
}

impl DirectiveArgumentCoordinate {
    /// Create a schema coordinate that points to the directive this argument is defined in.
    pub fn directive_coordinate(&self) -> DirectiveCoordinate {
        DirectiveCoordinate {
            directive: self.directive.clone(),
        }
    }

    fn lookup_ref<'coord, 'schema>(
        directive: &'coord Name,
        argument: &'coord Name,
        schema: &'schema Schema,
    ) -> Result<&'schema Node<InputValueDefinition>, SchemaLookupError<'coord, 'schema>> {
        DirectiveCoordinate::lookup_ref(directive, schema)?
            .argument_by_name(argument)
            .ok_or(SchemaLookupError::MissingArgument(argument))
    }

    /// Look up this directive argument in a schema.
    pub fn lookup<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<&'schema Node<InputValueDefinition>, SchemaLookupError<'coord, 'schema>> {
        Self::lookup_ref(&self.directive, &self.argument, schema)
    }
}

impl FromStr for DirectiveArgumentCoordinate {
    type Err = SchemaCoordinateParseError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let Some((directive, rest)) = input.split_once('(') else {
            return Err(SchemaCoordinateParseError::InvalidFormat);
        };
        let directive = DirectiveCoordinate::from_str(directive)?;

        let Some((argument, ")")) = rest.split_once(':') else {
            return Err(SchemaCoordinateParseError::InvalidFormat);
        };
        Ok(Self {
            directive: directive.directive,
            argument: Name::try_from(argument)?,
        })
    }
}

impl<'schema> From<&'schema ExtendedType> for SchemaCoordinateLookup<'schema> {
    fn from(inner: &'schema ExtendedType) -> Self {
        Self::Type(inner)
    }
}

impl<'schema> From<&'schema Node<DirectiveDefinition>> for SchemaCoordinateLookup<'schema> {
    fn from(inner: &'schema Node<DirectiveDefinition>) -> Self {
        Self::Directive(inner)
    }
}

impl<'schema> From<&'schema Component<FieldDefinition>> for SchemaCoordinateLookup<'schema> {
    fn from(inner: &'schema Component<FieldDefinition>) -> Self {
        Self::Field(inner)
    }
}

impl<'schema> From<&'schema Component<InputValueDefinition>> for SchemaCoordinateLookup<'schema> {
    fn from(inner: &'schema Component<InputValueDefinition>) -> Self {
        Self::InputField(inner)
    }
}

impl<'schema> From<&'schema Component<EnumValueDefinition>> for SchemaCoordinateLookup<'schema> {
    fn from(inner: &'schema Component<EnumValueDefinition>) -> Self {
        Self::EnumValue(inner)
    }
}

impl<'schema> From<TypeAttributeLookup<'schema>> for SchemaCoordinateLookup<'schema> {
    fn from(attr: TypeAttributeLookup<'schema>) -> Self {
        match attr {
            TypeAttributeLookup::Field(field) => SchemaCoordinateLookup::Field(field),
            TypeAttributeLookup::InputField(field) => SchemaCoordinateLookup::InputField(field),
            TypeAttributeLookup::EnumValue(field) => SchemaCoordinateLookup::EnumValue(field),
        }
    }
}

impl<'schema> From<&'schema Node<InputValueDefinition>> for SchemaCoordinateLookup<'schema> {
    fn from(inner: &'schema Node<InputValueDefinition>) -> Self {
        Self::Argument(inner)
    }
}

impl SchemaCoordinate {
    /// Look up this coordinate in a schema.
    pub fn lookup<'coord, 'schema>(
        &'coord self,
        schema: &'schema Schema,
    ) -> Result<SchemaCoordinateLookup<'schema>, SchemaLookupError<'coord, 'schema>> {
        match self {
            SchemaCoordinate::Type(coordinate) => coordinate.lookup(schema).map(Into::into),
            SchemaCoordinate::TypeAttribute(coordinate) => {
                coordinate.lookup(schema).map(Into::into)
            }
            SchemaCoordinate::FieldArgument(coordinate) => {
                coordinate.lookup(schema).map(Into::into)
            }
            SchemaCoordinate::Directive(coordinate) => coordinate.lookup(schema).map(Into::into),
            SchemaCoordinate::DirectiveArgument(coordinate) => {
                coordinate.lookup(schema).map(Into::into)
            }
        }
    }
}

impl FromStr for SchemaCoordinate {
    type Err = SchemaCoordinateParseError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        if input.starts_with('@') {
            DirectiveArgumentCoordinate::from_str(input)
                .map(Self::DirectiveArgument)
                .or_else(|_| DirectiveCoordinate::from_str(input).map(Self::Directive))
        } else {
            FieldArgumentCoordinate::from_str(input)
                .map(Self::FieldArgument)
                .or_else(|_| TypeAttributeCoordinate::from_str(input).map(Self::TypeAttribute))
                .or_else(|_| TypeCoordinate::from_str(input).map(Self::Type))
        }
    }
}

impl From<TypeCoordinate> for SchemaCoordinate {
    fn from(inner: TypeCoordinate) -> Self {
        Self::Type(inner)
    }
}

impl From<TypeAttributeCoordinate> for SchemaCoordinate {
    fn from(inner: TypeAttributeCoordinate) -> Self {
        Self::TypeAttribute(inner)
    }
}

impl From<FieldArgumentCoordinate> for SchemaCoordinate {
    fn from(inner: FieldArgumentCoordinate) -> Self {
        Self::FieldArgument(inner)
    }
}

impl From<DirectiveCoordinate> for SchemaCoordinate {
    fn from(inner: DirectiveCoordinate) -> Self {
        Self::Directive(inner)
    }
}

impl From<DirectiveArgumentCoordinate> for SchemaCoordinate {
    fn from(inner: DirectiveArgumentCoordinate) -> Self {
        Self::DirectiveArgument(inner)
    }
}

impl fmt::Display for TypeCoordinate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { ty } = self;
        write!(f, "{ty}")
    }
}

impl fmt::Display for TypeAttributeCoordinate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            ty,
            attribute: field,
        } = self;
        write!(f, "{ty}.{field}")
    }
}

impl fmt::Display for FieldArgumentCoordinate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            ty,
            field,
            argument,
        } = self;
        write!(f, "{ty}.{field}({argument}:)")
    }
}

impl fmt::Display for DirectiveCoordinate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { directive } = self;
        write!(f, "@{directive}")
    }
}

impl fmt::Display for DirectiveArgumentCoordinate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            directive,
            argument,
        } = self;
        write!(f, "@{directive}({argument}:)")
    }
}

impl fmt::Display for SchemaCoordinate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Type(inner) => inner.fmt(f),
            Self::TypeAttribute(inner) => inner.fmt(f),
            Self::FieldArgument(inner) => inner.fmt(f),
            Self::Directive(inner) => inner.fmt(f),
            Self::DirectiveArgument(inner) => inner.fmt(f),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn invalid_coordinates() {
        SchemaCoordinate::from_str("Type\\.field(arg:)").expect_err("invalid character");
        SchemaCoordinate::from_str("@directi^^ve").expect_err("invalid character");
        SchemaCoordinate::from_str("@directi@ve").expect_err("invalid character");
        SchemaCoordinate::from_str("@  spaces  ").expect_err("invalid character");

        SchemaCoordinate::from_str("@(:)").expect_err("directive argument syntax without names");
        SchemaCoordinate::from_str("@dir(:)")
            .expect_err("directive argument syntax without argument name");
        SchemaCoordinate::from_str("@(arg:)")
            .expect_err("directive argument syntax without directive name");

        SchemaCoordinate::from_str("Type.")
            .expect_err("type attribute syntax without attribute name");
        SchemaCoordinate::from_str(".field").expect_err("type attribute syntax without type name");
        SchemaCoordinate::from_str("Type.field(:)")
            .expect_err("field argument syntax without field name");
        SchemaCoordinate::from_str("Type.field(arg)").expect_err("field argument syntax without :");
    }
}