Skip to main content

libgraphql_parser/ast/
variable_reference.rs

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