Skip to main content

acl_core/
idl.rs

1//! IDL — Interface Definition Language for ACL vocabularies (spec §18).
2//!
3//! `.acl` files declare namespaced predicates and typed actions; `aclc`
4//! parses, type-checks, pretty-prints and generates code stubs.
5//!
6//! Grammar (line-based):
7//! ```text
8//! namespace fs v1;
9//! type Path = string;
10//! /// doc comment attached to next decl
11//! predicate file_exists(path: Path) -> bool;
12//! action text_reverse(text: string) -> string;
13//! ```
14//! Full name of a decl = `<namespace>.<local>` (e.g. `fs.file_exists`).
15
16use crate::cl::CommitmentStatus;
17use std::collections::BTreeMap;
18
19pub const PRIMITIVES: &[&str] = &["string", "int", "float", "bool", "bytes", "timestamp", "any"];
20
21#[derive(Debug, Clone, PartialEq)]
22pub struct Param {
23    pub name: String,
24    pub ty: String,
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub struct IdlFile {
29    pub namespace: String,
30    pub version: u32,
31    pub decls: Vec<Decl>,
32}
33
34#[derive(Debug)]
35pub struct IdlError {
36    pub line: usize,
37    pub message: String,
38}
39
40impl std::fmt::Display for IdlError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(f, "line {}: {}", self.line, self.message)
43    }
44}
45
46/// §31: deprecation metadata for a declaration.
47#[derive(Debug, Clone, PartialEq)]
48pub struct Deprecation {
49    pub reason: String,
50    pub since: String, // vocab version, e.g. "v1"
51}
52
53/// Parse a `.acl` source file.
54pub fn parse(src: &str) -> Result<IdlFile, Vec<IdlError>> {
55    struct WfWip {
56        local: String,
57        #[allow(dead_code)]
58        params: Vec<Param>,
59        ret: Option<String>,
60        steps: Vec<Step>,
61        cur_parallel: Option<Vec<String>>,
62    }
63    let mut wf_wip: Option<WfWip> = None;
64    macro_rules! wf_mut {
65        () => { wf_wip.as_mut().unwrap() };
66    }
67
68    let mut errors = Vec::new();
69    let mut namespace: Option<(String, u32)> = None;
70    let mut decls = Vec::new();
71    let mut doc: Option<String> = None;
72    let mut deprecation: Option<Deprecation> = None;
73    let namespace_version = namespace
74        .as_ref()
75        .map(|(_, v)| format!("v{}", v))
76        .unwrap_or_else(|| "v1".to_string());
77
78    for (idx, raw) in src.lines().enumerate() {
79        let line_no = idx + 1;
80        // doc comments MUST be detected before the plain-comment strip
81        // (a "///" line starts with "//" and would otherwise be eaten)
82        // §31: @deprecated("reason") annotation line before a decl
83        if raw.trim_start().starts_with("@deprecated(") {
84            let inner = raw.trim_start().trim_start_matches("@deprecated(").trim_end_matches(")");
85            deprecation = Some(Deprecation {
86                reason: inner.to_string(),
87                since: format!("v{}", 1), // refined below from namespace version
88            });
89            continue;
90        }
91        if raw.trim_start().starts_with("///") {
92            let text = raw.trim_start()[3..].trim().to_string();
93            doc = Some(match doc {
94                Some(d) => format!("{d}\n{text}"),
95                None => text,
96            });
97            continue;
98        }
99        let line = match raw.find("//") {
100            Some(i) => &raw[..i],
101            None => raw,
102        }
103        .trim();
104        if line.is_empty() {
105            continue;
106        }
107        if let Some(rest) = line.strip_prefix("///") {
108            let text = rest.trim().to_string();
109            doc = Some(match doc {
110                Some(d) => format!("{d}\n{text}"),
111                None => text,
112            });
113            continue;
114        }
115        if let Some(rest) = line.strip_prefix("namespace ") {
116            let body = rest.trim_end_matches(';').trim();
117            let mut parts = body.split_whitespace();
118            let ns = parts.next().unwrap_or_default().to_string();
119            let ver = parts
120                .next()
121                .and_then(|v| v.strip_prefix('v'))
122                .and_then(|v| v.parse().ok());
123            if ns.is_empty() || !ns.contains('.') || ver.is_none() || parts.next().is_some() {
124                errors.push(IdlError { line: line_no, message: format!("bad namespace decl: '{line}' (want 'namespace a.b v1;')") });
125                continue;
126            }
127            if namespace.is_some() {
128                errors.push(IdlError { line: line_no, message: "duplicate namespace declaration".into() });
129                continue;
130            }
131            namespace = Some((ns, ver.unwrap()));
132            doc = None; // doc before namespace is ignored
133            continue;
134        }
135        if let Some(rest) = line.strip_prefix("type ") {
136            let body = rest.trim_end_matches(';').trim();
137            match body.split_once('=') {
138                Some((alias, ty)) => {
139                    // aliases register as decls for typecheck; represented as Predicate-less
140                    let alias = alias.trim();
141                    let ty = ty.trim();
142                    if !valid_type_name(alias) {
143                        errors.push(IdlError { line: line_no, message: format!("bad alias name '{alias}'") });
144                    }
145                    // alias recorded via decls for checking; stored as Action-like marker
146                    decls.push(Decl::Alias { local: alias.to_string(), target: ty.to_string() });
147                }
148                None => errors.push(IdlError { line: line_no, message: format!("bad type decl: '{line}'") }),
149            }
150            doc = None;
151            continue;
152        }
153        // workflow block handling (multi-line)
154        if wf_wip.is_some() {
155            if line == "}" {
156                // close parallel group if open; otherwise close the workflow
157                if let Some(par) = wf_wip.as_mut().unwrap().cur_parallel.take() {
158                    if par.is_empty() {
159                        errors.push(IdlError { line: line_no, message: "empty parallel group".into() });
160                    } else {
161                        wf_wip.as_mut().unwrap().steps.push(Step::Parallel(par));
162                    }
163                } else {
164                    let w = wf_wip.take().unwrap();
165                    decls.push(Decl::Workflow {
166                        local: w.local,
167                        params: w.params,
168                        steps: w.steps,
169                        ret: w.ret,
170                        doc: doc.take(),
171                    });
172                }
173                continue;
174            }
175            if let Some(rest) = line.strip_prefix("parallel {") {
176                let _ = rest;
177                if wf_wip.as_mut().unwrap().cur_parallel.is_some() {
178                    errors.push(IdlError { line: line_no, message: "nested parallel not allowed".into() });
179                } else {
180                    wf_wip.as_mut().unwrap().cur_parallel = Some(Vec::new());
181                }
182                continue;
183            }
184            if let Some(rest) = line.strip_prefix("do ") {
185                let name = rest.trim_end_matches(';').trim().to_string();
186                if name.is_empty() {
187                    errors.push(IdlError { line: line_no, message: "empty 'do' target".into() });
188                } else if let Some(par) = wf_wip.as_mut().unwrap().cur_parallel.as_mut() {
189                    par.push(name);
190                } else {
191                    wf_wip.as_mut().unwrap().steps.push(Step::Do(name));
192                }
193                continue;
194            }
195            errors.push(IdlError {
196                line: line_no,
197                message: format!("unrecognized line inside workflow: '{line}'"),
198            });
199            continue;
200        }
201        if line.starts_with("workflow ") {
202            let body = line.trim_end_matches('{').trim();
203            let body = body.strip_prefix("workflow ").unwrap_or(body).trim();
204            let (sig, ret) = match body.rsplit_once("->") {
205                Some((h, r)) => (h.trim(), Some(r.trim().to_string())),
206                None => (body, None),
207            };
208            let open = match sig.find('(') {
209                Some(o) => o,
210                None => {
211                    errors.push(IdlError { line: line_no, message: format!("bad workflow decl: '{line}'") });
212                    doc = None;
213                    continue;
214                }
215            };
216            let local = sig[..open].trim().to_string();
217            let inner = sig[open + 1..].trim_end();
218            let inner = inner.strip_suffix(')').unwrap_or(inner).trim();
219            let mut params = Vec::new();
220            let mut bad = false;
221            if !inner.is_empty() {
222                for pr in inner.split(',') {
223                    match pr.trim().split_once(':') {
224                        Some((pn, pt)) => params.push(Param {
225                            name: pn.trim().to_string(),
226                            ty: pt.trim().to_string(),
227                        }),
228                        None => {
229                            errors.push(IdlError {
230                                line: line_no,
231                                message: format!("bad workflow param '{pr}'"),
232                            });
233                            bad = true;
234                        }
235                    }
236                }
237            }
238            if !bad {
239                wf_wip = Some(WfWip {
240                    local,
241                    params,
242                    ret,
243                    steps: Vec::new(),
244                    cur_parallel: None,
245                });
246            } else {
247                doc = None;
248            }
249            continue;
250        }
251        let kind = if line.starts_with("predicate ") {
252            Some(("predicate", "predicate "))
253        } else if line.starts_with("action ") {
254            Some(("action", "action "))
255        } else {
256            None
257        };
258        if let Some((kind_name, prefix)) = kind {
259            match parse_signature(&line[prefix.len()..], line_no) {
260                Ok((local, params, ret)) => {
261                    let dep = deprecation.take().map(|mut d| { d.since = namespace_version.clone(); d });
262                    let d = if kind_name == "predicate" {
263                        Decl::Predicate { local, params, ret, doc: doc.take(), deprecation: dep }
264                    } else {
265                        Decl::Action { local, params, ret, doc: doc.take(), deprecation: dep }
266                    };
267                    decls.push(d);
268                    continue;
269                }
270                Err(e) => {
271                    errors.push(e);
272                    doc = None;
273                    continue;
274                }
275            }
276        }
277        errors.push(IdlError { line: line_no, message: format!("unrecognized line: '{line}'") });
278        doc = None;
279    }
280
281    match namespace {
282        None => errors.push(IdlError { line: 0, message: "missing namespace declaration".into() }),
283        Some((ns, v)) => {
284            if !errors.is_empty() {
285                return Err(errors);
286            }
287            return Ok(IdlFile { namespace: ns, version: v, decls });
288        }
289    }
290    Err(errors)
291}
292
293#[derive(Debug, Clone, PartialEq)]
294pub enum Decl {
295    Predicate { local: String, params: Vec<Param>, ret: String, doc: Option<String>, deprecation: Option<Deprecation> },
296    Action { local: String, params: Vec<Param>, ret: String, doc: Option<String>, deprecation: Option<Deprecation> },
297    Alias { local: String, target: String },
298    /// §20: ordered plan of action groups; groups run in sequence,
299    /// actions inside a group run in parallel.
300    Workflow { local: String, params: Vec<Param>, steps: Vec<Step>, ret: Option<String>, doc: Option<String> },
301}
302
303/// One step of a workflow: a single action, or a parallel group of actions.
304#[derive(Debug, Clone, PartialEq)]
305pub enum Step {
306    Do(String),
307    Parallel(Vec<String>),
308}
309
310pub(crate) fn valid_type_name(s: &str) -> bool {
311    !s.is_empty()
312        && s.chars().next().map(|c| c.is_ascii_uppercase()).unwrap_or(false)
313        && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
314}
315
316/// Parse `name(a: T, b: U) -> R` (no kind prefix).
317fn parse_signature(body: &str, line_no: usize) -> Result<(String, Vec<Param>, String), IdlError> {
318    let bad = |m: String| IdlError { line: line_no, message: m };
319    let (head, ret) = body
320        .split_once("->")
321        .ok_or_else(|| bad(format!("missing '->' in: {body}")))?;
322    let ret = ret.trim().trim_end_matches(';').trim().to_string();
323    let open = head.find('(').ok_or_else(|| bad("missing '('".into()))?;
324    let name = head[..open].trim().to_string();
325    if !name.chars().next().map(|c| c.is_ascii_lowercase()).unwrap_or(false)
326        || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
327    {
328        return Err(bad(format!("bad decl name '{name}'")));
329    }
330    // strip exactly ONE closing paren (trim_end_matches would eat the
331    // param-list paren of single-param decls: "(path: Path)" -> "path: Path)")
332    let inner_raw = head[open + 1..].trim_end();
333    let inner = inner_raw.strip_suffix(')').unwrap_or(inner_raw).trim();
334    let mut params = Vec::new();
335    if !inner.is_empty() {
336        for p in inner.split(',') {
337            let p = p.trim();
338            let (pname, pty) = p
339                .split_once(':')
340                .ok_or_else(|| bad(format!("bad param '{p}' (want 'name: Type')")))?;
341            params.push(Param { name: pname.trim().to_string(), ty: pty.trim().to_string() });
342        }
343    }
344    Ok((name, params, ret))
345}
346
347/// Type-check: all referenced types must be primitives or declared aliases;
348/// full names must be unique; predicate full name must not collide with
349/// action full name. Returns fully-qualified names.
350pub fn typecheck(file: &IdlFile) -> Result<Vec<String>, Vec<IdlError>> {
351    let mut errors = Vec::new();
352    let mut aliases: BTreeMap<String, String> = BTreeMap::new();
353    for d in &file.decls {
354        if let Decl::Alias { local, target } = d {
355            if aliases.insert(local.clone(), target.clone()).is_some() {
356                errors.push(IdlError { line: 0, message: format!("duplicate alias '{local}'") });
357            }
358        }
359    }
360    let check_type = |ty: &str| aliases.contains_key(ty) || PRIMITIVES.contains(&ty);
361    let mut seen: BTreeMap<String, &str> = BTreeMap::new();
362    let mut full_names = Vec::new();
363    for (idx, d) in file.decls.iter().enumerate() {
364        let (local, params, ret, is_action) = match d {
365            Decl::Predicate { local, params, ret, .. } => (local, params, ret, false),
366            Decl::Action { local, params, ret, .. } => (local, params, ret, true),
367            Decl::Alias { .. } => continue,
368            Decl::Workflow { local, params, ret, steps, .. } => {
369                let full = format!("{}.{}", file.namespace, local);
370                if let Some(prev_kind) = seen.insert(full.clone(), "workflow") {
371                    errors.push(IdlError {
372                        line: 0,
373                        message: format!("duplicate full name '{full}' (already a {prev_kind})"),
374                    });
375                }
376                for p in params {
377                    if !check_type(&p.ty) {
378                        errors.push(IdlError {
379                            line: 0,
380                            message: format!("{full}: unknown type '{}' for param '{}'", p.ty, p.name),
381                        });
382                    }
383                }
384                if let Some(r) = ret {
385                    if !check_type(r) {
386                        errors.push(IdlError { line: 0, message: format!("{full}: unknown return type '{r}'") });
387                    }
388                }
389                for st in steps {
390                    let targets: Vec<&String> = match st {
391                        Step::Do(n) => vec![n],
392                        Step::Parallel(g) => g.iter().collect(),
393                    };
394                    for t in targets {
395                        let ok = file.decls.iter().any(|d2| {
396                            matches!(d2, Decl::Action { local: l, .. } if format!("{}.{}", file.namespace, l) == *t)
397                        });
398                        if !ok {
399                            errors.push(IdlError {
400                                line: 0,
401                                message: format!("workflow '{full}': 'do {t}' is not a declared action"),
402                            });
403                        }
404                    }
405                }
406                full_names.push(full);
407                continue;
408            }
409        };
410        let full = format!("{}.{}", file.namespace, local);
411        if let Some(prev_kind) = seen.insert(full.clone(), if is_action { "action" } else { "predicate" }) {
412            errors.push(IdlError {
413                line: 0,
414                message: format!("duplicate full name '{full}' (already a {prev_kind})"),
415            });
416        }
417        for p in params {
418            if !check_type(&p.ty) {
419                errors.push(IdlError {
420                    line: 0,
421                    message: format!("{full}: unknown type '{}' for param '{}'", p.ty, p.name),
422                });
423            }
424        }
425        if !check_type(ret) {
426            errors.push(IdlError { line: 0, message: format!("{full}: unknown return type '{ret}'") });
427        }
428        full_names.push(full);
429        let _ = idx;
430    }
431    if errors.is_empty() {
432        Ok(full_names)
433    } else {
434        Err(errors)
435    }
436}
437
438/// Canonical pretty-print (also the human-readable surface syntax).
439/// Declarations keep file order; params aligned; doc comments preserved.
440pub fn pretty(file: &IdlFile) -> String {
441    let mut out = format!("namespace {} v{};\n", file.namespace, file.version);
442    let mut current_doc: Option<String> = None;
443    for d in &file.decls {
444        let (kind, local, params, ret, doc, _dep) = match d {
445            Decl::Predicate { local, params, ret, doc, deprecation } => ("predicate", local, params, ret, doc, deprecation),
446            Decl::Action { local, params, ret, doc, deprecation } => ("action", local, params, ret, doc, deprecation),
447            Decl::Alias { local, target } => {
448                out.push_str(&format!("\ntype {local} = {target};\n"));
449                continue;
450            }
451            Decl::Workflow { local, params, steps, ret, doc } => {
452                if doc.is_some() && doc != &current_doc {
453                    out.push('\n');
454                    for l in doc.as_ref().unwrap().lines() {
455                        out.push_str(&format!("/// {l}\n"));
456                    }
457                }
458                current_doc = doc.clone();
459                let ps = params
460                    .iter()
461                    .map(|p| format!("{}: {}", p.name, p.ty))
462                    .collect::<Vec<_>>()
463                    .join(", ");
464                let ret_s = ret.as_ref().map(|r| format!(" -> {r}")).unwrap_or_default();
465                out.push_str(&format!("\nworkflow {local}({ps}){ret_s} {{\n"));
466                for st in steps {
467                    match st {
468                        Step::Do(n) => out.push_str(&format!("  do {n};\n")),
469                        Step::Parallel(g) => {
470                            out.push_str("  parallel {\n");
471                            for n in g {
472                                out.push_str(&format!("    do {n};\n"));
473                            }
474                            out.push_str("  }\n");
475                        }
476                    }
477                }
478                out.push_str("}\n");
479                continue;
480            }
481        };
482        if doc.is_some() && doc != &current_doc {
483            out.push('\n');
484            for l in doc.as_ref().unwrap().lines() {
485                out.push_str(&format!("/// {l}\n"));
486            }
487        }
488        current_doc = doc.clone();
489        let ps = params
490            .iter()
491            .map(|p| format!("{}: {}", p.name, p.ty))
492            .collect::<Vec<_>>()
493            .join(", ");
494        out.push_str(&format!("{kind} {local}({ps}) -> {ret};\n"));
495    }
496    out
497}
498
499/// Generate Rust builder stubs for a vocabulary.
500pub fn gen_rust(file: &IdlFile) -> String {
501    let mut out = format!(
502        "// Generated by aclc from namespace {} v{} — do not edit.\nuse acl_core::cl::{{ClExpr, ClAction, CommitmentStatus}};\npub const NAMESPACE: &str = \"{}\";\npub const VERSION: u32 = {};\n\n",
503        file.namespace, file.version, file.namespace, file.version
504    );
505    for d in &file.decls {
506        match d {
507            Decl::Predicate { local, params, .. } => {
508                let full = format!("{}.{}", file.namespace, local);
509                let args = params
510                    .iter()
511                    .map(|p| format!("(\"{}\", serde_json::json!({})),", p.name, p.name))
512                    .collect::<Vec<_>>()
513                    .join(" ");
514                out.push_str(&format!(
515                    "pub fn fact_{local}({}) -> ClExpr {{ ClExpr::fact(\"{full}\", serde_json::json!([{}])) }}\n",
516                    params.iter().map(|p| format!("{}: serde_json::Value", p.name)).collect::<Vec<_>>().join(", "),
517                    args
518                ));
519            }
520            Decl::Action { local, params, .. } => {
521                let full = format!("{}.{}", file.namespace, local);
522                let params_obj = params
523                    .iter()
524                    .map(|p| format!("\"{}\": serde_json::json!({})", p.name, p.name))
525                    .collect::<Vec<_>>()
526                    .join(", ");
527                out.push_str(&format!(
528                    "pub fn action_{local}({}) -> ClExpr {{ ClExpr::Action {{ name: \"{full}\".into(), params: serde_json::json!({{{params_obj}}}), result_schema: None }} }}\n",
529                    params.iter().map(|p| format!("{}: serde_json::Value", p.name)).collect::<Vec<_>>().join(", ")
530                ));
531            }
532            Decl::Alias { .. } => {}
533            Decl::Workflow { local, steps, .. } => {
534                let groups: Vec<String> = steps
535                    .iter()
536                    .map(|st| match st {
537                        Step::Do(n) => format!("vec![\"{n}\"]"),
538                        Step::Parallel(g) => format!(
539                            "vec![{}]",
540                            g.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", ")
541                        ),
542                    })
543                    .collect();
544                out.push_str(&format!(
545                    "pub fn plan_{local}() -> Vec<Vec<&'static str>> {{ vec![{}] }}\n",
546                    groups.join(", ")
547                ));
548            }
549        }
550    }
551    let _ = CommitmentStatus::Proposed;
552    out
553}
554
555/// Generate Python builder stubs.
556pub fn gen_py(file: &IdlFile) -> String {
557    let mut out = format!(
558        "# Generated by aclc from namespace {} v{} — do not edit.\nNAMESPACE = \"{}\"\nVERSION = {}\n\n",
559        file.namespace, file.version, file.namespace, file.version
560    );
561    for d in &file.decls {
562        match d {
563            Decl::Predicate { local, params, .. } => {
564                let full = format!("{}.{}", file.namespace, local);
565                let sig = params.iter().map(|p| p.name.clone()).collect::<Vec<_>>().join(", ");
566                let args = params
567                    .iter()
568                    .map(|p| format!("\"{}\": {}", p.name, p.name))
569                    .collect::<Vec<_>>()
570                    .join(", ");
571                out.push_str(&format!(
572                    "def fact_{local}({sig}):\n    return {{\"op\": \"fact\", \"predicate\": \"{full}\", \"args\": {{{args}}}, \"truth\": True}}\n\n"
573                ));
574            }
575            Decl::Action { local, params, .. } => {
576                let full = format!("{}.{}", file.namespace, local);
577                let sig = params.iter().map(|p| p.name.clone()).collect::<Vec<_>>().join(", ");
578                let args = params
579                    .iter()
580                    .map(|p| format!("\"{}\": {}", p.name, p.name))
581                    .collect::<Vec<_>>()
582                    .join(", ");
583                out.push_str(&format!(
584                    "def action_{local}({sig}):\n    return {{\"op\": \"action\", \"name\": \"{full}\", \"params\": {{{args}}}}}\n\n"
585                ));
586            }
587            Decl::Workflow { local, steps, .. } => {
588                let groups: Vec<String> = steps
589                    .iter()
590                    .map(|st| match st {
591                        Step::Do(n) => format!("[\"{n}\"]"),
592                        Step::Parallel(g) => format!(
593                            "[{}]",
594                            g.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", ")
595                        ),
596                    })
597                    .collect();
598                out.push_str(&format!(
599                    "def plan_{local}():\n    return [{}]\n\n",
600                    groups.join(", ")
601                ));
602            }
603            Decl::Alias { .. } => {}
604        }
605    }
606    out
607}
608
609/// Generate a runtime-validation schema (JSON) for `gen schema`.
610pub fn gen_schema(file: &IdlFile) -> String {
611    let mut aliases = BTreeMap::new();
612    let mut predicates = BTreeMap::new();
613    let mut actions = BTreeMap::new();
614    for d in &file.decls {
615        match d {
616            Decl::Alias { local, target } => {
617                aliases.insert(local.clone(), target.clone());
618            }
619            Decl::Predicate { local, params, ret, doc, .. } => {
620                predicates.insert(
621                    local.clone(),
622                    SchemaOpView {
623                        params: params.iter().map(|p| (p.name.clone(), p.ty.clone())).collect(),
624                        ret: ret.clone(),
625                        doc: doc.clone(),
626                    },
627                );
628            }
629            Decl::Action { local, params, ret, doc, .. } => {
630                actions.insert(
631                    local.clone(),
632                    SchemaOpView {
633                        params: params.iter().map(|p| (p.name.clone(), p.ty.clone())).collect(),
634                        ret: ret.clone(),
635                        doc: doc.clone(),
636                    },
637                );
638            }
639            Decl::Workflow { .. } => {}
640        }
641    }
642    // §31: deprecated terms map (term -> reason)
643    let mut deprecated = serde_json::Map::new();
644    for d in &file.decls {
645        let (full, dep) = match d {
646            Decl::Predicate { local, deprecation: Some(dp), .. }
647            | Decl::Action { local, deprecation: Some(dp), .. } => {
648                (format!("{}.{}", file.namespace, local), Some(dp))
649            }
650            _ => (String::new(), None),
651        };
652        if let Some(dp) = dep {
653            deprecated.insert(full, serde_json::Value::String(format!("{} (since {})", dp.reason, dp.since)));
654        }
655    }
656    let view = serde_json::json!({
657        "namespace": file.namespace,
658        "version": file.version,
659        "aliases": aliases,
660        "predicates": predicates,
661        "actions": actions,
662        "deprecated": deprecated,
663    });
664    String::from_utf8(serde_json::to_vec_pretty(&view).unwrap_or_default()).unwrap_or_default()
665}
666
667#[derive(serde::Serialize)]
668struct SchemaOpView {
669    params: BTreeMap<String, String>,
670    ret: String,
671    #[serde(skip_serializing_if = "Option::is_none")]
672    doc: Option<String>,
673}
674
675/// Generate TypeScript builder stubs.
676pub fn gen_ts(file: &IdlFile) -> String {
677    let mut out = format!(
678        "// Generated by aclc from namespace {} v{} — do not edit.\nexport const NAMESPACE = \"{}\";\nexport const VERSION = {};\n\n",
679        file.namespace, file.version, file.namespace, file.version
680    );
681    for d in &file.decls {
682        match d {
683            Decl::Predicate { local, params, .. } => {
684                let full = format!("{}.{}", file.namespace, local);
685                let sig = params.iter().map(|p| format!("{}: unknown", p.name)).collect::<Vec<_>>().join(", ");
686                let args = params
687                    .iter()
688                    .map(|p| format!("\"{}\": {}", p.name, p.name))
689                    .collect::<Vec<_>>()
690                    .join(", ");
691                out.push_str(&format!(
692                    "export function fact_{local}({sig}) {{ return {{ op: \"fact\", predicate: \"{full}\", args: {{{args}}}, truth: true }}; }}\n\n"
693                ));
694            }
695            Decl::Action { local, params, .. } => {
696                let full = format!("{}.{}", file.namespace, local);
697                let sig = params.iter().map(|p| format!("{}: unknown", p.name)).collect::<Vec<_>>().join(", ");
698                let args = params
699                    .iter()
700                    .map(|p| format!("\"{}\": {}", p.name, p.name))
701                    .collect::<Vec<_>>()
702                    .join(", ");
703                out.push_str(&format!(
704                    "export function action_{local}({sig}) {{ return {{ op: \"action\", name: \"{full}\", params: {{{args}}} }}; }}\n\n"
705                ));
706            }
707            Decl::Alias { .. } => {}
708            Decl::Workflow { local, steps, .. } => {
709                let groups: Vec<String> = steps
710                    .iter()
711                    .map(|st| match st {
712                        Step::Do(n) => format!("[\"{n}\"]"),
713                        Step::Parallel(g) => format!(
714                            "[{}]",
715                            g.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", ")
716                        ),
717                    })
718                    .collect();
719                out.push_str(&format!(
720                    "export function plan_{local}() {{ return [{}]; }}\n\n",
721                    groups.join(", ")
722                ));
723            }
724        }
725    }
726    out
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    const SAMPLE: &str = r#"
734namespace acl.std.fs v1;
735
736/// Path on a local filesystem.
737type Path = string;
738
739/// Check whether a path exists on the agent's filesystem.
740predicate file_exists(path: Path) -> bool;
741predicate file_size(path: Path) -> int;
742action text_reverse(text: string) -> string;
743"#;
744
745    #[test]
746    fn parse_and_typecheck_sample() {
747        let f = parse(SAMPLE).expect("parse");
748        assert_eq!(f.namespace, "acl.std.fs");
749        assert_eq!(f.version, 1);
750        let names = typecheck(&f).expect("typecheck");
751        assert_eq!(names, vec!["acl.std.fs.file_exists", "acl.std.fs.file_size", "acl.std.fs.text_reverse"]);
752        // doc attached
753        match &f.decls[1] {
754            Decl::Predicate { doc, .. } => assert!(doc.as_deref().unwrap().contains("exists on the agent's filesystem")),
755            _ => panic!("expected predicate"),
756        }
757    }
758
759    #[test]
760    fn type_errors() {
761        let src = "namespace a.b v1;\npredicate f(x: UnknownType) -> bool;\n";
762        let errs = typecheck(&parse(src).unwrap()).unwrap_err();
763        assert!(errs.iter().any(|e| e.message.contains("unknown type")));
764        // duplicate full name across kinds
765        let src2 = "namespace a.b v1;\npredicate f() -> bool;\naction f() -> bool;\n";
766        let errs2 = typecheck(&parse(src2).unwrap()).unwrap_err();
767        assert!(errs2.iter().any(|e| e.message.contains("duplicate full name")));
768    }
769
770    #[test]
771    fn parse_errors_have_lines() {
772        let src = "namespace a.b v9;\ngarbage line here;\n";
773        let errs = parse(src).unwrap_err();
774        assert_eq!(errs[0].line, 2);
775    }
776
777    #[test]
778    fn pretty_is_roundtrip_stable() {
779        let f = parse(SAMPLE).unwrap();
780        let pretty1 = pretty(&f);
781        let f2 = parse(&pretty1).unwrap();
782        assert_eq!(f, f2);
783        assert_eq!(pretty(&f2), pretty1, "fmt must be idempotent");
784        assert!(pretty1.contains("/// Check whether a path exists"));
785    }
786
787    #[test]
788    fn workflow_parse_typecheck_codegen() {
789        let src = r#"
790namespace acl.demo v1;
791action step_a(text: string) -> bool;
792action step_b() -> bool;
793workflow pipeline(text: string) -> bool {
794  do acl.demo.step_a;
795  parallel {
796    do acl.demo.step_b;
797    do acl.demo.step_b;
798  }
799  do acl.demo.step_a;
800}
801"#;
802        let f = parse(src).expect("parse");
803        typecheck(&f).expect("typecheck");
804        match &f.decls[2] {
805            Decl::Workflow { local, steps, ret, .. } => {
806                assert_eq!(local, "pipeline");
807                assert_eq!(steps.len(), 3, "do, parallel, do");
808                assert_eq!(ret.as_deref(), Some("bool"));
809                match &steps[1] {
810                    Step::Parallel(g) => assert_eq!(g.len(), 2),
811                    other => panic!("expected parallel, got {other:?}"),
812                }
813            }
814            other => panic!("expected workflow, got {other:?}"),
815        }
816        // pretty roundtrip
817        let p1 = pretty(&f);
818        assert_eq!(parse(&p1).unwrap(), f);
819        assert!(p1.contains("workflow pipeline(text: string) -> bool {"));
820        assert!(p1.contains("  parallel {"));
821        // codegen: plan preserves order and parallel groups
822        let rust = gen_rust(&f);
823        assert!(rust.contains("pub fn plan_pipeline() -> Vec<Vec<&'static str>>"));
824        let py = gen_py(&f);
825        assert!(py.contains("def plan_pipeline():"));
826    }
827
828    #[test]
829    fn deprecation_parsed() {
830        let src = "namespace a.b v1;\n@deprecated(\"use file_v2 instead\")\npredicate old_thing() -> bool;\n";
831        let f = parse(src).expect("parse");
832        match &f.decls[0] {
833            Decl::Predicate { local, deprecation, .. } => {
834                assert_eq!(local, "old_thing");
835                let dp = deprecation.as_ref().expect("deprecation expected");
836                assert!(dp.reason.contains("file_v2"));
837            }
838            other => panic!("expected predicate, got {other:?}"),
839        }
840        // non-deprecated decl has none
841        match &f.decls[0] {
842            Decl::Predicate { deprecation, .. } => assert!(deprecation.is_some()),
843            _ => {}
844        }
845    }
846
847    #[test]
848    fn workflow_type_errors() {
849        let src = "namespace a.b v1;
850workflow w() {
851  do a.b.missing;
852}
853";
854        let errs = typecheck(&parse(src).unwrap()).unwrap_err();
855        assert!(errs.iter().any(|e| e.message.contains("'do a.b.missing' is not a declared action")));
856    }
857
858    #[test]
859    fn codegen_contains_builders() {
860        let f = parse(SAMPLE).unwrap();
861        let rust = gen_rust(&f);
862        assert!(rust.contains("pub fn fact_file_exists(path: serde_json::Value)"));
863        assert!(rust.contains("pub fn action_text_reverse(text: serde_json::Value)"));
864        assert!(rust.contains("NAMESPACE: &str = \"acl.std.fs\""));
865        let py = gen_py(&f);
866        assert!(py.contains("def fact_file_exists(path):"));
867        let ts = gen_ts(&f);
868        assert!(ts.contains("export function action_text_reverse(text: unknown)"));
869    }
870}