aura-lang 0.3.0

Aura configuration language: deterministic, capability-secured, schema-validated configs — embeddable library + the `aura` CLI
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
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
//! `aura types`: generate host-language types from a manifest's `type` and
//! `enum` declarations (SPEC §7.2).
//!
//! One schema, two jobs: it validates the config *and* types the service that
//! consumes the resulting JSON. Emission works on the AST (not on values), so a
//! manifest never has to be evaluated — no I/O, no capabilities involved.
//!
//! Optional fields (D15) are emitted as **required**: evaluation always inserts
//! the default, so the JSON a consumer receives always carries the field.
//!
//! Nullable fields (D27) are the opposite case and are emitted as optional —
//! `Option<T>`, `T | null`, `*T`. The field is always present in the JSON, but
//! its value may be `null`, and a host type that cannot hold one would fail to
//! deserialise a value the schema explicitly permits.

use crate::error::Diagnostic;
use crate::lexer::Lexer;
use crate::parser::ast::{EnumDeclaration, SchemaDeclaration, Stmt, TypeName};
use crate::parser::Parser;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lang {
    Rust,
    TypeScript,
    Go,
}

impl Lang {
    pub fn parse(s: &str) -> Option<Lang> {
        match s {
            "rust" | "rs" => Some(Lang::Rust),
            "ts" | "typescript" => Some(Lang::TypeScript),
            "go" | "golang" => Some(Lang::Go),
            _ => None,
        }
    }
}

/// Declarations worth emitting, in source order.
enum Decl<'a> {
    Schema(&'a SchemaDeclaration<'a>),
    Enum(&'a EnumDeclaration<'a>),
}

/// Generate types for every `type` and `enum` declared in `src`.
pub fn generate(src: &str, lang: Lang) -> Result<String, Diagnostic> {
    let tokens = Lexer::new(src, 0).tokenize()?;
    let module = Parser::new(tokens)
        .parse_module()
        .map_err(|mut ds| ds.remove(0))?;

    let decls: Vec<Decl> = module
        .stmts
        .iter()
        .filter_map(|s| match s {
            Stmt::TypeDecl(t) => Some(Decl::Schema(t)),
            Stmt::EnumDecl(e) => Some(Decl::Enum(e)),
            _ => None,
        })
        .collect();

    // An enum-typed field maps to the enum's own generated type name, which is
    // just `TypeName::Custom(name)` — no extra bookkeeping needed.
    Ok(match lang {
        Lang::Rust => rust(&decls),
        Lang::TypeScript => typescript(&decls),
        Lang::Go => go(&decls),
    })
}

// ---- name helpers ----

/// A member string turned into a type-identifier fragment: `"eu-central"` ->
/// `EuCentral`. Non-alphanumerics separate words; a leading digit is prefixed so
/// the result is always a valid identifier.
fn pascal(s: &str) -> String {
    let mut out = String::new();
    let mut upper = true;
    for c in s.chars() {
        if c.is_alphanumeric() {
            if upper {
                out.extend(c.to_uppercase());
            } else {
                out.push(c);
            }
            upper = false;
        } else {
            upper = true;
        }
    }
    if out.is_empty() {
        out.push_str("Empty");
    } else if out.starts_with(|c: char| c.is_ascii_digit()) {
        out.insert(0, 'N');
    }
    out
}

/// Go field names must be exported (capitalised): `min_version` -> `MinVersion`.
/// The wire name is preserved by the `json:` tag.
fn exported(s: &str) -> String {
    pascal(s)
}

const HEADER: &str = "Generated by `aura types` — do not edit by hand.";

// ---- Rust ----

fn rust_ty(ty: &TypeName) -> String {
    match ty {
        TypeName::String => "String".into(),
        TypeName::Int => "i64".into(),
        TypeName::Float => "f64".into(),
        TypeName::Bool => "bool".into(),
        // D26: an element type turns the commonest configuration shape from
        // an untyped bag into the schema the host actually wants.
        TypeName::List(None) => "Vec<serde_json::Value>".into(),
        TypeName::List(Some(el)) => format!("Vec<{}>", rust_ty(el)),
        TypeName::Object => "serde_json::Map<String, serde_json::Value>".into(),
        TypeName::Custom(name) => (*name).to_string(),
    }
}

fn rust(decls: &[Decl]) -> String {
    let mut out = format!("// {HEADER}\n\nuse serde::{{Deserialize, Serialize}};\n");
    for d in decls {
        match d {
            Decl::Enum(e) => {
                out.push_str(&format!(
                    "\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\npub enum {} {{\n",
                    e.name
                ));
                for m in &e.members {
                    out.push_str(&format!(
                        "    #[serde(rename = \"{m}\")]\n    {},\n",
                        pascal(m)
                    ));
                }
                out.push_str("}\n");
            }
            Decl::Schema(s) => {
                out.push_str(&format!(
                    "\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct {} {{\n",
                    s.name
                ));
                for f in &s.fields {
                    // D27: a nullable field really can arrive as JSON null, so
                    // the host type has to admit it or deserialisation fails on
                    // a value the schema explicitly permits.
                    let ty = rust_ty(&f.ty);
                    let ty = if f.nullable {
                        format!("Option<{ty}>")
                    } else {
                        ty
                    };
                    out.push_str(&format!("    pub {}: {},\n", f.name, ty));
                }
                out.push_str("}\n");
            }
        }
    }
    out
}

// ---- TypeScript ----

fn ts_ty(ty: &TypeName) -> String {
    match ty {
        TypeName::String => "string".into(),
        TypeName::Int | TypeName::Float => "number".into(),
        TypeName::Bool => "boolean".into(),
        TypeName::List(None) => "unknown[]".into(),
        TypeName::List(Some(el)) => format!("{}[]", ts_ty(el)),
        TypeName::Object => "Record<string, unknown>".into(),
        TypeName::Custom(name) => (*name).to_string(),
    }
}

fn typescript(decls: &[Decl]) -> String {
    let mut out = format!("// {HEADER}\n");
    for d in decls {
        match d {
            // A string-literal union is the exact TypeScript equivalent of D18.
            Decl::Enum(e) => {
                let union = e
                    .members
                    .iter()
                    .map(|m| format!("\"{m}\""))
                    .collect::<Vec<_>>()
                    .join(" | ");
                out.push_str(&format!("\nexport type {} = {union};\n", e.name));
            }
            Decl::Schema(s) => {
                out.push_str(&format!("\nexport interface {} {{\n", s.name));
                for f in &s.fields {
                    let ty = ts_ty(&f.ty);
                    let ty = if f.nullable {
                        format!("{ty} | null")
                    } else {
                        ty
                    };
                    out.push_str(&format!("  {}: {};\n", f.name, ty));
                }
                out.push_str("}\n");
            }
        }
    }
    out
}

// ---- Go ----

fn go_ty(ty: &TypeName) -> String {
    match ty {
        TypeName::String => "string".into(),
        TypeName::Int => "int64".into(),
        TypeName::Float => "float64".into(),
        TypeName::Bool => "bool".into(),
        TypeName::List(None) => "[]any".into(),
        TypeName::List(Some(el)) => format!("[]{}", go_ty(el)),
        TypeName::Object => "map[string]any".into(),
        TypeName::Custom(name) => (*name).to_string(),
    }
}

/// Column-align a run of lines the way `gofmt`'s tabwriter does: every column
/// but the last is padded to the widest cell, separated by a single space. Emitting
/// gofmt-canonical output means `gofmt -l` on a generated file stays silent, so
/// checking in generated types never produces formatting churn.
fn align_go(rows: &[Vec<String>]) -> String {
    let cols = rows.iter().map(Vec::len).max().unwrap_or(0);
    let widths: Vec<usize> = (0..cols)
        .map(|i| {
            rows.iter()
                .filter(|r| i + 1 < r.len()) // only cells that are followed by another
                .map(|r| r[i].chars().count())
                .max()
                .unwrap_or(0)
        })
        .collect();
    let mut out = String::new();
    for row in rows {
        out.push('\t');
        for (i, cell) in row.iter().enumerate() {
            out.push_str(cell);
            if i + 1 < row.len() {
                let pad = widths[i].saturating_sub(cell.chars().count());
                out.push_str(&" ".repeat(pad + 1));
            }
        }
        out.push('\n');
    }
    out
}

fn go(decls: &[Decl]) -> String {
    let mut out = format!("// {HEADER}\n\npackage config\n");
    for d in decls {
        match d {
            // Idiomatic Go: a named string type plus typed constants.
            Decl::Enum(e) => {
                out.push_str(&format!("\ntype {} string\n\nconst (\n", e.name));
                let rows: Vec<Vec<String>> = e
                    .members
                    .iter()
                    .map(|m| {
                        vec![
                            format!("{}{}", e.name, pascal(m)),
                            e.name.to_string(),
                            format!("= \"{m}\""),
                        ]
                    })
                    .collect();
                out.push_str(&align_go(&rows));
                out.push_str(")\n");
            }
            Decl::Schema(s) => {
                out.push_str(&format!("\ntype {} struct {{\n", s.name));
                let rows: Vec<Vec<String>> = s
                    .fields
                    .iter()
                    .map(|f| {
                        vec![
                            exported(f.name),
                            // A pointer is Go's only way to tell an absent value
                            // from a zero one, which is the whole distinction.
                            if f.nullable {
                                format!("*{}", go_ty(&f.ty))
                            } else {
                                go_ty(&f.ty)
                            },
                            format!("`json:\"{}\"`", f.name),
                        ]
                    })
                    .collect();
                out.push_str(&align_go(&rows));
                out.push_str("}\n");
            }
        }
    }
    out
}

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

    const SRC: &str = concat!(
        "enum Tier\n  \"frontend\"\n  \"backend\"\nend\n",
        "type Endpoint\n  host: String\n  port: Int = 443\nend\n",
        "type Service\n",
        "  name:     String\n",
        "  tier:     Tier\n",
        "  endpoint: Endpoint\n",
        "  ratio:    Float\n",
        "  enabled:  Bool\n",
        "  tags:     List\n",
        "  labels:   Object\n",
        "end\n",
    );

    /// D26: the shape that used to reach the host untyped.
    const TYPED: &str = concat!(
        "enum Tier
  \"frontend\"
  \"backend\"
end
",
        "type Endpoint
  host: String
end
",
        "type Service
",
        "  endpoints: [Endpoint]
",
        "  tags:      [String]
",
        "  grid:      [[Int]]
",
        "  tiers:     [Tier]
",
        "end
",
    );

    #[test]
    fn a_nullable_field_reaches_the_host_as_an_optional() {
        // D27: the host must admit null or deserialisation fails on a value the
        // schema explicitly allows. Go needs a pointer, its only way to tell an
        // absent value from a zero one.
        let src = "type Plan\n  id: String\n  quota: Int?\n  channels: Int\nend\n";
        let rs = generate(src, Lang::Rust).unwrap();
        assert!(rs.contains("pub quota: Option<i64>,"), "{rs}");
        assert!(
            rs.contains("pub channels: i64,"),
            "a plain field is untouched"
        );

        let ts = generate(src, Lang::TypeScript).unwrap();
        assert!(ts.contains("quota: number | null;"), "{ts}");

        let go = generate(src, Lang::Go).unwrap();
        assert!(go.contains("*int64"), "{go}");
    }

    #[test]
    fn an_element_type_reaches_the_host() {
        // Before D26 every one of these was Vec<serde_json::Value> / unknown[] /
        // []any — the commonest configuration shape, arriving untyped.
        let rs = generate(TYPED, Lang::Rust).unwrap();
        assert!(rs.contains("pub endpoints: Vec<Endpoint>,"), "{rs}");
        assert!(rs.contains("pub tags: Vec<String>,"), "{rs}");
        assert!(rs.contains("pub grid: Vec<Vec<i64>>,"), "{rs}");
        assert!(rs.contains("pub tiers: Vec<Tier>,"), "{rs}");

        let ts = generate(TYPED, Lang::TypeScript).unwrap();
        assert!(ts.contains("  endpoints: Endpoint[];"), "{ts}");
        assert!(ts.contains("  grid: number[][];"), "{ts}");

        let go = generate(TYPED, Lang::Go).unwrap();
        assert!(go.contains("[]Endpoint"), "{go}");
        assert!(go.contains("[][]int64"), "{go}");
    }

    #[test]
    fn rust_output() {
        let out = generate(SRC, Lang::Rust).unwrap();
        assert!(out.contains("pub enum Tier {"));
        assert!(out.contains("#[serde(rename = \"frontend\")]"));
        assert!(out.contains("    Frontend,"));
        assert!(out.contains("pub struct Service {"));
        assert!(out.contains("pub tier: Tier,"));
        assert!(out.contains("pub endpoint: Endpoint,"));
        assert!(out.contains("pub port: i64,")); // optional field is still required
        assert!(out.contains("pub tags: Vec<serde_json::Value>,"));
        assert!(out.contains("pub labels: serde_json::Map<String, serde_json::Value>,"));
    }

    #[test]
    fn typescript_output_uses_a_literal_union() {
        let out = generate(SRC, Lang::TypeScript).unwrap();
        assert!(out.contains("export type Tier = \"frontend\" | \"backend\";"));
        assert!(out.contains("export interface Service {"));
        assert!(out.contains("  tier: Tier;"));
        assert!(out.contains("  ratio: number;"));
        assert!(out.contains("  labels: Record<string, unknown>;"));
    }

    #[test]
    fn go_output_uses_typed_constants_and_json_tags() {
        let out = generate(SRC, Lang::Go).unwrap();
        assert!(out.contains("type Tier string"));
        assert!(out.contains("\tTierFrontend Tier = \"frontend\""));
        assert!(out.contains("type Service struct {"));
        // Columns are gofmt-aligned: `gofmt -l` on the output must stay silent.
        assert!(
            out.contains("\tTier     Tier           `json:\"tier\"`\n"),
            "{out}"
        );
        assert!(
            out.contains("\tLabels   map[string]any `json:\"labels\"`\n"),
            "{out}"
        );
        // Enum constants align on the type column too.
        assert!(out.contains("\tTierBackend  Tier = \"backend\"\n"), "{out}");
    }

    #[test]
    fn member_names_are_sanitised() {
        // Non-identifier members still produce valid type identifiers.
        let src = "enum Region\n  \"eu-central\"\n  \"us.east\"\n  \"2fa\"\nend\n";
        let out = generate(src, Lang::Rust).unwrap();
        assert!(out.contains("    EuCentral,"), "{out}");
        assert!(out.contains("    UsEast,"), "{out}");
        assert!(out.contains("    N2fa,"), "{out}"); // a leading digit is prefixed
                                                     // and the wire value is preserved verbatim
        assert!(out.contains("#[serde(rename = \"eu-central\")]"));
    }

    #[test]
    fn a_manifest_without_declarations_emits_only_a_header() {
        let out = generate("x: 1\n", Lang::TypeScript).unwrap();
        assert!(out.starts_with("// Generated by"));
        assert!(!out.contains("interface"));
    }

    #[test]
    fn a_broken_manifest_is_an_error_not_a_panic() {
        assert!(generate("type\n", Lang::Rust).is_err());
    }
}