primate 0.2.0

A small DSL for cross-language constants. Write once, generate typed Rust, TypeScript, and Python.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! CLI interface for primate
//!
//! Implements command-line argument parsing and command dispatch.

mod watch_tui;

use crate::config::Config;
use crate::diagnostics::{Diagnostics, Severity};
use crate::generators::Generator;
use crate::generators::python::PythonGenerator;
use crate::generators::rust::RustGenerator;
use crate::generators::typescript::TypeScriptGenerator;
use crate::ir::CodeGenRequest;
use crate::parser::{ParsedProject, discover_files, parse_project};
use crate::sourcemap::{Sourcemap, SourcemapEntry};
use clap::{Parser, Subcommand};
use notify_debouncer_mini::{new_debouncer, notify::RecursiveMode};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::channel;
use std::time::Duration;

/// Cross-language constant transpiler
#[derive(Parser)]
#[command(name = "primate")]
#[command(version, about, long_about = None)]
pub struct Cli {
    /// Path to config file
    #[arg(short, long, default_value = "primate.toml")]
    pub config: PathBuf,

    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Subcommand)]
pub enum Command {
    /// Validate constants without generating output
    // r[impl cli.check]
    Check {
        /// Watch for changes and re-validate
        // r[impl cli.check-watch]
        #[arg(long)]
        watch: bool,

        /// Output format
        // r[impl cli.check-format]
        #[arg(long, default_value = "text")]
        format: String,
    },

    /// Start the LSP server
    // r[impl cli.lsp]
    Lsp {
        /// Use stdio transport (default)
        #[arg(long)]
        stdio: bool,
    },

    /// Generate constants (default command)
    Generate {
        /// Input directory (overrides config)
        #[arg(short, long)]
        input: Option<PathBuf>,

        /// Output specification (e.g., ts:./out.ts)
        #[arg(short, long)]
        output: Option<String>,

        /// Watch for changes and regenerate
        // r[impl cli.generate-watch]
        #[arg(long)]
        watch: bool,
    },

    /// Format `.prim` files in place. With `--check`, exit non-zero if any
    /// file is not already formatted.
    Fmt {
        /// Files or directories to format. Defaults to the input directory
        /// from the active config.
        paths: Vec<PathBuf>,

        /// Don't write changes; exit non-zero if any file would be reformatted.
        #[arg(long)]
        check: bool,
    },

    /// Write a primate skill file for AI coding agents (a terse cheat-sheet
    /// covering syntax, setup, the always-fmt-after-edits rule, and common
    /// patterns).
    ///
    /// Two output formats are supported:
    ///
    /// - **agents** (default): plain Markdown, written to `AGENTS.md` at the
    ///   project root. This is the `agents.md` open standard and is read by
    ///   Claude Code, Cursor, GitHub Copilot, Codex, Aider, Devin, and most
    ///   other coding agents. Many tools that read other formats (e.g.
    ///   Cursor's `.cursor/rules/`, GitHub's `.github/copilot-instructions.md`)
    ///   also consume the same Markdown — point `--output` at the right path.
    ///
    /// - **claude**: Claude Code's structured skill format with YAML
    ///   frontmatter, written to `.claude/skills/primate/SKILL.md`. The
    ///   frontmatter lets Claude auto-load the skill when it sees `.prim`
    ///   files or primate-related questions.
    Skill {
        /// Output format. `agents` (the default) writes plain Markdown to
        /// `AGENTS.md`. `claude` writes a Claude Code skill with YAML
        /// frontmatter to `.claude/skills/primate/SKILL.md`.
        #[arg(long, default_value = "agents", value_parser = ["agents", "claude"])]
        target: String,

        /// Override the destination path. The content is determined by
        /// `--target`; this just changes where it's written. Useful for
        /// agents that read other paths (e.g. `.cursor/rules/primate.md`,
        /// `.github/copilot-instructions.md`).
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Print to stdout instead of writing a file.
        #[arg(long)]
        stdout: bool,

        /// Overwrite the destination if it already exists.
        #[arg(long)]
        force: bool,
    },
}

pub fn run() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Some(Command::Check { watch, format }) => {
            if watch {
                run_check_watch(&cli.config, &format)?;
            } else {
                run_check(&cli.config, &format)?;
            }
        }
        Some(Command::Lsp { stdio: _ }) => {
            crate::lsp::run_server(&cli.config)?;
        }
        Some(Command::Generate {
            input,
            output,
            watch,
        }) => {
            if watch {
                run_generate_watch(&cli.config, input)?;
            } else {
                run_generate(&cli.config, input, output)?;
            }
        }
        Some(Command::Fmt { paths, check }) => {
            run_fmt(&cli.config, paths, check)?;
        }
        Some(Command::Skill {
            target,
            output,
            stdout,
            force,
        }) => {
            run_skill(&target, output, stdout, force)?;
        }
        None => {
            // r[impl cli.default-config]
            // Default: run generate with config
            run_generate(&cli.config, None, None)?;
        }
    }

    Ok(())
}

fn run_check(config_path: &PathBuf, format: &str) -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::load(config_path)?;
    let files = discover_files(&config.input)?;

    if files.is_empty() {
        eprintln!("No .prim files found in {}", config.input.display());
        return Ok(());
    }

    let project = parse_project(files);

    if format == "json" {
        println!("{}", serde_json::to_string_pretty(&project.diagnostics)?);
    } else {
        print_diagnostics(&project.diagnostics);
    }

    if project.diagnostics.has_errors() {
        std::process::exit(1);
    }

    eprintln!(
        "Checked {} modules, {} constants, {} enums",
        project.modules.len(),
        project
            .modules
            .iter()
            .map(|m| m.constants.len())
            .sum::<usize>(),
        project.enums.len()
    );

    Ok(())
}

// r[impl cli.check-watch]
fn run_check_watch(config_path: &PathBuf, format: &str) -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::load(config_path)?;

    // Initial check
    eprintln!("Watching {} for changes...", config.input.display());
    let _ = run_check(config_path, format);

    // Set up file watcher
    let (tx, rx) = channel();
    let mut debouncer = new_debouncer(Duration::from_millis(500), tx)?;

    debouncer
        .watcher()
        .watch(&config.input, RecursiveMode::Recursive)?;

    loop {
        match rx.recv() {
            Ok(Ok(_events)) => {
                eprintln!("\n--- File changed, re-checking ---\n");
                let _ = run_check(config_path, format);
            }
            Ok(Err(e)) => eprintln!("Watch error: {:?}", e),
            Err(e) => {
                eprintln!("Channel error: {:?}", e);
                break;
            }
        }
    }

    Ok(())
}

fn run_generate(
    config_path: &PathBuf,
    input_override: Option<PathBuf>,
    _output_override: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = Config::load(config_path)?;
    let input_dir = input_override.as_ref().unwrap_or(&config.input);

    let files = discover_files(input_dir)?;

    if files.is_empty() {
        eprintln!("No .prim files found in {}", input_dir.display());
        return Ok(());
    }

    let project = parse_project(files);

    if project.diagnostics.has_errors() {
        print_diagnostics(&project.diagnostics);
        std::process::exit(1);
    }

    print_diagnostics(&project.diagnostics);

    // r[impl sourcemap.json]
    let mut sourcemap = Sourcemap::new();

    for output_config in &config.outputs {
        let output_path = output_config.path.display().to_string();

        let options: HashMap<String, serde_json::Value> = output_config
            .options
            .iter()
            .map(|(k, v)| (k.clone(), toml_to_json(v)))
            .collect();

        let mut request = CodeGenRequest::new(output_path.clone(), options.clone());
        request.modules = project.modules.clone();
        request.enums = project.enums.clone();
        request.aliases = project.aliases.clone();

        if let Some(ref generator_name) = output_config.generator {
            // Validate that `path` matches what the generator expects. The
            // generators emit one (rust) or many (ts, python) files into
            // `path`; getting the shape wrong produces opaque OS errors
            // ("Is a directory", "Not a directory") down the line, so catch
            // it here with a message that points at the config field.
            if let Err(msg) = validate_output_path(generator_name, &output_path) {
                eprintln!(
                    "Config error in [[output]] generator = \"{}\": {}",
                    generator_name, msg
                );
                std::process::exit(2);
            }

            match generator_name.as_str() {
                "typescript" => {
                    let generator = TypeScriptGenerator::from_options(&options);
                    let response = generator.generate(&request);
                    write_response_files(
                        generator_name,
                        &response.files,
                        &mut sourcemap,
                        &project,
                    )?;
                }
                "rust" => {
                    let generator = RustGenerator::from_options(&options);
                    let response = generator.generate(&request);
                    write_response_files(
                        generator_name,
                        &response.files,
                        &mut sourcemap,
                        &project,
                    )?;
                }
                "python" => {
                    let generator = PythonGenerator::from_options(&options);
                    let response = generator.generate(&request);
                    write_response_files(
                        generator_name,
                        &response.files,
                        &mut sourcemap,
                        &project,
                    )?;
                }
                _ => {
                    eprintln!("Unknown generator: {}", generator_name);
                }
            }
        } else if let Some(ref plugin_name) = output_config.plugin {
            match crate::plugin::resolve_plugin(plugin_name) {
                Ok(plugin_path) => match crate::plugin::invoke_plugin(&plugin_path, &request) {
                    Ok(response) => {
                        write_response_files(
                            plugin_name,
                            &response.files,
                            &mut sourcemap,
                            &project,
                        )?;
                        for error in response.errors {
                            eprintln!("Plugin error: {}", error.message);
                        }
                    }
                    Err(e) => eprintln!("Plugin execution failed: {}", e),
                },
                Err(e) => eprintln!("Plugin resolution failed: {}", e),
            }
        }
    }

    // Write sourcemap
    // r[impl sourcemap.json]
    if !sourcemap.entries.is_empty() {
        let sourcemap_path = config.sourcemap_path(config_path);
        std::fs::write(&sourcemap_path, sourcemap.to_json()?)
            .map_err(|e| format!("writing sourcemap to {}: {}", sourcemap_path.display(), e))?;
        eprintln!("Generated: {}", sourcemap_path.display());
    }

    Ok(())
}

/// Check that the configured `path` matches what the generator expects.
/// `rust` writes one file; `typescript` and `python` write directories.
fn validate_output_path(generator: &str, path: &str) -> Result<(), String> {
    let p = std::path::Path::new(path);
    let looks_like_dir = path.ends_with('/')
        || path.ends_with(std::path::MAIN_SEPARATOR)
        || (p.extension().is_none() && !path.is_empty());
    let exists_as_dir = p.is_dir();
    let exists_as_file = p.is_file();

    match generator {
        "rust" => {
            if exists_as_dir {
                return Err(format!(
                    "path = {:?} is a directory but the rust generator emits a single .rs file. \
                     Set path to something like \"src/generated/constants.rs\".",
                    path,
                ));
            }
            if looks_like_dir && !exists_as_file {
                return Err(format!(
                    "path = {:?} looks like a directory; the rust generator emits a single .rs file. \
                     Set path to something like \"src/generated/constants.rs\".",
                    path,
                ));
            }
            Ok(())
        }
        "typescript" | "python" => {
            if exists_as_file {
                return Err(format!(
                    "path = {:?} is an existing file but the {} generator emits a directory of files. \
                     Set path to a directory (e.g. \"web/src/generated/constants/\").",
                    path, generator,
                ));
            }
            // Heuristic: a non-existent path with an extension and no trailing
            // slash probably came from the old single-file mode — surface it
            // before producing a confusing nested file like `foo.ts/limits.ts`.
            if !exists_as_dir && p.extension().is_some() && !looks_like_dir {
                return Err(format!(
                    "path = {:?} looks like a file but the {} generator emits a directory of files. \
                     Set path to a directory (e.g. \"web/src/generated/constants/\").",
                    path, generator,
                ));
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

/// Write each generated file to disk, attaching the path and generator name
/// to any I/O error so the user sees what failed.
fn write_response_files(
    generator: &str,
    files: &[crate::ir::GeneratedFile],
    sourcemap: &mut Sourcemap,
    project: &ParsedProject,
) -> Result<(), Box<dyn std::error::Error>> {
    for file in files {
        if let Some(parent) = std::path::Path::new(&file.path).parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    format!(
                        "creating output directory {} for {} generator: {}",
                        parent.display(),
                        generator,
                        e,
                    )
                })?;
            }
        }
        std::fs::write(&file.path, &file.content).map_err(|e| {
            format!(
                "writing {} (from {} generator): {}",
                file.path, generator, e,
            )
        })?;
        eprintln!("Generated: {}", file.path);
        add_sourcemap_entries(sourcemap, project, file);
    }
    Ok(())
}

// r[impl cli.generate-watch]
fn run_generate_watch(
    config_path: &PathBuf,
    input_override: Option<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    watch_tui::run(config_path.clone(), input_override)
}

fn run_skill(
    target: &str,
    output: Option<PathBuf>,
    stdout: bool,
    force: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    // The skill body is the same plain-Markdown text in both modes; the
    // `claude` target just prepends YAML frontmatter so Claude Code can
    // auto-invoke it. Keeping one source of truth avoids drift.
    const BODY: &str = include_str!("./skill.md");

    let (default_path, content) = match target {
        "claude" => (
            PathBuf::from(".claude/skills/primate/SKILL.md"),
            // YAML frontmatter for Claude Code skills. `description`
            // determines when Claude loads the skill automatically;
            // primate-flavored keywords up front so it surfaces on
            // anything `.prim`/`primate.toml`-related.
            format!(
                "---\n\
                 name: primate\n\
                 description: Use when working with primate — a DSL that generates typed constants for Rust, TypeScript, and Python from one source. Triggers on `.prim` files, `primate.toml`, or questions about the `primate` CLI. Covers setup, syntax, unit suffixes, enums, namespaces, and the always-fmt-after-edits rule.\n\
                 ---\n\n{}",
                BODY,
            ),
        ),
        // Default `agents` target: plain markdown for AGENTS.md. The
        // agents.md open standard is read by 60+ AI coding tools.
        _ => (PathBuf::from("AGENTS.md"), BODY.to_string()),
    };

    if stdout {
        print!("{}", content);
        return Ok(());
    }

    let dest = output.unwrap_or(default_path);

    if dest.exists() && !force {
        return Err(format!(
            "{} already exists. Pass --force to overwrite, --output to write \
             elsewhere, or --stdout to inspect the contents first.",
            dest.display()
        )
        .into());
    }

    if let Some(parent) = dest.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("creating directory {}: {}", parent.display(), e))?;
        }
    }
    std::fs::write(&dest, content)
        .map_err(|e| format!("writing skill to {}: {}", dest.display(), e))?;
    eprintln!("Wrote primate skill ({}) to {}", target, dest.display());
    Ok(())
}

fn run_fmt(
    config_path: &PathBuf,
    paths: Vec<PathBuf>,
    check: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    // Resolve target paths: explicit args win, otherwise fall back to the input dir.
    let targets: Vec<PathBuf> = if paths.is_empty() {
        let config = Config::load(config_path).ok();
        match config {
            Some(c) => vec![c.input],
            None => {
                eprintln!(
                    "no paths provided and no config found at {}",
                    config_path.display()
                );
                std::process::exit(2);
            }
        }
    } else {
        paths
    };

    // Expand directories to .prim files.
    let mut files: Vec<PathBuf> = Vec::new();
    for t in &targets {
        if t.is_file() {
            files.push(t.clone());
        } else if t.is_dir() {
            for entry in walkdir::WalkDir::new(t)
                .follow_links(true)
                .into_iter()
                .filter_map(|e| e.ok())
            {
                let p = entry.path();
                if p.is_file() && p.extension().and_then(|s| s.to_str()) == Some("const") {
                    files.push(p.to_path_buf());
                }
            }
        } else {
            eprintln!("path not found: {}", t.display());
            std::process::exit(2);
        }
    }

    if files.is_empty() {
        eprintln!("no .prim files to format");
        return Ok(());
    }

    let mut had_diff = false;
    let mut had_error = false;
    for path in &files {
        let original = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}: {}", path.display(), e);
                had_error = true;
                continue;
            }
        };
        match crate::formatter::format_source(&original) {
            Ok(formatted) => {
                if formatted != original {
                    had_diff = true;
                    if check {
                        eprintln!("would reformat: {}", path.display());
                    } else {
                        std::fs::write(path, &formatted)?;
                        eprintln!("formatted: {}", path.display());
                    }
                }
            }
            Err(diags) => {
                for diag in diags.diagnostics {
                    eprintln!(
                        "{}:{}:{}: error: {}",
                        path.display(),
                        diag.line,
                        diag.column,
                        diag.message
                    );
                }
                had_error = true;
            }
        }
    }

    if had_error {
        std::process::exit(1);
    }
    if check && had_diff {
        std::process::exit(1);
    }
    Ok(())
}

fn add_sourcemap_entries(
    sourcemap: &mut Sourcemap,
    project: &ParsedProject,
    generated_file: &crate::ir::GeneratedFile,
) {
    let mut symbol_to_source = HashMap::new();
    for module in &project.modules {
        for constant in &module.constants {
            symbol_to_source.insert(
                format!("{}.{}", module.namespace, constant.name),
                (
                    &constant.source.file,
                    constant.source.line,
                    constant.source.column,
                ),
            );
        }
    }
    for enum_def in &project.enums {
        symbol_to_source.insert(
            format!("{}.{}", enum_def.namespace, enum_def.name),
            (
                &enum_def.source.file,
                enum_def.source.line,
                enum_def.source.column,
            ),
        );
    }

    for mapping in &generated_file.mappings {
        if let Some((source_file, source_line, source_column)) =
            symbol_to_source.get(&mapping.symbol)
        {
            sourcemap.add_entry(SourcemapEntry {
                symbol: mapping.symbol.clone(),
                source_file: (*source_file).clone(),
                source_line: *source_line,
                source_column: *source_column,
                output_file: generated_file.path.clone(),
                output_line: mapping.line,
                output_column: mapping.column,
            });
        }
    }
}

fn print_diagnostics(diagnostics: &Diagnostics) {
    for diag in &diagnostics.diagnostics {
        let level = match diag.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Info => "info",
        };

        eprintln!(
            "{}:{}:{}: {}: [{}] {}",
            diag.file, diag.line, diag.column, level, diag.code, diag.message
        );
    }
}

pub(crate) fn toml_to_json(value: &toml::Value) -> serde_json::Value {
    match value {
        toml::Value::String(s) => serde_json::Value::String(s.clone()),
        toml::Value::Integer(i) => serde_json::Value::Number((*i).into()),
        toml::Value::Float(f) => serde_json::Number::from_f64(*f)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        toml::Value::Boolean(b) => serde_json::Value::Bool(*b),
        toml::Value::Array(arr) => serde_json::Value::Array(arr.iter().map(toml_to_json).collect()),
        toml::Value::Table(t) => {
            let map: serde_json::Map<String, serde_json::Value> = t
                .iter()
                .map(|(k, v)| (k.clone(), toml_to_json(v)))
                .collect();
            serde_json::Value::Object(map)
        }
        toml::Value::Datetime(dt) => serde_json::Value::String(dt.to_string()),
    }
}