Skip to main content

link_cli/graphql/
document.rs

1//! GraphQL documents: operations, selections, fragments and values.
2
3use std::collections::HashMap;
4
5use anyhow::{anyhow, bail, Result};
6
7use super::json::Json;
8
9#[derive(Debug, Clone, PartialEq)]
10pub enum Value {
11    Variable(String),
12    Literal(Json),
13    List(Vec<Value>),
14    Object(Vec<(String, Value)>),
15}
16
17impl Value {
18    /// The value with its variables replaced; a variable nobody passed is null.
19    pub fn resolve(&self, variables: &Json) -> Json {
20        match self {
21            Value::Variable(name) => variables.get(name).cloned().unwrap_or(Json::Null),
22            Value::Literal(json) => json.clone(),
23            Value::List(items) => {
24                Json::Array(items.iter().map(|item| item.resolve(variables)).collect())
25            }
26            Value::Object(pairs) => Json::Object(
27                pairs
28                    .iter()
29                    .map(|(key, value)| (key.clone(), value.resolve(variables)))
30                    .collect(),
31            ),
32        }
33    }
34}
35
36#[derive(Debug, Clone, PartialEq)]
37pub struct Directive {
38    pub name: String,
39    pub arguments: Vec<(String, Value)>,
40}
41
42#[derive(Debug, Clone, PartialEq)]
43pub enum Selection {
44    Field(Field),
45    Spread(String, Vec<Directive>),
46    Inline(Option<String>, Vec<Directive>, Vec<Selection>),
47}
48
49#[derive(Debug, Clone, PartialEq)]
50pub struct Field {
51    pub alias: Option<String>,
52    pub name: String,
53    pub arguments: Vec<(String, Value)>,
54    pub directives: Vec<Directive>,
55    pub selections: Vec<Selection>,
56}
57
58impl Field {
59    pub fn response_key(&self) -> &str {
60        self.alias.as_deref().unwrap_or(&self.name)
61    }
62
63    pub fn argument(&self, name: &str, variables: &Json) -> Option<Json> {
64        self.arguments
65            .iter()
66            .find(|(key, _)| key == name)
67            .map(|(_, value)| value.resolve(variables))
68            .filter(|value| !value.is_null())
69    }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum OperationKind {
74    Query,
75    Mutation,
76    Subscription,
77}
78
79#[derive(Debug, Clone, PartialEq)]
80pub struct Operation {
81    pub kind: OperationKind,
82    pub name: Option<String>,
83    /// Variable name and default value.
84    pub variables: Vec<(String, Option<Value>)>,
85    pub selections: Vec<Selection>,
86}
87
88#[derive(Debug, Clone, PartialEq, Default)]
89pub struct Document {
90    pub operations: Vec<Operation>,
91    pub fragments: HashMap<String, Vec<Selection>>,
92}
93
94impl Document {
95    pub fn parse(text: &str) -> Result<Document> {
96        let tokens = tokenize(text)?;
97        let mut parser = Parser { tokens, at: 0 };
98        let mut document = Document::default();
99        while parser.peek().is_some() {
100            if parser.eat_name("fragment") {
101                let name = parser.name()?;
102                if !parser.eat_name("on") {
103                    bail!("Expected 'on' in fragment {name}.");
104                }
105                parser.name()?;
106                parser.directives(0)?;
107                let selections = parser.selection_set(0)?;
108                document.fragments.insert(name, selections);
109            } else {
110                document.operations.push(parser.operation()?);
111            }
112        }
113        if document.operations.is_empty() {
114            bail!("A document has at least one operation.");
115        }
116        Ok(document)
117    }
118
119    pub fn operation(&self, name: Option<&str>) -> Result<&Operation> {
120        match name {
121            Some(name) => self
122                .operations
123                .iter()
124                .find(|operation| operation.name.as_deref() == Some(name))
125                .ok_or_else(|| anyhow!("Unknown operation named '{name}'.")),
126            None if self.operations.len() == 1 => Ok(&self.operations[0]),
127            None => bail!("Must provide operation name if query contains multiple operations."),
128        }
129    }
130}
131
132#[derive(Debug, Clone, PartialEq)]
133enum Token {
134    Punctuator(char),
135    Name(String),
136    Int(i64),
137    Float(f64),
138    String(String),
139}
140
141fn tokenize(text: &str) -> Result<Vec<Token>> {
142    let chars: Vec<char> = text.chars().collect();
143    let mut tokens = Vec::new();
144    let mut at = 0;
145    while at < chars.len() {
146        let character = chars[at];
147        match character {
148            ' ' | '\n' | '\r' | '\t' | ',' | '\u{feff}' => at += 1,
149            '#' => {
150                while at < chars.len() && chars[at] != '\n' {
151                    at += 1;
152                }
153            }
154            '!' | '$' | '(' | ')' | ':' | '=' | '@' | '[' | ']' | '{' | '}' | '|' | '&' => {
155                tokens.push(Token::Punctuator(character));
156                at += 1;
157            }
158            '.' => {
159                if chars.get(at + 1) == Some(&'.') && chars.get(at + 2) == Some(&'.') {
160                    tokens.push(Token::Punctuator('.'));
161                    at += 3;
162                } else {
163                    bail!("Unexpected '.' in the document.");
164                }
165            }
166            '"' => {
167                if chars.get(at + 1) == Some(&'"') && chars.get(at + 2) == Some(&'"') {
168                    at += 3;
169                    let mut out = String::new();
170                    loop {
171                        if at + 2 >= chars.len() {
172                            bail!("Unterminated block string.");
173                        }
174                        if chars[at] == '"' && chars[at + 1] == '"' && chars[at + 2] == '"' {
175                            at += 3;
176                            break;
177                        }
178                        out.push(chars[at]);
179                        at += 1;
180                    }
181                    tokens.push(Token::String(out));
182                } else {
183                    let start = at;
184                    at += 1;
185                    while at < chars.len() && chars[at] != '"' {
186                        at += if chars[at] == '\\' { 2 } else { 1 };
187                    }
188                    if at >= chars.len() {
189                        bail!("Unterminated string.");
190                    }
191                    at += 1;
192                    let literal: String = chars[start..at].iter().collect();
193                    match Json::parse(&literal)? {
194                        Json::String(value) => tokens.push(Token::String(value)),
195                        _ => bail!("Invalid string."),
196                    }
197                }
198            }
199            '-' | '0'..='9' => {
200                let start = at;
201                at += 1;
202                while at < chars.len()
203                    && matches!(chars[at], '0'..='9' | '.' | 'e' | 'E' | '+' | '-')
204                {
205                    at += 1;
206                }
207                let literal: String = chars[start..at].iter().collect();
208                if let Ok(value) = literal.parse::<i64>() {
209                    tokens.push(Token::Int(value));
210                } else if let Ok(value) = literal.parse::<f64>() {
211                    tokens.push(Token::Float(value));
212                } else {
213                    bail!("Invalid number '{literal}'.");
214                }
215            }
216            '_' | 'a'..='z' | 'A'..='Z' => {
217                let start = at;
218                while at < chars.len() && (chars[at] == '_' || chars[at].is_ascii_alphanumeric()) {
219                    at += 1;
220                }
221                tokens.push(Token::Name(chars[start..at].iter().collect()));
222            }
223            other => bail!("Unexpected character '{other}' in the document."),
224        }
225    }
226    Ok(tokens)
227}
228
229/// Deep enough for any selection a client means.
230const MAX_DEPTH: usize = 64;
231
232struct Parser {
233    tokens: Vec<Token>,
234    at: usize,
235}
236
237impl Parser {
238    fn peek(&self) -> Option<&Token> {
239        self.tokens.get(self.at)
240    }
241
242    fn eat(&mut self, punctuator: char) -> bool {
243        if self.peek() == Some(&Token::Punctuator(punctuator)) {
244            self.at += 1;
245            true
246        } else {
247            false
248        }
249    }
250
251    fn expect(&mut self, punctuator: char) -> Result<()> {
252        if self.eat(punctuator) {
253            Ok(())
254        } else {
255            bail!("Expected '{punctuator}', found {:?}.", self.peek())
256        }
257    }
258
259    fn eat_name(&mut self, name: &str) -> bool {
260        if matches!(self.peek(), Some(Token::Name(found)) if found == name) {
261            self.at += 1;
262            true
263        } else {
264            false
265        }
266    }
267
268    fn name(&mut self) -> Result<String> {
269        match self.peek() {
270            Some(Token::Name(name)) => {
271                let name = name.clone();
272                self.at += 1;
273                Ok(name)
274            }
275            other => bail!("Expected a name, found {other:?}."),
276        }
277    }
278
279    fn operation(&mut self) -> Result<Operation> {
280        if self.peek() == Some(&Token::Punctuator('{')) {
281            return Ok(Operation {
282                kind: OperationKind::Query,
283                name: None,
284                variables: Vec::new(),
285                selections: self.selection_set(0)?,
286            });
287        }
288        let keyword = self.name()?;
289        let kind = match keyword.as_str() {
290            "query" => OperationKind::Query,
291            "mutation" => OperationKind::Mutation,
292            "subscription" => OperationKind::Subscription,
293            other => bail!("Unknown operation type '{other}'."),
294        };
295        let name = match self.peek() {
296            Some(Token::Name(_)) => Some(self.name()?),
297            _ => None,
298        };
299        let mut variables = Vec::new();
300        if self.eat('(') {
301            while !self.eat(')') {
302                self.expect('$')?;
303                let variable = self.name()?;
304                self.expect(':')?;
305                self.skip_type(0)?;
306                let default = if self.eat('=') {
307                    Some(self.value(0)?)
308                } else {
309                    None
310                };
311                self.directives(0)?;
312                variables.push((variable, default));
313            }
314        }
315        self.directives(0)?;
316        Ok(Operation {
317            kind,
318            name,
319            variables,
320            selections: self.selection_set(0)?,
321        })
322    }
323
324    fn skip_type(&mut self, depth: usize) -> Result<()> {
325        if depth > MAX_DEPTH {
326            bail!("The type is nested too deeply.");
327        }
328        if self.eat('[') {
329            self.skip_type(depth + 1)?;
330            self.expect(']')?;
331        } else {
332            self.name()?;
333        }
334        self.eat('!');
335        Ok(())
336    }
337
338    fn selection_set(&mut self, depth: usize) -> Result<Vec<Selection>> {
339        if depth > MAX_DEPTH {
340            bail!("The selection is nested too deeply.");
341        }
342        self.expect('{')?;
343        let mut selections = Vec::new();
344        while !self.eat('}') {
345            if self.eat('.') {
346                if self.eat_name("on") {
347                    let on = self.name()?;
348                    let directives = self.directives(depth)?;
349                    selections.push(Selection::Inline(
350                        Some(on),
351                        directives,
352                        self.selection_set(depth + 1)?,
353                    ));
354                } else if matches!(self.peek(), Some(Token::Name(_))) {
355                    let name = self.name()?;
356                    let directives = self.directives(depth)?;
357                    selections.push(Selection::Spread(name, directives));
358                } else {
359                    let directives = self.directives(depth)?;
360                    selections.push(Selection::Inline(
361                        None,
362                        directives,
363                        self.selection_set(depth + 1)?,
364                    ));
365                }
366            } else {
367                let first = self.name()?;
368                let (alias, name) = if self.eat(':') {
369                    (Some(first), self.name()?)
370                } else {
371                    (None, first)
372                };
373                let arguments = self.arguments(depth)?;
374                let directives = self.directives(depth)?;
375                let selections_of = if self.peek() == Some(&Token::Punctuator('{')) {
376                    self.selection_set(depth + 1)?
377                } else {
378                    Vec::new()
379                };
380                selections.push(Selection::Field(Field {
381                    alias,
382                    name,
383                    arguments,
384                    directives,
385                    selections: selections_of,
386                }));
387            }
388        }
389        Ok(selections)
390    }
391
392    fn arguments(&mut self, depth: usize) -> Result<Vec<(String, Value)>> {
393        let mut arguments = Vec::new();
394        if self.eat('(') {
395            while !self.eat(')') {
396                let name = self.name()?;
397                self.expect(':')?;
398                arguments.push((name, self.value(depth)?));
399            }
400        }
401        Ok(arguments)
402    }
403
404    fn directives(&mut self, depth: usize) -> Result<Vec<Directive>> {
405        let mut directives = Vec::new();
406        while self.eat('@') {
407            let name = self.name()?;
408            let arguments = self.arguments(depth)?;
409            directives.push(Directive { name, arguments });
410        }
411        Ok(directives)
412    }
413
414    fn value(&mut self, depth: usize) -> Result<Value> {
415        if depth > MAX_DEPTH {
416            bail!("The value is nested too deeply.");
417        }
418        let token = self.peek().cloned();
419        self.at += 1;
420        Ok(match token {
421            Some(Token::Punctuator('$')) => Value::Variable(self.name()?),
422            Some(Token::Int(value)) => Value::Literal(Json::Int(value)),
423            Some(Token::Float(value)) => Value::Literal(Json::Float(value)),
424            Some(Token::String(value)) => Value::Literal(Json::String(value)),
425            Some(Token::Name(name)) => Value::Literal(match name.as_str() {
426                "true" => Json::Bool(true),
427                "false" => Json::Bool(false),
428                "null" => Json::Null,
429                // An enum value travels as its name, as JSON variables do.
430                _ => Json::String(name),
431            }),
432            Some(Token::Punctuator('[')) => {
433                let mut items = Vec::new();
434                while !self.eat(']') {
435                    items.push(self.value(depth + 1)?);
436                }
437                Value::List(items)
438            }
439            Some(Token::Punctuator('{')) => {
440                let mut pairs = Vec::new();
441                while !self.eat('}') {
442                    let name = self.name()?;
443                    self.expect(':')?;
444                    pairs.push((name, self.value(depth + 1)?));
445                }
446                Value::Object(pairs)
447            }
448            other => bail!("Expected a value, found {other:?}."),
449        })
450    }
451}