hyprstream_rpc_build/backend.rs
1//! Language-agnostic code generation backend trait.
2//!
3//! Defines the `CodegenBackend` trait that each code generator backend must implement.
4//! The TypeScript backend wraps the existing `ts_codegen` emitters; additional backends
5//! (e.g., Python, Rust client stubs) can implement the trait independently.
6
7use crate::schema::types::{FieldDef, ParsedSchema};
8
9/// Backend trait for multi-language code generation from Cap'n Proto schemas.
10///
11/// Implementations map Cap'n Proto types and wire format to a target language's
12/// type system, serialization API, and file layout. The language-agnostic
13/// `generate_all` driver calls these methods to produce output files.
14pub trait CodegenBackend {
15 /// Map a Cap'n Proto type name to the target language's type.
16 ///
17 /// E.g., `"Text"` → `"string"` for TypeScript, `"str"` for Python.
18 fn map_type(&self, capnp_type: &str) -> String;
19
20 /// Return the setter method name on a builder for this type, if the runtime
21 /// supports a direct method call. Returns `None` for types handled specially
22 /// (struct pointers, enum ordinals, etc.).
23 fn setter_method(&self, type_name: &str) -> Option<String>;
24
25 /// Return an expression that reads a field's value from a reader variable.
26 fn getter_expr(&self, reader_var: &str, field: &FieldDef) -> String;
27
28 /// Return the default value expression for a type (used for optional field coalescing).
29 fn default_value(&self, type_name: &str) -> String;
30
31 /// Generate the complete source file content for a service schema.
32 fn generate_service_file(&self, service_name: &str, schema: &ParsedSchema) -> String;
33
34 /// Return `(filename, content)` for the shared runtime file included in all output.
35 ///
36 /// E.g., TypeScript returns `("capnp.ts", <wire-format runtime>)`.
37 fn runtime_file(&self) -> (String, String);
38
39 /// Return the file extension for generated service files (e.g., `"ts"`, `"py"`).
40 fn file_extension(&self) -> &str;
41
42 /// Return `(filename, content)` for an optional index/manifest file.
43 ///
44 /// Returns `None` if this backend does not generate an index file.
45 /// TypeScript overrides this to produce `index.ts` with re-exports.
46 ///
47 /// `module_contents` pairs each schema's module name with the full source
48 /// text already written for it, so the barrel generator can detect
49 /// cross-module export name collisions from the single source of truth
50 /// (the actual emitted symbols) instead of re-deriving naming rules
51 /// independently and risking drift.
52 fn index_file(
53 &self,
54 _all_names: &[String],
55 _client_names: &[String],
56 _module_contents: &[(String, String)],
57 ) -> Option<(String, String)> {
58 None
59 }
60}