graphql_parser/
common.rs

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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use std::{collections::BTreeMap, fmt};

use combine::easy::{Error, Info};
use combine::{choice, many, many1, optional, position, StdParseResult};
use combine::{parser, Parser};

use crate::helpers::{ident, kind, name, punct};
use crate::position::Pos;
use crate::tokenizer::{Kind as T, Token, TokenStream};

/// Text abstracts over types that hold a string value.
/// It is used to make the AST generic over the string type.
pub trait Text<'a>: 'a {
    type Value: 'a
        + From<&'a str>
        + AsRef<str>
        + std::borrow::Borrow<str>
        + PartialEq
        + Eq
        + PartialOrd
        + Ord
        + fmt::Debug
        + Clone;
}

impl<'a> Text<'a> for &'a str {
    type Value = Self;
}

impl<'a> Text<'a> for String {
    type Value = String;
}

impl<'a> Text<'a> for std::borrow::Cow<'a, str> {
    type Value = Self;
}

#[derive(Debug, Clone, PartialEq)]
pub struct Directive<'a, T: Text<'a>> {
    pub position: Pos,
    pub name: T::Value,
    pub arguments: Vec<(T::Value, Value<'a, T>)>,
}

/// This represents integer number
///
/// But since there is no definition on limit of number in spec
/// (only in implemetation), we do a trick similar to the one
/// in `serde_json`: encapsulate value in new-type, allowing type
/// to be extended later.
#[derive(Debug, Clone, PartialEq)]
// we use i64 as a reference implementation: graphql-js thinks even 32bit
// integers is enough. We might consider lift this limit later though
pub struct Number(pub(crate) i64);

#[derive(Debug, Clone, PartialEq)]
pub enum Value<'a, T: Text<'a>> {
    Variable(T::Value),
    Int(Number),
    Float(f64),
    String(String),
    Boolean(bool),
    Null,
    Enum(T::Value),
    List(Vec<Value<'a, T>>),
    Object(BTreeMap<T::Value, Value<'a, T>>),
}

impl<'a, T: Text<'a>> Value<'a, T> {
    pub fn into_static(&self) -> Value<'static, String> {
        match self {
            Self::Variable(v) => Value::Variable(v.as_ref().into()),
            Self::Int(i) => Value::Int(i.clone()),
            Self::Float(f) => Value::Float(*f),
            Self::String(s) => Value::String(s.clone()),
            Self::Boolean(b) => Value::Boolean(*b),
            Self::Null => Value::Null,
            Self::Enum(v) => Value::Enum(v.as_ref().into()),
            Self::List(l) => Value::List(l.iter().map(|e| e.into_static()).collect()),
            Self::Object(o) => Value::Object(
                o.iter()
                    .map(|(k, v)| (k.as_ref().into(), v.into_static()))
                    .collect(),
            ),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Type<'a, T: Text<'a>> {
    NamedType(T::Value),
    ListType(Box<Type<'a, T>>),
    NonNullType(Box<Type<'a, T>>),
}

impl Number {
    /// Returns a number as i64 if it fits the type
    pub fn as_i64(&self) -> Option<i64> {
        Some(self.0)
    }
}

impl From<i32> for Number {
    fn from(i: i32) -> Self {
        Number(i as i64)
    }
}

pub fn directives<'a, T>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Vec<Directive<'a, T>>, TokenStream<'a>>
where
    T: Text<'a>,
{
    many(
        position()
            .skip(punct("@"))
            .and(name::<'a, T>())
            .and(parser(arguments))
            .map(|((position, name), arguments)| Directive {
                position,
                name,
                arguments,
            }),
    )
    .parse_stream(input)
    .into_result()
}

#[allow(clippy::type_complexity)]
pub fn arguments<'a, T>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Vec<(T::Value, Value<'a, T>)>, TokenStream<'a>>
where
    T: Text<'a>,
{
    optional(
        punct("(")
            .with(many1(name::<'a, T>().skip(punct(":")).and(parser(value))))
            .skip(punct(")")),
    )
    .map(|opt| opt.unwrap_or_default())
    .parse_stream(input)
    .into_result()
}

pub fn int_value<'a, S>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Value<'a, S>, TokenStream<'a>>
where
    S: Text<'a>,
{
    kind(T::IntValue)
        .and_then(|tok| tok.value.parse())
        .map(Number)
        .map(Value::Int)
        .parse_stream(input)
        .into_result()
}

pub fn float_value<'a, S>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Value<'a, S>, TokenStream<'a>>
where
    S: Text<'a>,
{
    kind(T::FloatValue)
        .and_then(|tok| tok.value.parse())
        .map(Value::Float)
        .parse_stream(input)
        .into_result()
}

fn unquote_block_string(src: &str) -> Result<String, Error<Token<'_>, Token<'_>>> {
    debug_assert!(src.starts_with("\"\"\"") && src.ends_with("\"\"\""));
    let lines = src[3..src.len() - 3].lines();

    let mut common_indent = usize::MAX;
    let mut first_non_empty_line: Option<usize> = None;
    let mut last_non_empty_line = 0;
    for (idx, line) in lines.clone().enumerate() {
        let indent = line.len() - line.trim_start().len();
        if indent == line.len() {
            continue;
        }

        first_non_empty_line.get_or_insert(idx);
        last_non_empty_line = idx;

        if idx != 0 {
            common_indent = std::cmp::min(common_indent, indent);
        }
    }

    if first_non_empty_line.is_none() {
        // The block string contains only whitespace.
        return Ok("".to_string());
    }
    let first_non_empty_line = first_non_empty_line.unwrap();

    let mut result = String::with_capacity(src.len() - 6);
    let mut lines = lines
        .enumerate()
        // Skip leading and trailing empty lines.
        .skip(first_non_empty_line)
        .take(last_non_empty_line - first_non_empty_line + 1)
        // Remove indent, except the first line.
        .map(|(idx, line)| {
            if idx != 0 && line.len() >= common_indent {
                &line[common_indent..]
            } else {
                line
            }
        })
        // Handle escaped triple-quote (\""").
        .map(|x| x.replace(r#"\""""#, r#"""""#));

    if let Some(line) = lines.next() {
        result.push_str(&line);

        for line in lines {
            result.push_str("\n");
            result.push_str(&line);
        }
    }
    return Ok(result);
}

fn unquote_string(s: &str) -> Result<String, Error<Token, Token>> {
    let mut res = String::with_capacity(s.len());
    debug_assert!(s.starts_with('"') && s.ends_with('"'));
    let mut chars = s[1..s.len() - 1].chars();
    let mut temp_code_point = String::with_capacity(4);
    while let Some(c) = chars.next() {
        match c {
            '\\' => {
                match chars.next().expect("slash cant be at the end") {
                    c @ '"' | c @ '\\' | c @ '/' => res.push(c),
                    'b' => res.push('\u{0010}'),
                    'f' => res.push('\u{000C}'),
                    'n' => res.push('\n'),
                    'r' => res.push('\r'),
                    't' => res.push('\t'),
                    'u' => {
                        temp_code_point.clear();
                        for _ in 0..4 {
                            match chars.next() {
                                Some(inner_c) => temp_code_point.push(inner_c),
                                None => {
                                    return Err(Error::Unexpected(Info::Owned(
                                        format_args!(
                                            "\\u must have 4 characters after it, only found '{}'",
                                            temp_code_point
                                        )
                                        .to_string(),
                                    )))
                                }
                            }
                        }

                        // convert our hex string into a u32, then convert that into a char
                        match u32::from_str_radix(&temp_code_point, 16).map(std::char::from_u32) {
                            Ok(Some(unicode_char)) => res.push(unicode_char),
                            _ => {
                                return Err(Error::Unexpected(Info::Owned(
                                    format_args!(
                                        "{} is not a valid unicode code point",
                                        temp_code_point
                                    )
                                    .to_string(),
                                )))
                            }
                        }
                    }
                    c => {
                        return Err(Error::Unexpected(Info::Owned(
                            format_args!("bad escaped char {:?}", c).to_string(),
                        )));
                    }
                }
            }
            c => res.push(c),
        }
    }

    Ok(res)
}

pub fn string<'a>(input: &mut TokenStream<'a>) -> StdParseResult<String, TokenStream<'a>> {
    choice((
        kind(T::StringValue).and_then(|tok| unquote_string(tok.value)),
        kind(T::BlockString).and_then(|tok| unquote_block_string(tok.value)),
    ))
    .parse_stream(input)
    .into_result()
}

pub fn string_value<'a, S>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Value<'a, S>, TokenStream<'a>>
where
    S: Text<'a>,
{
    kind(T::StringValue)
        .and_then(|tok| unquote_string(tok.value))
        .map(Value::String)
        .parse_stream(input)
        .into_result()
}

pub fn block_string_value<'a, S>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Value<'a, S>, TokenStream<'a>>
where
    S: Text<'a>,
{
    kind(T::BlockString)
        .and_then(|tok| unquote_block_string(tok.value))
        .map(Value::String)
        .parse_stream(input)
        .into_result()
}

pub fn plain_value<'a, T>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Value<'a, T>, TokenStream<'a>>
where
    T: Text<'a>,
{
    ident("true")
        .map(|_| Value::Boolean(true))
        .or(ident("false").map(|_| Value::Boolean(false)))
        .or(ident("null").map(|_| Value::Null))
        .or(name::<'a, T>().map(Value::Enum))
        .or(parser(int_value))
        .or(parser(float_value))
        .or(parser(string_value))
        .or(parser(block_string_value))
        .parse_stream(input)
        .into_result()
}

pub fn value<'a, T>(input: &mut TokenStream<'a>) -> StdParseResult<Value<'a, T>, TokenStream<'a>>
where
    T: Text<'a>,
{
    parser(plain_value)
        .or(punct("$").with(name::<'a, T>()).map(Value::Variable))
        .or(punct("[")
            .with(many(parser(value)))
            .skip(punct("]"))
            .map(Value::List))
        .or(punct("{")
            .with(many(name::<'a, T>().skip(punct(":")).and(parser(value))))
            .skip(punct("}"))
            .map(Value::Object))
        .parse_stream(input)
        .into_result()
}

pub fn default_value<'a, T>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Value<'a, T>, TokenStream<'a>>
where
    T: Text<'a>,
{
    parser(plain_value)
        .or(punct("[")
            .with(many(parser(default_value)))
            .skip(punct("]"))
            .map(Value::List))
        .or(punct("{")
            .with(many(
                name::<'a, T>().skip(punct(":")).and(parser(default_value)),
            ))
            .skip(punct("}"))
            .map(Value::Object))
        .parse_stream(input)
        .into_result()
}

pub fn parse_type<'a, T>(
    input: &mut TokenStream<'a>,
) -> StdParseResult<Type<'a, T>, TokenStream<'a>>
where
    T: Text<'a>,
{
    name::<'a, T>()
        .map(Type::NamedType)
        .or(punct("[")
            .with(parser(parse_type))
            .skip(punct("]"))
            .map(Box::new)
            .map(Type::ListType))
        .and(optional(punct("!")).map(|v| v.is_some()))
        .map(|(typ, strict)| {
            if strict {
                Type::NonNullType(Box::new(typ))
            } else {
                typ
            }
        })
        .parse_stream(input)
        .into_result()
}

#[cfg(test)]
mod tests {
    use super::unquote_block_string;
    use super::unquote_string;
    use super::Number;

    #[test]
    fn number_from_i32_and_to_i64_conversion() {
        assert_eq!(Number::from(1).as_i64(), Some(1));
        assert_eq!(Number::from(584).as_i64(), Some(584));
        assert_eq!(
            Number::from(i32::min_value()).as_i64(),
            Some(i32::min_value() as i64)
        );
        assert_eq!(
            Number::from(i32::max_value()).as_i64(),
            Some(i32::max_value() as i64)
        );
    }

    #[test]
    fn unquote_unicode_string() {
        // basic tests
        assert_eq!(unquote_string(r#""\u0009""#).expect(""), "\u{0009}");
        assert_eq!(unquote_string(r#""\u000A""#).expect(""), "\u{000A}");
        assert_eq!(unquote_string(r#""\u000D""#).expect(""), "\u{000D}");
        assert_eq!(unquote_string(r#""\u0020""#).expect(""), "\u{0020}");
        assert_eq!(unquote_string(r#""\uFFFF""#).expect(""), "\u{FFFF}");

        // a more complex string
        assert_eq!(
            unquote_string(r#""\u0009 hello \u000A there""#).expect(""),
            "\u{0009} hello \u{000A} there"
        );
    }

    #[test]
    fn block_string_leading_and_trailing_empty_lines() {
        let block = &triple_quote("   \n\n  Hello,\n    World!\n\n  Yours,\n    GraphQL.\n\n\n");
        assert_eq!(
            unquote_block_string(&block),
            Result::Ok("Hello,\n  World!\n\nYours,\n  GraphQL.".to_string())
        );
    }

    #[test]
    fn block_string_indent() {
        let block = &triple_quote("Hello   \n\n  Hello,\n    World!\n");
        assert_eq!(
            unquote_block_string(&block),
            Result::Ok("Hello   \n\nHello,\n  World!".to_string())
        );
    }

    #[test]
    fn block_string_escaping() {
        let block = triple_quote(r#"\""""#);
        assert_eq!(
            unquote_block_string(&block),
            Result::Ok("\"\"\"".to_string())
        );
    }

    #[test]
    fn block_string_empty() {
        let block = triple_quote("");
        assert_eq!(unquote_block_string(&block), Result::Ok("".to_string()));
        let block = triple_quote("   \n\t\n");
        assert_eq!(unquote_block_string(&block), Result::Ok("".to_string()));
    }

    fn triple_quote(input: &str) -> String {
        return format!("\"\"\"{}\"\"\"", input);
    }
}