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
//! Operation registry generation for OpenAPI specifications.
//!
//! Generates a static registry of operation metadata from analyzed OpenAPI operations.
//! The registry contains everything needed to:
//! - Build CLI subcommands dynamically (names, params, help text)
//! - Route and validate operations in a proxy (URL templates, param types, methods)
//!
//! The generated code is pure data — no HTTP client, no clap derives, no runtime dependencies
//! beyond serde. Consumers (CLI shims, proxy routers) interpret the registry generically.
use crate::analysis::SchemaAnalysis;
use crate::generator::CodeGenerator;
use proc_macro2::TokenStream;
use quote::quote;
impl CodeGenerator {
/// Generate the registry.rs file content
pub fn generate_registry(&self, analysis: &SchemaAnalysis) -> crate::Result<String> {
let registry_types = Self::generate_registry_types();
let operation_defs = self.generate_operation_defs(analysis);
let tokens = quote! {
//! Auto-generated operation registry. Do not edit.
#registry_types
#operation_defs
};
let file = syn::parse2(tokens).map_err(|e| {
crate::GeneratorError::CodeGenError(format!("Failed to parse registry tokens: {}", e))
})?;
Ok(prettyplease::unparse(&file))
}
/// Generate the registry data types
fn generate_registry_types() -> TokenStream {
quote! {
/// HTTP method for an operation
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum HttpMethod {
Get,
Post,
Put,
Patch,
Delete,
}
impl HttpMethod {
pub fn as_str(&self) -> &'static str {
match self {
Self::Get => "GET",
Self::Post => "POST",
Self::Put => "PUT",
Self::Patch => "PATCH",
Self::Delete => "DELETE",
}
}
}
impl std::fmt::Display for HttpMethod {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// Where a parameter appears in the request
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ParamLocation {
Path,
Query,
Header,
}
/// Primitive type of a parameter (for validation and CLI parsing)
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ParamType {
String,
Integer,
Number,
Boolean,
}
/// Content type for request bodies
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum BodyContentType {
Json,
FormUrlEncoded,
Multipart,
OctetStream,
TextPlain,
}
/// Definition of an operation parameter.
///
/// Only `Serialize` is derived: this struct holds `&'static`
/// references to data baked into the binary, which cannot be
/// reconstructed by `Deserialize`.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ParamDef {
pub name: &'static str,
pub location: ParamLocation,
pub required: bool,
pub param_type: ParamType,
pub description: Option<&'static str>,
}
/// Definition of a request body.
///
/// `Serialize`-only for the same reason as [`ParamDef`].
#[derive(Debug, Clone, serde::Serialize)]
pub struct BodyDef {
pub content_type: BodyContentType,
/// Name of the schema type (for JSON/form bodies)
pub schema_name: Option<&'static str>,
}
/// A single operation in the registry.
///
/// `Serialize`-only because of the `&'static` fields.
#[derive(Debug, Clone, serde::Serialize)]
pub struct OperationDef {
/// Unique operation identifier (e.g. "repos/get", "issues/create-comment")
pub id: &'static str,
/// HTTP method
pub method: HttpMethod,
/// URL path template with {param} placeholders
pub path: &'static str,
/// Short summary for CLI help
pub summary: Option<&'static str>,
/// Longer description
pub description: Option<&'static str>,
/// Parameters (path, query, header)
pub params: &'static [ParamDef],
/// Request body definition
pub body: Option<BodyDef>,
/// Response schema name for the success (2xx) case
pub response_schema: Option<&'static str>,
}
/// Look up an operation by ID
pub fn find_operation(id: &str) -> Option<&'static OperationDef> {
OPERATIONS.iter().find(|op| op.id == id)
}
/// List all operation IDs
pub fn operation_ids() -> impl Iterator<Item = &'static str> {
OPERATIONS.iter().map(|op| op.id)
}
}
}
/// Generate the static OPERATIONS slice from analyzed operations
fn generate_operation_defs(&self, analysis: &SchemaAnalysis) -> TokenStream {
let mut param_statics: Vec<TokenStream> = Vec::new();
let mut op_entries: Vec<TokenStream> = Vec::new();
// Sort for deterministic output
let mut sorted_ops: Vec<_> = analysis.operations.values().collect();
sorted_ops.sort_by_key(|op| &op.operation_id);
for op in sorted_ops {
let id = &op.operation_id;
let method = match op.method.as_str() {
"GET" => quote! { HttpMethod::Get },
"POST" => quote! { HttpMethod::Post },
"PUT" => quote! { HttpMethod::Put },
"PATCH" => quote! { HttpMethod::Patch },
"DELETE" => quote! { HttpMethod::Delete },
_ => quote! { HttpMethod::Get },
};
let path = &op.path;
let summary = match &op.summary {
Some(s) => quote! { Some(#s) },
None => quote! { None },
};
let description = match &op.description {
Some(d) => quote! { Some(#d) },
None => quote! { None },
};
// Generate params
let param_defs: Vec<TokenStream> = op
.parameters
.iter()
.map(|p| {
let name = &p.name;
let location = match p.location.as_str() {
"path" => quote! { ParamLocation::Path },
"query" => quote! { ParamLocation::Query },
"header" => quote! { ParamLocation::Header },
_ => quote! { ParamLocation::Query },
};
let required = p.required;
let param_type = match p.rust_type.as_str() {
"i64" | "i32" => quote! { ParamType::Integer },
"f64" => quote! { ParamType::Number },
"bool" => quote! { ParamType::Boolean },
_ => quote! { ParamType::String },
};
let desc = match &p.description {
Some(d) => quote! { Some(#d) },
None => quote! { None },
};
quote! {
ParamDef {
name: #name,
location: #location,
required: #required,
param_type: #param_type,
description: #desc,
}
}
})
.collect();
// Sanitize operation ID to a valid Rust identifier for the static name
let sanitized_id: String = op
.operation_id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_uppercase()
} else {
'_'
}
})
.collect();
let params_static_name = syn::Ident::new(
&format!("PARAMS_{sanitized_id}"),
proc_macro2::Span::call_site(),
);
let param_count = param_defs.len();
// Emit the param array as a separate static
param_statics.push(quote! {
static #params_static_name: [ParamDef; #param_count] = [#(#param_defs),*];
});
// Generate body def
let body = match &op.request_body {
Some(rb) => {
use crate::analysis::RequestBodyContent;
let (content_type, schema_name) = match rb {
RequestBodyContent::Json { schema_name } => (
quote! { BodyContentType::Json },
quote! { Some(#schema_name) },
),
RequestBodyContent::FormUrlEncoded { schema_name } => (
quote! { BodyContentType::FormUrlEncoded },
quote! { Some(#schema_name) },
),
RequestBodyContent::Multipart => {
(quote! { BodyContentType::Multipart }, quote! { None })
}
RequestBodyContent::OctetStream => {
(quote! { BodyContentType::OctetStream }, quote! { None })
}
RequestBodyContent::TextPlain => {
(quote! { BodyContentType::TextPlain }, quote! { None })
}
};
quote! {
Some(BodyDef {
content_type: #content_type,
schema_name: #schema_name,
})
}
}
None => quote! { None },
};
// Response schema (2xx)
let response_schema = op
.response_schemas
.get("200")
.or_else(|| op.response_schemas.get("201"))
.or_else(|| {
op.response_schemas
.iter()
.find(|(code, _)| code.starts_with('2'))
.map(|(_, v)| v)
});
let response_schema_token = match response_schema {
Some(s) => quote! { Some(#s) },
None => quote! { None },
};
op_entries.push(quote! {
OperationDef {
id: #id,
method: #method,
path: #path,
summary: #summary,
description: #description,
params: &#params_static_name,
body: #body,
response_schema: #response_schema_token,
}
});
}
let op_count = op_entries.len();
quote! {
#(#param_statics)*
pub static OPERATIONS: [OperationDef; #op_count] = [#(#op_entries),*];
}
}
}