Skip to main content

libgraphql_parser/ast/
fragment_definition.rs

1use crate::ast::ast_node::append_span_source_slice;
2use crate::ast::AstNode;
3use crate::ast::DirectiveAnnotation;
4use crate::ast::Name;
5use crate::ast::SelectionSet;
6use crate::ast::StringValue;
7use crate::ast::TypeCondition;
8use crate::ByteSpan;
9use crate::SourceMap;
10use crate::SourceSpan;
11use crate::token::GraphQLToken;
12use inherent::inherent;
13
14/// A named fragment definition.
15///
16/// See
17/// [Fragment Definitions](https://spec.graphql.org/September2025/#sec-Language.Fragments)
18/// in the spec.
19#[derive(Clone, Debug, PartialEq)]
20pub struct FragmentDefinition<'src> {
21    pub description: Option<StringValue<'src>>,
22    pub directives: Vec<DirectiveAnnotation<'src>>,
23    pub name: Name<'src>,
24    pub selection_set: SelectionSet<'src>,
25    pub span: ByteSpan,
26    pub syntax:
27        Option<Box<FragmentDefinitionSyntax<'src>>>,
28    pub type_condition: TypeCondition<'src>,
29}
30
31/// Syntax detail for a [`FragmentDefinition`].
32///
33/// The `on` keyword token is stored in the
34/// [`TypeConditionSyntax`](crate::ast::TypeConditionSyntax)
35/// of the fragment's [`type_condition`](FragmentDefinition::type_condition).
36#[derive(Clone, Debug, PartialEq)]
37pub struct FragmentDefinitionSyntax<'src> {
38    pub fragment_keyword: GraphQLToken<'src>,
39}
40
41impl<'src> FragmentDefinition<'src> {
42    /// Returns the name of this fragment definition as a string
43    /// slice.
44    ///
45    /// Convenience accessor for `self.name.value`.
46    #[inline]
47    pub fn name_value(&self) -> &str {
48        self.name.value.as_ref()
49    }
50}
51
52#[inherent]
53impl AstNode for FragmentDefinition<'_> {
54    /// See [`AstNode::append_source()`](crate::ast::AstNode::append_source).
55    pub fn append_source(
56        &self,
57        sink: &mut String,
58        source: Option<&str>,
59    ) {
60        if let Some(src) = source {
61            append_span_source_slice(
62                self.span, sink, src,
63            );
64        }
65    }
66
67    /// Returns this fragment definition's byte-offset span within the
68    /// source text.
69    ///
70    /// The returned [`ByteSpan`] can be resolved to line/column
71    /// positions via [`source_span()`](Self::source_span) or
72    /// [`ByteSpan::resolve()`].
73    #[inline]
74    pub fn byte_span(&self) -> ByteSpan {
75        self.span
76    }
77
78    /// Resolves this fragment definition's position to line/column
79    /// coordinates using the given [`SourceMap`].
80    ///
81    /// Returns [`None`] if the byte offsets cannot be resolved
82    /// (e.g. the span was synthetically constructed without
83    /// valid position data).
84    #[inline]
85    pub fn source_span(
86        &self,
87        source_map: &SourceMap,
88    ) -> Option<SourceSpan> {
89        self.byte_span().resolve(source_map)
90    }
91}