1use crate::schema::{Schema, SchemaType};
9use std::fmt::Write;
10
11pub struct JavaGenerator;
13
14impl JavaGenerator {
15 pub fn generate_class(schema: &Schema) -> String {
17 let mut output = String::new();
18
19 let _ = writeln!(output, "package com.a2a.generated;");
21 let _ = writeln!(output);
22
23 let _ = writeln!(output, "import com.fasterxml.jackson.annotation.*;");
25 let _ = writeln!(output, "import java.util.List;");
26 let _ = writeln!(output, "import java.util.ArrayList;");
27 let _ = writeln!(output);
28
29 if let Some(desc) = &schema.description {
31 let _ = writeln!(output, "/**\n * {}\n */", desc);
32 }
33
34 let _ = writeln!(output, "@JsonInclude(JsonInclude.Include.NON_NULL)");
36 let _ = writeln!(output, "public class {} {{", schema.name);
37 let _ = writeln!(output);
38
39 for field in &schema.fields {
41 if let Some(desc) = &field.description {
42 let _ = writeln!(output, " /**\n * {}\n */", desc);
43 }
44 let _ = writeln!(
45 output,
46 " private {} {};",
47 Self::field_type_to_java(&field.field_type),
48 Self::to_camel_case(&field.name)
49 );
50 let _ = writeln!(output);
51 }
52
53 for field in &schema.fields {
55 let field_name_camel = Self::to_camel_case(&field.name);
56 let java_type = Self::field_type_to_java(&field.field_type);
57
58 let _ = writeln!(
60 output,
61 " public {} get{}() {{",
62 java_type,
63 Self::capitalize(&field_name_camel)
64 );
65 let _ = writeln!(output, " return this.{};", field_name_camel);
66 let _ = writeln!(output, " }}");
67 let _ = writeln!(output);
68
69 let _ = writeln!(
71 output,
72 " public void set{}({} {}) {{",
73 Self::capitalize(&field_name_camel),
74 java_type,
75 field_name_camel
76 );
77 let _ = writeln!(
78 output,
79 " this.{} = {};",
80 field_name_camel, field_name_camel
81 );
82 let _ = writeln!(output, " }}");
83 let _ = writeln!(output);
84 }
85
86 let _ = writeln!(output, " @Override");
88 let _ = writeln!(output, " public String toString() {{");
89 let _ = writeln!(output, " return \"{}{{\" +", schema.name);
90 let field_names: Vec<String> = schema
91 .fields
92 .iter()
93 .map(|f| Self::to_camel_case(&f.name))
94 .collect();
95 for (i, field_name) in field_names.iter().enumerate() {
96 let suffix = if i < field_names.len() - 1 { "," } else { "" };
97 let _ = writeln!(
98 output,
99 " \"{}=\" + {}{}\"",
100 field_name, field_name, suffix
101 );
102 }
103 let _ = writeln!(output, " \"}}\";");
104 let _ = writeln!(output, " }}");
105
106 let _ = writeln!(output, "}}");
107
108 output
109 }
110
111 fn field_type_to_java(field_type: &SchemaType) -> String {
113 match field_type {
114 SchemaType::String => "String".to_string(),
115 SchemaType::Integer => "Long".to_string(),
116 SchemaType::Boolean => "Boolean".to_string(),
117 SchemaType::Float => "Double".to_string(),
118 SchemaType::Any => "Object".to_string(),
119 SchemaType::Array(inner) => format!("List<{}>", Self::field_type_to_java(inner)),
120 SchemaType::Object(_) => "Map<String, Object>".to_string(),
121 SchemaType::Reference(name) => name.clone(),
122 }
123 }
124
125 fn to_camel_case(s: &str) -> String {
127 let parts: Vec<&str> = s.split('_').collect();
128 let mut result = parts[0].to_string();
129 for part in &parts[1..] {
130 result.push_str(&Self::capitalize(part));
131 }
132 result
133 }
134
135 fn capitalize(s: &str) -> String {
137 let mut chars = s.chars();
138 match chars.next() {
139 None => String::new(),
140 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
141 }
142 }
143}
144
145pub struct ElixirGenerator;
147
148impl ElixirGenerator {
149 pub fn generate_struct(schema: &Schema) -> String {
151 let mut output = String::new();
152
153 let _ = writeln!(output, "defmodule {} do", schema.name);
155 let _ = writeln!(output, " @moduledoc \"\"\"");
156 if let Some(desc) = &schema.description {
157 let _ = writeln!(output, " {}", desc);
158 } else {
159 let _ = writeln!(output, " Auto-generated A2A schema: {}", schema.name);
160 }
161 let _ = writeln!(output, " \"\"\"");
162 let _ = writeln!(output);
163
164 let _ = writeln!(output, " defstruct [");
166 for (i, field) in schema.fields.iter().enumerate() {
167 let comma = if i < schema.fields.len() - 1 { "," } else { "" };
168 let _ = writeln!(output, " :{}{}", field.name, comma);
169 }
170 let _ = writeln!(output, " ]");
171 let _ = writeln!(output);
172
173 let _ = writeln!(output, " @type t :: %__MODULE__{{");
175 for field in &schema.fields {
176 let elixir_type = Self::field_type_to_elixir(&field.field_type, field.optional);
177 let _ = writeln!(output, " {}: {},", field.name, elixir_type);
178 }
179 let _ = writeln!(output, " }}");
180 let _ = writeln!(output);
181
182 let _ = writeln!(output, " @doc \"\"\"");
184 let _ = writeln!(output, " Create a new {} struct", schema.name);
185 let _ = writeln!(output, " \"\"\"");
186 let _ = writeln!(output, " def new(fields \\\\ %{{}}) do");
187 let _ = writeln!(output, " struct = struct!(__MODULE__, fields)");
188 let _ = writeln!(output, " {{:ok, struct}}");
189 let _ = writeln!(output, " rescue");
190 let _ = writeln!(output, " error -> {{:error, error}}");
191 let _ = writeln!(output, " end");
192 let _ = writeln!(output);
193
194 let _ = writeln!(output, " @doc \"\"\"");
196 let _ = writeln!(output, " Validate required fields");
197 let _ = writeln!(output, " \"\"\"");
198 let _ = writeln!(
199 output,
200 " def validate(%__MODULE__{} = struct) do",
201 schema
202 .fields
203 .iter()
204 .map(|f| format!("{}: _", f.name))
205 .collect::<Vec<_>>()
206 .join(", ")
207 );
208 let _ = writeln!(output, " required = [");
209 for field in schema.fields.iter().filter(|f| !f.optional) {
210 let _ = writeln!(output, " :{},", field.name);
211 }
212 let _ = writeln!(output, " ]");
213 let _ = writeln!(output);
214 let _ = writeln!(output, " missing = required -- Map.keys(struct)");
215 let _ = writeln!(output);
216 let _ = writeln!(output, " if Enum.empty?(missing) do");
217 let _ = writeln!(output, " {{:ok, struct}}");
218 let _ = writeln!(output, " else");
219 let _ = writeln!(output, " {{:error, {{:missing_fields, missing}}}}");
220 let _ = writeln!(output, " end");
221 let _ = writeln!(output, " end");
222 let _ = writeln!(output);
223
224 let _ = writeln!(output, " @doc \"\"\"");
226 let _ = writeln!(output, " Encode to JSON");
227 let _ = writeln!(output, " \"\"\"");
228 let _ = writeln!(
229 output,
230 " def to_json(%__MODULE__{} = struct) do",
231 schema
232 .fields
233 .iter()
234 .map(|f| format!("{}: _", f.name))
235 .collect::<Vec<_>>()
236 .join(", ")
237 );
238 let _ = writeln!(output, " Jason.encode!(struct)");
239 let _ = writeln!(output, " end");
240
241 let _ = writeln!(output, "end");
242
243 output
244 }
245
246 fn field_type_to_elixir(field_type: &SchemaType, optional: bool) -> String {
248 let base_type = match field_type {
249 SchemaType::String => "String.t()".to_string(),
250 SchemaType::Integer => "integer()".to_string(),
251 SchemaType::Boolean => "boolean()".to_string(),
252 SchemaType::Float => "float()".to_string(),
253 SchemaType::Any => "term()".to_string(),
254 SchemaType::Array(inner) => {
255 format!("list({})", Self::field_type_to_elixir(inner, false))
256 }
257 SchemaType::Object(_) => "map()".to_string(),
258 SchemaType::Reference(name) => format!("{}()", name),
259 };
260
261 if optional {
262 format!("{} | nil", base_type)
263 } else {
264 base_type
265 }
266 }
267}
268
269pub struct TypeScriptGenerator;
271
272impl TypeScriptGenerator {
273 pub fn generate_interface(schema: &Schema) -> String {
275 let mut output = String::new();
276
277 let _ = writeln!(output, "/**");
279 let _ = writeln!(
280 output,
281 " * Auto-generated TypeScript interface from A2A schema: {}",
282 schema.name
283 );
284 if let Some(desc) = &schema.description {
285 let _ = writeln!(output, " * {}", desc);
286 }
287 let _ = writeln!(output, " */");
288 let _ = writeln!(output);
289
290 let _ = writeln!(output, "/**");
292 if let Some(desc) = &schema.description {
293 let _ = writeln!(output, " * {}", desc);
294 } else {
295 let _ = writeln!(output, " * {} interface", schema.name);
296 }
297 let _ = writeln!(output, " */");
298 let _ = writeln!(output, "export interface {} {{", schema.name);
299
300 for field in &schema.fields {
302 if let Some(desc) = &field.description {
303 let _ = writeln!(output, " /** {} */", desc);
304 }
305 let optional_marker = if field.optional { "?" } else { "" };
306 let ts_type = Self::field_type_to_typescript(&field.field_type);
307 let _ = writeln!(output, " {}{}: {};", field.name, optional_marker, ts_type);
308 let _ = writeln!(output);
309 }
310
311 let _ = writeln!(output, "}}");
312
313 output
314 }
315
316 fn field_type_to_typescript(field_type: &SchemaType) -> String {
318 match field_type {
319 SchemaType::String => "string".to_string(),
320 SchemaType::Integer => "number".to_string(),
321 SchemaType::Boolean => "boolean".to_string(),
322 SchemaType::Float => "number".to_string(),
323 SchemaType::Any => "any".to_string(),
324 SchemaType::Array(inner) => format!("{}[]", Self::field_type_to_typescript(inner)),
325 SchemaType::Object(_) => "Record<string, any>".to_string(),
326 SchemaType::Reference(name) => name.clone(),
327 }
328 }
329}
330
331impl Schema {
333 pub fn to_rust_struct(&self) -> String {
335 RustGenerator::generate(self)
336 }
337
338 pub fn to_go_struct(&self) -> String {
340 GoGenerator::generate(self)
341 }
342
343 pub fn to_elixir_struct(&self) -> String {
345 ElixirGenerator::generate_struct(self)
346 }
347
348 pub fn to_java_class(&self) -> String {
350 JavaGenerator::generate_class(self)
351 }
352
353 pub fn to_typescript_interface(&self) -> String {
355 TypeScriptGenerator::generate_interface(self)
356 }
357}
358
359pub struct RustGenerator;
360
361impl RustGenerator {
362 pub fn generate(schema: &crate::schema::Schema) -> String {
364 let mut output = String::new();
365
366 if let Some(desc) = &schema.description {
367 let _ = writeln!(output, "/// {}", desc);
368 }
369 let _ = writeln!(output, "#[derive(Debug, Clone, Serialize, Deserialize)]");
370 let _ = writeln!(output, "pub struct {} {{", schema.name);
371
372 for field in &schema.fields {
373 if let Some(desc) = &field.description {
374 let _ = writeln!(output, " /// {}", desc);
375 }
376 let rust_type = Self::field_type_to_rust(&field.field_type, field.optional);
377 let _ = writeln!(output, " pub {}: {},", field.name, rust_type);
378 }
379
380 let _ = writeln!(output, "}}");
381 output
382 }
383
384 fn field_type_to_rust(field_type: &SchemaType, optional: bool) -> String {
385 let base = match field_type {
386 SchemaType::String => "String".to_string(),
387 SchemaType::Integer => "i64".to_string(),
388 SchemaType::Boolean => "bool".to_string(),
389 SchemaType::Float => "f64".to_string(),
390 SchemaType::Any => "serde_json::Value".to_string(),
391 SchemaType::Array(inner) => format!("Vec<{}>", Self::field_type_to_rust(inner, false)),
392 SchemaType::Object(_) => {
393 "std::collections::HashMap<String, serde_json::Value>".to_string()
394 }
395 SchemaType::Reference(name) => name.clone(),
396 };
397 if optional {
398 format!("Option<{}>", base)
399 } else {
400 base
401 }
402 }
403}
404
405pub struct GoGenerator;
407
408impl GoGenerator {
409 pub fn generate(schema: &crate::schema::Schema) -> String {
411 let mut output = String::new();
412
413 if let Some(desc) = &schema.description {
414 let _ = writeln!(output, "// {} describes the request.", desc);
415 }
416 let _ = writeln!(output, "type {} struct {{", schema.name);
417
418 for field in &schema.fields {
419 let go_type = Self::field_type_to_go(&field.field_type, field.optional);
420 let json_tag = if field.optional {
421 format!("{},omitempty", field.name)
422 } else {
423 field.name.clone()
424 };
425 let _ = writeln!(
426 output,
427 " {} {} `json:\"{}\"`",
428 Self::capitalize(&field.name),
429 go_type,
430 json_tag
431 );
432 }
433
434 let _ = writeln!(output, "}}");
435 output
436 }
437
438 fn field_type_to_go(field_type: &SchemaType, _optional: bool) -> String {
439 match field_type {
441 SchemaType::String => "string".to_string(),
442 SchemaType::Integer => "int64".to_string(),
443 SchemaType::Boolean => "bool".to_string(),
444 SchemaType::Float => "float64".to_string(),
445 SchemaType::Any => "interface{}".to_string(),
446 SchemaType::Array(inner) => format!("[]{}", Self::field_type_to_go(inner, false)),
447 SchemaType::Object(_) => "map[string]interface{}".to_string(),
448 SchemaType::Reference(name) => name.clone(),
449 }
450 }
451
452 fn capitalize(s: &str) -> String {
453 let mut chars = s.chars();
454 match chars.next() {
455 None => String::new(),
456 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
457 }
458 }
459}
460
461pub struct PythonGenerator;
463
464impl PythonGenerator {
465 pub fn generate(_schema: &crate::schema::Schema) -> String {
467 "# Python code generation not yet implemented for A2A schemas\n# Use OntologySchema instead"
468 .to_string()
469 }
470}
471
472#[cfg(test)]
473mod tests {
474 use super::*;
475 use crate::schema::{Field, SchemaParser};
476
477 fn create_test_schema() -> Schema {
478 Schema {
479 name: "FileReadRequest".to_string(),
480 description: Some("Request to read a file".to_string()),
481 fields: vec![
482 Field {
483 name: "path".to_string(),
484 field_type: SchemaType::String,
485 optional: false,
486 description: Some("File path to read".to_string()),
487 },
488 Field {
489 name: "offset".to_string(),
490 field_type: SchemaType::Integer,
491 optional: true,
492 description: Some("Byte offset to start reading".to_string()),
493 },
494 Field {
495 name: "limit".to_string(),
496 field_type: SchemaType::Integer,
497 optional: true,
498 description: None,
499 },
500 ],
501 nested_schemas: vec![],
502 }
503 }
504
505 #[test]
506 fn test_java_generator() {
507 let schema = create_test_schema();
508 let java_code = schema.to_java_class();
509
510 assert!(java_code.contains("public class FileReadRequest"));
511 assert!(java_code.contains("private String path;"));
512 assert!(java_code.contains("private Long offset;"));
513 assert!(java_code.contains("public String getPath()"));
514 assert!(java_code.contains("public void setPath(String path)"));
515 assert!(java_code.contains("@JsonInclude(JsonInclude.Include.NON_NULL)"));
516 }
517
518 #[test]
519 fn test_elixir_generator() {
520 let schema = create_test_schema();
521 let elixir_code = schema.to_elixir_struct();
522
523 assert!(elixir_code.contains("defmodule FileReadRequest do"));
524 assert!(elixir_code.contains("defstruct ["));
525 assert!(elixir_code.contains(":path"));
526 assert!(elixir_code.contains("@type t :: %__MODULE__{"));
527 assert!(elixir_code.contains("path: String.t()"));
528 assert!(elixir_code.contains("offset: integer() | nil"));
529 assert!(elixir_code.contains("limit: integer() | nil"));
530 }
531
532 #[test]
533 fn test_typescript_generator() {
534 let schema = create_test_schema();
535 let ts_code = schema.to_typescript_interface();
536
537 assert!(ts_code.contains("export interface FileReadRequest {"));
538 assert!(ts_code.contains("path: string;"));
539 assert!(ts_code.contains("offset?: number;"));
540 assert!(ts_code.contains("limit?: number;"));
541 }
542
543 #[test]
544 fn test_array_types() {
545 let schema = Schema {
546 name: "ArrayTest".to_string(),
547 description: None,
548 fields: vec![Field {
549 name: "tags".to_string(),
550 field_type: SchemaType::Array(Box::new(SchemaType::String)),
551 optional: false,
552 description: None,
553 }],
554 nested_schemas: vec![],
555 };
556
557 let java = schema.to_java_class();
559 assert!(java.contains("List<String> tags"));
560
561 let elixir = schema.to_elixir_struct();
563 assert!(elixir.contains("list(String.t())"));
564
565 let ts = schema.to_typescript_interface();
567 assert!(ts.contains("tags: string[]"));
568 }
569
570 #[test]
571 #[ignore = "JSON Schema parsing not yet implemented; enable when SchemaParser::from_json_schema is implemented"]
572 fn test_nested_schema() -> Result<(), String> {
573 let json_schema = r#"
574 {
575 "title": "NestedRequest",
576 "type": "object",
577 "properties": {
578 "metadata": {
579 "type": "object",
580 "properties": {
581 "created_at": { "type": "string" }
582 }
583 },
584 "items": {
585 "type": "array",
586 "items": { "type": "string" }
587 }
588 },
589 "required": ["items"]
590 }
591 "#;
592
593 let schema = SchemaParser::from_json_schema(json_schema)?;
594 assert_eq!(schema.name, "NestedRequest");
595 assert_eq!(schema.fields.len(), 2);
596
597 let java = schema.to_java_class();
598 assert!(java.contains("private List<String> items;"));
599 Ok(())
600 }
601}