Skip to main content

crossplane_forge/
go_spec.rs

1//! `go_spec` — the Go **macro-farm** surface.
2//!
3//! This module is the Go-codegen analog of `tatara-rust-ast`'s
4//! `*DeriveSpec` family (`tatara_rust_derive::PerFieldDeriveSpec`, …).
5//! Where a tatara Rust spec is a typed, serde-serializable declaration
6//! that lowers to a Rust AST and renders through `ToRustTokens` +
7//! `prettyplease`, a [`GoSpec`] here is a typed, serde-serializable
8//! declaration that lowers to a [`go_synthesizer::GoFile`] and renders
9//! through [`go_synthesizer::print_file`].
10//!
11//! ```text
12//!  tatara-rust-ast                       go_spec (this module)
13//!  ───────────────                       ──────────────────────
14//!  PerFieldDeriveSpec  (typed spec)      GoSpec        (typed spec)
15//!        │                                     │
16//!        ▼ compile_to_crate                    ▼ to_go_file
17//!  Rust AST (syn / proc-macro2)          go_synthesizer::GoFile
18//!        │                                     │
19//!        ▼ ToRustTokens + prettyplease         ▼ go_synthesizer::print_file
20//!  buildable .rs source                  buildable .go source
21//! ```
22//!
23//! ## Why this is the right shape
24//!
25//! The org-level ★★ EMITTER SUBSTRATE / PRIME DIRECTIVE rule says
26//! *every repeating impl is a Spec; emit, don't author* — and *never
27//! hand-roll `format!()` strings of target syntax*. The fleet already
28//! has that surface for Rust (tatara-rust-ast) and for whole-file Go
29//! AST authoring (`go_synthesizer`). What was **missing** was the
30//! intermediate *spec → Go* layer: a small typed declaration a caller
31//! authors once, that mechanically expands into the canonical
32//! `go_synthesizer` AST. [`GoSpec`] closes that gap. It is deliberately
33//! **minimal** — the two families that the canonical
34//! [`go_synthesizer::GoTypeBody`] / [`go_synthesizer::GoFuncDecl`]
35//! surface fully supports today (tagged structs and funcs). Adding a
36//! third family (e.g. named interfaces with method sets) is a one-enum-
37//! variant follow-up *once `go_synthesizer` grows the matching
38//! `GoTypeBody::Interface` node* — see [the extension path][ext] below.
39//!
40//! [ext]: #extension-path
41//!
42//! ## Extension path
43//!
44//! 1. **New field family** — add a variant to [`GoFieldSpec`]; lower it
45//!    in [`GoStructSpec::to_decl`]. No `go_synthesizer` change needed
46//!    (the struct/field surface is already complete).
47//! 2. **New item family** (e.g. `Interface`, `Const`, `VarBlock`) — add
48//!    a variant to [`GoItemSpec`] + a `to_decl`-style lowering. If the
49//!    family needs a Go syntactic form `go_synthesizer` lacks (named
50//!    interfaces with methods), add exactly one
51//!    [`go_synthesizer::GoTypeBody`] variant upstream first, then lower
52//!    onto it — the substrate-hygienic way to surface need rather than
53//!    re-introducing `format!()` shortcuts.
54//! 3. **A `(defgostruct …)` / `(defgofunc …)` tatara-lisp authoring
55//!    surface** — because [`GoSpec`] is plain serde, a `defform` macro
56//!    can deserialize the Lisp form straight into a [`GoSpec`]; the
57//!    lowering here stays unchanged.
58
59use go_synthesizer::{
60    GoBlock, GoDecl, GoExpr, GoField, GoFile, GoFuncDecl, GoImport, GoMod, GoParam, GoRecv,
61    GoRequire, GoStmt, GoStructTag, GoType, GoTypeBody, GoTypeDecl, JsonTag, KubeMarker,
62    YamlTag, print_file,
63};
64use serde::{Deserialize, Serialize};
65
66/// A typed Go reference type, mirroring the subset of
67/// [`go_synthesizer::GoType`] that a spec author needs. Kept as its own
68/// serde-friendly enum (rather than re-using `GoType` directly) so the
69/// spec surface stays stable even if `go_synthesizer::GoType` grows
70/// `#[non_exhaustive]` variants.
71#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(rename_all = "kebab-case", tag = "kind")]
73pub enum GoTypeSpec {
74    /// `string`, `int64`, `MyStruct` — a name in the current package or
75    /// a builtin.
76    Named { name: String },
77    /// `pkg.Name` — a qualified reference to another package's type.
78    Qualified { pkg: String, name: String },
79    /// `*T`.
80    Pointer { inner: Box<GoTypeSpec> },
81    /// `[]T`.
82    Slice { elem: Box<GoTypeSpec> },
83    /// `map[K]V`.
84    Map { key: Box<GoTypeSpec>, value: Box<GoTypeSpec> },
85}
86
87impl GoTypeSpec {
88    /// Convenience constructor for a bare named type.
89    #[must_use]
90    pub fn named(name: impl Into<String>) -> Self {
91        Self::Named { name: name.into() }
92    }
93
94    /// Convenience constructor for a qualified `pkg.Name` type.
95    #[must_use]
96    pub fn qualified(pkg: impl Into<String>, name: impl Into<String>) -> Self {
97        Self::Qualified { pkg: pkg.into(), name: name.into() }
98    }
99
100    /// Lower to the canonical [`go_synthesizer::GoType`].
101    #[must_use]
102    pub fn to_go_type(&self) -> GoType {
103        match self {
104            Self::Named { name } => GoType::named(name.clone()),
105            Self::Qualified { pkg, name } => GoType::qualified(pkg.clone(), name.clone()),
106            Self::Pointer { inner } => GoType::pointer(inner.to_go_type()),
107            Self::Slice { elem } => GoType::slice(elem.to_go_type()),
108            Self::Map { key, value } => {
109                GoType::Map(Box::new(key.to_go_type()), Box::new(value.to_go_type()))
110            }
111        }
112    }
113}
114
115/// A serialization tag on a struct field. Mirrors the structured subset
116/// of [`go_synthesizer::GoStructTag`] (json / yaml) — the canonical
117/// "discouraged" `Custom` variant is intentionally not exposed here so
118/// the spec stays opinionated.
119#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "kebab-case", tag = "encoding")]
121pub enum GoTagSpec {
122    /// `json:"<name>[,omitempty]"`.
123    Json { name: String, #[serde(default)] omitempty: bool },
124    /// `yaml:"<name>[,omitempty]"`.
125    Yaml { name: String, #[serde(default)] omitempty: bool },
126}
127
128impl GoTagSpec {
129    fn to_struct_tag(&self) -> GoStructTag {
130        match self {
131            Self::Json { name, omitempty } => GoStructTag::Json(JsonTag {
132                name: name.clone(),
133                omitempty: *omitempty,
134                inline: false,
135            }),
136            Self::Yaml { name, omitempty } => GoStructTag::Yaml(YamlTag {
137                name: name.clone(),
138                omitempty: *omitempty,
139                inline: false,
140            }),
141        }
142    }
143}
144
145/// A kubebuilder marker a field can carry, mirroring the common subset
146/// of [`go_synthesizer::KubeMarker`].
147#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(rename_all = "kebab-case")]
149pub enum GoMarkerSpec {
150    /// `+kubebuilder:validation:Required`.
151    Required,
152    /// `+optional`.
153    Optional,
154}
155
156impl GoMarkerSpec {
157    fn to_kube_marker(&self) -> KubeMarker {
158        match self {
159            Self::Required => KubeMarker::Required,
160            Self::Optional => KubeMarker::Optional,
161        }
162    }
163}
164
165/// One field of a struct family.
166#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
167pub struct GoFieldSpec {
168    /// Field identifier (Go exported name, e.g. `Name`).
169    pub name: String,
170    /// Field type.
171    pub ty: GoTypeSpec,
172    /// Optional doc comment.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub doc: Option<String>,
175    /// Serialization tags (json / yaml).
176    #[serde(default, skip_serializing_if = "Vec::is_empty")]
177    pub tags: Vec<GoTagSpec>,
178    /// kubebuilder markers.
179    #[serde(default, skip_serializing_if = "Vec::is_empty")]
180    pub markers: Vec<GoMarkerSpec>,
181}
182
183impl GoFieldSpec {
184    fn to_field(&self) -> GoField {
185        GoField {
186            name: Some(self.name.clone()),
187            ty: self.ty.to_go_type(),
188            doc: self.doc.clone(),
189            markers: self.markers.iter().map(GoMarkerSpec::to_kube_marker).collect(),
190            tags: self.tags.iter().map(GoTagSpec::to_struct_tag).collect(),
191        }
192    }
193}
194
195/// The **struct family** — `type <Name> struct { … }`.
196#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
197pub struct GoStructSpec {
198    /// Type name (`StaticSecret`, `Config`, …).
199    pub name: String,
200    /// Optional doc comment.
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub doc: Option<String>,
203    /// Fields, in source order.
204    #[serde(default)]
205    pub fields: Vec<GoFieldSpec>,
206}
207
208impl GoStructSpec {
209    fn to_decl(&self) -> GoDecl {
210        GoDecl::Type(GoTypeDecl {
211            name: self.name.clone(),
212            doc: self.doc.clone(),
213            markers: vec![],
214            body: GoTypeBody::Struct(self.fields.iter().map(GoFieldSpec::to_field).collect()),
215        })
216    }
217}
218
219/// One parameter of a func family.
220#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
221pub struct GoParamSpec {
222    pub name: String,
223    pub ty: GoTypeSpec,
224}
225
226/// The minimal func body the spec supports today: an ordered list of
227/// `return <exprs>` lines is over-engineered for a "minimal but real"
228/// surface, so we model exactly the two bodies generated Go funcs
229/// overwhelmingly need — a single `return <expr>` or an empty body.
230///
231/// Anything richer should be authored directly as a
232/// [`go_synthesizer::GoBlock`] by the caller (the spec layer is for the
233/// *common* shapes; the AST layer is always available for the rest).
234#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
235#[serde(rename_all = "kebab-case", tag = "body")]
236pub enum GoFuncBodySpec {
237    /// `{}` — empty body.
238    Empty,
239    /// `return nil`.
240    ReturnNil,
241    /// `return &<TypeName>{}` — the canonical "constructor returns a
242    /// fresh zero value" shape (e.g. `func New() *Client { return &Client{} }`).
243    ReturnNewOf { ty: GoTypeSpec },
244}
245
246impl GoFuncBodySpec {
247    fn to_block(&self) -> GoBlock {
248        let mut b = GoBlock::new();
249        match self {
250            Self::Empty => {}
251            Self::ReturnNil => b.push(GoStmt::Return(vec![GoExpr::nil()])),
252            Self::ReturnNewOf { ty } => b.push(GoStmt::Return(vec![GoExpr::Composite {
253                ty: ty.to_go_type(),
254                fields: vec![],
255                addr_of: true,
256            }])),
257        }
258        b
259    }
260}
261
262/// The **func family** — `func [(<recv>)] <Name>(<params>) <returns> { … }`.
263#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
264pub struct GoFuncSpec {
265    /// Function name.
266    pub name: String,
267    /// Optional doc comment.
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub doc: Option<String>,
270    /// Optional method receiver `(name ty)`; `None` is a free function.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub recv: Option<GoParamSpec>,
273    /// Parameters.
274    #[serde(default, skip_serializing_if = "Vec::is_empty")]
275    pub params: Vec<GoParamSpec>,
276    /// Return types.
277    #[serde(default, skip_serializing_if = "Vec::is_empty")]
278    pub returns: Vec<GoTypeSpec>,
279    /// Function body.
280    pub body: GoFuncBodySpec,
281}
282
283impl GoFuncSpec {
284    fn to_decl(&self) -> GoDecl {
285        GoDecl::Func(GoFuncDecl {
286            name: self.name.clone(),
287            doc: self.doc.clone(),
288            recv: self.recv.as_ref().map(|r| GoRecv {
289                name: r.name.clone(),
290                ty: r.ty.to_go_type(),
291            }),
292            params: self
293                .params
294                .iter()
295                .map(|p| GoParam { name: p.name.clone(), ty: p.ty.to_go_type() })
296                .collect(),
297            returns: self.returns.iter().map(GoTypeSpec::to_go_type).collect(),
298            body: self.body.to_block(),
299        })
300    }
301}
302
303/// A single top-level item the spec can emit. The macro-farm "kind"
304/// dispatch — the Go analog of `tatara_rust_catalog::CatalogSpec`'s
305/// per-kind variants.
306#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(rename_all = "kebab-case", tag = "kind")]
308pub enum GoItemSpec {
309    /// A `type … struct { … }` declaration.
310    Struct(GoStructSpec),
311    /// A `func …` declaration.
312    Func(GoFuncSpec),
313}
314
315impl GoItemSpec {
316    fn to_decl(&self) -> GoDecl {
317        match self {
318            Self::Struct(s) => s.to_decl(),
319            Self::Func(f) => f.to_decl(),
320        }
321    }
322}
323
324/// An import declaration for the generated file.
325#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
326pub struct GoImportSpec {
327    pub path: String,
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub alias: Option<String>,
330}
331
332impl GoImportSpec {
333    fn to_import(&self) -> GoImport {
334        match &self.alias {
335            Some(a) => GoImport::aliased(a.clone(), self.path.clone()),
336            None => GoImport::plain(self.path.clone()),
337        }
338    }
339}
340
341/// The top-level Go-codegen **spec** — a typed, serde-serializable
342/// declaration of one Go source file. Lowers to a
343/// [`go_synthesizer::GoFile`] and renders to buildable Go source via
344/// [`go_synthesizer::print_file`].
345///
346/// This is the Go analog of a tatara-rust-ast `*DeriveSpec` value.
347#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
348pub struct GoSpec {
349    /// `package <name>`.
350    pub package: String,
351    /// File-level doc comment.
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub doc: Option<String>,
354    /// Imports.
355    #[serde(default, skip_serializing_if = "Vec::is_empty")]
356    pub imports: Vec<GoImportSpec>,
357    /// Top-level items in source order.
358    #[serde(default)]
359    pub items: Vec<GoItemSpec>,
360}
361
362impl GoSpec {
363    /// Construct an empty spec for a package.
364    #[must_use]
365    pub fn new(package: impl Into<String>) -> Self {
366        Self { package: package.into(), doc: None, imports: vec![], items: vec![] }
367    }
368
369    /// Lower this spec to the canonical [`go_synthesizer::GoFile`] AST.
370    /// This is the structural core; rendering is a one-liner on top.
371    #[must_use]
372    pub fn to_go_file(&self) -> GoFile {
373        let mut file = GoFile::new(self.package.clone());
374        file.doc = self.doc.clone();
375        file.imports = self.imports.iter().map(GoImportSpec::to_import).collect();
376        file.decls = self.items.iter().map(GoItemSpec::to_decl).collect();
377        file
378    }
379
380    /// Render this spec to buildable, gofmt-stable Go source.
381    ///
382    /// Goes **entirely** through [`go_synthesizer::print_file`] — there
383    /// is no `format!()` of Go syntax anywhere in this module.
384    #[must_use]
385    pub fn render(&self) -> String {
386        print_file(&self.to_go_file())
387    }
388
389    /// Render a companion `go.mod` for this spec, so a generated file
390    /// can be compiled in isolation. The module path + go version are
391    /// caller-supplied; `requires` are typed [`GoRequire`]-equivalents.
392    ///
393    /// Goes through [`go_synthesizer::GoMod::print`] — again, no
394    /// `format!()` of go.mod syntax.
395    #[must_use]
396    pub fn render_go_mod(
397        module: &str,
398        go_version: &str,
399        requires: &[(String, String)],
400    ) -> String {
401        let mut m = GoMod::new(module, go_version);
402        m.require = requires
403            .iter()
404            .map(|(path, version)| GoRequire::new(path.clone(), version.clone()))
405            .collect();
406        m.print()
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413
414    /// A worked spec mirroring a real Crossplane-style managed-resource
415    /// fragment: a tagged `Parameters` struct + a constructor func.
416    fn worked_spec() -> GoSpec {
417        GoSpec {
418            package: "v1alpha1".to_string(),
419            doc: Some("Code authored as a typed GoSpec.".to_string()),
420            imports: vec![GoImportSpec {
421                path: "k8s.io/apimachinery/pkg/apis/meta/v1".to_string(),
422                alias: Some("metav1".to_string()),
423            }],
424            items: vec![
425                GoItemSpec::Struct(GoStructSpec {
426                    name: "StaticSecretParameters".to_string(),
427                    doc: Some("StaticSecretParameters are the input attributes.".to_string()),
428                    fields: vec![
429                        GoFieldSpec {
430                            name: "Name".to_string(),
431                            ty: GoTypeSpec::named("string"),
432                            doc: Some("Name of the secret.".to_string()),
433                            tags: vec![GoTagSpec::Json {
434                                name: "name".to_string(),
435                                omitempty: false,
436                            }],
437                            markers: vec![GoMarkerSpec::Required],
438                        },
439                        GoFieldSpec {
440                            name: "Value".to_string(),
441                            ty: GoTypeSpec::Pointer {
442                                inner: Box::new(GoTypeSpec::named("string")),
443                            },
444                            doc: None,
445                            tags: vec![GoTagSpec::Json {
446                                name: "value".to_string(),
447                                omitempty: true,
448                            }],
449                            markers: vec![GoMarkerSpec::Optional],
450                        },
451                        GoFieldSpec {
452                            name: "Labels".to_string(),
453                            ty: GoTypeSpec::Map {
454                                key: Box::new(GoTypeSpec::named("string")),
455                                value: Box::new(GoTypeSpec::named("string")),
456                            },
457                            doc: None,
458                            tags: vec![GoTagSpec::Json {
459                                name: "labels".to_string(),
460                                omitempty: true,
461                            }],
462                            markers: vec![],
463                        },
464                    ],
465                }),
466                GoItemSpec::Func(GoFuncSpec {
467                    name: "NewStaticSecretParameters".to_string(),
468                    doc: Some("NewStaticSecretParameters returns a zero value.".to_string()),
469                    recv: None,
470                    params: vec![],
471                    returns: vec![GoTypeSpec::Pointer {
472                        inner: Box::new(GoTypeSpec::named("StaticSecretParameters")),
473                    }],
474                    body: GoFuncBodySpec::ReturnNewOf {
475                        ty: GoTypeSpec::named("StaticSecretParameters"),
476                    },
477                }),
478                GoItemSpec::Func(GoFuncSpec {
479                    name: "Validate".to_string(),
480                    doc: None,
481                    recv: Some(GoParamSpec {
482                        name: "p".to_string(),
483                        ty: GoTypeSpec::Pointer {
484                            inner: Box::new(GoTypeSpec::named("StaticSecretParameters")),
485                        },
486                    }),
487                    params: vec![],
488                    returns: vec![GoTypeSpec::named("error")],
489                    body: GoFuncBodySpec::ReturnNil,
490                }),
491            ],
492        }
493    }
494
495    /// THE round-trip test: a typed `GoSpec` → Go source via
496    /// `go_synthesizer::print_file`, asserting the typed constructs all
497    /// landed. This is the Go analog of tatara-rust-emit's
498    /// `emit_file_for_impl` test.
499    #[test]
500    fn spec_renders_buildable_go_through_synthesizer() {
501        let spec = worked_spec();
502        let go = spec.render();
503
504        // File-level scaffolding from go_synthesizer's printer.
505        assert!(go.starts_with("// Code generated by iac-forge. DO NOT EDIT.\n"));
506        assert!(go.contains("\npackage v1alpha1\n"));
507        assert!(go.contains("// Code authored as a typed GoSpec."));
508
509        // Import grouping (aliased third-party).
510        assert!(go.contains("metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\""));
511
512        // Struct family: name, doc, fields with typed tags + markers.
513        assert!(go.contains("type StaticSecretParameters struct {"));
514        assert!(go.contains("// StaticSecretParameters are the input attributes."));
515        assert!(go.contains("// +kubebuilder:validation:Required"));
516        assert!(go.contains("// +optional"));
517        assert!(go.contains("Name string `json:\"name\"`"));
518        assert!(go.contains("Value *string `json:\"value,omitempty\"`"));
519        assert!(go.contains("Labels map[string]string `json:\"labels,omitempty\"`"));
520
521        // Func family: free constructor + method with receiver.
522        assert!(go.contains("func NewStaticSecretParameters() *StaticSecretParameters {"));
523        assert!(go.contains("return &StaticSecretParameters{}"));
524        assert!(go.contains("func (p *StaticSecretParameters) Validate() error {"));
525        assert!(go.contains("\treturn nil"));
526    }
527
528    /// Determinism: two structurally identical specs render byte-equal
529    /// (the `go_synthesizer` byte-equal contract surfaced through the
530    /// spec layer).
531    #[test]
532    fn render_is_deterministic_and_byte_equal() {
533        assert_eq!(worked_spec().render(), worked_spec().render());
534    }
535
536    /// The spec is pure serde — it can round-trip through JSON, which is
537    /// what makes a future `(defgostruct …)` tatara-lisp authoring
538    /// surface a drop-in (deserialize Lisp form → `GoSpec`).
539    #[test]
540    fn spec_serde_roundtrips_through_json() {
541        let spec = worked_spec();
542        let json = serde_json::to_string(&spec).unwrap();
543        let back: GoSpec = serde_json::from_str(&json).unwrap();
544        assert_eq!(spec, back);
545        // And the deserialized spec renders identically.
546        assert_eq!(spec.render(), back.render());
547    }
548
549    /// The companion go.mod renders through `GoMod::print` (no
550    /// `format!()` of go.mod syntax), so a generated file is compilable
551    /// in isolation.
552    #[test]
553    fn companion_go_mod_renders_through_synthesizer() {
554        let go_mod = GoSpec::render_go_mod(
555            "github.com/pleme-io/example",
556            "1.22",
557            &[(
558                "k8s.io/apimachinery".to_string(),
559                "v0.29.0".to_string(),
560            )],
561        );
562        assert!(go_mod.contains("module github.com/pleme-io/example"));
563        assert!(go_mod.contains("go 1.22"));
564        assert!(go_mod.contains("k8s.io/apimachinery v0.29.0"));
565    }
566
567    /// No `format!()` of Go syntax leaks into the rendered output: the
568    /// only path from spec to source is `to_go_file` + `print_file`.
569    /// This mirrors crossplane-forge's existing
570    /// `no_format_string_leakage_in_any_emitter` discipline.
571    #[test]
572    fn empty_spec_still_well_formed() {
573        let spec = GoSpec::new("p");
574        let go = spec.render();
575        assert!(go.starts_with("// Code generated by iac-forge. DO NOT EDIT.\n"));
576        assert!(go.contains("\npackage p\n"));
577        assert!(go.ends_with('\n'));
578    }
579}