zap-schema 1.0.0

ZAP Schema Compiler - Zero-Copy Application Protocol with whitespace-significant syntax
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
//! ZAP Schema Compiler (zapc)
//!
//! A CLI tool for compiling ZAP schemas to various output formats.
//!
//! # Usage
//!
//! ```bash
//! # Compile to Cap'n Proto format
//! zapc compile schema.zap --out=schema.capnp
//!
//! # Generate code for a specific language
//! zapc generate schema.zap --lang=rust --out=./gen/
//!
//! # Convert Cap'n Proto to ZAP format
//! zapc migrate schema.capnp schema.zap
//!
//! # Validate a schema
//! zapc check schema.zap
//!
//! # Format a schema
//! zapc fmt schema.zap
//! ```

use clap::{Parser, Subcommand};
use std::fs;
use std::path::PathBuf;
use zap::schema::{compile_to_rust, migrate_capnp_to_zap, transpile_str, ZapSchema};

#[derive(Parser)]
#[command(name = "zapc")]
#[command(author = "Hanzo AI <dev@hanzo.ai>")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "ZAP Schema Compiler - compile .zap schemas to various formats")]
#[command(long_about = r#"
ZAP Schema Compiler

Compile ZAP schemas (.zap) to Cap'n Proto format (.capnp) or generate
code for various languages. Also supports migrating existing Cap'n Proto
schemas to the cleaner ZAP format.

Examples:
  # Compile a schema
  zapc compile schema.zap

  # Generate Rust code
  zapc generate schema.zap --lang=rust --out=./gen/

  # Migrate from Cap'n Proto to ZAP
  zapc migrate old.capnp new.zap

  # Check schema for errors
  zapc check schema.zap
"#)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Compile a ZAP schema to Cap'n Proto format
    Compile {
        /// Input schema file (.zap or .capnp)
        input: PathBuf,

        /// Output file (defaults to stdout)
        #[arg(short, long)]
        out: Option<PathBuf>,

        /// Force overwrite existing files
        #[arg(short, long)]
        force: bool,
    },

    /// Generate code from a ZAP schema
    Generate {
        /// Input schema file (.zap or .capnp)
        input: PathBuf,

        /// Target language (rust, go, ts, python, c, cpp, haskell, elixir)
        #[arg(short, long)]
        lang: String,

        /// Output directory
        #[arg(short, long)]
        out: PathBuf,

        /// Force overwrite existing files
        #[arg(short, long)]
        force: bool,
    },

    /// Convert Cap'n Proto schema to ZAP format
    Migrate {
        /// Input Cap'n Proto file (.capnp)
        input: PathBuf,

        /// Output ZAP file (.zap)
        output: PathBuf,

        /// Force overwrite existing files
        #[arg(short, long)]
        force: bool,
    },

    /// Check a schema for errors
    Check {
        /// Schema file to check
        input: PathBuf,

        /// Show verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Format a ZAP schema
    Fmt {
        /// Schema file to format
        input: PathBuf,

        /// Write output back to file (otherwise print to stdout)
        #[arg(short, long)]
        write: bool,
    },

    /// Print version information
    Version,
}

fn main() {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::Compile { input, out, force } => cmd_compile(input, out, force),
        Commands::Generate { input, lang, out, force } => cmd_generate(input, lang, out, force),
        Commands::Migrate { input, output, force } => cmd_migrate(input, output, force),
        Commands::Check { input, verbose } => cmd_check(input, verbose),
        Commands::Fmt { input, write } => cmd_fmt(input, write),
        Commands::Version => cmd_version(),
    };

    if let Err(e) = result {
        eprintln!("Error: {}", e);
        std::process::exit(1);
    }
}

fn cmd_compile(input: PathBuf, out: Option<PathBuf>, force: bool) -> Result<(), String> {
    let source = fs::read_to_string(&input)
        .map_err(|e| format!("Failed to read {}: {}", input.display(), e))?;

    let filename = input.file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("schema.zap");

    let result = transpile_str(&source, filename)
        .map_err(|e| format!("Compilation failed: {}", e))?;

    match out {
        Some(path) => {
            if path.exists() && !force {
                return Err(format!("Output file {} already exists. Use --force to overwrite.", path.display()));
            }
            fs::write(&path, &result)
                .map_err(|e| format!("Failed to write {}: {}", path.display(), e))?;
            println!("Compiled {} -> {}", input.display(), path.display());
        }
        None => {
            println!("{}", result);
        }
    }

    Ok(())
}

fn cmd_generate(input: PathBuf, lang: String, out: PathBuf, force: bool) -> Result<(), String> {
    let source = fs::read_to_string(&input)
        .map_err(|e| format!("Failed to read {}: {}", input.display(), e))?;

    let filename = input.file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("schema.zap");

    let code = match lang.to_lowercase().as_str() {
        "rust" | "rs" => {
            compile_to_rust(&source, filename)
                .map_err(|e| format!("Rust code generation failed: {}", e))?
        }
        "go" => {
            // TODO: Implement Go code generation
            return Err("Go code generation not yet implemented".to_string());
        }
        "typescript" | "ts" => {
            // TODO: Implement TypeScript code generation
            return Err("TypeScript code generation not yet implemented".to_string());
        }
        "python" | "py" => {
            // TODO: Implement Python code generation
            return Err("Python code generation not yet implemented".to_string());
        }
        "c" => {
            // TODO: Implement C code generation
            return Err("C code generation not yet implemented".to_string());
        }
        "cpp" | "c++" => {
            // TODO: Implement C++ code generation
            return Err("C++ code generation not yet implemented".to_string());
        }
        "haskell" | "hs" => {
            // TODO: Implement Haskell code generation
            return Err("Haskell code generation not yet implemented".to_string());
        }
        "elixir" | "ex" => {
            // TODO: Implement Elixir code generation
            return Err("Elixir code generation not yet implemented".to_string());
        }
        _ => {
            return Err(format!("Unknown language: {}. Supported: rust, go, ts, python, c, cpp, haskell, elixir", lang));
        }
    };

    // Create output directory if it doesn't exist
    fs::create_dir_all(&out)
        .map_err(|e| format!("Failed to create output directory {}: {}", out.display(), e))?;

    // Determine output filename
    let stem = input.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("schema");

    let ext = match lang.to_lowercase().as_str() {
        "rust" | "rs" => "rs",
        "go" => "go",
        "typescript" | "ts" => "ts",
        "python" | "py" => "py",
        "c" => "h",
        "cpp" | "c++" => "hpp",
        "haskell" | "hs" => "hs",
        "elixir" | "ex" => "ex",
        _ => "txt",
    };

    let output_path = out.join(format!("{}.{}", stem, ext));

    if output_path.exists() && !force {
        return Err(format!("Output file {} already exists. Use --force to overwrite.", output_path.display()));
    }

    fs::write(&output_path, &code)
        .map_err(|e| format!("Failed to write {}: {}", output_path.display(), e))?;

    println!("Generated {} ({}) -> {}", input.display(), lang, output_path.display());

    Ok(())
}

fn cmd_migrate(input: PathBuf, output: PathBuf, force: bool) -> Result<(), String> {
    if output.exists() && !force {
        return Err(format!("Output file {} already exists. Use --force to overwrite.", output.display()));
    }

    migrate_capnp_to_zap(&input, &output)
        .map_err(|e| format!("Migration failed: {}", e))?;

    println!("Migrated {} -> {}", input.display(), output.display());

    Ok(())
}

fn cmd_check(input: PathBuf, verbose: bool) -> Result<(), String> {
    let source = fs::read_to_string(&input)
        .map_err(|e| format!("Failed to read {}: {}", input.display(), e))?;

    let filename = input.file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("schema.zap");

    let schema = ZapSchema::new(&source, filename);

    if verbose {
        println!("Checking: {}", input.display());
        println!("Format: {:?}", schema.format());
    }

    // Try to parse and compile
    let result = schema.compile();

    match result {
        Ok(compiled) => {
            if verbose {
                let lines: Vec<_> = compiled.lines().collect();
                let structs = lines.iter().filter(|l| l.contains("struct ")).count();
                let enums = lines.iter().filter(|l| l.contains("enum ")).count();
                let interfaces = lines.iter().filter(|l| l.contains("interface ")).count();

                println!("Structures: {}", structs);
                println!("Enums: {}", enums);
                println!("Interfaces: {}", interfaces);
            }
            println!("✓ {} is valid", input.display());
            Ok(())
        }
        Err(e) => {
            Err(format!("✗ {} has errors: {}", input.display(), e))
        }
    }
}

fn cmd_fmt(input: PathBuf, write: bool) -> Result<(), String> {
    let source = fs::read_to_string(&input)
        .map_err(|e| format!("Failed to read {}: {}", input.display(), e))?;

    // For now, just normalize whitespace and ensure consistent indentation
    let mut formatted = String::new();
    let mut in_block = 0;

    for line in source.lines() {
        let trimmed = line.trim();

        // Decrease indent for closing or before struct/enum/interface at same level
        if trimmed.is_empty() {
            formatted.push('\n');
            continue;
        }

        // Check if this line decreases indentation
        if trimmed.starts_with("struct ") || trimmed.starts_with("enum ") || trimmed.starts_with("interface ") {
            // Top-level definitions get no indent
            if in_block == 0 {
                formatted.push_str(trimmed);
                formatted.push('\n');
                in_block = 1;
                continue;
            }
        }

        // Add appropriate indentation
        let indent = "  ".repeat(in_block);
        formatted.push_str(&indent);
        formatted.push_str(trimmed);
        formatted.push('\n');

        // Adjust block level based on content
        if trimmed.starts_with("struct ") || trimmed.starts_with("enum ") || trimmed.starts_with("interface ") || trimmed.starts_with("union") {
            in_block += 1;
        }
    }

    if write {
        fs::write(&input, &formatted)
            .map_err(|e| format!("Failed to write {}: {}", input.display(), e))?;
        println!("Formatted {}", input.display());
    } else {
        print!("{}", formatted);
    }

    Ok(())
}

fn cmd_version() -> Result<(), String> {
    println!("zapc {} (ZAP Schema Compiler)", env!("CARGO_PKG_VERSION"));
    println!("Copyright (C) 2024 Hanzo AI");
    println!("License: Apache-2.0 OR MIT");
    println!();
    println!("Features:");
    println!("  - ZAP whitespace syntax (.zap)");
    println!("  - Cap'n Proto compatibility (.capnp)");
    println!("  - Code generation: Rust (more coming)");
    println!("  - Schema migration tools");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_compile_simple_schema() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "struct Person").unwrap();
        writeln!(file, "  name Text").unwrap();
        writeln!(file, "  age UInt32").unwrap();

        let result = cmd_compile(file.path().to_path_buf(), None, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_check_valid_schema() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "struct Person").unwrap();
        writeln!(file, "  name Text").unwrap();

        let result = cmd_check(file.path().to_path_buf(), false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_generate_rust() {
        let mut file = NamedTempFile::with_suffix(".zap").unwrap();
        writeln!(file, "struct Person").unwrap();
        writeln!(file, "  name Text").unwrap();
        writeln!(file, "  age UInt32").unwrap();

        let out_dir = tempfile::tempdir().unwrap();
        let result = cmd_generate(
            file.path().to_path_buf(),
            "rust".to_string(),
            out_dir.path().to_path_buf(),
            false,
        );
        assert!(result.is_ok());
    }
}