Skip to main content

libgraphql_parser/ast/
field_selection.rs

1use crate::ast::Argument;
2use crate::ast::ast_node::append_span_source_slice;
3use crate::ast::AstNode;
4use crate::ast::DelimiterPair;
5use crate::ast::DirectiveAnnotation;
6use crate::ast::Name;
7use crate::ast::SelectionSet;
8use crate::ByteSpan;
9use crate::SourceMap;
10use crate::SourceSpan;
11use crate::token::GraphQLToken;
12use inherent::inherent;
13
14/// A field selection within a selection set, optionally
15/// aliased, with arguments, directives, and a nested
16/// selection set.
17///
18/// See
19/// [Fields](https://spec.graphql.org/September2025/#sec-Language.Fields)
20/// in the spec.
21#[derive(Clone, Debug, PartialEq)]
22pub struct FieldSelection<'src> {
23    pub alias: Option<Name<'src>>,
24    pub arguments: Vec<Argument<'src>>,
25    pub directives: Vec<DirectiveAnnotation<'src>>,
26    pub name: Name<'src>,
27    pub selection_set: Option<SelectionSet<'src>>,
28    pub span: ByteSpan,
29    pub syntax: Option<Box<FieldSelectionSyntax<'src>>>,
30}
31
32/// Syntax detail for a [`FieldSelection`].
33#[derive(Clone, Debug, PartialEq)]
34pub struct FieldSelectionSyntax<'src> {
35    /// The colon between alias and field name. `None`
36    /// when no alias is present.
37    pub alias_colon: Option<GraphQLToken<'src>>,
38    pub argument_parens: Option<DelimiterPair<'src>>,
39}
40
41impl<'src> FieldSelection<'src> {
42    /// Returns the name of this field selection as a
43    /// string 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 FieldSelection<'_> {
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 field selection's byte-offset span
68    /// within the 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 field selection's position to
79    /// line/column coordinates using the given
80    /// [`SourceMap`].
81    ///
82    /// Returns [`None`] if the byte offsets cannot be resolved
83    /// (e.g. the span was synthetically constructed without
84    /// valid position data).
85    #[inline]
86    pub fn source_span(
87        &self,
88        source_map: &SourceMap,
89    ) -> Option<SourceSpan> {
90        self.byte_span().resolve(source_map)
91    }
92}