1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use crate::ast::executable::{
    ExecutableDefinition, ExplicitOperationDefinition, Field, FragmentDefinition, FragmentSpread,
    ImplicitOperationDefinition, InlineFragment, OperationDefinition, Selection, SelectionSet,
    VariableDefinition, VariableDefinitions, VariableType,
};
use crate::ast::{
    Argument, Arguments, Directive, Directives, ParseError, ScannerTokens, TryFromTokens, Value,
};
use crate::scanner::LogosScanner;
use crate::Error;

#[derive(Debug)]
pub struct ExecutableDocument<'a> {
    operation_definitions: Vec<OperationDefinition<'a>>,
    fragment_definitions: Vec<FragmentDefinition<'a>>,
}

impl<'a> ExecutableDocument<'a> {
    pub(crate) fn new(
        operation_definitions: Vec<OperationDefinition<'a>>,
        fragment_definitions: Vec<FragmentDefinition<'a>>,
    ) -> Self {
        Self {
            operation_definitions,
            fragment_definitions,
        }
    }

    pub fn operation_definitions(&self) -> &[OperationDefinition<'a>] {
        &self.operation_definitions
    }

    pub fn fragment_definitions(&self) -> &[FragmentDefinition<'a>] {
        &self.fragment_definitions
    }

    pub fn parse(s: &'a str) -> Result<Self, Vec<Error>> {
        let scanner = LogosScanner::new(s);
        let mut tokens = ScannerTokens::new(scanner);

        let mut instance: Self = Self::new(Vec::new(), Vec::new());
        let mut errors = Vec::new();
        let mut last_pass_had_error = false;

        loop {
            last_pass_had_error =
                if let Some(res) = ExecutableDefinition::try_from_tokens(&mut tokens) {
                    match res {
                        Ok(ExecutableDefinition::Operation(operation_definition)) => {
                            instance.operation_definitions.push(operation_definition);
                            false
                        }
                        Ok(ExecutableDefinition::Fragment(fragment_definition)) => {
                            instance.fragment_definitions.push(fragment_definition);
                            false
                        }
                        Err(err) => {
                            if !last_pass_had_error {
                                errors.push(err);
                            }
                            true
                        }
                    }
                } else if let Some(token) = tokens.next() {
                    if !last_pass_had_error {
                        errors.push(ParseError::UnexpectedToken { span: token.into() });
                    }
                    true
                } else {
                    break;
                }
        }

        let errors = if tokens.errors.is_empty() {
            if errors.is_empty() && instance.is_empty() {
                vec![ParseError::EmptyDocument.into()]
            } else {
                errors.into_iter().map(Into::into).collect()
            }
        } else {
            tokens.errors.into_iter().map(Into::into).collect()
        };

        if errors.is_empty() {
            Ok(instance)
        } else {
            Err(errors)
        }
    }

    fn is_empty(&self) -> bool {
        self.operation_definitions.is_empty() && self.fragment_definitions.is_empty()
    }
}

impl<'a> bluejay_core::executable::ExecutableDocument for ExecutableDocument<'a> {
    type Value<const CONST: bool> = Value<'a, CONST>;
    type VariableType = VariableType<'a>;
    type Argument<const CONST: bool> = Argument<'a, CONST>;
    type Arguments<const CONST: bool> = Arguments<'a, CONST>;
    type Directive<const CONST: bool> = Directive<'a, CONST>;
    type Directives<const CONST: bool> = Directives<'a, CONST>;
    type FragmentSpread = FragmentSpread<'a>;
    type Field = Field<'a>;
    type Selection = Selection<'a>;
    type SelectionSet = SelectionSet<'a>;
    type InlineFragment = InlineFragment<'a>;
    type VariableDefinition = VariableDefinition<'a>;
    type VariableDefinitions = VariableDefinitions<'a>;
    type ExplicitOperationDefinition = ExplicitOperationDefinition<'a>;
    type ImplicitOperationDefinition = ImplicitOperationDefinition<'a>;
    type OperationDefinition = OperationDefinition<'a>;
    type FragmentDefinition = FragmentDefinition<'a>;

    fn operation_definitions(&self) -> &[Self::OperationDefinition] {
        &self.operation_definitions
    }

    fn fragment_definitions(&self) -> &[Self::FragmentDefinition] {
        &self.fragment_definitions
    }
}

#[cfg(test)]
mod tests {
    use super::ExecutableDocument;

    #[test]
    fn test_success() {
        let document = r#"
            {
                dog {
                    ...fragmentOne
                    ...fragmentTwo
                }
            }

            fragment fragmentOne on Dog {
                name
            }

            fragment fragmentTwo on Dog {
                owner {
                    name
                }
            }
        "#;

        let defs = ExecutableDocument::parse(document).unwrap();

        assert_eq!(2, defs.fragment_definitions().len());
        assert_eq!(1, defs.operation_definitions().len());
    }
}