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
482
483
484
485
486
487
488
489
use std::{
    collections::{BTreeMap, BTreeSet, HashMap},
    io::Write,
    path::Path,
    sync::{Arc, OnceLock},
};

use maplit::btreemap;
use quote::quote;
use regex::Regex;
use trustfall::{Schema, SchemaAdapter, TryIntoStruct};

use crate::util::{escaped_rust_name, parse_import, to_lower_snake_case, upper_case_variant_name};

use super::{
    adapter_creator::make_adapter_file, edges_creator::make_edges_file,
    entrypoints_creator::make_entrypoints_file, properties_creator::make_properties_file,
};

/// Given a schema, make a Rust adapter stub for it in the given directory.
///
/// Generated code structure:
/// - adapter/mod.rs          connects everything together
/// - adapter/schema.graphql  contains the schema for the adapter
/// - adapter/adapter_impl.rs contains the adapter implementation
/// - adapter/vertex.rs       contains the vertex type definition
/// - adapter/entrypoints.rs  contains the entry points where all queries must start
/// - adapter/properties.rs   contains the property implementations
/// - adapter/edges.rs        contains the edge implementations
/// - adapter/tests.rs        contains test code
///
/// # Example
/// ```no_run
/// # use std::path::Path;
/// #
/// # use trustfall_stubgen::generate_rust_stub;
/// #
/// # fn main() {
/// let schema_text = std::fs::read_to_string("./schema.graphql").expect("failed to read schema");
/// generate_rust_stub(&schema_text, Path::new("crate/with/generated/stubs/src"))
///     .expect("stub generation failed");
/// # }
/// ```
pub fn generate_rust_stub(schema: &str, target: &Path) -> anyhow::Result<()> {
    let target_schema = Schema::parse(schema)?;

    let querying_schema =
        Schema::parse(SchemaAdapter::schema_text()).expect("schema querying schema was not valid");
    let schema_adapter = Arc::new(SchemaAdapter::new(&target_schema));

    let mut stub = AdapterStub::with_standard_mod(schema);

    let mut entrypoint_match_arms = proc_macro2::TokenStream::new();

    ensure_no_vertex_name_conflicts(&querying_schema, schema_adapter.clone());
    ensure_no_field_name_conflicts_on_vertex_type(&querying_schema, schema_adapter.clone());

    make_vertex_file(&querying_schema, schema_adapter.clone(), &mut stub.vertex);
    make_entrypoints_file(
        &querying_schema,
        schema_adapter.clone(),
        &mut stub.entrypoints,
        &mut entrypoint_match_arms,
    );
    make_properties_file(&querying_schema, schema_adapter.clone(), &mut stub.properties);
    make_edges_file(&querying_schema, schema_adapter.clone(), &mut stub.edges);
    make_adapter_file(
        &querying_schema,
        schema_adapter.clone(),
        &mut stub.adapter_impl,
        entrypoint_match_arms,
    );
    make_tests_file(&mut stub.tests);

    stub.write_to_directory(target)
}

#[derive(Debug, Default)]
pub(crate) struct RustFile {
    pub(crate) builtin_imports: BTreeSet<Vec<String>>,
    pub(crate) internal_imports: BTreeSet<Vec<String>>,
    pub(crate) external_imports: BTreeSet<Vec<String>>,
    pub(crate) top_level_items: Vec<proc_macro2::TokenStream>,
}

impl RustFile {
    fn write_to_file(self, target: &Path) -> anyhow::Result<()> {
        let mut buffer: Vec<u8> = Vec::with_capacity(8192);

        write_import_tree(&mut buffer, &self.builtin_imports)?;
        if !self.builtin_imports.is_empty() {
            buffer.write_all("\n".as_bytes())?;
        }

        write_import_tree(&mut buffer, &self.external_imports)?;
        if !self.external_imports.is_empty() {
            buffer.write_all("\n".as_bytes())?;
        }

        write_import_tree(&mut buffer, &self.internal_imports)?;
        if !self.internal_imports.is_empty() {
            buffer.write_all("\n".as_bytes())?;
        }

        let mut item_iter = self.top_level_items.into_iter();
        let Some(first_item) = item_iter.next() else {
            return std::fs::write(target, "").map_err(Into::into);
        };
        Self::pretty_print_item(&mut buffer, first_item)?;

        for item in item_iter {
            buffer.write_all("\n".as_bytes())?;
            Self::pretty_print_item(&mut buffer, item)?;
        }

        std::fs::write(target, buffer)?;

        Ok(())
    }

    /// Pretty-print an item into the buffer.
    ///
    /// First use `prettyplease`, then postprocess with a regex to further improve quality.
    /// `prettyplease` does not add blank lines between sibling items, so we add them via regex.
    fn pretty_print_item(
        buffer: &mut impl std::io::Write,
        item: proc_macro2::TokenStream,
    ) -> anyhow::Result<()> {
        static PATTERN: OnceLock<Regex> = OnceLock::new();
        let pattern =
            PATTERN.get_or_init(|| Regex::new("([^{])\n    (pub|fn|use)").expect("invalid regex"));
        let pretty_item =
            prettyplease::unparse(&syn::parse_str(&item.to_string()).expect("not valid Rust"));
        let postprocessed = pattern.replace_all(&pretty_item, "$1\n\n    $2");

        buffer.write_all(postprocessed.as_bytes())?;

        Ok(())
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum NodeOrLeaf<'a> {
    Leaf,
    Node(BTreeMap<&'a str, NodeOrLeaf<'a>>),
}

impl<'a> NodeOrLeaf<'a> {
    fn insert(&mut self, path: &'a [String]) {
        if let Some(first) = path.first() {
            let rest = &path[1..];
            match self {
                Self::Leaf => {
                    *self = Self::Node(btreemap! {
                        "self" => Self::Leaf,
                        first.as_str() => Self::from_path(rest),
                    })
                }
                Self::Node(ref mut map) => match map.entry(first) {
                    std::collections::btree_map::Entry::Vacant(e) => {
                        e.insert(Self::from_path(rest));
                    }
                    std::collections::btree_map::Entry::Occupied(mut e) => {
                        e.get_mut().insert(rest);
                    }
                },
            }
        } else {
            match self {
                Self::Leaf => {} // self is already here
                Self::Node(ref mut map) => {
                    map.insert("self", Self::Leaf);
                }
            }
        }
    }

    fn from_path(path: &[String]) -> NodeOrLeaf<'_> {
        if let Some(first) = path.first() {
            let rest = &path[1..];
            NodeOrLeaf::Node(btreemap! {
                first.as_str() => Self::from_path(rest)
            })
        } else {
            NodeOrLeaf::Leaf
        }
    }
}

fn make_import_forest(imports: &BTreeSet<Vec<String>>) -> BTreeMap<&str, NodeOrLeaf<'_>> {
    let first_import = imports.first().expect("no imports").as_slice();
    let mut node = NodeOrLeaf::from_path(first_import);

    for import in imports.iter().skip(1) {
        node.insert(import.as_slice());
    }

    match node {
        NodeOrLeaf::Node(map) => map,
        NodeOrLeaf::Leaf => {
            unreachable!("unexpectedly got a leaf node for the top level of the import forest")
        }
    }
}

fn write_import_tree<W: std::io::Write>(
    writer: &mut W,
    imports: &BTreeSet<Vec<String>>,
) -> anyhow::Result<()> {
    if imports.is_empty() {
        return Ok(());
    }

    let forest = make_import_forest(imports);

    for (root, nodes) in forest {
        writer.write_all("use ".as_bytes())?;
        writer.write_all(root.as_bytes())?;

        write_import_subtree(writer, nodes)?;
        writer.write_all(";\n".as_bytes())?;
    }

    Ok(())
}

fn write_import_subtree<W: std::io::Write>(
    writer: &mut W,
    nodes: NodeOrLeaf<'_>,
) -> anyhow::Result<()> {
    match nodes {
        NodeOrLeaf::Leaf => {}
        NodeOrLeaf::Node(map) => {
            writer.write_all("::".as_bytes())?;

            if map.len() == 1 {
                for (root, inner) in map {
                    writer.write_all(root.as_bytes())?;
                    write_import_subtree(writer, inner)?;
                }
            } else {
                writer.write_all("{".as_bytes())?;

                let mut map_iter = map.into_iter();
                let (root, inner) = map_iter.next().expect("empty map found");
                writer.write_all(root.as_bytes())?;
                write_import_subtree(writer, inner)?;

                for (root, inner) in map_iter {
                    writer.write_all(", ".as_bytes())?;
                    writer.write_all(root.as_bytes())?;
                    write_import_subtree(writer, inner)?;
                }

                writer.write_all("}".as_bytes())?;
            }
        }
    }

    Ok(())
}

#[derive(Debug)]
struct AdapterStub<'a> {
    mod_: RustFile,
    schema: &'a str,
    adapter_impl: RustFile,
    vertex: RustFile,
    entrypoints: RustFile,
    properties: RustFile,
    edges: RustFile,
    tests: RustFile,
}

impl<'a> AdapterStub<'a> {
    fn with_standard_mod(schema: &'a str) -> Self {
        let mut mod_ = RustFile::default();

        mod_.top_level_items.push(quote! {
            mod adapter_impl;
            mod vertex;
            mod entrypoints;
            mod properties;
            mod edges;
        });
        mod_.top_level_items.push(quote! {
            #[cfg(test)]
            mod tests;
        });
        mod_.top_level_items.push(quote! {
            pub use adapter_impl::Adapter;
            pub use vertex::Vertex;
        });

        Self {
            mod_,
            schema,
            adapter_impl: Default::default(),
            vertex: Default::default(),
            entrypoints: Default::default(),
            properties: Default::default(),
            edges: Default::default(),
            tests: Default::default(),
        }
    }

    fn write_to_directory(self, target: &Path) -> anyhow::Result<()> {
        let mut path_buf = target.to_path_buf();
        path_buf.push("adapter");
        std::fs::create_dir_all(&path_buf)?;

        path_buf.push("schema.graphql");
        std::fs::write(path_buf.as_path(), self.schema)?;
        path_buf.pop();

        path_buf.push("mod.rs");
        self.mod_.write_to_file(path_buf.as_path())?;
        path_buf.pop();

        path_buf.push("adapter_impl.rs");
        self.adapter_impl.write_to_file(path_buf.as_path())?;
        path_buf.pop();

        path_buf.push("vertex.rs");
        self.vertex.write_to_file(path_buf.as_path())?;
        path_buf.pop();

        path_buf.push("entrypoints.rs");
        self.entrypoints.write_to_file(path_buf.as_path())?;
        path_buf.pop();

        path_buf.push("properties.rs");
        self.properties.write_to_file(path_buf.as_path())?;
        path_buf.pop();

        path_buf.push("edges.rs");
        self.edges.write_to_file(path_buf.as_path())?;
        path_buf.pop();

        path_buf.push("tests.rs");
        self.tests.write_to_file(path_buf.as_path())?;
        path_buf.pop();

        Ok(())
    }
}

fn make_tests_file(tests_file: &mut RustFile) {
    tests_file
        .external_imports
        .insert(parse_import("trustfall::provider::check_adapter_invariants"));

    tests_file.internal_imports.insert(parse_import("super::Adapter"));

    tests_file.top_level_items.push(quote! {
        #[test]
        fn adapter_satisfies_trustfall_invariants() {
            let adapter = Adapter::new();
            let schema = Adapter::schema();
            check_adapter_invariants(schema, adapter);
        }
    });
}

fn make_vertex_file(
    querying_schema: &Schema,
    adapter: Arc<SchemaAdapter<'_>>,
    vertex_file: &mut RustFile,
) {
    let query = r#"
{
    VertexType {
        name @output
    }
}"#;
    let variables: BTreeMap<String, String> = Default::default();

    #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize)]
    struct ResultRow {
        name: String,
    }

    let mut variants = proc_macro2::TokenStream::new();
    let mut rows: Vec<_> = trustfall::execute_query(querying_schema, adapter, query, variables)
        .expect("invalid query")
        .map(|x| x.try_into_struct::<ResultRow>().expect("invalid conversion"))
        .collect();
    rows.sort_unstable();
    for row in rows {
        let name = &escaped_rust_name(upper_case_variant_name(&row.name));
        let ident = syn::Ident::new(name.as_str(), proc_macro2::Span::call_site());
        variants.extend(quote! {
            #ident(()),
        });
    }

    let vertex = quote! {
        #[non_exhaustive]
        #[derive(Debug, Clone, trustfall::provider::TrustfallEnumVertex)]
        pub enum Vertex {
            #variants
        }
    };

    vertex_file.top_level_items.push(vertex);
}

fn ensure_no_vertex_name_conflicts(querying_schema: &Schema, adapter: Arc<SchemaAdapter<'_>>) {
    let query = r#"
{
    VertexType {
        name @output
    }
}"#;
    let variables: BTreeMap<String, String> = Default::default();

    #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize)]
    struct ResultRow {
        name: String,
    }

    let mut rows: Vec<_> = trustfall::execute_query(querying_schema, adapter, query, variables)
        .expect("invalid query")
        .map(|x| x.try_into_struct::<ResultRow>().expect("invalid conversion"))
        .collect();
    rows.sort_unstable();

    let mut uniq: HashMap<String, String> = HashMap::new();

    for row in rows {
        let name = row.name.clone();
        // we normalize to lower snake case here, however in vertex name we capitalize this name instead
        // it doesn't really matter though because the important one is just to normalize to the same capitalization scheme
        let converted = escaped_rust_name(to_lower_snake_case(&name));
        let v = uniq.insert(converted, name);
        if let Some(v) = v {
            panic!(
                "cannot generate adapter for a schema containing both '{}' and '{}' vertices, consider renaming one of them",
                v, &row.name
            );
        }
    }
}

fn ensure_no_field_name_conflicts_on_vertex_type(
    querying_schema: &Schema,
    adapter: Arc<SchemaAdapter<'_>>,
) {
    let query = r#"
{
    VertexType {
        name @output
        edge_: edge @fold {
            names: name @output
        }
        property_: property @fold {
            names: name @output
        }
    }
}"#;
    let variables: BTreeMap<String, String> = Default::default();

    #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize)]
    struct ResultRow {
        name: String,
        edge_names: Vec<String>,
        property_names: Vec<String>,
    }

    let mut rows: Vec<_> = trustfall::execute_query(querying_schema, adapter, query, variables)
        .expect("invalid query")
        .map(|x| x.try_into_struct::<ResultRow>().expect("invalid conversion"))
        .collect();
    rows.sort_unstable();

    for row in &rows {
        let mut uniq: HashMap<String, String> = HashMap::new();

        for field_name in row.edge_names.iter().chain(row.property_names.iter()) {
            let converted = escaped_rust_name(to_lower_snake_case(field_name));
            if let Some(v) = uniq.insert(converted, field_name.clone()) {
                panic!(
                    "cannot generate adapter for a schema containing both '{}' and '{}' as field names on vertex '{}', consider renaming one of them",
                    v, &field_name, &row.name
                );
            }
        }
    }
}