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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use std::{fmt, slice::Iter};

use rowan::{GreenNode, GreenNodeBuilder};

use crate::{ast::Document, Error, SyntaxElement, SyntaxKind, SyntaxNode};

use super::LimitTracker;

/// An AST generated by the parser. Consists of a syntax tree and a `Vec<Error>`
/// if any.
///
/// ## Example
///
/// Given a syntactically incorrect token `uasdf21230jkdw` which cannot be part
/// of any of GraphQL definitions and a syntactically correct SelectionSet, we
/// are able to see both the AST for the SelectionSet and the error with an
/// incorrect token.
/// ```rust
/// use apollo_parser::Parser;
///
/// let schema = r#"
/// uasdf21230jkdw
///
/// {
///   pet
///   faveSnack
/// }
/// "#;
/// let parser = Parser::new(schema);
///
/// let ast = parser.parse();
/// // The Vec<Error> that's part of the SyntaxTree struct.
/// assert_eq!(ast.errors().len(), 1);
///
/// // The AST with Document as its root node.
/// let doc = ast.document();
/// let nodes: Vec<_> = doc.definitions().into_iter().collect();
/// assert_eq!(nodes.len(), 1);
/// ```

#[derive(PartialEq, Eq, Clone)]
pub struct SyntaxTree {
    pub(crate) green: GreenNode,
    pub(crate) errors: Vec<crate::Error>,
    pub(crate) recursion_limit: LimitTracker,
    pub(crate) token_limit: LimitTracker,
}

impl SyntaxTree {
    /// Get a reference to the syntax tree's errors.
    pub fn errors(&self) -> Iter<'_, crate::Error> {
        self.errors.iter()
    }

    /// Get the syntax tree's recursion limit.
    pub fn recursion_limit(&self) -> LimitTracker {
        self.recursion_limit
    }

    /// Get the syntax tree's token limit.
    pub fn token_limit(&self) -> LimitTracker {
        self.token_limit
    }

    pub fn green(&self) -> GreenNode {
        self.green.clone()
    }

    pub(crate) fn syntax_node(&self) -> SyntaxNode {
        rowan::SyntaxNode::new_root(self.green.clone())
    }

    /// Return the root typed `Document` node.
    pub fn document(self) -> Document {
        Document {
            syntax: self.syntax_node(),
        }
    }
}

impl fmt::Debug for SyntaxTree {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn print(f: &mut fmt::Formatter<'_>, indent: usize, element: SyntaxElement) -> fmt::Result {
            let kind: SyntaxKind = element.kind();
            write!(f, "{:indent$}", "", indent = indent)?;
            match element {
                rowan::NodeOrToken::Node(node) => {
                    writeln!(f, "- {:?}@{:?}", kind, node.text_range())?;
                    for child in node.children_with_tokens() {
                        print(f, indent + 4, child)?;
                    }
                    Ok(())
                }

                rowan::NodeOrToken::Token(token) => {
                    writeln!(
                        f,
                        "- {:?}@{:?} {:?}",
                        kind,
                        token.text_range(),
                        token.text()
                    )
                }
            }
        }

        fn print_err(f: &mut fmt::Formatter<'_>, errors: Vec<Error>) -> fmt::Result {
            for err in errors {
                writeln!(f, "- {err:?}")?;
            }

            write!(f, "")
        }

        fn print_recursion_limit(
            f: &mut fmt::Formatter<'_>,
            recursion_limit: LimitTracker,
        ) -> fmt::Result {
            write!(f, "{recursion_limit:?}")
        }

        print(f, 0, self.syntax_node().into())?;
        print_err(f, self.errors.clone())?;
        print_recursion_limit(f, self.recursion_limit)
    }
}

#[derive(Debug)]
pub(crate) struct SyntaxTreeBuilder {
    builder: GreenNodeBuilder<'static>,
}

impl SyntaxTreeBuilder {
    /// Create a new instance of `SyntaxBuilder`.
    pub(crate) fn new() -> Self {
        Self {
            builder: GreenNodeBuilder::new(),
        }
    }

    pub(crate) fn checkpoint(&self) -> rowan::Checkpoint {
        self.builder.checkpoint()
    }

    /// Start new node and make it current.
    pub(crate) fn start_node(&mut self, kind: SyntaxKind) {
        self.builder.start_node(rowan::SyntaxKind(kind as u16));
    }

    /// Finish current branch and restore previous branch as current.
    pub(crate) fn finish_node(&mut self) {
        self.builder.finish_node();
    }

    pub(crate) fn wrap_node(&mut self, checkpoint: rowan::Checkpoint, kind: SyntaxKind) {
        self.builder
            .start_node_at(checkpoint, rowan::SyntaxKind(kind as u16));
    }

    /// Adds new token to the current branch.
    pub(crate) fn token(&mut self, kind: SyntaxKind, text: &str) {
        self.builder.token(rowan::SyntaxKind(kind as u16), text);
    }

    pub(crate) fn finish(
        self,
        errors: Vec<Error>,
        recursion_limit: LimitTracker,
        token_limit: LimitTracker,
    ) -> SyntaxTree {
        SyntaxTree {
            green: self.builder.finish(),
            // TODO: keep the errors in the builder rather than pass it in here?
            errors,
            // TODO: keep the recursion and token limits in the builder rather than pass it in here?
            recursion_limit,
            token_limit,
        }
    }
}

#[cfg(test)]
mod test {
    use crate::ast::Definition;
    use crate::Parser;

    #[test]
    fn directive_name() {
        let input = "directive @example(isTreat: Boolean, treatKind: String) on FIELD | MUTATION";
        let parser = Parser::new(input);
        let ast = parser.parse();
        let doc = ast.document();

        for def in doc.definitions() {
            if let Definition::DirectiveDefinition(directive) = def {
                assert_eq!(directive.name().unwrap().text(), "example");
            }
        }
    }

    #[test]
    fn object_type_definition() {
        let input = "
        type ProductDimension {
          size: String
          weight: Float @tag(name: \"hi from inventory value type field\")
        }
        ";
        let parser = Parser::new(input);
        let ast = parser.parse();
        assert_eq!(0, ast.errors().len());

        let doc = ast.document();

        for def in doc.definitions() {
            if let Definition::ObjectTypeDefinition(object_type) = def {
                assert_eq!(object_type.name().unwrap().text(), "ProductDimension");
                for field_def in object_type.fields_definition().unwrap().field_definitions() {
                    println!("{}", field_def.name().unwrap().text()); // size weight
                }
            }
        }
    }
}