bluejay_parser/ast/executable/
fragment_definition.rs1use crate::ast::executable::{SelectionSet, TypeCondition};
2use crate::ast::try_from_tokens::TryFromTokens;
3use crate::ast::{DepthLimiter, FromTokens, IsMatch, ParseError, Tokens, VariableDirectives};
4use crate::lexical_token::{Name, StringValue};
5use crate::{HasSpan, Span};
6
7#[derive(Debug)]
8pub struct FragmentDefinition<'a> {
9 description: Option<StringValue<'a>>,
10 name: Name<'a>,
11 type_condition: TypeCondition<'a>,
12 directives: Option<VariableDirectives<'a>>,
13 selection_set: SelectionSet<'a>,
14 span: Span,
15}
16
17impl<'a> IsMatch<'a> for FragmentDefinition<'a> {
18 #[inline]
19 fn is_match(tokens: &mut impl Tokens<'a>) -> bool {
20 tokens.peek_name_matches(0, "fragment")
21 || (tokens.peek_string_value(0) && tokens.peek_name_matches(1, "fragment"))
22 }
23}
24
25impl<'a> FromTokens<'a> for FragmentDefinition<'a> {
26 #[inline]
27 fn from_tokens(
28 tokens: &mut impl Tokens<'a>,
29 depth_limiter: DepthLimiter,
30 ) -> Result<Self, ParseError> {
31 let description = tokens.next_if_string_value();
32 let fragment_identifier_span = tokens.expect_name_value("fragment")?;
33 let name = tokens.expect_name()?;
34 if name.as_ref() == TypeCondition::ON {
35 return Err(ParseError::UnexpectedToken { span: name.into() });
37 }
38 let type_condition = TypeCondition::from_tokens(tokens, depth_limiter.bump()?)?;
39 let directives = VariableDirectives::try_from_tokens(tokens, depth_limiter.bump()?)?;
40 let selection_set = SelectionSet::from_tokens(tokens, depth_limiter.bump()?)?;
41 let span = if let Some(desc) = &description {
42 desc.span().merge(selection_set.span())
43 } else {
44 fragment_identifier_span.merge(selection_set.span())
45 };
46 Ok(Self {
47 description,
48 name,
49 type_condition,
50 directives,
51 selection_set,
52 span,
53 })
54 }
55}
56
57impl<'a> FragmentDefinition<'a> {
58 pub fn name(&self) -> &Name<'a> {
59 &self.name
60 }
61
62 pub fn type_condition(&self) -> &TypeCondition<'a> {
63 &self.type_condition
64 }
65
66 pub fn selection_set(&self) -> &SelectionSet<'_> {
67 &self.selection_set
68 }
69}
70
71impl bluejay_core::Indexable for FragmentDefinition<'_> {
72 type Id = Span;
73
74 fn id(&self) -> &Self::Id {
75 &self.span
76 }
77}
78
79impl<'a> bluejay_core::executable::FragmentDefinition for FragmentDefinition<'a> {
80 type Directives = VariableDirectives<'a>;
81 type SelectionSet = SelectionSet<'a>;
82
83 fn description(&self) -> Option<&str> {
84 self.description.as_ref().map(AsRef::as_ref)
85 }
86
87 fn name(&self) -> &str {
88 self.name.as_ref()
89 }
90
91 fn type_condition(&self) -> &str {
92 self.type_condition.named_type().as_ref()
93 }
94
95 fn directives(&self) -> Option<&Self::Directives> {
96 self.directives.as_ref()
97 }
98
99 fn selection_set(&self) -> &Self::SelectionSet {
100 &self.selection_set
101 }
102}
103
104impl HasSpan for FragmentDefinition<'_> {
105 fn span(&self) -> &Span {
106 &self.span
107 }
108}