ggen-core 26.6.25

Core graph-aware code generation engine
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Schema Parser for A2A Skills
//!
//! Parses schema definitions from a simple syntax into structured representations.
//! Syntax: `TypeName { field: type, optional_field?: type }`
//!
//! This parser uses PEST (Parsing Expression Grammar Tool) for robust parsing.
//! See grammar.pest for the formal grammar definition.

use pest::Parser;
use pest_derive::Parser;
use serde::{Deserialize, Serialize};
use std::fmt;

#[derive(Parser)]
#[grammar = "schema/grammar.pest"]
struct SchemaParserInternal;

/// Schema definition for an A2A skill input/output type
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Schema {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub fields: Vec<Field>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub nested_schemas: Vec<Schema>,
}

impl fmt::Display for Schema {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {{ ", self.name)?;
        for (i, field) in self.fields.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}", field)?;
        }
        write!(f, " }}")
    }
}

/// Field definition within a schema
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Field {
    pub name: String,
    pub field_type: SchemaType,
    pub optional: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl fmt::Display for Field {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.optional {
            write!(f, "{}?: {}", self.name, self.field_type)
        } else {
            write!(f, "{}: {}", self.name, self.field_type)
        }
    }
}

/// Schema type definitions
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SchemaType {
    String,
    Integer,
    Float,
    Boolean,
    Any,
    Reference(String),
    Array(Box<SchemaType>),
    Object(Vec<Field>),
}

impl fmt::Display for SchemaType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SchemaType::String => write!(f, "string"),
            SchemaType::Integer => write!(f, "integer"),
            SchemaType::Float => write!(f, "float"),
            SchemaType::Boolean => write!(f, "boolean"),
            SchemaType::Any => write!(f, "any"),
            SchemaType::Reference(name) => write!(f, "{}", name),
            SchemaType::Array(inner) => write!(f, "{}[]", inner),
            SchemaType::Object(fields) => {
                write!(f, "{{ ")?;
                for (i, field) in fields.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", field)?;
                }
                write!(f, " }}")
            }
        }
    }
}

impl SchemaType {
    pub fn as_str(&self) -> &'static str {
        match self {
            SchemaType::String => "string",
            SchemaType::Integer => "integer",
            SchemaType::Float => "float",
            SchemaType::Boolean => "boolean",
            SchemaType::Any => "any",
            SchemaType::Reference(_) => "reference",
            SchemaType::Array(_) => "array",
            SchemaType::Object(_) => "object",
        }
    }
}

/// Schema parser that converts string definitions into Schema structs
pub struct SchemaParser;

impl SchemaParser {
    /// Parse a schema string into a Schema struct
    ///
    /// # Examples
    ///
    /// ```
    /// use crate::schema::SchemaParser;
    ///
    /// let schema = SchemaParser::parse("Request { field: string }").unwrap();
    /// assert_eq!(schema.name, "Request");
    /// assert_eq!(schema.fields.len(), 1);
    /// ```
    pub fn parse(input: &str) -> Result<Schema, String> {
        let pairs = SchemaParserInternal::parse(Rule::schema, input)
            .map_err(|e| format!("Parse error: {}", e))?;

        let mut schema = None;

        for pair in pairs {
            match pair.as_rule() {
                Rule::schema => {
                    schema = Some(Self::build_schema(pair)?);
                }
                Rule::EOI => {
                    // End of input - nothing to do
                }
                _ => {}
            }
        }

        schema.ok_or_else(|| "No schema found".to_string())
    }

    fn build_schema(pair: pest::iterators::Pair<Rule>) -> Result<Schema, String> {
        let mut name = String::new();
        let mut fields = Vec::new();

        for inner_pair in pair.into_inner() {
            match inner_pair.as_rule() {
                Rule::identifier => {
                    name = inner_pair.as_str().trim().to_string();
                }
                Rule::fields => {
                    // fields contains: "{", field_list?, "}"
                    // We need to go into field_list to get the actual fields
                    for nested_pair in inner_pair.into_inner() {
                        if nested_pair.as_rule() == Rule::field_list {
                            for field_pair in nested_pair.into_inner() {
                                if field_pair.as_rule() == Rule::field {
                                    fields.push(Self::build_field(field_pair)?);
                                }
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        Ok(Schema {
            name,
            description: None,
            fields,
            nested_schemas: vec![],
        })
    }

    fn build_field(pair: pest::iterators::Pair<Rule>) -> Result<Field, String> {
        let mut name = String::new();
        let mut field_type = SchemaType::Any;
        let mut optional = false;

        // Iterate through the tokens in order
        for inner_pair in pair.into_inner() {
            match inner_pair.as_rule() {
                Rule::identifier => {
                    name = inner_pair.as_str().trim().to_string();
                }
                Rule::type_ => {
                    field_type = Self::build_type(inner_pair)?;
                }
                Rule::optional_marker => {
                    optional = true;
                }
                _ => {
                    // Ignore other tokens (like ":" which is not a named rule)
                }
            }
        }

        Ok(Field {
            name,
            field_type,
            optional,
            description: None,
        })
    }

    fn build_type(pair: pest::iterators::Pair<Rule>) -> Result<SchemaType, String> {
        let inner = pair
            .into_inner()
            .next()
            .ok_or_else(|| "Empty type".to_string())?;

        match inner.as_rule() {
            Rule::primitive_type => {
                let type_str = inner.as_str().to_lowercase();
                match type_str.as_str() {
                    "string" => Ok(SchemaType::String),
                    "integer" => Ok(SchemaType::Integer),
                    "boolean" => Ok(SchemaType::Boolean),
                    "float" => Ok(SchemaType::Float),
                    "any" => Ok(SchemaType::Any),
                    _ => Err(format!("Unknown primitive type: {}", type_str)),
                }
            }
            Rule::named_type => {
                let name = inner.as_str().to_string();
                Ok(SchemaType::Reference(name))
            }
            Rule::array_type => {
                // array_type now directly contains the base type
                let mut inner_pairs = inner.into_inner();
                let base_type_pair = inner_pairs
                    .next()
                    .ok_or_else(|| "Array type missing inner type".to_string())?;

                // The base type could be primitive or named
                let base_type = match base_type_pair.as_rule() {
                    Rule::primitive_type => {
                        let type_str = base_type_pair.as_str().to_lowercase();
                        match type_str.as_str() {
                            "string" => SchemaType::String,
                            "integer" => SchemaType::Integer,
                            "boolean" => SchemaType::Boolean,
                            "float" => SchemaType::Float,
                            "any" => SchemaType::Any,
                            _ => {
                                return Err(format!(
                                    "Unknown primitive type in array: {}",
                                    type_str
                                ))
                            }
                        }
                    }
                    Rule::named_type => {
                        let name = base_type_pair.as_str().to_string();
                        SchemaType::Reference(name)
                    }
                    _ => {
                        return Err(format!(
                            "Unexpected array base type rule: {:?}",
                            base_type_pair.as_rule()
                        ))
                    }
                };

                Ok(SchemaType::Array(Box::new(base_type)))
            }
            _ => Err(format!("Unknown type rule: {:?}", inner.as_rule())),
        }
    }

    /// Parse a JSON Schema into a Schema struct
    pub fn from_json_schema(json: &str) -> Result<Schema, String> {
        let v: serde_json::Value =
            serde_json::from_str(json).map_err(|e| format!("Invalid JSON: {}", e))?;

        let title = v
            .get("title")
            .and_then(|t| t.as_str())
            .unwrap_or("UnnamedSchema")
            .to_string();

        let description = v
            .get("description")
            .and_then(|d| d.as_str())
            .map(String::from);

        let mut fields = Vec::new();

        if let Some(properties) = v.get("properties").and_then(|p| p.as_object()) {
            let required_fields: Vec<&str> = v
                .get("required")
                .and_then(|r| r.as_array())
                .map(|r| r.iter().filter_map(|v| v.as_str()).collect())
                .unwrap_or_default();

            for (key, prop) in properties {
                let optional = !required_fields.contains(&key.as_str());
                let field_type_str = prop.get("type").and_then(|t| t.as_str()).unwrap_or("any");

                let field_type = match field_type_str {
                    "string" => SchemaType::String,
                    "integer" => SchemaType::Integer,
                    "number" => SchemaType::Float,
                    "boolean" => SchemaType::Boolean,
                    "array" => {
                        if let Some(items) = prop.get("items") {
                            let item_type =
                                items.get("type").and_then(|t| t.as_str()).unwrap_or("any");
                            let inner = match item_type {
                                "string" => SchemaType::String,
                                "integer" => SchemaType::Integer,
                                "number" => SchemaType::Float,
                                "boolean" => SchemaType::Boolean,
                                _ => SchemaType::Any,
                            };
                            SchemaType::Array(Box::new(inner))
                        } else {
                            SchemaType::Array(Box::new(SchemaType::Any))
                        }
                    }
                    _ => SchemaType::Any,
                };

                let field_desc = prop
                    .get("description")
                    .and_then(|d| d.as_str())
                    .map(String::from);

                fields.push(Field {
                    name: key.clone(),
                    field_type,
                    optional,
                    description: field_desc,
                });
            }
        }

        Ok(Schema {
            name: title,
            description,
            fields,
            nested_schemas: Vec::new(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_schema() {
        let schema = SchemaParser::parse("Request { field: string }").unwrap();
        assert_eq!(schema.name, "Request");
        assert_eq!(schema.fields.len(), 1);
        assert_eq!(schema.fields[0].name, "field");
        assert!(!schema.fields[0].optional);
        assert_eq!(schema.fields[0].field_type, SchemaType::String);
    }

    #[test]
    fn test_parse_optional_field() {
        let schema = SchemaParser::parse("Request { field?: string }").unwrap();
        assert!(schema.fields[0].optional);
    }

    #[test]
    fn test_parse_example_file_read_request() {
        let schema =
            SchemaParser::parse("FileReadRequest { path: string, offset?: integer }").unwrap();
        assert_eq!(schema.name, "FileReadRequest");
        assert_eq!(schema.fields.len(), 2);
        assert_eq!(schema.fields[0].name, "path");
        assert_eq!(schema.fields[1].name, "offset");
        assert!(schema.fields[1].optional);
    }

    #[test]
    fn test_parse_array_type() {
        let schema = SchemaParser::parse("Request { items: string[] }").unwrap();
        assert_eq!(
            schema.fields[0].field_type,
            SchemaType::Array(Box::new(SchemaType::String))
        );
    }

    #[test]
    fn test_parse_named_type() {
        let schema = SchemaParser::parse("Request { custom: MyType }").unwrap();
        assert_eq!(
            schema.fields[0].field_type,
            SchemaType::Reference("MyType".to_string())
        );
    }

    #[test]
    fn test_parse_multiple_fields() {
        let schema =
            SchemaParser::parse("Request { name: string, age: integer, active?: boolean }")
                .unwrap();
        assert_eq!(schema.fields.len(), 3);
        assert_eq!(schema.fields[0].name, "name");
        assert_eq!(schema.fields[1].name, "age");
        assert_eq!(schema.fields[2].name, "active");
        assert!(schema.fields[2].optional);
    }

    #[test]
    fn test_parse_error_missing_brace() {
        let result = SchemaParser::parse("Request { field: string");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_error_empty_name() {
        let result = SchemaParser::parse("{ field: string }");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_error_invalid_type() {
        // The parser accepts any identifier as a named type reference
        // Validation of whether the type exists happens later
        let result = SchemaParser::parse("Request { field: CustomType }");
        assert!(result.is_ok()); // Named types are valid syntax

        // Test actual parse error - missing colon
        let result = SchemaParser::parse("Request { field string }");
        assert!(result.is_err());
    }

    #[test]
    fn test_schema_display() {
        let schema = SchemaParser::parse("Request { name: string, age?: integer }").unwrap();
        let display = format!("{}", schema);
        assert!(display.contains("Request {"));
        assert!(display.contains("name: string"));
        assert!(display.contains("age?: integer"));
    }

    #[test]
    fn test_field_type_display() {
        assert_eq!(format!("{}", SchemaType::String), "string");
        assert_eq!(format!("{}", SchemaType::Integer), "integer");
        assert_eq!(
            format!("{}", SchemaType::Array(Box::new(SchemaType::String))),
            "string[]"
        );
        assert_eq!(
            format!("{}", SchemaType::Reference("MyType".to_string())),
            "MyType"
        );
    }
}