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
use std::fmt::{self, Display, Write};

use crate::{
    Deprecated, EnumType, EnumValue, Field, FieldType, InputObjectType, InputValue, InterfaceType,
    ObjectType, ScalarType, Type, UnionType,
};

use super::Schema;

impl Schema {
    /// Writes the SDL for this schema into `f`
    pub fn write_sdl(&self, f: &mut dyn Write) -> std::fmt::Result {
        write!(f, "{}", SchemaDisplay(self))
    }

    /// Returns the SDL for this schema as a string
    pub fn to_sdl(&self) -> String {
        let mut output = String::new();
        self.write_sdl(&mut output)
            .expect("Writing to a string shouldn't fail");
        output
    }
}

struct SchemaDisplay<'a>(&'a Schema);

impl Display for SchemaDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let schema = &self.0;
        if self.should_should_schema_definition() {
            writeln!(f, "schema {{")?;
            let f2 = &mut indented(f);
            writeln!(f2, "query: {}", schema.query_type)?;
            if let Some(mutation_type) = &schema.mutation_type {
                writeln!(f2, "mutation: {}", mutation_type)?;
            }
            if let Some(subscription_type) = &schema.subscription_type {
                writeln!(f2, "subscription: {}", subscription_type)?;
            }
            writeln!(f, "}}")?;
        }

        for ty in &schema.types {
            let ty = TypeDisplay(ty);
            write!(f, "{ty}")?;
        }

        Ok(())
    }
}

impl SchemaDisplay<'_> {
    fn should_should_schema_definition(&self) -> bool {
        self.0.query_type != "Query"
            || self
                .0
                .mutation_type
                .as_ref()
                .map(|mutation_type| mutation_type != "Mutation")
                .unwrap_or_default()
            || self
                .0
                .subscription_type
                .as_ref()
                .map(|subscription_type| subscription_type != "Subscription")
                .unwrap_or_default()
    }
}

struct TypeDisplay<'a>(&'a Type);

impl std::fmt::Display for TypeDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ty = self.0;

        if ty.name().starts_with("__") {
            // Don't render introspection types.
            return Ok(());
        }

        match ty {
            Type::Scalar(
                scalar @ ScalarType {
                    name,
                    description,
                    specified_by_url,
                },
            ) => {
                if scalar.is_builtin() {
                    // Don't render built in scalars
                    return Ok(());
                }
                write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
                writeln!(
                    f,
                    "scalar {name}{}\n",
                    SpecifiedByDisplay(specified_by_url.as_deref())
                )
            }
            Type::Object(ObjectType {
                name,
                description,
                fields,
                interfaces,
            }) => {
                write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
                if fields.is_empty() {
                    writeln!(f, "type {name}{}", ImplementsDisplay(interfaces))
                } else {
                    writeln!(f, "type {name}{} {{", ImplementsDisplay(interfaces))?;
                    for field in fields {
                        writeln!(indented(f), "{}", FieldDisplay(field))?;
                    }
                    writeln!(f, "}}\n")
                }
            }
            Type::InputObject(InputObjectType {
                name,
                description,
                fields,
            }) => {
                write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
                if fields.is_empty() {
                    writeln!(f, "input {name}")
                } else {
                    writeln!(f, "input {name} {{")?;
                    for field in fields {
                        writeln!(indented(f), "{}", InputValueDisplay(field))?;
                    }
                    writeln!(f, "}}\n")
                }
            }
            Type::Enum(EnumType {
                name,
                description,
                values,
            }) => {
                write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
                if values.is_empty() {
                    writeln!(f, "enum {name}")
                } else {
                    writeln!(f, "enum {name} {{")?;
                    for value in values {
                        write!(indented(f), "{}", EnumValueDisplay(value))?;
                    }
                    writeln!(f, "}}\n")
                }
            }
            Type::Interface(InterfaceType {
                name,
                description,
                fields,
                interfaces,
                possible_types: _,
            }) => {
                write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
                if fields.is_empty() {
                    writeln!(f, "interface {name}{}", ImplementsDisplay(interfaces))
                } else {
                    writeln!(f, "interface {name}{} {{", ImplementsDisplay(interfaces))?;
                    for field in fields {
                        writeln!(indented(f), "{}", FieldDisplay(field))?;
                    }
                    writeln!(f, "}}\n")
                }
            }
            Type::Union(union) => {
                write!(f, "{}", UnionDisplay(union))
            }
        }
    }
}

struct UnionDisplay<'a>(&'a UnionType);

impl Display for UnionDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let UnionType {
            name,
            description,
            possible_types,
        } = self.0;
        write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
        let wrap = possible_types.iter().map(String::len).sum::<usize>() > 80;

        write!(f, "union {name} =")?;
        if wrap {
            write!(f, "\n   ")?;
        }
        for (i, ty) in possible_types.iter().enumerate() {
            if i != 0 {
                if wrap {
                    write!(f, "\n ")?;
                }
                write!(f, " |")?;
            }
            write!(f, " {ty}")?;
        }
        writeln!(f, "\n")
    }
}

struct DescriptionDisplay<'a>(Option<&'a str>);

impl Display for DescriptionDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(description) = self.0 {
            writeln!(f, r#"""""#)?;
            writeln!(f, "{description}")?;
            writeln!(f, r#"""""#)?;
        }

        Ok(())
    }
}

struct FieldDisplay<'a>(&'a Field);

impl Display for FieldDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Field {
            name,
            description,
            args,
            ty,
            deprecated,
        } = self.0;
        write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
        write!(f, "{name}")?;
        if !args.is_empty() {
            let wrap = self.should_wrap_arguments();
            if wrap {
                writeln!(f, "(")?;
                for (i, arg) in args.iter().enumerate() {
                    if i != 0 {
                        writeln!(f)?;
                    }
                    write!(indented(f), "{}", InputValueDisplay(arg))?;
                }
                write!(f, "\n)")?;
            } else {
                write!(f, "(")?;
                for (i, arg) in args.iter().enumerate() {
                    if i != 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", InputValueDisplay(arg))?;
                }
                write!(f, ")")?;
            }
        }
        write!(
            f,
            ": {}{}",
            FieldTypeDisplay(ty),
            DeprecatedDisplay(deprecated)
        )?;

        Ok(())
    }
}

impl FieldDisplay<'_> {
    /// Hacky heuristic for whether we should wrap the field arguments
    fn should_wrap_arguments(&self) -> bool {
        if self.0.args.iter().any(|arg| arg.description.is_some()) {
            return true;
        }
        let arg_len = self
            .0
            .args
            .iter()
            .map(|arg| arg.name.len() + arg.ty.name.len())
            .sum::<usize>();
        arg_len + self.0.ty.name.len() > 80
    }
}

struct ImplementsDisplay<'a>(&'a [String]);

impl Display for ImplementsDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let interfaces = &self.0;
        if interfaces.is_empty() {
            return Ok(());
        }
        write!(f, " implements ")?;
        for (i, interface) in interfaces.iter().enumerate() {
            if i != 0 {
                write!(f, " & ")?;
            }
            write!(f, "{interface}")?;
        }
        Ok(())
    }
}

struct FieldTypeDisplay<'a>(&'a FieldType);

impl Display for FieldTypeDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

struct InputValueDisplay<'a>(&'a InputValue);

impl Display for InputValueDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let InputValue {
            name,
            description,
            ty,
            default_value,
        } = self.0;
        write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
        write!(f, "{name}: {}", FieldTypeDisplay(ty))?;
        if let Some(default_value) = default_value {
            write!(f, " = {}", default_value)?;
        }
        Ok(())
    }
}

struct EnumValueDisplay<'a>(&'a EnumValue);

impl Display for EnumValueDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let EnumValue {
            name,
            description,
            deprecated,
        } = self.0;
        write!(f, "{}", DescriptionDisplay(description.as_deref()))?;
        write!(f, "{name}")?;
        writeln!(f, "{}", DeprecatedDisplay(deprecated))
    }
}

struct DeprecatedDisplay<'a>(&'a Deprecated);

impl Display for DeprecatedDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Deprecated::No => {}
            Deprecated::Yes(None) => write!(f, " @deprecated")?,
            Deprecated::Yes(Some(reason)) => {
                write!(f, " @deprecated(reason: \"{}\")", escape_string(reason))?
            }
        }
        Ok(())
    }
}

struct SpecifiedByDisplay<'a>(Option<&'a str>);

impl Display for SpecifiedByDisplay<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            None => {}
            Some(url) => write!(f, " @specifiedBy(url: {url})")?,
        }
        Ok(())
    }
}

pub fn indented<D>(f: &mut D) -> indenter::Indented<'_, D> {
    indenter::indented(f).with_str("  ")
}

fn escape_string(src: &str) -> String {
    let mut dest = String::with_capacity(src.len());

    for character in src.chars() {
        match character {
            '"' | '\\' | '\n' | '\r' | '\t' => {
                dest.extend(character.escape_default());
            }
            _ => dest.push(character),
        }
    }

    dest
}