Skip to main content

bluejay_parser/ast/executable/
inline_fragment.rs

1use crate::ast::executable::{SelectionSet, TypeCondition};
2use crate::ast::{DepthLimiter, FromTokens, IsMatch, ParseError, Tokens, VariableDirectives};
3use crate::lexical_token::PunctuatorType;
4use crate::{HasSpan, Span};
5
6#[derive(Debug)]
7pub struct InlineFragment<'a> {
8    type_condition: Option<TypeCondition<'a>>,
9    directives: Option<VariableDirectives<'a>>,
10    selection_set: SelectionSet<'a>,
11    span: Span,
12}
13
14impl<'a> FromTokens<'a> for InlineFragment<'a> {
15    #[inline]
16    fn from_tokens(
17        tokens: &mut impl Tokens<'a>,
18        depth_limiter: DepthLimiter,
19    ) -> Result<Self, ParseError> {
20        let ellipse_span = tokens.expect_punctuator(PunctuatorType::Ellipse)?;
21        let type_condition = if TypeCondition::is_match(tokens) {
22            Some(TypeCondition::from_tokens(tokens, depth_limiter.bump()?)?)
23        } else {
24            None
25        };
26        let directives = if VariableDirectives::is_match(tokens) {
27            Some(VariableDirectives::from_tokens(
28                tokens,
29                depth_limiter.bump()?,
30            )?)
31        } else {
32            None
33        };
34        let selection_set = SelectionSet::from_tokens(tokens, depth_limiter.bump()?)?;
35        let span = ellipse_span.merge(selection_set.span());
36        Ok(Self {
37            type_condition,
38            directives,
39            selection_set,
40            span,
41        })
42    }
43}
44
45impl<'a> IsMatch<'a> for InlineFragment<'a> {
46    #[inline]
47    fn is_match(tokens: &mut impl Tokens<'a>) -> bool {
48        tokens.peek_punctuator_matches(0, PunctuatorType::Ellipse)
49            && tokens
50                .peek_name(1)
51                .map(|n| n.as_ref() == TypeCondition::ON)
52                .unwrap_or(true)
53    }
54}
55
56impl<'a> InlineFragment<'a> {
57    pub fn type_condition(&self) -> Option<&TypeCondition<'a>> {
58        self.type_condition.as_ref()
59    }
60
61    pub fn selection_set(&self) -> &SelectionSet<'a> {
62        &self.selection_set
63    }
64}
65
66impl<'a> bluejay_core::executable::InlineFragment for InlineFragment<'a> {
67    type Directives = VariableDirectives<'a>;
68    type SelectionSet = SelectionSet<'a>;
69
70    fn type_condition(&self) -> Option<&str> {
71        self.type_condition
72            .as_ref()
73            .map(|tc| tc.named_type().as_ref())
74    }
75
76    fn directives(&self) -> Option<&Self::Directives> {
77        self.directives.as_ref()
78    }
79
80    fn selection_set(&self) -> &Self::SelectionSet {
81        &self.selection_set
82    }
83}
84
85impl HasSpan for InlineFragment<'_> {
86    fn span(&self) -> &Span {
87        &self.span
88    }
89}