libgraphql_parser/ast/type_annotation.rs
1use crate::ast::AstNode;
2use crate::ast::ListTypeAnnotation;
3use crate::ast::NamedTypeAnnotation;
4use crate::ByteSpan;
5use crate::SourceMap;
6use crate::SourceSpan;
7use inherent::inherent;
8
9/// A GraphQL
10/// [type reference](https://spec.graphql.org/September2025/#sec-Type-References)
11/// (type annotation).
12///
13/// Represents [`NamedType`](https://spec.graphql.org/September2025/#NamedType) and
14/// [`ListType`](https://spec.graphql.org/September2025/#ListType) from the spec grammar. The spec's
15/// [`NonNullType`](https://spec.graphql.org/September2025/#NonNullType) is not a separate variant
16/// here — instead, nullability is expressed via the [`Nullability`](crate::ast::Nullability) field
17/// on each variant's inner struct.
18#[derive(Clone, Debug, PartialEq)]
19pub enum TypeAnnotation<'src> {
20 List(ListTypeAnnotation<'src>),
21 Named(NamedTypeAnnotation<'src>),
22}
23
24impl<'src> TypeAnnotation<'src> {
25 /// Returns `true` if this type annotation is nullable
26 /// (i.e. does **not** have a trailing `!`).
27 pub fn nullable(&self) -> bool {
28 match self {
29 Self::List(annot) => annot.nullable(),
30 Self::Named(annot) => annot.nullable(),
31 }
32 }
33}
34
35#[inherent]
36impl AstNode for TypeAnnotation<'_> {
37 /// See [`AstNode::append_source()`](crate::ast::AstNode::append_source).
38 pub fn append_source(
39 &self,
40 sink: &mut String,
41 source: Option<&str>,
42 ) {
43 match self {
44 TypeAnnotation::List(v) => {
45 v.append_source(sink, source)
46 },
47 TypeAnnotation::Named(v) => {
48 v.append_source(sink, source)
49 },
50 }
51 }
52
53 /// Returns this type annotation's byte-offset span within
54 /// the source text.
55 ///
56 /// The returned [`ByteSpan`] can be resolved to line/column
57 /// positions via [`source_span()`](Self::source_span) or
58 /// [`ByteSpan::resolve()`].
59 pub fn byte_span(&self) -> ByteSpan {
60 match self {
61 Self::List(annot) => annot.span,
62 Self::Named(annot) => annot.span,
63 }
64 }
65
66 /// Resolves this type annotation's position to line/column
67 /// coordinates using the given [`SourceMap`].
68 ///
69 /// Returns [`None`] if the byte offsets cannot be resolved
70 /// (e.g. the span was synthetically constructed without
71 /// valid position data).
72 pub fn source_span(
73 &self,
74 source_map: &SourceMap,
75 ) -> Option<SourceSpan> {
76 self.byte_span().resolve(source_map)
77 }
78}