Skip to main content

libgraphql_parser/ast/
variable_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::StringValue;
6use crate::ast::TypeAnnotation;
7use crate::ast::Value;
8use crate::ByteSpan;
9use crate::SourceMap;
10use crate::SourceSpan;
11use crate::token::GraphQLToken;
12use inherent::inherent;
13
14/// A variable definition within an operation's
15/// variable list (e.g. `$id: ID! = "default"`).
16///
17/// See
18/// [Variable Definitions](https://spec.graphql.org/September2025/#sec-Language.Variables)
19/// in the spec.
20#[derive(Clone, Debug, PartialEq)]
21pub struct VariableDefinition<'src> {
22    pub default_value: Option<Value<'src>>,
23    pub description: Option<StringValue<'src>>,
24    pub directives: Vec<DirectiveAnnotation<'src>>,
25    pub span: ByteSpan,
26    pub syntax:
27        Option<Box<VariableDefinitionSyntax<'src>>>,
28    pub var_type: TypeAnnotation<'src>,
29    pub variable: Name<'src>,
30}
31
32/// Syntax detail for a [`VariableDefinition`].
33#[derive(Clone, Debug, PartialEq)]
34pub struct VariableDefinitionSyntax<'src> {
35    pub colon: GraphQLToken<'src>,
36    pub dollar: GraphQLToken<'src>,
37    pub equals: Option<GraphQLToken<'src>>,
38}
39
40#[inherent]
41impl AstNode for VariableDefinition<'_> {
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 definition's byte-offset span within the
56    /// 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 definition'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    #[inline]
73    pub fn source_span(
74        &self,
75        source_map: &SourceMap,
76    ) -> Option<SourceSpan> {
77        self.byte_span().resolve(source_map)
78    }
79}