Skip to main content

hyprstream_rpc_build/
lib.rs

1//! Shared Cap'n Proto build helpers for annotation extraction and TypeScript codegen.
2//!
3//! This crate provides:
4//! - Schema types (`ParsedSchema`, `StructDef`, `FieldDef`, etc.) shared between
5//!   the proc-macro derive crate and the TypeScript codegen binary
6//! - CGR (CodeGeneratorRequest) parsing with full wire format info
7//! - Metadata JSON extraction for proc-macro annotation merging
8//! - TypeScript codegen from parsed schemas (via the `hyprstream-ts-codegen` binary)
9
10#![allow(clippy::print_stdout)] // cargo:warning= directives require println!
11
12pub mod backend;
13pub mod schema;
14pub mod util;
15
16use std::path::Path;
17
18/// Compile Cap'n Proto schemas with CGR + metadata extraction.
19///
20/// For each schema name, compiles `{schema_dir}/{name}.capnp` via capnpc,
21/// saves the raw CGR to `{out_dir}/{name}.cgr`, and extracts annotation
22/// metadata to `{out_dir}/{name}_metadata.json`.
23///
24/// `import_paths` are passed to capnpc for resolving `using import` directives.
25pub fn compile_schemas(schema_dir: &Path, out_dir: &Path, import_paths: &[&Path], names: &[&str]) {
26    for name in names {
27        let path = schema_dir.join(format!("{name}.capnp"));
28        if !path.exists() {
29            continue;
30        }
31
32        let cgr_path = out_dir.join(format!("{name}.cgr"));
33        let metadata_path = out_dir.join(format!("{name}_metadata.json"));
34
35        let mut cmd = capnpc::CompilerCommand::new();
36        cmd.src_prefix(schema_dir);
37        for ip in import_paths {
38            cmd.import_path(ip);
39        }
40        cmd.file(&path)
41            .raw_code_generator_request_path(&cgr_path)
42            .run()
43            .unwrap_or_else(|e| panic!("Failed to compile {name}.capnp: {e}"));
44
45        if let Err(e) = parse_schema_and_extract_annotations(&cgr_path, &metadata_path, name) {
46            // A maxLen(0) violation is a schema-contract failure (annotations.capnp:
47            // "the build fails if a schema sets maxLen(0)") — a warning would let the
48            // unbounded reader generate silently. Generic parse errors stay warnings.
49            if e.to_string()
50                .contains(crate::schema::MAXLEN_ZERO_CONTRACT_ERROR)
51            {
52                panic!("schema contract violation in {name}.capnp: {e}");
53            }
54            println!("cargo:warning=Failed to parse schema for {name}: {e}");
55        }
56    }
57}
58
59/// Parse a CodeGeneratorRequest CGR file and extract schema metadata with annotations.
60///
61/// Writes a JSON file at `output_path` containing structs, enums, and annotations
62/// extracted from the compiled Cap'n Proto schema.
63pub fn parse_schema_and_extract_annotations(
64    cgr_path: &Path,
65    output_path: &Path,
66    name: &str,
67) -> Result<(), Box<dyn std::error::Error>> {
68    use capnp::message::ReaderOptions;
69    use capnp::schema_capnp::{field, node};
70    use capnp::serialize;
71
72    // Read the CodeGeneratorRequest binary
73    let file = std::fs::File::open(cgr_path)?;
74    let reader = serialize::read_message(file, ReaderOptions::new())?;
75
76    // Parse as CodeGeneratorRequest (defined in schema.capnp)
77    let cgr = reader.get_root::<capnp::schema_capnp::code_generator_request::Reader>()?;
78
79    // Extract all nodes (structs, enums, etc.)
80    let nodes = cgr.get_nodes()?;
81
82    // Build annotation name map: annotation node ID -> short name
83    let mut annotation_names: std::collections::HashMap<u64, String> =
84        std::collections::HashMap::new();
85    for i in 0..nodes.len() {
86        let node = nodes.get(i);
87        if let Ok(capnp::schema_capnp::node::Annotation(_)) = node.which() {
88            let dn = node.get_display_name()?.to_str()?.to_owned();
89            let short = dn.rsplit(':').next().unwrap_or(&dn).to_owned();
90            annotation_names.insert(node.get_id(), short);
91        }
92    }
93
94    let mut structs = Vec::new();
95    let mut enums = Vec::new();
96    let mut annotations_map = serde_json::Map::new();
97
98    // Iterate through nodes and extract structure + annotations
99    for i in 0..nodes.len() {
100        let node = nodes.get(i);
101        let node_id = node.get_id();
102        let display_name = node.get_display_name()?.to_str()?.to_owned();
103
104        // Extract node-level annotations
105        let node_annotations = extract_annotations(node.get_annotations()?, &annotation_names)?;
106        if !node_annotations.is_empty() {
107            annotations_map.insert(display_name.clone(), serde_json::json!(node_annotations));
108        }
109
110        // Process based on node type
111        match node.which()? {
112            node::Struct(struct_reader) => {
113                let mut fields = Vec::new();
114                let struct_fields = struct_reader.get_fields()?;
115
116                for j in 0..struct_fields.len() {
117                    let field = struct_fields.get(j);
118                    let field_name = field.get_name()?.to_str()?.to_owned();
119                    let discriminant = field.get_discriminant_value();
120
121                    // Extract field-level annotations
122                    let field_annotations =
123                        extract_annotations(field.get_annotations()?, &annotation_names)?;
124
125                    // Get field type name
126                    let type_name = match field.which()? {
127                        field::Slot(slot) => extract_type_name(slot.get_type()?),
128                        field::Group(_) => "Group".to_owned(),
129                    };
130
131                    fields.push(serde_json::json!({
132                        "name": field_name,
133                        "type": type_name,
134                        "discriminant": discriminant,
135                        "annotations": field_annotations,
136                    }));
137                }
138
139                structs.push(serde_json::json!({
140                    "name": display_name,
141                    "id": node_id,
142                    "fields": fields,
143                }));
144            }
145            node::Enum(enum_reader) => {
146                let mut variants = Vec::new();
147                let enumerants = enum_reader.get_enumerants()?;
148
149                for j in 0..enumerants.len() {
150                    let enumerant = enumerants.get(j);
151                    let variant_name = enumerant.get_name()?.to_str()?.to_owned();
152                    let code_order = enumerant.get_code_order();
153
154                    variants.push(serde_json::json!({
155                        "name": variant_name,
156                        "value": code_order,
157                    }));
158                }
159
160                enums.push(serde_json::json!({
161                    "name": display_name,
162                    "id": node_id,
163                    "variants": variants,
164                }));
165            }
166            _ => {
167                // Ignore interfaces, consts, etc. for now
168            }
169        }
170    }
171
172    let metadata = serde_json::json!({
173        "service": name,
174        "structs": structs,
175        "enums": enums,
176        "annotations": annotations_map,
177    });
178
179    // Write metadata JSON
180    std::fs::write(output_path, serde_json::to_string_pretty(&metadata)?)?;
181
182    Ok(())
183}
184
185/// Extract annotations from a list and return as JSON array.
186///
187/// Each annotation includes its `id`, resolved `name`, and `value`.
188/// Supports Text, Void, Bool, and Enum annotation values.
189fn extract_annotations(
190    annotations: capnp::struct_list::Reader<capnp::schema_capnp::annotation::Owned>,
191    annotation_names: &std::collections::HashMap<u64, String>,
192) -> Result<Vec<serde_json::Value>, Box<dyn std::error::Error>> {
193    let mut result = Vec::new();
194
195    for i in 0..annotations.len() {
196        let ann = annotations.get(i);
197        let ann_id = ann.get_id();
198        let name = annotation_names.get(&ann_id).cloned().unwrap_or_default();
199
200        if let Ok(value) = ann.get_value() {
201            let val = extract_value_json(value);
202            match val {
203                Some(v) => result.push(serde_json::json!({
204                    "id": ann_id,
205                    "name": name,
206                    "value": v,
207                })),
208                None => {
209                    // Void annotations (e.g., $cliHidden) -- presence is the value
210                    result.push(serde_json::json!({
211                        "id": ann_id,
212                        "name": name,
213                        "value": true,
214                    }));
215                }
216            }
217        }
218    }
219
220    Ok(result)
221}
222
223/// Extract a JSON-compatible value from a Cap'n Proto Value.
224///
225/// Returns Some for Text, Bool, Enum(ordinal), None for Void/unsupported.
226fn extract_value_json(value: capnp::schema_capnp::value::Reader) -> Option<serde_json::Value> {
227    use capnp::schema_capnp::value;
228
229    match value.which().ok()? {
230        value::Text(text_reader) => Some(serde_json::Value::String(
231            text_reader.ok()?.to_str().ok()?.to_owned(),
232        )),
233        value::Bool(b) => Some(serde_json::Value::Bool(b)),
234        value::Uint32(n) => Some(serde_json::Value::Number(n.into())),
235        value::Enum(ordinal) => Some(serde_json::json!({"enum_ordinal": ordinal})),
236        _ => None,
237    }
238}
239
240/// Extract a human-readable type name from a Type.
241fn extract_type_name(type_reader: capnp::schema_capnp::type_::Reader) -> String {
242    use capnp::schema_capnp::type_;
243
244    match type_reader.which() {
245        Ok(type_::Void(())) => "Void".to_owned(),
246        Ok(type_::Bool(())) => "Bool".to_owned(),
247        Ok(type_::Int8(())) => "Int8".to_owned(),
248        Ok(type_::Int16(())) => "Int16".to_owned(),
249        Ok(type_::Int32(())) => "Int32".to_owned(),
250        Ok(type_::Int64(())) => "Int64".to_owned(),
251        Ok(type_::Uint8(())) => "UInt8".to_owned(),
252        Ok(type_::Uint16(())) => "UInt16".to_owned(),
253        Ok(type_::Uint32(())) => "UInt32".to_owned(),
254        Ok(type_::Uint64(())) => "UInt64".to_owned(),
255        Ok(type_::Float32(())) => "Float32".to_owned(),
256        Ok(type_::Float64(())) => "Float64".to_owned(),
257        Ok(type_::Text(())) => "Text".to_owned(),
258        Ok(type_::Data(())) => "Data".to_owned(),
259        Ok(type_::List(list_type)) => {
260            if let Ok(element_type) = list_type.get_element_type() {
261                format!("List({})", extract_type_name(element_type))
262            } else {
263                "List".to_owned()
264            }
265        }
266        Ok(type_::Enum(_)) => "Enum".to_owned(),
267        Ok(type_::Struct(_)) => "Struct".to_owned(),
268        Ok(type_::Interface(_)) => "Interface".to_owned(),
269        Ok(type_::AnyPointer(_)) => "AnyPointer".to_owned(),
270        Err(_) => "Unknown".to_owned(),
271    }
272}