Skip to main content

decl_lang/
cli.rs

1//! `decl check` / `decl evaluate` / `decl validate` / `decl fmt` (cli.ts). Output is byte-identical to
2//! the reference implementation's CLI so the three implementations can
3//! be diffed (tests/parity/differential.py).
4use crate::ast::DeclBody;
5use crate::checker::check_module;
6use crate::conformance::judge_corpus;
7use crate::fmt::format;
8use crate::module::{load_modules, run_universe, Bind, LoadResult, Module};
9use crate::package::{open_package_universe, verify_lock};
10use crate::render::{
11    absolute, declared_form, emit_root, emit_root_to, emits_in_pieces, layout, resolve_in,
12    Emission, Emitted, Form,
13};
14use crate::semantics::{json_str, read_json, Diag, Value};
15use crate::yaml::{is_yaml_path, read_yaml, to_json};
16use std::cell::RefCell;
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19use std::rc::Rc;
20
21fn usage() -> i32 {
22    eprintln!("usage:\n  decl --version\n  decl check <files...>\n  decl evaluate <file> [--input name=doc.(json|yaml)]... [--output name[=file|dir|-]]...\n                       [--format json|yaml] [--indent n | --pretty] [--template [root=]path]...\n  decl validate <dir>\n  decl validate <file> [--input name=doc.(json|yaml)]... [--expect-errors E1,E2]\n  decl fmt <files...> [--check]\n  decl repl [file.decl] [--input name=doc.(json|yaml)]... [--script session.txt | --script -] [--compact]\n  (check / validate accept --json: diagnostics as a JSON array on stdout)");
23    2
24}
25
26/// the module graph of an entry file inside its package universe
27/// (manifest and lock diagnostics first), as the reference CLI opens it
28pub fn open_universe(file: &str) -> LoadResult {
29    let abs = std::path::absolute(file).unwrap_or_else(|_| PathBuf::from(file));
30    let pkg = open_package_universe(&abs);
31    let mut diags: Vec<Diag> = vec![];
32    if let Some(u) = &pkg {
33        diags.extend(u.diags.clone());
34        diags.extend(verify_lock(u));
35    }
36    let r = load_modules(&abs, pkg.as_ref().map(|u| &u.resolver), None);
37    diags.extend(r.diags);
38    LoadResult {
39        modules: r.modules,
40        entry: r.entry,
41        diags,
42    }
43}
44
45fn print_diag(file: &str, d: &Diag, json: bool, collected: &mut Vec<String>) {
46    if json {
47        collected.push(d.to_json(Some(file)));
48        return;
49    }
50    let at = match &d.loc {
51        Some(l) => format!("{file}:{}:{}", l.sl + 1, l.sc + 1),
52        None => file.to_string(),
53    };
54    eprintln!(
55        "{at}: {}{}{}{}: {}",
56        d.severity,
57        d.code
58            .as_ref()
59            .map(|c| format!(" [{c}]"))
60            .unwrap_or_default(),
61        d.id.as_ref().map(|i| format!(" {i}")).unwrap_or_default(),
62        if d.path.is_empty() {
63            String::new()
64        } else {
65            format!(" at {}", d.path)
66        },
67        d.message
68    );
69}
70
71/// the documents named by `--input`, each bound to the module that
72/// declares its input (§10): `name=doc.json`; Err carries the exit code
73/// of a usage error (already printed)
74/// the documents named by --input, each bound to the module that declares
75/// its input (§10): `name=doc.json`. A usage error (bad spec, unknown input)
76/// is printed and returned as exit 2; a document that cannot be read or is
77/// not well-formed JSON is returned as one E6004 diagnostic (exit 1)
78pub fn input_binds(
79    modules: &[Rc<Module>],
80    specs: &[String],
81) -> Result<Vec<Bind>, (i32, Option<Diag>)> {
82    let doc_error = |name: &str, message: String| -> (i32, Option<Diag>) {
83        (
84            1,
85            Some(Diag {
86                severity: "error".into(),
87                id: None,
88                message,
89                path: name.to_string(),
90                code: Some("E6004".into()),
91                loc: None,
92                by: None,
93            }),
94        )
95    };
96    let mut binds = vec![];
97    for spec in specs {
98        let Some((name, file)) = spec.split_once('=') else {
99            eprintln!("--input expects name=doc.json, got {spec}");
100            return Err((2, None));
101        };
102        let Some(module) = modules
103            .iter()
104            .find(|m| m.env.inputs.borrow().contains_key(name))
105        else {
106            eprintln!("no input named {name}");
107            return Err((2, None));
108        };
109        let text = match std::fs::read_to_string(file) {
110            Ok(t) => t,
111            Err(_) => {
112                return Err(doc_error(
113                    name,
114                    format!("bound document cannot be read: {file}"),
115                ))
116            }
117        };
118        // `name=doc.yaml` is read as YAML by its extension (docs/tooling/05_render.md §2)
119        let raw = if is_yaml_path(file) {
120            match read_yaml(&text) {
121                Ok(v) => v,
122                Err(e) => {
123                    return Err(doc_error(
124                        name,
125                        format!("bound document is not well-formed YAML: {file}: {e}"),
126                    ));
127                }
128            }
129        } else {
130            match read_json(&text) {
131                Ok(v) => v,
132                Err(_) => {
133                    return Err(doc_error(
134                        name,
135                        format!("bound document is not well-formed JSON: {file}"),
136                    ));
137                }
138            }
139        };
140        binds.push(Bind {
141            module: Some(module.clone()),
142            input: name.to_string(),
143            raw,
144        });
145    }
146    Ok(binds)
147}
148
149/// `decl evaluate`: (exit code, the document for stdout, diagnostics tagged
150/// with the file each is reported against, bare stderr lines to print
151/// after them). What to emit, and where (§5.5): each `--output name[=file]`
152/// names a root — an output, or an input bound by --input or demanded
153/// through its fallback — and the file its document goes to (stdout
154/// without one); with no --output, the entry module's exported outputs, as
155/// one object keyed by name, on stdout
156/// the overrides of the declared forms: `--format`, `--indent` / `--pretty`
157/// (docs/tooling/05_render.md §3.4); `json` is the --json report
158#[derive(Debug, Clone, Default)]
159pub struct Overrides {
160    /// `--format yaml`
161    pub yaml: Option<bool>,
162    /// `--indent n`, or 2 for `--pretty`
163    pub indent: Option<usize>,
164    /// `--json`: the report carries the document itself, whatever the layout
165    pub json: bool,
166}
167
168/// `--format json|yaml`, `--indent n`, `--pretty`: the layout of every
169/// document emitted (docs/tooling/05_render.md §3.4, §4); None for a usage error
170pub fn form_overrides(flags: &HashMap<String, String>) -> Option<Overrides> {
171    let json = flags.contains_key("json");
172    let mut out = Overrides {
173        json,
174        ..Default::default()
175    };
176    if let Some(format) = flags.get("format") {
177        if format != "json" && format != "yaml" {
178            eprintln!(
179                "--format expects json or yaml, got {}",
180                if format == "true" { "nothing" } else { format }
181            );
182            return None;
183        }
184        if format == "yaml" && json {
185            eprintln!("--json reports are JSON: it cannot be combined with --format yaml");
186            return None;
187        }
188        out.yaml = Some(format == "yaml");
189    }
190    let indent = flags.get("indent");
191    if indent.is_some() && flags.contains_key("pretty") {
192        eprintln!("--indent and --pretty exclude each other");
193        return None;
194    }
195    if let Some(indent) = indent {
196        let ok = indent.len() <= 2
197            && indent.bytes().all(|b| b.is_ascii_digit())
198            && !(indent.len() == 2 && indent.starts_with('0'))
199            && indent.parse::<usize>().is_ok_and(|n| n <= 16);
200        if indent == "true" || !ok {
201            eprintln!(
202                "--indent expects an integer in 0..16, got {}",
203                if indent == "true" { "nothing" } else { indent }
204            );
205            return None;
206        }
207        out.indent = Some(indent.parse().unwrap());
208    } else if flags.contains_key("pretty") {
209        out.indent = Some(2);
210    }
211    Some(out)
212}
213
214thread_local! {
215    static ONE_SHOT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
216}
217
218/// The command line of a process that exits when the command returns (the
219/// `decl` binary). Such a process need not take apart what an evaluation
220/// built: dropping the runtime and sweeping its cycles only delays the exit,
221/// and the operating system reclaims the memory at once. `main` itself keeps
222/// the full teardown, for callers that live on.
223pub fn run_once(args: Vec<String>) -> i32 {
224    ONE_SHOT.with(|f| f.set(true));
225    main(args)
226}
227
228/// In a one-shot process, keep what an evaluation built alive to the exit: one
229/// leaked handle per owner turns every later drop into a count decrement.
230fn leave_to_process(eng: &Rc<crate::engine::Engine>, modules: &[Rc<Module>]) {
231    if !ONE_SHOT.with(std::cell::Cell::get) {
232        return;
233    }
234    std::mem::forget(Rc::clone(eng));
235    for m in modules {
236        std::mem::forget(Rc::clone(m));
237    }
238    crate::semantics::lifetime::leave_to_process();
239}
240
241/// `decl evaluate`: (exit code, the text for stdout, the diagnostics tagged
242/// with their file, the bare stderr lines that follow them); a usage error
243/// is exit 2 with its line already printed
244pub fn evaluate(
245    file: &str,
246    outputs: &[String],
247    inputs: &[String],
248    templates: &[String],
249    over: &Overrides,
250) -> (i32, Option<String>, Vec<(String, Diag)>, Vec<String>) {
251    let tag = |ds: Vec<Diag>| -> Vec<(String, Diag)> {
252        ds.into_iter().map(|d| (file.to_string(), d)).collect()
253    };
254    // what to emit, and where (§5.5, docs/tooling/05_render.md §3.2): each
255    // `--output name[=file|dir|-]` names a root and where its document goes:
256    // the file given, `-` for stdout, or, alone, the file the root's @render
257    // declares, else stdout
258    let mut targets: Vec<(String, Option<String>)> = vec![];
259    for spec in outputs {
260        let (name, dest) = match spec.split_once('=') {
261            Some((n, f)) => (n.to_string(), Some(f.to_string())),
262            None => (spec.clone(), None),
263        };
264        if name.is_empty() || dest.as_deref() == Some("") {
265            eprintln!("--output expects name or name=file, got {spec}");
266            return (2, None, vec![], vec![]);
267        }
268        targets.push((name, dest));
269    }
270    let r = open_universe(file);
271    let Some(entry) = r.entry else {
272        return (1, None, tag(r.diags), vec![]);
273    };
274    if !r.diags.is_empty() {
275        return (1, None, tag(r.diags), vec![]);
276    }
277    let checks: Vec<(String, Diag)> = r
278        .modules
279        .iter()
280        .flat_map(|m| {
281            let path = file_tag(file, Some(entry.path.as_path()), &m.path);
282            check_module(&m.decls, Some(m.env.clone()), None)
283                .into_iter()
284                .map(move |d| (path.clone(), d))
285                .collect::<Vec<_>>()
286        })
287        .collect();
288    if checks.iter().any(|(_, d)| d.severity == "error") {
289        return (1, None, checks, vec![]);
290    }
291    // each target's declared form (§3): an invalid @render is E7004 at
292    // emission and the root is not emitted; the others still are
293    let decl_of = |n: &str| {
294        r.modules
295            .iter()
296            .flat_map(|m| m.decls.iter())
297            .find(|d| matches!(&d.body, DeclBody::Output { name, .. } if name == n))
298    };
299    let forms: Vec<Result<Form, String>> = targets
300        .iter()
301        .map(|(n, _)| decl_of(n).map(declared_form).unwrap_or(Ok(Form::default())))
302        .collect();
303    let module_dirs: Vec<String> = targets
304        .iter()
305        .map(|(n, _)| {
306            let m = r
307                .modules
308                .iter()
309                .find(|m| {
310                    m.decls
311                        .iter()
312                        .any(|d| matches!(&d.body, DeclBody::Output { name, .. } if name == n))
313                })
314                .map(|m| m.path.clone())
315                .unwrap_or_else(|| entry.path.clone());
316            m.parent()
317                .map(|p| p.to_string_lossy().to_string())
318                .unwrap_or_else(|| ".".into())
319        })
320        .collect();
321    // the templates named by --template (§3.4): `[root=]path`, `-` for
322    // standard input; a root named must be emitted, and once
323    let mut tpl_flags: HashMap<String, String> = HashMap::new(); // "" names every root
324    for spec in templates {
325        let (root, path) = match spec.split_once('=') {
326            Some((r, p))
327                if !r.is_empty()
328                    && r.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
329                    && r.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') =>
330            {
331                (r.to_string(), p.to_string())
332            }
333            _ => (String::new(), spec.clone()),
334        };
335        if path.is_empty() {
336            eprintln!("--template expects [root=]path, got {spec}");
337            return (2, None, vec![], vec![]);
338        }
339        if !root.is_empty() && !targets.iter().any(|(n, _)| *n == root) {
340            eprintln!("--template {root}=: no --output {root}");
341            return (2, None, vec![], vec![]);
342        }
343        if tpl_flags.contains_key(&root) {
344            if root.is_empty() {
345                eprintln!("--template given twice");
346            } else {
347                eprintln!("--template {root}= given twice");
348            }
349            return (2, None, vec![], vec![]);
350        }
351        tpl_flags.insert(root, path);
352    }
353    // destinations (§3.2, §6): one root at most to stdout; a fan-out root
354    // goes to a directory, never to stdout
355    let fan_out = |i: usize| -> bool { matches!(&forms[i], Ok(f) if f.each.is_some()) };
356    let to_stdout = |i: usize| -> bool {
357        match &targets[i].1 {
358            Some(d) => d == "-",
359            None => matches!(&forms[i], Ok(f) if f.file.is_none()),
360        }
361    };
362    for (i, (n, dest)) in targets.iter().enumerate() {
363        if !fan_out(i) {
364            continue;
365        }
366        if dest.as_deref() == Some("-") {
367            eprintln!("--output {n}=-: a fan-out root cannot go to stdout");
368            return (2, None, vec![], vec![]);
369        }
370        if dest.is_none() && matches!(&forms[i], Ok(f) if f.file.is_none()) {
371            eprintln!(
372                "--output {n}: a fan-out root needs a directory ({n}=dir, or file in @render)"
373            );
374            return (2, None, vec![], vec![]);
375        }
376    }
377    if (0..targets.len())
378        .filter(|&i| !fan_out(i) && to_stdout(i))
379        .count()
380        > 1
381    {
382        eprintln!("--output: at most one document can go to stdout");
383        return (2, None, vec![], vec![]);
384    }
385    let binds = match input_binds(&r.modules, inputs) {
386        Ok(b) => b,
387        Err((code, diag)) => {
388            let mut all = checks;
389            all.extend(diag.into_iter().map(|d| (file.to_string(), d)));
390            return (code, None, all, vec![]);
391        }
392    };
393    let (eng, diags) = run_universe(&r.modules, &entry, binds);
394    leave_to_process(&eng, &r.modules);
395    let mut all = checks; // a warning of the checks (W0001) is reported with the run's
396    all.extend(tag(diags.clone()));
397    if diags.iter().any(|d| d.severity == "error") {
398        return (1, None, all, vec![]);
399    }
400    let names: Vec<String> = if targets.is_empty() {
401        entry
402            .decls
403            .iter()
404            .filter(|d| d.exported)
405            .filter_map(|d| match &d.body {
406                DeclBody::Output { name, .. } => Some(name.clone()),
407                _ => None,
408            })
409            .collect()
410    } else {
411        targets.iter().map(|(n, _)| n.clone()).collect()
412    };
413    let mut notes = vec![];
414    for n in &names {
415        if entry.env.root(n).is_none() {
416            notes.push(format!("no root named {n}"));
417        }
418    }
419    if !notes.is_empty() {
420        return (1, None, all.clone(), notes);
421    }
422    let doc = |n: &str| {
423        read_json(&eng.serialize(&entry.env.root(n).unwrap(), n, false))
424            .unwrap_or_else(|_| panic!("canonical JSON"))
425    };
426    let mut text = None;
427    let mut bad = false;
428    if targets.is_empty() {
429        if names.is_empty() {
430            notes.push(format!(
431                "{file}: exports no output; --output <name> selects a root"
432            ));
433        }
434        let all_docs = Value::JObj(Rc::new(names.iter().map(|n| (n.clone(), doc(n))).collect()));
435        // a --json report carries the document itself, whatever the layout
436        text = Some(if over.json {
437            to_json(&all_docs, 0) + "\n"
438        } else {
439            layout(&all_docs, over.yaml.unwrap_or(false), over.indent)
440        });
441    } else {
442        // templates are read once (§3.3): by absolute path, or standard input
443        let texts: RefCell<HashMap<String, Option<String>>> = RefCell::new(HashMap::new());
444        let read_tpl = |abs: &str| -> Option<String> {
445            if !texts.borrow().contains_key(abs) {
446                let t = std::fs::read_to_string(abs).ok();
447                texts.borrow_mut().insert(abs.to_string(), t);
448            }
449            texts.borrow().get(abs).cloned().flatten()
450        };
451        let mut stdin_text: Option<String> = None;
452        for (i, (n, dest)) in targets.iter().enumerate() {
453            let form = match &forms[i] {
454                Ok(f) => f.clone(),
455                Err(m) => {
456                    all.push((
457                        file.to_string(),
458                        Diag::error(m.clone(), n.clone(), Some("E7004")),
459                    ));
460                    bad = true;
461                    continue;
462                }
463            };
464            // the template: the override, else the declared one, relative to the module's directory
465            let given = tpl_flags.get(n).or_else(|| tpl_flags.get(""));
466            let template: Option<(String, String, String)> = match given {
467                Some(g) if g == "-" => {
468                    if stdin_text.is_none() {
469                        let mut t = String::new();
470                        if std::io::Read::read_to_string(&mut std::io::stdin(), &mut t).is_err() {
471                            all.push((
472                                "-".to_string(),
473                                Diag::error("template cannot be read", n.clone(), Some("E7003")),
474                            ));
475                            bad = true;
476                            continue;
477                        }
478                        stdin_text = Some(t);
479                    }
480                    let cwd = std::env::current_dir()
481                        .map(|p| p.to_string_lossy().to_string())
482                        .unwrap_or_else(|_| ".".into());
483                    Some(("-".to_string(), stdin_text.clone().unwrap(), cwd))
484                }
485                Some(g) => {
486                    let abs = absolute(g);
487                    match read_tpl(&abs) {
488                        Some(t) => Some((g.clone(), t, parent_dir(&abs))),
489                        None => {
490                            all.push((
491                                g.clone(),
492                                Diag::error("template cannot be read", n.clone(), Some("E7003")),
493                            ));
494                            bad = true;
495                            continue;
496                        }
497                    }
498                }
499                None => match &form.template {
500                    Some(t) => {
501                        let abs = resolve_in(&module_dirs[i], t);
502                        match read_tpl(&abs) {
503                            Some(text) => Some((t.clone(), text, parent_dir(&abs))),
504                            None => {
505                                all.push((
506                                    t.clone(),
507                                    Diag::error(
508                                        "template cannot be read",
509                                        n.clone(),
510                                        Some("E7003"),
511                                    ),
512                                ));
513                                bad = true;
514                                continue;
515                            }
516                        }
517                    }
518                    None => None,
519                },
520            };
521            let has_template = template.is_some();
522            let emission = Emission {
523                eng: eng.clone(),
524                menv: entry.env.clone(),
525                root_name: n.clone(),
526                value: entry.env.root(n).unwrap(),
527                form: form.clone(),
528                yaml: over.yaml,
529                indent: over.indent,
530                template,
531                read_template: &read_tpl,
532            };
533            let dest = match dest {
534                Some(d) if d == "-" => None,
535                Some(d) => Some(d.clone()),
536                None => form.file.clone(),
537            };
538            // A compact JSON document bound for a file goes there in pieces: a
539            // large one is never held whole beside the universe it came from.
540            if let Some(path) = dest.as_ref().filter(|_| emits_in_pieces(&emission)) {
541                if let Some(dir) = std::path::Path::new(path).parent() {
542                    let _ = std::fs::create_dir_all(dir);
543                }
544                let written =
545                    std::fs::File::create(path).and_then(|mut to| emit_root_to(&emission, &mut to));
546                if written.is_err() {
547                    notes.push(format!("cannot write {path}"));
548                    return (1, None, all.clone(), notes);
549                }
550                continue;
551            }
552            let em = match emit_root(&emission) {
553                Ok(e) => e,
554                Err(e) => {
555                    all.push((e.file.clone().unwrap_or_else(|| file.to_string()), e.diag()));
556                    bad = true;
557                    continue;
558                }
559            };
560            match em {
561                Emitted::Many(files) => {
562                    // a fan-out's files, in element order, under the directory
563                    let dir = dest.unwrap();
564                    for (rel, body) in files {
565                        let path = absolute(&format!("{dir}/{rel}"));
566                        if let Some(d) = std::path::Path::new(&path).parent() {
567                            let _ = std::fs::create_dir_all(d);
568                        }
569                        if std::fs::write(&path, body).is_err() {
570                            notes.push(format!("cannot write {path}"));
571                            return (1, None, all.clone(), notes);
572                        }
573                    }
574                }
575                Emitted::One(body) => match dest {
576                    None => {
577                        // the report's value: the document itself, or a template's text as a string
578                        text = Some(if over.json {
579                            if has_template {
580                                json_str(&body) + "\n"
581                            } else {
582                                to_json(&doc(n), 0) + "\n"
583                            }
584                        } else {
585                            body
586                        })
587                    }
588                    Some(path) => {
589                        if let Some(dir) = std::path::Path::new(&path).parent() {
590                            let _ = std::fs::create_dir_all(dir);
591                        }
592                        if std::fs::write(&path, body).is_err() {
593                            notes.push(format!("cannot write {path}"));
594                            return (1, None, all.clone(), notes);
595                        }
596                    }
597                },
598            }
599        }
600    }
601    (if bad { 1 } else { 0 }, text, all.clone(), notes)
602}
603
604fn parent_dir(p: &str) -> String {
605    std::path::Path::new(p)
606        .parent()
607        .map(|d| d.to_string_lossy().to_string())
608        .unwrap_or_else(|| ".".into())
609}
610
611/// single-file validation, module-aware like `check` and `evaluate`: load
612/// the universe, check every module, then evaluate with the `--input`
613/// documents bound (none bound is fine: fallbacks apply). Diagnostics come
614/// tagged with the file each is reported against; Err carries a usage exit
615/// code as a negative
616pub fn validate_file(file: &str, inputs: &[String]) -> Result<Vec<(String, Diag)>, i64> {
617    let r = open_universe(file);
618    let mut diags: Vec<(String, Diag)> = r
619        .diags
620        .iter()
621        .map(|d| (file.to_string(), d.clone()))
622        .collect();
623    let Some(entry) = r.entry else {
624        return Ok(diags);
625    };
626    if !diags.is_empty() {
627        return Ok(diags);
628    }
629    let checks: Vec<(String, Diag)> = r
630        .modules
631        .iter()
632        .flat_map(|m| {
633            let path = file_tag(file, Some(entry.path.as_path()), &m.path);
634            check_module(&m.decls, Some(m.env.clone()), None)
635                .into_iter()
636                .map(move |d| (path.clone(), d))
637                .collect::<Vec<_>>()
638        })
639        .collect();
640    if checks.iter().any(|(_, d)| d.severity == "error") {
641        return Ok(checks);
642    }
643    diags.extend(checks); // a warning (W0001) is reported beside the run's diagnostics
644    let binds = match input_binds(&r.modules, inputs) {
645        Ok(b) => b,
646        Err((_, Some(d))) => {
647            diags.push((file.to_string(), d));
648            return Ok(diags);
649        }
650        Err((code, None)) => return Err(-(code as i64)),
651    };
652    let (eng, run) = run_universe(&r.modules, &entry, binds);
653    leave_to_process(&eng, &r.modules);
654    diags.extend(run.into_iter().map(|d| (file.to_string(), d)));
655    Ok(diags)
656}
657
658/// `decl check`: load each entry (following imports), report load
659/// diagnostics and every module's static findings, tagged with their file
660pub fn check_files(paths: &[String]) -> Vec<(String, Diag)> {
661    let mut out = vec![];
662    for f in paths {
663        let r = open_universe(f);
664        out.extend(r.diags.into_iter().map(|d| (f.clone(), d)));
665        for m in &r.modules {
666            let path = file_tag(f, r.entry.as_ref().map(|e| e.path.as_path()), &m.path);
667            out.extend(
668                check_module(&m.decls, Some(m.env.clone()), None)
669                    .into_iter()
670                    .map(|d| (path.clone(), d)),
671            );
672        }
673    }
674    out
675}
676
677/// the file a diagnostic is reported against: the entry module by the path
678/// given on the command line, any other module by its absolute path
679pub fn file_tag(given: &str, entry: Option<&Path>, module: &Path) -> String {
680    if entry == Some(module) {
681        given.to_string()
682    } else {
683        module.display().to_string()
684    }
685}
686
687/// the command line: returns the process exit code
688pub fn main(args: Vec<String>) -> i32 {
689    let _lifetime = crate::semantics::lifetime::CommandGuard;
690    let Some(cmd) = args.first().cloned() else {
691        return usage();
692    };
693    // `decl --version`: the package's version, the same string on every registry
694    if cmd == "--version" {
695        println!("decl {}", env!("CARGO_PKG_VERSION"));
696        return 0;
697    }
698    // `decl repl`: its own argument syntax (docs/tooling/02_repl.md)
699    if cmd == "repl" {
700        return crate::repl::run_repl(args[1..].to_vec());
701    }
702    let mut flags: HashMap<String, String> = HashMap::new();
703    let mut input_flags: Vec<String> = vec![]; // --input name=doc.json, repeatable
704    let mut output_flags: Vec<String> = vec![]; // --output name[=file|dir|-], repeatable
705    let mut template_flags: Vec<String> = vec![]; // --template [root=]path, repeatable
706    let mut pos: Vec<String> = vec![];
707    let mut i = 1;
708    while i < args.len() {
709        let a = &args[i];
710        if let Some(name) = a.strip_prefix("--") {
711            if [
712                "output",
713                "input",
714                "expect-errors",
715                "format",
716                "indent",
717                "template",
718            ]
719            .contains(&name)
720                && i + 1 < args.len()
721                && !args[i + 1].starts_with("--")
722            {
723                if name == "input" {
724                    input_flags.push(args[i + 1].clone());
725                } else if name == "output" {
726                    output_flags.push(args[i + 1].clone());
727                } else if name == "template" {
728                    template_flags.push(args[i + 1].clone());
729                } else {
730                    flags.insert(name.to_string(), args[i + 1].clone());
731                }
732                i += 2;
733                continue;
734            }
735            flags.insert(name.to_string(), "true".into());
736        } else {
737            pos.push(a.clone());
738        }
739        i += 1;
740    }
741    let json = flags.contains_key("json");
742    let mut collected: Vec<String> = vec![];
743    match cmd.as_str() {
744        "check" => {
745            if pos.is_empty() {
746                return usage();
747            }
748            let diags = check_files(&pos);
749            for (file, d) in &diags {
750                print_diag(file, d, json, &mut collected);
751            }
752            if diags.is_empty() {
753                eprintln!("ok: {} entry file(s) check clean", pos.len());
754            }
755            if json {
756                println!("[{}]", collected.join(","));
757            }
758            if diags.iter().any(|(_, d)| d.severity == "error") {
759                1 // a warning (W0001) is reported, not a failure
760            } else {
761                0
762            }
763        }
764        "evaluate" => {
765            let Some(f) = pos.first() else { return usage() };
766            let Some(over) = form_overrides(&flags) else {
767                return 2;
768            };
769            let (code, text, diags, notes) =
770                evaluate(f, &output_flags, &input_flags, &template_flags, &over);
771            if code == 2 {
772                return 2; // a usage error: already printed, no report
773            }
774            for (file, d) in &diags {
775                print_diag(file, d, json, &mut collected);
776            }
777            for n in &notes {
778                eprintln!("{n}");
779            }
780            if json {
781                println!(
782                    "{{\"ok\":{},\"value\":{},\"diagnostics\":[{}]}}",
783                    code == 0,
784                    text.as_deref().map(str::trim_end).unwrap_or("null"),
785                    collected.join(",")
786                );
787            } else if let Some(t) = text {
788                print!("{t}");
789            }
790            code
791        }
792        "validate" => {
793            let Some(target) = pos.first() else {
794                return usage();
795            };
796            if flags.get("expect-errors").map(String::as_str) == Some("true") {
797                eprintln!("--expect-errors expects a list of codes: E1,E2");
798                return 2;
799            }
800            let tp = Path::new(target);
801            if tp.is_dir() {
802                let abs = std::path::absolute(tp).unwrap_or_else(|_| tp.to_path_buf());
803                let (mut ok, mut fail) = (0, 0);
804                for v in judge_corpus(&abs) {
805                    if v.ok {
806                        ok += 1;
807                    } else {
808                        fail += 1;
809                        eprintln!("FAIL {} {}", v.file.display(), v.detail);
810                    }
811                }
812                eprintln!("{ok} ok, {fail} failed");
813                if fail > 0 {
814                    1
815                } else {
816                    0
817                }
818            } else {
819                let diags = match validate_file(target, &input_flags) {
820                    Ok(d) => d,
821                    Err(n) => return (-n) as i32,
822                };
823                for (file, d) in &diags {
824                    print_diag(file, d, json, &mut collected);
825                }
826                if json {
827                    println!("[{}]", collected.join(","));
828                }
829                let err_codes: Vec<String> = diags
830                    .iter()
831                    .filter(|(_, d)| d.severity == "error")
832                    .map(|(_, d)| d.code.clone().unwrap_or_default())
833                    .collect();
834                if let Some(expect) = flags.get("expect-errors") {
835                    let want: Vec<String> = expect
836                        .split(',')
837                        .map(|w| w.trim().to_string())
838                        .filter(|w| !w.is_empty())
839                        .collect();
840                    let missing: Vec<&String> =
841                        want.iter().filter(|w| !err_codes.contains(w)).collect();
842                    let extra: Vec<&String> =
843                        err_codes.iter().filter(|c| !want.contains(c)).collect();
844                    if !missing.is_empty() || !extra.is_empty() {
845                        if !missing.is_empty() {
846                            eprintln!(
847                                "expected error(s) not reported: {}",
848                                missing
849                                    .iter()
850                                    .map(|s| s.as_str())
851                                    .collect::<Vec<_>>()
852                                    .join(", ")
853                            );
854                        }
855                        if !extra.is_empty() {
856                            eprintln!(
857                                "unexpected error(s): {}",
858                                extra
859                                    .iter()
860                                    .map(|s| s.as_str())
861                                    .collect::<Vec<_>>()
862                                    .join(", ")
863                            );
864                        }
865                        return 1;
866                    }
867                    eprintln!(
868                        "ok: expected errors reported ({})",
869                        if want.is_empty() {
870                            "none".to_string()
871                        } else {
872                            want.join(", ")
873                        }
874                    );
875                    return 0;
876                }
877                if err_codes.is_empty() {
878                    0
879                } else {
880                    1
881                }
882            }
883        }
884        "fmt" => {
885            if pos.is_empty() {
886                return usage();
887            }
888            let (mut changed, mut bad) = (0, 0);
889            for f in &pos {
890                let Ok(src) = std::fs::read_to_string(f) else {
891                    eprintln!("{f}: cannot be read");
892                    bad += 1;
893                    continue;
894                };
895                let out = match format(&src) {
896                    Ok(o) => o,
897                    Err(e) => {
898                        eprintln!("{f}: {e}");
899                        bad += 1;
900                        continue;
901                    }
902                };
903                if out != src {
904                    changed += 1;
905                    if flags.contains_key("check") {
906                        eprintln!("would reformat {f}");
907                    } else {
908                        let _ = std::fs::write(f, out);
909                        eprintln!("reformatted {f}");
910                    }
911                }
912            }
913            if bad > 0 || (flags.contains_key("check") && changed > 0) {
914                1
915            } else {
916                0
917            }
918        }
919        _ => usage(),
920    }
921}