vox-codegen 0.8.1

Language bindings codegen for vox
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
//! Swift type generation and collection.
//!
//! This module handles:
//! - Collecting named types (structs and enums) from service definitions
//! - Generating Swift type definitions (structs, enums)
//! - Converting Rust types to Swift type strings

use std::collections::HashSet;

use facet_core::{ScalarType, Shape};
use heck::ToLowerCamelCase;
use vox_types::{
    EnumInfo, ServiceDescriptor, ShapeKind, StructInfo, VariantKind, classify_shape,
    classify_variant, is_bytes, is_rx, is_tx,
};

/// Collect all named types (structs and enums with a name) from a service.
/// Returns a vector of (name, Shape) pairs in dependency order.
pub fn collect_named_types(service: &ServiceDescriptor) -> Vec<(String, &'static Shape)> {
    let mut seen: HashSet<String> = HashSet::new();
    let mut types = Vec::new();

    fn visit(
        shape: &'static Shape,
        seen: &mut HashSet<String>,
        types: &mut Vec<(String, &'static Shape)>,
    ) {
        match classify_shape(shape) {
            ShapeKind::Struct(StructInfo {
                name: Some(name),
                fields,
                ..
            }) if seen.insert(name.to_string()) => {
                // Visit nested types first (dependencies before dependents)
                for field in fields {
                    visit(field.shape(), seen, types);
                }
                types.push((name.to_string(), shape));
            }
            ShapeKind::Enum(EnumInfo {
                name: Some(name),
                variants,
            }) if seen.insert(name.to_string()) => {
                // Visit nested types in variants
                for variant in variants {
                    match classify_variant(variant) {
                        VariantKind::Newtype { inner } => visit(inner, seen, types),
                        VariantKind::Struct { fields } | VariantKind::Tuple { fields } => {
                            for field in fields {
                                visit(field.shape(), seen, types);
                            }
                        }
                        VariantKind::Unit => {}
                    }
                }
                types.push((name.to_string(), shape));
            }
            ShapeKind::List { element }
            | ShapeKind::Slice { element }
            | ShapeKind::Option { inner: element }
            | ShapeKind::Array { element, .. }
            | ShapeKind::Set { element } => visit(element, seen, types),
            ShapeKind::Map { key, value } => {
                visit(key, seen, types);
                visit(value, seen, types);
            }
            ShapeKind::Tuple { elements } => {
                for param in elements {
                    visit(param.shape, seen, types);
                }
            }
            ShapeKind::Tx { inner } | ShapeKind::Rx { inner } => visit(inner, seen, types),
            ShapeKind::Pointer { pointee } => visit(pointee, seen, types),
            ShapeKind::Result { ok, err } => {
                visit(ok, seen, types);
                visit(err, seen, types);
            }
            _ => {}
        }
    }

    for method in service.methods {
        for arg in method.args {
            visit(arg.shape, &mut seen, &mut types);
        }
        visit(method.return_shape, &mut seen, &mut types);
    }

    types
}

/// Generate Swift type definitions for all named types.
pub fn generate_named_types(named_types: &[(String, &'static Shape)]) -> String {
    let mut out = String::new();

    for (name, shape) in named_types {
        match classify_shape(shape) {
            ShapeKind::Struct(StructInfo { fields, .. }) => {
                out.push_str(&format!("public struct {name}: Codable, Sendable {{\n"));
                for field in fields {
                    let field_name = swift_field_name(field.name);
                    let field_type = swift_type_base(field.shape());
                    out.push_str(&format!("    public var {field_name}: {field_type}\n"));
                }
                out.push('\n');
                // Generate initializer
                out.push_str("    nonisolated public init(");
                for (i, field) in fields.iter().enumerate() {
                    if i > 0 {
                        out.push_str(", ");
                    }
                    let field_name = swift_field_name(field.name);
                    let field_type = swift_type_base(field.shape());
                    out.push_str(&format!("{field_name}: {field_type}"));
                }
                out.push_str(") {\n");
                for field in fields {
                    let field_name = swift_field_name(field.name);
                    out.push_str(&format!("        self.{field_name} = {field_name}\n"));
                }
                out.push_str("    }\n");
                out.push_str("}\n\n");
            }
            ShapeKind::Enum(EnumInfo { variants, .. }) => {
                // Add Error conformance if the enum name ends with "Error"
                let protocols = if name.ends_with("Error") {
                    "Codable, Sendable, Error"
                } else {
                    "Codable, Sendable"
                };
                out.push_str(&format!("public enum {name}: {protocols} {{\n"));
                for variant in variants {
                    let variant_name = swift_field_name(variant.name);
                    match classify_variant(variant) {
                        VariantKind::Unit => {
                            out.push_str(&format!("    case {variant_name}\n"));
                        }
                        VariantKind::Newtype { inner } => {
                            let inner_type = swift_type_base(inner);
                            out.push_str(&format!("    case {variant_name}({inner_type})\n"));
                        }
                        VariantKind::Tuple { fields } => {
                            let field_types: Vec<_> =
                                fields.iter().map(|f| swift_type_base(f.shape())).collect();
                            out.push_str(&format!(
                                "    case {variant_name}({})\n",
                                field_types.join(", ")
                            ));
                        }
                        VariantKind::Struct { fields } => {
                            let field_decls: Vec<_> = fields
                                .iter()
                                .map(|f| {
                                    format!(
                                        "{}: {}",
                                        swift_field_name(f.name),
                                        swift_type_base(f.shape())
                                    )
                                })
                                .collect();
                            out.push_str(&format!(
                                "    case {variant_name}({})\n",
                                field_decls.join(", ")
                            ));
                        }
                    }
                }
                out.push_str("}\n\n");
            }
            _ => {}
        }
    }

    out
}

/// Map a Rust field or variant name to a valid Swift identifier.
///
/// Two transforms layered on top of `to_lower_camel_case`:
///   - Rust tuple-struct positional fields are exposed by facet with
///     numeric names ("0", "1", ...); prefix them with an underscore.
///   - Swift reserved keywords (e.g. `internal`, `class`) need
///     backticks when used as identifiers.
pub fn swift_field_name(name: &str) -> String {
    if name.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        return format!("_{name}");
    }
    let lower = name.to_lower_camel_case();
    if SWIFT_RESERVED.binary_search(&lower.as_str()).is_ok() {
        format!("`{lower}`")
    } else {
        lower
    }
}

/// Sorted list of Swift reserved words and contextual keywords that
/// can't be used as bare identifiers. Kept sorted so we can
/// `binary_search` it.
const SWIFT_RESERVED: &[&str] = &[
    "Any",
    "Self",
    "as",
    "associatedtype",
    "break",
    "case",
    "catch",
    "class",
    "continue",
    "default",
    "defer",
    "deinit",
    "do",
    "else",
    "enum",
    "extension",
    "fallthrough",
    "false",
    "fileprivate",
    "for",
    "func",
    "guard",
    "if",
    "import",
    "in",
    "init",
    "inout",
    "internal",
    "is",
    "let",
    "nil",
    "open",
    "operator",
    "precedencegroup",
    "private",
    "protocol",
    "public",
    "repeat",
    "rethrows",
    "return",
    "self",
    "static",
    "struct",
    "subscript",
    "super",
    "switch",
    "throw",
    "throws",
    "true",
    "try",
    "typealias",
    "var",
    "where",
    "while",
];

/// Convert ScalarType to Swift type string.
pub fn swift_scalar_type(scalar: ScalarType) -> String {
    match scalar {
        ScalarType::Bool => "Bool".into(),
        ScalarType::U8 => "UInt8".into(),
        ScalarType::U16 => "UInt16".into(),
        ScalarType::U32 => "UInt32".into(),
        ScalarType::U64 => "UInt64".into(),
        ScalarType::U128 => "UInt128".into(),
        ScalarType::USize => "UInt".into(),
        ScalarType::I8 => "Int8".into(),
        ScalarType::I16 => "Int16".into(),
        ScalarType::I32 => "Int32".into(),
        ScalarType::I64 => "Int64".into(),
        ScalarType::I128 => "Int128".into(),
        ScalarType::ISize => "Int".into(),
        ScalarType::F32 => "Float".into(),
        ScalarType::F64 => "Double".into(),
        ScalarType::Char | ScalarType::Str | ScalarType::String | ScalarType::CowStr => {
            "String".into()
        }
        ScalarType::Unit => "Void".into(),
        _ => "Data".into(),
    }
}

/// Convert Shape to Swift type string.
pub fn swift_type_base(shape: &'static Shape) -> String {
    // Check for bytes first
    if is_bytes(shape) {
        return "Data".into();
    }

    match classify_shape(shape) {
        ShapeKind::Scalar(scalar) => swift_scalar_type(scalar),
        ShapeKind::List { element } => format!("[{}]", swift_type_base(element)),
        ShapeKind::Slice { element } => format!("[{}]", swift_type_base(element)),
        ShapeKind::Option { inner } => format!("{}?", swift_type_base(inner)),
        ShapeKind::Array { element, .. } => format!("[{}]", swift_type_base(element)),
        ShapeKind::Map { key, value } => {
            format!("[{}: {}]", swift_type_base(key), swift_type_base(value))
        }
        ShapeKind::Set { element } => format!("Set<{}>", swift_type_base(element)),
        ShapeKind::Tuple { elements } => {
            if elements.is_empty() {
                "Void".into()
            } else {
                let types: Vec<_> = elements.iter().map(|p| swift_type_base(p.shape)).collect();
                format!("({})", types.join(", "))
            }
        }
        ShapeKind::Tx { inner } => format!("Tx<{}>", swift_type_base(inner)),
        ShapeKind::Rx { inner } => format!("Rx<{}>", swift_type_base(inner)),
        ShapeKind::Struct(StructInfo {
            name: Some(name), ..
        }) => name.to_string(),
        ShapeKind::Enum(EnumInfo {
            name: Some(name), ..
        }) => name.to_string(),
        ShapeKind::Struct(StructInfo {
            name: None, fields, ..
        }) => {
            // Anonymous struct - use tuple-like representation
            let types: Vec<_> = fields.iter().map(|f| swift_type_base(f.shape())).collect();
            format!("({})", types.join(", "))
        }
        ShapeKind::Enum(EnumInfo {
            name: None,
            variants,
        }) => {
            // Anonymous enum - not well supported in Swift, use Any
            let _ = variants; // suppress warning
            "Any".into()
        }
        ShapeKind::Pointer { pointee } => swift_type_base(pointee),
        ShapeKind::Result { ok, err } => {
            format!("Result<{}, {}>", swift_type_base(ok), swift_type_base(err))
        }
        ShapeKind::TupleStruct { fields } => {
            let types: Vec<_> = fields.iter().map(|f| swift_type_base(f.shape())).collect();
            format!("({})", types.join(", "))
        }
        ShapeKind::Opaque => "Data".into(),
    }
}

/// Convert Shape to Swift type string for client arguments.
pub fn swift_type_client_arg(shape: &'static Shape) -> String {
    match classify_shape(shape) {
        ShapeKind::Tx { inner } => format!("UnboundTx<{}>", swift_type_base(inner)),
        ShapeKind::Rx { inner } => format!("UnboundRx<{}>", swift_type_base(inner)),
        _ => swift_type_base(shape),
    }
}

/// Convert Shape to Swift type string for client returns.
pub fn swift_type_client_return(shape: &'static Shape) -> String {
    assert_no_channels_in_return_shape(shape);
    match classify_shape(shape) {
        ShapeKind::Scalar(ScalarType::Unit) => "Void".into(),
        ShapeKind::Tuple { elements: [] } => "Void".into(),
        _ => swift_type_base(shape),
    }
}

/// Convert Shape to Swift type string for server/handler arguments.
pub fn swift_type_server_arg(shape: &'static Shape) -> String {
    match classify_shape(shape) {
        ShapeKind::Tx { inner } => format!("Tx<{}>", swift_type_base(inner)),
        ShapeKind::Rx { inner } => format!("Rx<{}>", swift_type_base(inner)),
        _ => swift_type_base(shape),
    }
}

/// Convert Shape to Swift type string for server returns.
pub fn swift_type_server_return(shape: &'static Shape) -> String {
    assert_no_channels_in_return_shape(shape);
    match classify_shape(shape) {
        ShapeKind::Scalar(ScalarType::Unit) => "Void".into(),
        ShapeKind::Tuple { elements: [] } => "Void".into(),
        _ => swift_type_base(shape),
    }
}

/// Check if a shape represents a channel type (Tx or Rx).
pub fn is_channel(shape: &'static Shape) -> bool {
    is_tx(shape) || is_rx(shape)
}

/// Format documentation comments for Swift.
pub fn format_doc(doc: &str, indent: &str) -> String {
    doc.lines()
        .map(|line| format!("{indent}/// {line}\n"))
        .collect()
}

pub fn assert_no_channels_in_return_shape(shape: &'static Shape) {
    fn has_channel(shape: &'static Shape) -> bool {
        matches!(
            classify_shape(shape),
            ShapeKind::Tx { .. } | ShapeKind::Rx { .. }
        )
    }
    assert!(
        !has_channel(shape),
        "channels are not allowed in return types"
    );
}