facet_generate 0.17.2

Generate Swift, Kotlin, TypeScript, and C# from types annotated with `#[derive(Facet)]`
Documentation
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
#![allow(clippy::missing_errors_doc)]
// Copyright (c) Facebook, Inc. and its affiliates
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Configuration that controls code-generation behaviour independent of the
//! target language.
//!
//! Cross-module relationships are handled by [`ExternalDefinitions`] (which
//! types live in other modules) and [`ExternalPackages`] (where to import them
//! from), so generators can emit `import` / `using` statements instead of
//! redeclaring types.
//!
//! [`Feature`] flags are discovered automatically by
//! [`CodeGeneratorConfig::update_from`] scanning the registry — they tell the
//! installer which container-type helpers (`ListOfT`, `MapOfT`, …) to include.
//!
//! There are two configuration levels:
//!
//! - [`Config`] / [`ConfigBuilder`] — the public API entry point (package
//!   name, output directory, external packages).
//! - [`CodeGeneratorConfig`] — the internal, per-module config that generators
//!   and [`Emitter`](super::Emitter) implementations receive.

use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
};

use derive_builder::Builder;
use serde::Serialize;
use thiserror::Error;

use crate::{
    Registry,
    generation::indent::IndentConfig,
    reflection::format::{ContainerFormat, Format, FormatHolder, Namespace, VariantFormat},
};

/// Code generation options meant to be supported by all languages.
#[derive(Clone, Debug)]
pub struct CodeGeneratorConfig {
    pub module_name: String,
    pub external_definitions: ExternalDefinitions,
    pub external_packages: ExternalPackages,
    pub comments: DocComments,
    pub package_manifest: bool,
    pub features: BTreeSet<Feature>,
    /// The indentation style used when writing generated source code.
    ///
    /// Defaults to `IndentConfig::Space(4)`. Pass a custom value via
    /// [`with_indent`](Self::with_indent) if a different style is required
    /// (e.g. tabs, or a different space width).
    pub indent: IndentConfig,
    /// Which primitive/leaf format types are used in the registry.
    /// Populated by `update_from`. Used by TypeScript to emit type aliases.
    pub used_format_types: BTreeSet<String>,
    /// External namespaces actually referenced via `Format::TypeName` in the registry.
    /// Populated by `update_from`. Used to generate namespace import statements.
    pub referenced_namespaces: BTreeSet<String>,
    /// Names of all enums in the registry whose every variant is a unit variant.
    /// Populated by `update_from`. Used by the C# Bincode plugin to dispatch
    /// enum-typed fields through `{TypeName}Bincode.Serialize(...)` helpers.
    pub unit_variant_enums: BTreeSet<String>,
}

/// Container or leaf types in the registry that need a runtime support file
/// installed alongside the generated code.
///
/// Discovered automatically by [`CodeGeneratorConfig::update_from`] and
/// consumed by [`SourceInstaller`] implementations.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Ord, PartialOrd, Serialize)]
#[non_exhaustive]
pub enum Feature {
    BigInt,
    Bytes,
    ListOfT,
    MapOfT,
    OptionOfT,
    SetOfT,
    TupleArray,
    Uuid,
}

/// Track type definitions provided by other modules (key = `module`, value = `type names`).
pub type ExternalDefinitions =
    BTreeMap</* module */ String, /* type names */ Vec<String>>;

/// Track locations for imports of external packages (key = `module`, value = `import from`).
pub type ExternalPackages =
    BTreeMap</* module */ String, /* import from */ ExternalPackage>;

/// Track documentation to be attached to particular definitions.
pub type DocComments = BTreeMap</* qualified name */ Vec<String>, /* comment */ String>;

/// Errors that can occur during code generation and installation.
#[derive(Debug, Error)]
pub enum Error {
    /// An I/O error occurred while reading or writing files.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// A runtime file contained invalid UTF-8.
    #[error("invalid UTF-8 in runtime file: {0}")]
    Utf8(#[from] std::str::Utf8Error),

    /// JSON serialization failed (e.g. when writing a TypeScript `package.json`).
    #[error("JSON serialization error: {0}")]
    Json(#[from] serde_json::Error),
}

/// Writes generated source code and runtime support files to disk.
///
/// Each target language provides its own implementation. The installer is
/// the third layer of the pipeline — after [`CodeGenerator`](super::CodeGenerator)
/// produces the source text and [`Emitter`](super::Emitter) renders each
/// AST node, the installer places everything into the output directory and
/// writes any runtime files declared by the active plugins.
pub trait SourceInstaller {
    /// Create a module exposing the container types contained in the registry.
    fn install_module(
        &mut self,
        config: &CodeGeneratorConfig,
        registry: &Registry,
    ) -> std::result::Result<(), Error>;

    /// Install a package manifest.
    fn install_manifest(&self, _module_name: &str) -> std::result::Result<(), Error> {
        Ok(())
    }
}

impl CodeGeneratorConfig {
    /// Default config for the given module name.
    #[must_use]
    pub const fn new(module_name: String) -> Self {
        Self {
            module_name,
            external_definitions: BTreeMap::new(),
            external_packages: BTreeMap::new(),
            comments: BTreeMap::new(),
            package_manifest: true,
            features: BTreeSet::new(),
            used_format_types: BTreeSet::new(),
            referenced_namespaces: BTreeSet::new(),
            unit_variant_enums: BTreeSet::new(),
            indent: IndentConfig::Space(4),
        }
    }

    #[must_use]
    pub fn module_name(&self) -> &str {
        &self.module_name
    }

    /// for Kotlin: updates the module name to be a child of the specified parent
    #[must_use]
    pub fn with_parent(mut self, parent: &str) -> Self {
        if parent == self.module_name() {
            return self;
        }

        self.module_name = format!("{}.{}", parent, self.module_name());
        self
    }

    /// Which indentation style to use when writing generated source code.
    #[must_use]
    pub const fn with_indent(mut self, indent: IndentConfig) -> Self {
        self.indent = indent;
        self
    }

    /// Container names provided by other modules.
    #[must_use]
    pub fn with_external_definitions(mut self, external_definitions: ExternalDefinitions) -> Self {
        self.external_definitions = external_definitions;
        self
    }

    /// Comments attached to particular entity.
    #[must_use]
    pub fn with_comments(mut self, mut comments: DocComments) -> Self {
        // Make sure comments end with a (single) newline.
        for comment in comments.values_mut() {
            *comment = format!("{}\n", comment.trim());
        }
        self.comments = comments;
        self
    }

    /// Generate a package manifest file for the target language.
    #[must_use]
    pub const fn with_package_manifest(mut self, package_manifest: bool) -> Self {
        self.package_manifest = package_manifest;
        self
    }

    /// Updates a config with features present in the specified registry.
    ///
    /// # Panics
    ///
    /// Panics if the registry is not properly formatted.
    pub fn update_from(&mut self, registry: &Registry) {
        for format in registry.values() {
            format
                .visit(&mut |f| {
                    match f {
                        Format::I128 | Format::U128 => {
                            self.features.insert(Feature::BigInt);
                        }
                        Format::Bytes => {
                            self.features.insert(Feature::Bytes);
                        }
                        Format::Uuid => {
                            self.features.insert(Feature::Uuid);
                        }
                        Format::Seq(..) => {
                            self.features.insert(Feature::ListOfT);
                        }
                        Format::Option(..) => {
                            self.features.insert(Feature::OptionOfT);
                        }
                        Format::Set(..) => {
                            self.features.insert(Feature::SetOfT);
                        }
                        Format::Map { .. } => {
                            self.features.insert(Feature::MapOfT);
                        }
                        Format::TupleArray { .. } => {
                            self.features.insert(Feature::TupleArray);
                        }
                        _ => (),
                    }

                    // Track external namespaces actually referenced in format types.
                    if let Format::TypeName(qualified_name) = f
                        && let Namespace::Named(ns) = &qualified_name.namespace
                        && ns != &self.module_name
                    {
                        self.referenced_namespaces.insert(ns.clone());
                    }

                    // Also record the leaf format type key (used by TypeScript for type aliases).
                    let format_key = match f {
                        Format::Unit => "unit",
                        Format::Bool => "bool",
                        Format::I8 => "int8",
                        Format::I16 => "int16",
                        Format::I32 => "int32",
                        Format::I64 => "int64",
                        Format::I128 => "int128",
                        Format::U8 => "uint8",
                        Format::U16 => "uint16",
                        Format::U32 => "uint32",
                        Format::U64 => "uint64",
                        Format::U128 => "uint128",
                        Format::F32 => "float32",
                        Format::F64 => "float64",
                        Format::Char => "char",
                        Format::Str => "str",
                        Format::Bytes => "bytes",
                        Format::Uuid => "uuid",
                        Format::Option(_) => "option",
                        Format::Seq(_) | Format::Set(_) => "seq",
                        Format::Map { .. } => "map",
                        Format::Tuple(_) => "tuple",
                        Format::TupleArray { .. } => "list_tuple",
                        Format::TypeName(_) | Format::Variable(_) => "",
                    };
                    if !format_key.is_empty() {
                        self.used_format_types.insert(format_key.to_string());
                    }

                    Ok(())
                })
                .expect("failed to parse registry");
        }

        for (name, format) in registry {
            if let Namespace::Named(ns) = &name.namespace
                && ns != &self.module_name
            {
                let entry = self.external_definitions.entry(ns.to_owned()).or_default();
                entry.push(name.name.clone());
            }

            if let ContainerFormat::Enum(variants, _) = format
                && variants
                    .values()
                    .all(|v| matches!(v.value, VariantFormat::Unit))
            {
                self.unit_variant_enums.insert(name.name.clone());
            }
        }
    }
}

/// Public API entry point for configuring a generation run.
///
/// Use [`Config::builder`] to create one, then pass it to a language-specific
/// `generate` function.
#[derive(Default, Builder)]
#[builder(
    custom_constructor,
    create_empty = "empty",
    build_fn(private, name = "fallible_build")
)]
pub struct Config {
    /// The name of the package to generate.
    #[builder(setter(into))]
    pub package_name: String,
    /// The directory to generate the types in.
    #[builder(setter(into))]
    pub out_dir: PathBuf,
    /// External packages to reference.
    #[builder(default = vec![], setter(each(name = "reference")))]
    pub external_packages: Vec<ExternalPackage>,
}

impl Config {
    pub fn builder(name: &str, out_dir: impl AsRef<Path>) -> ConfigBuilder {
        ConfigBuilder {
            package_name: Some(name.to_string()),
            out_dir: Some(out_dir.as_ref().to_path_buf()),
            ..ConfigBuilder::empty()
        }
    }
}

impl ConfigBuilder {
    /// # Panics
    /// If any required fields are not initialized.
    #[must_use]
    pub fn build(&self) -> Config {
        self.fallible_build()
            .expect("All required fields were initialized")
    }
}

/// Where an external package can be found.
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum PackageLocation {
    /// Either a local file path or, for Kotlin, a dot-separated package name.
    Path(String),
    // The URL of a remote package.
    Url(String),
}

/// A reference to a package that provides types from another namespace,
/// so the generator can emit the correct import statements.
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ExternalPackage {
    /// The namespace as specified in `#[facet(fg::namespace = "namespace")]`.
    pub for_namespace: String,
    /// The location of the package.
    pub location: PackageLocation,
    /// The name of the module, if you are importing one from a package.
    /// e.g. in TypeScript: `import { Foo } from 'package_name/module_name';`
    pub module_name: Option<String>,
    /// An optional string to specify the version of a published package.
    pub version: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn with_parent() {
        let root_package = "root";
        let child_package = "child";

        let root_config = CodeGeneratorConfig::new(root_package.to_string());

        let actual = root_config.with_parent(root_package).module_name;
        let expected = root_package;
        assert_eq!(&actual, expected);

        let actual = CodeGeneratorConfig::new(child_package.to_string())
            .with_parent(root_package)
            .module_name;
        let expected = format!("{root_package}.{child_package}");
        assert_eq!(&actual, &expected);
    }

    #[test]
    fn config_builder_populates_external_packages() {
        let config = Config::builder("MyPackage", "/tmp/out")
            .reference(ExternalPackage {
                for_namespace: "serde".to_string(),
                location: PackageLocation::Path("../Serde".to_string()),
                module_name: None,
                version: None,
            })
            .reference(ExternalPackage {
                for_namespace: "other".to_string(),
                location: PackageLocation::Path("../Other".to_string()),
                module_name: None,
                version: None,
            })
            .build();

        assert_eq!(config.external_packages.len(), 2);
        assert_eq!(config.external_packages[0].for_namespace, "serde");
        assert_eq!(config.external_packages[1].for_namespace, "other");
    }

    #[test]
    fn config_builder_defaults_external_packages_to_empty() {
        let config = Config::builder("MyPackage", "/tmp/out").build();
        assert!(config.external_packages.is_empty());
    }
}