Skip to main content

vibe/
projectional.rs

1//! Projectional authoring — structure is the source of truth, text is a view (W1).
2//!
3//! This module implements the projectional authoring model for VibeScript:
4//!
5//! - **Project**: Convert an AST `Program` back to canonical source text.
6//!   The AST is the source of truth; the text is a *projection* of it.
7//! - **Edit**: Apply structural edits to a `Program` without round-tripping
8//!   through text. Edits are typed operations, not string patches.
9//! - **Round-trip**: `parse → project → parse` yields an equivalent AST.
10//! - **Trivia preservation**: When a CST is available (trivia collected),
11//!   the projector can interleave comments and whitespace from the original
12//!   source.
13//!
14//! This stops LLMs and humans from forking a second syntax: the structure
15//! is authoritative, and text is always derivable from it.
16//!
17//! Reference: `docs/vibescript-full-impl-PLAN.md` W1.
18
19use std::fmt::Write;
20
21use crate::ast::{
22    Arg, BinOp, Block, CellDecl, ConstDecl, EffectClass, EnumDecl, Expr, ExprKind, FieldDecl,
23    FieldRepresentation, FieldSupport, FunctionDecl, HookDecl, Item, LawDecl, Literal,
24    MaterialDecl, ModalKind, NamedArg, Pattern, Program, Stmt, TypeExpr, UnOp,
25};
26use crate::trivia::CstNode;
27
28// ── projection options ─────────────────────────────────────────────
29
30/// Options controlling how the projector formats source text.
31#[derive(Debug, Clone)]
32pub struct ProjectOptions {
33    /// Indentation string (default: two spaces).
34    pub indent: String,
35    /// Blank lines between top-level declarations (default: 1).
36    pub blank_lines_between_decls: usize,
37    /// Maximum line width before wrapping (default: 80).
38    pub max_line_width: usize,
39}
40
41impl Default for ProjectOptions {
42    fn default() -> Self {
43        Self {
44            indent: "  ".into(),
45            blank_lines_between_decls: 1,
46            max_line_width: 80,
47        }
48    }
49}
50
51// ── projector ──────────────────────────────────────────────────────
52
53/// Project a `Program` AST to canonical source text.
54///
55/// The output is valid VibeScript that, when re-parsed, yields an
56/// equivalent AST (modulo spans and trivia).
57pub fn project_program(prog: &Program, opts: &ProjectOptions) -> String {
58    let mut out = String::new();
59
60    for loc in &prog.locales {
61        write!(out, "locale {};\n", loc.code).unwrap();
62    }
63
64    // Module declaration
65    if let Some(module) = &prog.module {
66        project_name(&module.name, "module ", &mut out);
67        out.push('\n');
68    }
69
70    // Imports
71    for imp in &prog.imports {
72        write!(out, "import \"{}\"", imp.path).unwrap();
73        if let Some(alias) = &imp.alias {
74            write!(out, " as {}", alias).unwrap();
75        }
76        out.push('\n');
77    }
78
79    // Prefixes
80    for p in &prog.prefixes {
81        write!(out, "prefix {}: <{}>\n", p.prefix, p.iri).unwrap();
82    }
83
84    // Requires
85    if !prog.requires.is_empty() {
86        out.push_str("requires [\n");
87        for (i, cap) in prog.requires.iter().enumerate() {
88            write!(out, "{}capability(\"{}\"", opts.indent, cap.id).unwrap();
89            for arg in &cap.args {
90                write!(out, ", {}: ", arg.name).unwrap();
91                project_expr(&arg.value, opts, &mut out);
92            }
93            out.push(')');
94            if i + 1 < prog.requires.len() {
95                out.push(',');
96            }
97            out.push('\n');
98        }
99        out.push_str("];\n");
100    }
101
102    // Items
103    let blank = "\n".repeat(opts.blank_lines_between_decls);
104    let mut first = true;
105    for item in &prog.items {
106        if !first {
107            out.push_str(&blank);
108        }
109        project_item(item, opts, &mut out);
110        first = false;
111    }
112
113    out
114}
115
116/// Project a single top-level item.
117pub fn project_item(item: &Item, opts: &ProjectOptions, out: &mut String) {
118    match item {
119        Item::Function(fd) => project_function(fd, opts, out),
120        Item::Hook(hd) => project_hook(hd, opts, out),
121        Item::Const(cd) => project_const(cd, opts, out),
122        Item::Enum(ed) => project_enum(ed, opts, out),
123        Item::Field(fd) => project_field(fd, opts, out),
124        Item::Material(md) => project_material(md, opts, out),
125        Item::Law(ld) => project_law(ld, opts, out),
126        Item::Cell(cd) => project_cell(cd, opts, out),
127        Item::Present(pd) => {
128            out.push_str("present ");
129            out.push_str(&pd.name);
130            out.push_str(" {\n");
131            for prop in &pd.properties {
132                out.push_str(&opts.indent);
133                out.push_str(&prop.name);
134                out.push_str(": ");
135                project_expr(&prop.value, opts, out);
136                out.push('\n');
137            }
138            out.push_str("}\n");
139        }
140        Item::Bind(b) => {
141            out.push_str("bind ");
142            project_expr(&b.left, opts, out);
143            out.push_str(" <-> ");
144            project_expr(&b.right, opts, out);
145            if let Some((lo, hi)) = &b.clamp {
146                out.push_str(" using Clamp[");
147                project_expr(lo, opts, out);
148                out.push_str(", ");
149                project_expr(hi, opts, out);
150                out.push(']');
151            }
152            out.push_str(" resolve ");
153            out.push_str(match b.resolve {
154                crate::ast::BindResolve::Latest => "latest",
155                crate::ast::BindResolve::Left => "left",
156                crate::ast::BindResolve::Right => "right",
157            });
158            out.push_str(";\n");
159        }
160        Item::Statement(s) => {
161            project_stmt(s, opts, out, 0);
162            out.push('\n');
163        }
164    }
165}
166
167fn project_cell(cd: &CellDecl, opts: &ProjectOptions, out: &mut String) {
168    if let Some(effect) = cd.effect {
169        write!(out, "{} ", effect_keyword(effect)).unwrap();
170    }
171    write!(out, "cell {}", cd.name).unwrap();
172    if !cd.params.is_empty() {
173        out.push('(');
174        for (i, p) in cd.params.iter().enumerate() {
175            if i > 0 {
176                out.push_str(", ");
177            }
178            write!(out, "{}: ", p.name).unwrap();
179            project_type(&p.ty, out);
180        }
181        out.push(')');
182    }
183    if let Some(w) = &cd.when {
184        out.push_str(" when ");
185        project_expr(w, opts, out);
186    }
187    out.push_str(" := ");
188    project_expr(&cd.expr, opts, out);
189    out.push_str(";\n");
190}
191
192fn project_function(fd: &FunctionDecl, opts: &ProjectOptions, out: &mut String) {
193    if let Some(effect) = fd.effect {
194        write!(out, "{} ", effect_keyword(effect)).unwrap();
195    }
196    if fd.is_async {
197        out.push_str("async ");
198    }
199    write!(out, "fn {}(", fd.name).unwrap();
200    for (i, p) in fd.params.iter().enumerate() {
201        if i > 0 {
202            out.push_str(", ");
203        }
204        write!(out, "{}: ", p.name).unwrap();
205        project_type(&p.ty, out);
206    }
207    out.push(')');
208    if !fd.budget.is_empty() {
209        out.push_str(" budget(");
210        for (i, b) in fd.budget.iter().enumerate() {
211            if i > 0 {
212                out.push_str(", ");
213            }
214            write!(out, "{}: ", b.name).unwrap();
215            project_expr(&b.value, opts, out);
216        }
217        out.push(')');
218    }
219    if let Some(ret) = &fd.ret {
220        out.push_str(" -> ");
221        project_type(ret, out);
222    }
223    out.push(' ');
224    project_block(&fd.body, opts, out, 0);
225    out.push('\n');
226}
227
228fn project_hook(hd: &HookDecl, opts: &ProjectOptions, out: &mut String) {
229    out.push_str("on ");
230    for (i, seg) in hd.path.iter().enumerate() {
231        if i > 0 {
232            out.push(':');
233        }
234        out.push_str(seg);
235    }
236    out.push('(');
237    for (i, p) in hd.params.iter().enumerate() {
238        if i > 0 {
239            out.push_str(", ");
240        }
241        write!(out, "{}: ", p.name).unwrap();
242        project_type(&p.ty, out);
243    }
244    out.push(')');
245    if !hd.budget.is_empty() {
246        out.push_str(" budget(");
247        for (i, b) in hd.budget.iter().enumerate() {
248            if i > 0 {
249                out.push_str(", ");
250            }
251            write!(out, "{}: ", b.name).unwrap();
252            project_expr(&b.value, opts, out);
253        }
254        out.push(')');
255    }
256    if let Some(ret) = &hd.ret {
257        out.push_str(" -> ");
258        project_type(ret, out);
259    }
260    out.push(' ');
261    project_block(&hd.body, opts, out, 0);
262    out.push('\n');
263}
264
265fn project_const(cd: &ConstDecl, opts: &ProjectOptions, out: &mut String) {
266    out.push_str("const ");
267    out.push_str(&cd.name);
268    if let Some(ty) = &cd.ty {
269        out.push_str(": ");
270        project_type(ty, out);
271    }
272    out.push_str(" = ");
273    project_expr(&cd.value, opts, out);
274    out.push_str(";\n");
275}
276
277fn project_enum(ed: &EnumDecl, opts: &ProjectOptions, out: &mut String) {
278    write!(out, "enum {} {{\n", ed.name).unwrap();
279    for variant in &ed.variants {
280        out.push_str(&opts.indent);
281        out.push_str(&variant.name);
282        if !variant.payload.is_empty() {
283            out.push('(');
284            for (i, ty) in variant.payload.iter().enumerate() {
285                if i > 0 {
286                    out.push_str(", ");
287                }
288                project_type(ty, out);
289            }
290            out.push(')');
291        }
292        out.push_str(",\n");
293    }
294    out.push_str("}\n");
295}
296
297fn project_field(fd: &FieldDecl, opts: &ProjectOptions, out: &mut String) {
298    write!(out, "field {}: ", fd.name).unwrap();
299    project_type(&fd.ty, out);
300    let mut props: Vec<(String, String)> = Vec::new();
301    if let Some(unit) = &fd.unit {
302        props.push(("unit".into(), format!("<{}>", unit)));
303    }
304    if fd.support != FieldSupport::Region {
305        props.push(("support".into(), format!("{:?}", fd.support).to_lowercase()));
306    }
307    if fd.representation != FieldRepresentation::Grid {
308        props.push((
309            "representation".into(),
310            format!("{:?}", fd.representation).to_lowercase(),
311        ));
312    }
313    if props.is_empty() {
314        out.push_str(";\n");
315        return;
316    }
317    out.push('\n');
318    for (k, v) in props.iter() {
319        write!(out, "{}{}: {}\n", opts.indent, k, v).unwrap();
320    }
321    out.push_str(";\n");
322}
323
324fn project_material(md: &MaterialDecl, opts: &ProjectOptions, out: &mut String) {
325    write!(out, "material {}: Material", md.name).unwrap();
326    if md.properties.is_empty() {
327        out.push_str(";\n");
328        return;
329    }
330    out.push('\n');
331    for (i, prop) in md.properties.iter().enumerate() {
332        write!(out, "{}{}: ", opts.indent, prop.name).unwrap();
333        project_expr(&prop.value, opts, out);
334        if i + 1 < md.properties.len() {
335            out.push(',');
336        }
337        out.push('\n');
338    }
339    out.push_str(";\n");
340}
341
342fn project_law(ld: &LawDecl, opts: &ProjectOptions, out: &mut String) {
343    write!(out, "law {}\n", ld.name).unwrap();
344    write!(out, "{}when ", opts.indent).unwrap();
345    project_expr(&ld.condition, opts, out);
346    write!(out, "\n{}=> ", opts.indent).unwrap();
347    project_expr(&ld.consequence, opts, out);
348    out.push_str(";\n");
349}
350
351fn project_block(block: &Block, opts: &ProjectOptions, out: &mut String, depth: usize) {
352    out.push('{');
353    if block.stmts.is_empty() {
354        out.push('}');
355        return;
356    }
357    out.push('\n');
358    for stmt in &block.stmts {
359        project_stmt(stmt, opts, out, depth + 1);
360        out.push('\n');
361    }
362    for _ in 0..depth {
363        out.push_str(&opts.indent);
364    }
365    out.push('}');
366}
367
368fn project_stmt(stmt: &Stmt, opts: &ProjectOptions, out: &mut String, depth: usize) {
369    let indent = opts.indent.repeat(depth);
370    match stmt {
371        Stmt::Let {
372            mutable,
373            name,
374            ty,
375            value,
376            ..
377        } => {
378            out.push_str(&indent);
379            out.push_str("let ");
380            if *mutable {
381                out.push_str("mut ");
382            }
383            out.push_str(name);
384            if let Some(ty) = ty {
385                out.push_str(": ");
386                project_type(ty, out);
387            }
388            if let Some(value) = value {
389                out.push_str(" = ");
390                project_expr(value, opts, out);
391            }
392            out.push(';');
393        }
394        Stmt::LetPat {
395            mutable,
396            pattern,
397            ty,
398            value,
399            ..
400        } => {
401            out.push_str(&indent);
402            out.push_str("let ");
403            if *mutable {
404                out.push_str("mut ");
405            }
406            project_pattern(pattern, out);
407            if let Some(t) = ty {
408                out.push_str(": ");
409                project_type(t, out);
410            }
411            out.push_str(" = ");
412            project_expr(value, opts, out);
413            out.push(';');
414        }
415        Stmt::Assign { target, value, .. } => {
416            out.push_str(&indent);
417            project_expr(target, opts, out);
418            out.push_str(" = ");
419            project_expr(value, opts, out);
420            out.push(';');
421        }
422        Stmt::If {
423            cond,
424            then_block,
425            else_block,
426            ..
427        } => {
428            out.push_str(&indent);
429            out.push_str("if ");
430            project_expr(cond, opts, out);
431            out.push(' ');
432            project_block(then_block, opts, out, depth);
433            if let Some(else_stmt) = else_block {
434                out.push_str(" else ");
435                match else_stmt.as_ref() {
436                    Stmt::If { .. } => {
437                        // else if — no brace, inline
438                        project_stmt(else_stmt, opts, out, depth);
439                    }
440                    _ => {
441                        project_block(
442                            match else_stmt.as_ref() {
443                                Stmt::Block(b) => b,
444                                _ => {
445                                    // Wrap single statement in block
446                                    return;
447                                }
448                            },
449                            opts,
450                            out,
451                            depth,
452                        );
453                    }
454                }
455            }
456        }
457        Stmt::For {
458            name, iter, body, ..
459        } => {
460            out.push_str(&indent);
461            write!(out, "for {} in ", name).unwrap();
462            project_expr(iter, opts, out);
463            out.push(' ');
464            project_block(body, opts, out, depth);
465        }
466        Stmt::While { cond, body, .. } => {
467            out.push_str(&indent);
468            out.push_str("while ");
469            project_expr(cond, opts, out);
470            out.push(' ');
471            project_block(body, opts, out, depth);
472        }
473        Stmt::Match {
474            scrutinee, arms, ..
475        } => {
476            out.push_str(&indent);
477            out.push_str("match ");
478            project_expr(scrutinee, opts, out);
479            out.push_str(" {\n");
480            for arm in arms {
481                out.push_str(&opts.indent.repeat(depth + 1));
482                project_pattern(&arm.pattern, out);
483                out.push_str(" => ");
484                match &arm.body {
485                    crate::ast::ArmBody::Block(b) => {
486                        project_block(b, opts, out, depth + 1);
487                    }
488                    crate::ast::ArmBody::Expr(e) => {
489                        project_expr(e, opts, out);
490                    }
491                }
492                out.push_str(",\n");
493            }
494            out.push_str(&opts.indent.repeat(depth));
495            out.push('}');
496        }
497        Stmt::Return { value, .. } => {
498            out.push_str(&indent);
499            out.push_str("return");
500            if let Some(v) = value {
501                out.push(' ');
502                project_expr(v, opts, out);
503            }
504            out.push(';');
505        }
506        Stmt::Yield { value, .. } => {
507            out.push_str(&indent);
508            out.push_str("yield");
509            if let Some(v) = value {
510                out.push(' ');
511                project_expr(v, opts, out);
512            }
513            out.push(';');
514        }
515        Stmt::Transaction { args, body, .. } => {
516            out.push_str(&indent);
517            out.push_str("transaction");
518            if !args.is_empty() {
519                out.push('(');
520                for (i, a) in args.iter().enumerate() {
521                    if i > 0 {
522                        out.push_str(", ");
523                    }
524                    write!(out, "{}: ", a.name).unwrap();
525                    project_expr(&a.value, opts, out);
526                }
527                out.push(')');
528            }
529            out.push(' ');
530            project_block(body, opts, out, depth);
531        }
532        Stmt::Effect { expr, .. } => {
533            out.push_str(&indent);
534            out.push_str("effect ");
535            project_expr(expr, opts, out);
536            out.push(';');
537        }
538        Stmt::Expr { expr, .. } => {
539            out.push_str(&indent);
540            if matches!(expr.kind, ExprKind::IfElse { .. }) {
541                out.push('(');
542                project_expr(expr, opts, out);
543                out.push(')');
544            } else {
545                project_expr(expr, opts, out);
546            }
547            out.push(';');
548        }
549        Stmt::Block(b) => {
550            out.push_str(&indent);
551            project_block(b, opts, out, depth);
552        }
553    }
554}
555
556fn project_pattern(pat: &Pattern, out: &mut String) {
557    match pat {
558        Pattern::Wildcard => out.push('_'),
559        Pattern::Ident(s) => out.push_str(s),
560        Pattern::Literal(l) => project_literal(l, out),
561        Pattern::Ok(inner) => {
562            out.push_str("Ok(");
563            project_pattern(inner, out);
564            out.push(')');
565        }
566        Pattern::Err(inner) => {
567            out.push_str("Err(");
568            project_pattern(inner, out);
569            out.push(')');
570        }
571        Pattern::Some(inner) => {
572            out.push_str("Some(");
573            project_pattern(inner, out);
574            out.push(')');
575        }
576        Pattern::None => out.push_str("None"),
577        Pattern::Record(fields) => {
578            out.push_str("{ ");
579            for (i, (k, p)) in fields.iter().enumerate() {
580                if i > 0 {
581                    out.push_str(", ");
582                }
583                if let Pattern::Ident(id) = p {
584                    if id == k {
585                        out.push_str(k);
586                        continue;
587                    }
588                }
589                out.push_str(k);
590                out.push_str(": ");
591                project_pattern(p, out);
592            }
593            out.push_str(" }");
594        }
595        Pattern::List(elements) => {
596            out.push('[');
597            for (i, p) in elements.iter().enumerate() {
598                if i > 0 {
599                    out.push_str(", ");
600                }
601                project_pattern(p, out);
602            }
603            out.push(']');
604        }
605        Pattern::Constructor { name, args } => {
606            out.push_str(name);
607            out.push('(');
608            for (i, p) in args.iter().enumerate() {
609                if i > 0 {
610                    out.push_str(", ");
611                }
612                project_pattern(p, out);
613            }
614            out.push(')');
615        }
616        Pattern::Variant {
617            enum_name,
618            variant_name,
619            args,
620        } => {
621            write!(out, "{}.{}", enum_name, variant_name).unwrap();
622            if !args.is_empty() {
623                out.push('(');
624                for (i, a) in args.iter().enumerate() {
625                    if i > 0 {
626                        out.push_str(", ");
627                    }
628                    project_pattern(a, out);
629                }
630                out.push(')');
631            }
632        }
633    }
634}
635
636fn project_postfix_recv(recv: &Expr, opts: &ProjectOptions, out: &mut String) {
637    if matches!(recv.kind, ExprKind::IfElse { .. }) {
638        out.push('(');
639        project_expr(recv, opts, out);
640        out.push(')');
641    } else {
642        project_expr(recv, opts, out);
643    }
644}
645
646fn project_expr(expr: &Expr, opts: &ProjectOptions, out: &mut String) {
647    match &expr.kind {
648        ExprKind::Literal(l) => project_literal(l, out),
649        ExprKind::Ident(s) => out.push_str(s),
650        ExprKind::QueryVar(s) => {
651            out.push('?');
652            out.push_str(s);
653        }
654        ExprKind::Iri(s) => {
655            out.push('<');
656            out.push_str(s);
657            out.push('>');
658        }
659        ExprKind::Prefixed(p, l) => {
660            write!(out, "{}:{}", p, l).unwrap();
661        }
662        ExprKind::Blank(s) => {
663            out.push_str("_:");
664            out.push_str(s);
665        }
666        ExprKind::Binary { op, left, right } => {
667            project_expr(left, opts, out);
668            out.push(' ');
669            out.push_str(binop_str(*op));
670            out.push(' ');
671            project_expr(right, opts, out);
672        }
673        ExprKind::Unary { op, expr } => {
674            out.push_str(unop_str(*op));
675            project_expr(expr, opts, out);
676        }
677        ExprKind::Await(inner) => {
678            project_expr(inner, opts, out);
679            out.push_str(".await");
680        }
681        ExprKind::Member { recv, name } => {
682            project_postfix_recv(recv, opts, out);
683            out.push('.');
684            out.push_str(name);
685        }
686        ExprKind::Call { callee, args } => {
687            project_postfix_recv(callee, opts, out);
688            out.push('(');
689            for (i, arg) in args.iter().enumerate() {
690                if i > 0 {
691                    out.push_str(", ");
692                }
693                match arg {
694                    Arg::Pos(e) => project_expr(e, opts, out),
695                    Arg::Named(na) => {
696                        write!(out, "{}: ", na.name).unwrap();
697                        project_expr(&na.value, opts, out);
698                    }
699                }
700            }
701            out.push(')');
702        }
703        ExprKind::Index { recv, index } => {
704            project_postfix_recv(recv, opts, out);
705            out.push('[');
706            project_expr(index, opts, out);
707            out.push(']');
708        }
709        ExprKind::Try(inner) => {
710            project_postfix_recv(inner, opts, out);
711            out.push('?');
712        }
713        ExprKind::IfElse {
714            cond,
715            then_value,
716            else_value,
717        } => {
718            out.push_str("if ");
719            if matches!(cond.kind, ExprKind::IfElse { .. } | ExprKind::Record(_)) {
720                out.push('(');
721                project_expr(cond, opts, out);
722                out.push(')');
723            } else {
724                project_expr(cond, opts, out);
725            }
726            out.push_str(" { ");
727            project_expr(then_value, opts, out);
728            out.push_str(" } else ");
729            if matches!(else_value.kind, ExprKind::IfElse { .. }) {
730                project_expr(else_value, opts, out);
731            } else {
732                out.push_str("{ ");
733                project_expr(else_value, opts, out);
734                out.push_str(" }");
735            }
736        }
737        ExprKind::List(items) => {
738            out.push('[');
739            for (i, item) in items.iter().enumerate() {
740                if i > 0 {
741                    out.push_str(", ");
742                }
743                project_expr(item, opts, out);
744            }
745            out.push(']');
746        }
747        ExprKind::Record(entries) => {
748            out.push('{');
749            if !entries.is_empty() {
750                out.push(' ');
751            }
752            for (i, entry) in entries.iter().enumerate() {
753                if i > 0 {
754                    out.push_str(", ");
755                }
756                write!(out, "{}: ", entry.name).unwrap();
757                project_expr(&entry.value, opts, out);
758            }
759            if !entries.is_empty() {
760                out.push(' ');
761            }
762            out.push('}');
763        }
764        ExprKind::Triple {
765            subject,
766            predicate,
767            object,
768        } => {
769            out.push_str("<<(");
770            project_expr(subject, opts, out);
771            out.push(' ');
772            project_expr(predicate, opts, out);
773            out.push(' ');
774            project_expr(object, opts, out);
775            out.push_str(")>>");
776        }
777        ExprKind::Reified {
778            subject,
779            predicate,
780            object,
781            reifier,
782        } => {
783            out.push_str("<<(");
784            project_expr(subject, opts, out);
785            out.push(' ');
786            project_expr(predicate, opts, out);
787            out.push(' ');
788            project_expr(object, opts, out);
789            out.push_str(") ~ ");
790            project_expr(reifier, opts, out);
791            out.push_str(">>");
792        }
793        ExprKind::Pipe { left, right } => {
794            project_expr(left, opts, out);
795            out.push_str(" |> ");
796            project_expr(right, opts, out);
797        }
798        ExprKind::GraphQuery {
799            is_ask, pattern, ..
800        } => {
801            if *is_ask {
802                out.push_str("graph? { ");
803            } else {
804                out.push_str("graph { ");
805            }
806            out.push_str(pattern);
807            out.push_str(" }");
808        }
809        ExprKind::ModalLogic {
810            modality,
811            args,
812            body,
813        } => {
814            let name = match modality {
815                ModalKind::DeonticObligate => "obligate",
816                ModalKind::DeonticPermit => "permit",
817                ModalKind::DeonticForbid => "forbid",
818                ModalKind::EpistemicKnows => "knows",
819                ModalKind::EpistemicBelieves => "believes",
820                ModalKind::Paraconsistent => "paraconsistent",
821                ModalKind::LtlGlobally => "always",
822                ModalKind::LtlFinally => "eventually",
823                ModalKind::LtlUntil => "until",
824                ModalKind::DlSubsumes => "subsumes",
825                ModalKind::N3Defeasible => "defeasible_rule",
826            };
827            out.push_str(name);
828            if !args.is_empty() {
829                out.push('(');
830                for (i, a) in args.iter().enumerate() {
831                    if i > 0 {
832                        out.push_str(", ");
833                    }
834                    project_expr(a, opts, out);
835                }
836                out.push(')');
837            }
838            if let Some(b) = body {
839                out.push_str(" { ");
840                project_expr(b, opts, out);
841                out.push_str(" }");
842            }
843        }
844        ExprKind::Interpolate(parts) => {
845            out.push_str("f\"");
846            for p in parts {
847                if let ExprKind::Literal(Literal::String(s)) = &p.kind {
848                    out.push_str(s);
849                } else {
850                    out.push('{');
851                    project_expr(p, opts, out);
852                    out.push('}');
853                }
854            }
855            out.push('"');
856        }
857        ExprKind::Lambda { params, body } => {
858            out.push('|');
859            for (i, p) in params.iter().enumerate() {
860                if i > 0 {
861                    out.push_str(", ");
862                }
863                out.push_str(p);
864            }
865            out.push_str("| ");
866            project_expr(body, opts, out);
867        }
868        ExprKind::Tween {
869            from,
870            to,
871            over,
872            ease,
873            spring,
874        } => {
875            project_expr(from, opts, out);
876            out.push_str(" ~ ");
877            project_expr(to, opts, out);
878            out.push_str(" over ");
879            project_expr(over, opts, out);
880            if let Some(e) = ease {
881                out.push_str(" ease ");
882                out.push_str(e);
883            }
884            if let Some(args) = spring {
885                out.push_str(" spring(");
886                for (i, a) in args.iter().enumerate() {
887                    if i > 0 {
888                        out.push_str(", ");
889                    }
890                    write!(out, "{}: ", a.name).unwrap();
891                    project_expr(&a.value, opts, out);
892                }
893                out.push(')');
894            }
895        }
896    }
897}
898
899fn project_literal(lit: &Literal, out: &mut String) {
900    match lit {
901        Literal::Null => out.push_str("null"),
902        Literal::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
903        Literal::Int(n) => write!(out, "{}", n).unwrap(),
904        Literal::UInt(n) => write!(out, "{}u", n).unwrap(),
905        Literal::Float(bits) => {
906            let f = f64::from_bits(*bits);
907            if f == f.trunc() && f.is_finite() {
908                write!(out, "{:.1}", f).unwrap();
909            } else {
910                write!(out, "{}", f).unwrap();
911            }
912        }
913        Literal::Quantity { value, unit } => {
914            let f = f64::from_bits(*value);
915            write!(out, "{}{}", f, unit).unwrap();
916        }
917        Literal::Color(c) => {
918            write!(out, "#{:02x}{:02x}{:02x}", c.r, c.g, c.b).unwrap();
919            if c.a != 255 {
920                write!(out, "{:02x}", c.a).unwrap();
921            }
922        }
923        Literal::String(s) => {
924            out.push('"');
925            out.push_str(s);
926            out.push('"');
927        }
928    }
929}
930
931fn project_type(ty: &TypeExpr, out: &mut String) {
932    out.push_str(&ty.name);
933    if !ty.args.is_empty() {
934        out.push('<');
935        for (i, a) in ty.args.iter().enumerate() {
936            if i > 0 {
937                out.push_str(", ");
938            }
939            project_type(a, out);
940        }
941        out.push('>');
942    }
943}
944
945fn project_name(name: &crate::ast::Name, prefix: &str, out: &mut String) {
946    out.push_str(prefix);
947    match name {
948        crate::ast::Name::Ident(s) => out.push_str(s),
949        crate::ast::Name::Iri(s) => {
950            out.push('<');
951            out.push_str(s);
952            out.push('>');
953        }
954    }
955}
956
957fn effect_keyword(e: EffectClass) -> &'static str {
958    match e {
959        EffectClass::Pure => "pure",
960        EffectClass::Hot => "hot",
961        EffectClass::Cold => "cold",
962        EffectClass::Async => "async",
963        EffectClass::External => "effect",
964    }
965}
966
967fn binop_str(op: BinOp) -> &'static str {
968    match op {
969        BinOp::Or => "||",
970        BinOp::And => "&&",
971        BinOp::Eq => "==",
972        BinOp::Ne => "!=",
973        BinOp::Lt => "<",
974        BinOp::Le => "<=",
975        BinOp::Gt => ">",
976        BinOp::Ge => ">=",
977        BinOp::Add => "+",
978        BinOp::Sub => "-",
979        BinOp::Mul => "*",
980        BinOp::Div => "/",
981        BinOp::Rem => "%",
982    }
983}
984
985fn unop_str(op: UnOp) -> &'static str {
986    match op {
987        UnOp::Not => "!",
988        UnOp::Neg => "-",
989        UnOp::Plus => "+",
990    }
991}
992
993// ── structural edits ───────────────────────────────────────────────
994
995/// A structural edit operation on a `Program`.
996///
997/// Edits are typed — they operate on the AST structure, not on text.
998/// This is the core of projectional authoring: the structure is
999/// authoritative, text is derived.
1000#[derive(Debug, Clone)]
1001pub enum Edit {
1002    /// Add a new top-level item at the end (or at a specific index).
1003    AddItem { item: Item, index: Option<usize> },
1004    /// Remove the item at the given index.
1005    RemoveItem { index: usize },
1006    /// Replace the item at the given index.
1007    ReplaceItem { index: usize, item: Item },
1008    /// Rename a function, const, field, material, or law.
1009    RenameItem { index: usize, new_name: String },
1010    /// Modify a field's unit.
1011    SetFieldUnit { index: usize, unit: Option<String> },
1012    /// Modify a field's support.
1013    SetFieldSupport { index: usize, support: FieldSupport },
1014    /// Modify a field's representation.
1015    SetFieldRepresentation {
1016        index: usize,
1017        representation: FieldRepresentation,
1018    },
1019    /// Add a property to a material.
1020    AddMaterialProperty { index: usize, property: NamedArg },
1021    /// Remove a property from a material by name.
1022    RemoveMaterialProperty { index: usize, name: String },
1023    /// Set a law's condition.
1024    SetLawCondition { index: usize, condition: Expr },
1025    /// Set a law's consequence.
1026    SetLawConsequence { index: usize, consequence: Expr },
1027    /// Add a prefix declaration.
1028    AddPrefix { prefix: String, iri: String },
1029    /// Remove a prefix declaration by prefix name.
1030    RemovePrefix { prefix: String },
1031    /// Add a requires capability.
1032    AddRequires { cap: crate::ast::CapSpec },
1033    /// Remove a requires capability by id.
1034    RemoveRequires { id: String },
1035}
1036
1037/// Apply a structural edit to a program, returning a new program.
1038///
1039/// This does not modify the original — projectional authoring treats
1040/// the AST as immutable structure; edits produce new structure.
1041pub fn apply_edit(prog: &Program, edit: &Edit) -> Program {
1042    let mut p = prog.clone();
1043    match edit {
1044        Edit::AddItem { item, index } => {
1045            if let Some(i) = index {
1046                p.items.insert(*i, item.clone());
1047            } else {
1048                p.items.push(item.clone());
1049            }
1050        }
1051        Edit::RemoveItem { index } => {
1052            if *index < p.items.len() {
1053                p.items.remove(*index);
1054            }
1055        }
1056        Edit::ReplaceItem { index, item } => {
1057            if *index < p.items.len() {
1058                p.items[*index] = item.clone();
1059            }
1060        }
1061        Edit::RenameItem { index, new_name } => {
1062            if *index < p.items.len() {
1063                rename_item(&mut p.items[*index], new_name);
1064            }
1065        }
1066        Edit::SetFieldUnit { index, unit } => {
1067            if let Some(Item::Field(fd)) = p.items.get_mut(*index) {
1068                fd.unit = unit.clone();
1069            }
1070        }
1071        Edit::SetFieldSupport { index, support } => {
1072            if let Some(Item::Field(fd)) = p.items.get_mut(*index) {
1073                fd.support = *support;
1074            }
1075        }
1076        Edit::SetFieldRepresentation {
1077            index,
1078            representation,
1079        } => {
1080            if let Some(Item::Field(fd)) = p.items.get_mut(*index) {
1081                fd.representation = *representation;
1082            }
1083        }
1084        Edit::AddMaterialProperty { index, property } => {
1085            if let Some(Item::Material(md)) = p.items.get_mut(*index) {
1086                md.properties.push(property.clone());
1087            }
1088        }
1089        Edit::RemoveMaterialProperty { index, name } => {
1090            if let Some(Item::Material(md)) = p.items.get_mut(*index) {
1091                md.properties.retain(|p| p.name != *name);
1092            }
1093        }
1094        Edit::SetLawCondition { index, condition } => {
1095            if let Some(Item::Law(ld)) = p.items.get_mut(*index) {
1096                ld.condition = condition.clone();
1097            }
1098        }
1099        Edit::SetLawConsequence { index, consequence } => {
1100            if let Some(Item::Law(ld)) = p.items.get_mut(*index) {
1101                ld.consequence = consequence.clone();
1102            }
1103        }
1104        Edit::AddPrefix { prefix, iri } => {
1105            p.prefixes.push(crate::ast::PrefixDecl {
1106                span: crate::span::Span::point(0),
1107                prefix: prefix.clone(),
1108                iri: iri.clone(),
1109            });
1110        }
1111        Edit::RemovePrefix { prefix } => {
1112            p.prefixes.retain(|p| p.prefix != *prefix);
1113        }
1114        Edit::AddRequires { cap } => {
1115            p.requires.push(cap.clone());
1116        }
1117        Edit::RemoveRequires { id } => {
1118            p.requires.retain(|c| c.id != *id);
1119        }
1120    }
1121    p
1122}
1123
1124/// Apply a structural edit with bounds and target-kind validation.
1125/// Returns `Err` if the target index is out of range or has an incompatible item kind.
1126pub fn try_apply_edit(prog: &Program, edit: &Edit) -> Result<Program, String> {
1127    let mut p = prog.clone();
1128    match edit {
1129        Edit::AddItem { item, index } => {
1130            if let Some(i) = index {
1131                if *i > p.items.len() {
1132                    return Err(format!("insert index {i} out of bounds (len {})", p.items.len()));
1133                }
1134                p.items.insert(*i, item.clone());
1135            } else {
1136                p.items.push(item.clone());
1137            }
1138        }
1139        Edit::RemoveItem { index } => {
1140            if *index >= p.items.len() {
1141                return Err(format!("remove index {index} out of bounds (len {})", p.items.len()));
1142            }
1143            p.items.remove(*index);
1144        }
1145        Edit::ReplaceItem { index, item } => {
1146            if *index >= p.items.len() {
1147                return Err(format!("replace index {index} out of bounds (len {})", p.items.len()));
1148            }
1149            p.items[*index] = item.clone();
1150        }
1151        Edit::RenameItem { index, new_name } => {
1152            let len = p.items.len();
1153            let slot = p.items.get_mut(*index).ok_or_else(|| {
1154                format!("rename index {index} out of bounds (len {len})")
1155            })?;
1156            rename_item(slot, new_name);
1157        }
1158        Edit::SetFieldUnit { index, unit } => match p.items.get_mut(*index) {
1159            Some(Item::Field(fd)) => fd.unit = unit.clone(),
1160            Some(_) => return Err(format!("item at index {index} is not a field")),
1161            None => return Err(format!("field index {index} out of bounds")),
1162        },
1163        Edit::SetFieldSupport { index, support } => match p.items.get_mut(*index) {
1164            Some(Item::Field(fd)) => fd.support = *support,
1165            Some(_) => return Err(format!("item at index {index} is not a field")),
1166            None => return Err(format!("field index {index} out of bounds")),
1167        },
1168        Edit::SetFieldRepresentation { index, representation } => match p.items.get_mut(*index) {
1169            Some(Item::Field(fd)) => fd.representation = *representation,
1170            Some(_) => return Err(format!("item at index {index} is not a field")),
1171            None => return Err(format!("field index {index} out of bounds")),
1172        },
1173        Edit::AddMaterialProperty { index, property } => match p.items.get_mut(*index) {
1174            Some(Item::Material(md)) => md.properties.push(property.clone()),
1175            Some(_) => return Err(format!("item at index {index} is not a material")),
1176            None => return Err(format!("material index {index} out of bounds")),
1177        },
1178        Edit::RemoveMaterialProperty { index, name } => match p.items.get_mut(*index) {
1179            Some(Item::Material(md)) => md.properties.retain(|prop| prop.name != *name),
1180            Some(_) => return Err(format!("item at index {index} is not a material")),
1181            None => return Err(format!("material index {index} out of bounds")),
1182        },
1183        Edit::SetLawCondition { index, condition } => match p.items.get_mut(*index) {
1184            Some(Item::Law(ld)) => ld.condition = condition.clone(),
1185            Some(_) => return Err(format!("item at index {index} is not a law")),
1186            None => return Err(format!("law index {index} out of bounds")),
1187        },
1188        Edit::SetLawConsequence { index, consequence } => match p.items.get_mut(*index) {
1189            Some(Item::Law(ld)) => ld.consequence = consequence.clone(),
1190            Some(_) => return Err(format!("item at index {index} is not a law")),
1191            None => return Err(format!("law index {index} out of bounds")),
1192        },
1193        Edit::AddPrefix { prefix, iri } => {
1194            p.prefixes.push(crate::ast::PrefixDecl {
1195                span: crate::span::Span::point(0),
1196                prefix: prefix.clone(),
1197                iri: iri.clone(),
1198            });
1199        }
1200        Edit::RemovePrefix { prefix } => {
1201            p.prefixes.retain(|decl| decl.prefix != *prefix);
1202        }
1203        Edit::AddRequires { cap } => {
1204            p.requires.push(cap.clone());
1205        }
1206        Edit::RemoveRequires { id } => {
1207            p.requires.retain(|c| c.id != *id);
1208        }
1209    }
1210    Ok(p)
1211}
1212
1213/// Apply a sequence of edits, producing the final program.
1214pub fn apply_edits(prog: &Program, edits: &[Edit]) -> Program {
1215    let mut p = prog.clone();
1216    for edit in edits {
1217        p = apply_edit(&p, edit);
1218    }
1219    p
1220}
1221
1222fn rename_item(item: &mut Item, new_name: &str) {
1223    match item {
1224        Item::Function(fd) => fd.name = new_name.to_string(),
1225        Item::Const(cd) => cd.name = new_name.to_string(),
1226        Item::Field(fd) => fd.name = new_name.to_string(),
1227        Item::Material(md) => md.name = new_name.to_string(),
1228        Item::Law(ld) => ld.name = new_name.to_string(),
1229        Item::Enum(ed) => ed.name = new_name.to_string(),
1230        _ => {}
1231    }
1232}
1233
1234// ── trivia-aware projection ────────────────────────────────────────
1235
1236/// Project a program with trivia preservation.
1237///
1238/// Given a CST (program with trivia), the projector interleaves
1239/// comments and whitespace from the original source into the
1240/// projected text. This is a best-effort process — structural edits
1241/// may invalidate original trivia positions.
1242pub fn project_with_trivia(
1243    prog: &Program,
1244    cst_items: &[CstNode<Item>],
1245    opts: &ProjectOptions,
1246) -> String {
1247    let mut out = String::new();
1248
1249    // Project the program structure first
1250    let base = project_program(prog, opts);
1251
1252    // If we have CST items, try to interleave leading comments
1253    // from each item. This is a simple approach: for each CST item,
1254    // extract leading comments and insert them before the projected
1255    // item text.
1256    if cst_items.is_empty() {
1257        return base;
1258    }
1259
1260    // Re-project item by item, prepending leading trivia
1261    let blank = "\n".repeat(opts.blank_lines_between_decls);
1262    let mut first = true;
1263
1264    // Project headers (module, imports, prefixes, requires) from base
1265    // by finding where items start
1266    // Simple approach: project headers, then items with trivia
1267    for loc in &prog.locales {
1268        write!(out, "locale {};\n", loc.code).unwrap();
1269    }
1270    if let Some(module) = &prog.module {
1271        project_name(&module.name, "module ", &mut out);
1272        out.push('\n');
1273    }
1274    for imp in &prog.imports {
1275        write!(out, "import \"{}\"", imp.path).unwrap();
1276        if let Some(alias) = &imp.alias {
1277            write!(out, " as {}", alias).unwrap();
1278        }
1279        out.push('\n');
1280    }
1281    for p in &prog.prefixes {
1282        write!(out, "prefix {}: <{}>\n", p.prefix, p.iri).unwrap();
1283    }
1284    if !prog.requires.is_empty() {
1285        out.push_str("requires [\n");
1286        for (i, cap) in prog.requires.iter().enumerate() {
1287            write!(out, "{}capability(\"{}\"", opts.indent, cap.id).unwrap();
1288            for arg in &cap.args {
1289                write!(out, ", {}: ", arg.name).unwrap();
1290                project_expr(&arg.value, opts, &mut out);
1291            }
1292            out.push(')');
1293            if i + 1 < prog.requires.len() {
1294                out.push(',');
1295            }
1296            out.push('\n');
1297        }
1298        out.push_str("];\n");
1299    }
1300
1301    for (i, item) in prog.items.iter().enumerate() {
1302        if !first {
1303            out.push_str(&blank);
1304        }
1305        // Prepend leading comments from CST if available
1306        if let Some(cst) = cst_items.get(i) {
1307            for trivia in &cst.leading {
1308                if trivia.is_comment() {
1309                    out.push_str(&trivia.text);
1310                    out.push('\n');
1311                }
1312            }
1313        }
1314        project_item(item, opts, &mut out);
1315        first = false;
1316    }
1317
1318    out
1319}
1320
1321// ── helpers for building AST nodes ────────────────────────────────
1322
1323/// Helper: build a simple field declaration.
1324pub fn make_field(
1325    name: &str,
1326    ty: &str,
1327    unit: Option<&str>,
1328    support: FieldSupport,
1329    representation: FieldRepresentation,
1330) -> Item {
1331    Item::Field(FieldDecl {
1332        span: crate::span::Span::point(0),
1333        name: name.to_string(),
1334        ty: TypeExpr {
1335            span: crate::span::Span::point(0),
1336            name: ty.to_string(),
1337            args: Vec::new(),
1338        },
1339        unit: unit.map(|s| s.to_string()),
1340        support,
1341        representation,
1342    })
1343}
1344
1345/// Helper: build a simple material declaration.
1346pub fn make_material(name: &str, properties: Vec<(&str, Expr)>) -> Item {
1347    Item::Material(MaterialDecl {
1348        span: crate::span::Span::point(0),
1349        name: name.to_string(),
1350        properties: properties
1351            .into_iter()
1352            .map(|(n, v)| NamedArg {
1353                span: crate::span::Span::point(0),
1354                name: n.to_string(),
1355                value: v,
1356            })
1357            .collect(),
1358    })
1359}
1360
1361/// Helper: build a simple law declaration.
1362pub fn make_law(name: &str, condition: Expr, consequence: Expr) -> Item {
1363    Item::Law(LawDecl {
1364        span: crate::span::Span::point(0),
1365        name: name.to_string(),
1366        condition,
1367        consequence,
1368    })
1369}
1370
1371/// Helper: build an integer literal expression.
1372pub fn make_int(n: i64) -> Expr {
1373    Expr {
1374        span: crate::span::Span::point(0),
1375        kind: ExprKind::Literal(Literal::Int(n)),
1376    }
1377}
1378
1379/// Helper: build a float literal expression.
1380pub fn make_float(f: f64) -> Expr {
1381    Expr {
1382        span: crate::span::Span::point(0),
1383        kind: ExprKind::Literal(Literal::Float(f.to_bits())),
1384    }
1385}
1386
1387/// Helper: build a string literal expression.
1388pub fn make_string(s: &str) -> Expr {
1389    Expr {
1390        span: crate::span::Span::point(0),
1391        kind: ExprKind::Literal(Literal::String(s.to_string())),
1392    }
1393}
1394
1395/// Helper: build an identifier expression.
1396pub fn make_ident(s: &str) -> Expr {
1397    Expr {
1398        span: crate::span::Span::point(0),
1399        kind: ExprKind::Ident(s.to_string()),
1400    }
1401}
1402
1403/// Helper: build a binary expression.
1404pub fn make_binary(op: BinOp, left: Expr, right: Expr) -> Expr {
1405    Expr {
1406        span: crate::span::Span::point(0),
1407        kind: ExprKind::Binary {
1408            op,
1409            left: Box::new(left),
1410            right: Box::new(right),
1411        },
1412    }
1413}
1414
1415/// Helper: build a call expression.
1416pub fn make_call(callee: &str, args: Vec<Expr>) -> Expr {
1417    Expr {
1418        span: crate::span::Span::point(0),
1419        kind: ExprKind::Call {
1420            callee: Box::new(make_ident(callee)),
1421            args: args.into_iter().map(Arg::Pos).collect(),
1422        },
1423    }
1424}
1425
1426/// Helper: build a member access expression.
1427pub fn make_member(recv: &str, name: &str) -> Expr {
1428    Expr {
1429        span: crate::span::Span::point(0),
1430        kind: ExprKind::Member {
1431            recv: Box::new(make_ident(recv)),
1432            name: name.to_string(),
1433        },
1434    }
1435}
1436
1437#[cfg(test)]
1438mod tests {
1439    use super::*;
1440    use crate::ast::{EnumVariant, Param};
1441    use crate::parse::parse_program;
1442    use crate::trivia::Trivia;
1443
1444    // ── projection tests ───────────────────────────────────────────
1445
1446    #[test]
1447    fn project_empty_program() {
1448        let prog = Program {
1449            span: crate::span::Span::point(0),
1450            module: None,
1451            imports: Vec::new(),
1452            prefixes: Vec::new(),
1453            locales: Vec::new(),
1454            requires: Vec::new(),
1455            items: Vec::new(),
1456        };
1457        let out = project_program(&prog, &ProjectOptions::default());
1458        assert!(out.is_empty());
1459    }
1460
1461    #[test]
1462    fn project_field_basic() {
1463        let prog = Program {
1464            span: crate::span::Span::point(0),
1465            module: None,
1466            imports: Vec::new(),
1467            prefixes: Vec::new(),
1468            locales: Vec::new(),
1469            requires: Vec::new(),
1470            items: vec![make_field(
1471                "pressure",
1472                "Pressure",
1473                Some("qudt:KiloPascal"),
1474                FieldSupport::Region,
1475                FieldRepresentation::Grid,
1476            )],
1477        };
1478        let out = project_program(&prog, &ProjectOptions::default());
1479        assert!(out.contains("field pressure: Pressure"));
1480        assert!(out.contains("unit: <qudt:KiloPascal>"));
1481        assert!(out.ends_with(";\n"));
1482    }
1483
1484    #[test]
1485    fn project_field_with_support_and_repr() {
1486        let prog = Program {
1487            span: crate::span::Span::point(0),
1488            module: None,
1489            imports: Vec::new(),
1490            prefixes: Vec::new(),
1491            locales: Vec::new(),
1492            requires: Vec::new(),
1493            items: vec![make_field(
1494                "temp",
1495                "Temperature",
1496                Some("qudt:Kelvin"),
1497                FieldSupport::Point,
1498                FieldRepresentation::Sampled,
1499            )],
1500        };
1501        let out = project_program(&prog, &ProjectOptions::default());
1502        assert!(out.contains("field temp: Temperature"));
1503        assert!(out.contains("unit: <qudt:Kelvin>"));
1504        assert!(out.contains("support: point"));
1505        assert!(out.contains("representation: sampled"));
1506    }
1507
1508    #[test]
1509    fn project_material_basic() {
1510        let prog = Program {
1511            span: crate::span::Span::point(0),
1512            module: None,
1513            imports: Vec::new(),
1514            prefixes: Vec::new(),
1515            locales: Vec::new(),
1516            requires: Vec::new(),
1517            items: vec![make_material(
1518                "steel",
1519                vec![
1520                    ("yield", make_float(250.0)),
1521                    ("density", make_float(7850.0)),
1522                ],
1523            )],
1524        };
1525        let out = project_program(&prog, &ProjectOptions::default());
1526        assert!(out.contains("material steel: Material"));
1527        assert!(out.contains("yield: 250.0"));
1528        assert!(out.contains("density: 7850.0"));
1529    }
1530
1531    #[test]
1532    fn project_law_basic() {
1533        let prog = Program {
1534            span: crate::span::Span::point(0),
1535            module: None,
1536            imports: Vec::new(),
1537            prefixes: Vec::new(),
1538            locales: Vec::new(),
1539            requires: Vec::new(),
1540            items: vec![make_law(
1541                "crush",
1542                make_binary(
1543                    BinOp::Gt,
1544                    make_ident("pressure"),
1545                    make_member("steel", "yield"),
1546                ),
1547                make_int(1),
1548            )],
1549        };
1550        let out = project_program(&prog, &ProjectOptions::default());
1551        assert!(out.contains("law crush"));
1552        assert!(out.contains("when pressure > steel.yield"));
1553        assert!(out.contains("=> 1"));
1554    }
1555
1556    #[test]
1557    fn project_function_basic() {
1558        let prog = Program {
1559            span: crate::span::Span::point(0),
1560            module: None,
1561            imports: Vec::new(),
1562            prefixes: Vec::new(),
1563            locales: Vec::new(),
1564            requires: Vec::new(),
1565            items: vec![Item::Function(FunctionDecl {
1566                span: crate::span::Span::point(0),
1567                effect: Some(EffectClass::Pure),
1568                is_async: false,
1569                name: "add".to_string(),
1570                params: vec![
1571                    Param {
1572                        span: crate::span::Span::point(0),
1573                        name: "a".to_string(),
1574                        ty: TypeExpr {
1575                            span: crate::span::Span::point(0),
1576                            name: "i64".to_string(),
1577                            args: Vec::new(),
1578                        },
1579                    },
1580                    Param {
1581                        span: crate::span::Span::point(0),
1582                        name: "b".to_string(),
1583                        ty: TypeExpr {
1584                            span: crate::span::Span::point(0),
1585                            name: "i64".to_string(),
1586                            args: Vec::new(),
1587                        },
1588                    },
1589                ],
1590                budget: Vec::new(),
1591                ret: Some(TypeExpr {
1592                    span: crate::span::Span::point(0),
1593                    name: "i64".to_string(),
1594                    args: Vec::new(),
1595                }),
1596                body: Block {
1597                    span: crate::span::Span::point(0),
1598                    stmts: vec![Stmt::Return {
1599                        span: crate::span::Span::point(0),
1600                        value: Some(make_binary(BinOp::Add, make_ident("a"), make_ident("b"))),
1601                    }],
1602                },
1603            })],
1604        };
1605        let out = project_program(&prog, &ProjectOptions::default());
1606        assert!(out.contains("pure fn add(a: i64, b: i64) -> i64"));
1607        assert!(out.contains("return a + b;"));
1608    }
1609
1610    #[test]
1611    fn project_const_basic() {
1612        let prog = Program {
1613            span: crate::span::Span::point(0),
1614            module: None,
1615            imports: Vec::new(),
1616            prefixes: Vec::new(),
1617            locales: Vec::new(),
1618            requires: Vec::new(),
1619            items: vec![Item::Const(ConstDecl {
1620                span: crate::span::Span::point(0),
1621                name: "PI".to_string(),
1622                ty: Some(TypeExpr {
1623                    span: crate::span::Span::point(0),
1624                    name: "f64".to_string(),
1625                    args: Vec::new(),
1626                }),
1627                value: make_float(3.14159),
1628            })],
1629        };
1630        let out = project_program(&prog, &ProjectOptions::default());
1631        assert!(out.contains("const PI: f64 = 3.14159;"));
1632    }
1633
1634    #[test]
1635    fn project_enum_basic() {
1636        let prog = Program {
1637            span: crate::span::Span::point(0),
1638            module: None,
1639            imports: Vec::new(),
1640            prefixes: Vec::new(),
1641            locales: Vec::new(),
1642            requires: Vec::new(),
1643            items: vec![Item::Enum(EnumDecl {
1644                span: crate::span::Span::point(0),
1645                name: "Shape".to_string(),
1646                variants: vec![
1647                    EnumVariant {
1648                        span: crate::span::Span::point(0),
1649                        name: "Circle".to_string(),
1650                        payload: vec![TypeExpr {
1651                            span: crate::span::Span::point(0),
1652                            name: "f64".to_string(),
1653                            args: Vec::new(),
1654                        }],
1655                    },
1656                    EnumVariant {
1657                        span: crate::span::Span::point(0),
1658                        name: "Point".to_string(),
1659                        payload: Vec::new(),
1660                    },
1661                ],
1662            })],
1663        };
1664        let out = project_program(&prog, &ProjectOptions::default());
1665        assert!(out.contains("enum Shape {"));
1666        assert!(out.contains("Circle(f64),"));
1667        assert!(out.contains("Point,"));
1668    }
1669
1670    #[test]
1671    fn project_prefix_and_requires() {
1672        let prog = Program {
1673            span: crate::span::Span::point(0),
1674            module: None,
1675            imports: Vec::new(),
1676            prefixes: vec![crate::ast::PrefixDecl {
1677                span: crate::span::Span::point(0),
1678                prefix: "qudt".to_string(),
1679                iri: "http://qudt.org/vocab/unit".to_string(),
1680            }],
1681            locales: Vec::new(),
1682            requires: vec![crate::ast::CapSpec {
1683                span: crate::span::Span::point(0),
1684                id: "graph.read".to_string(),
1685                args: Vec::new(),
1686            }],
1687            items: Vec::new(),
1688        };
1689        let out = project_program(&prog, &ProjectOptions::default());
1690        assert!(out.contains("prefix qudt: <http://qudt.org/vocab/unit>"));
1691        assert!(out.contains("requires ["));
1692        assert!(out.contains("capability(\"graph.read\")"));
1693    }
1694
1695    // ── round-trip tests ───────────────────────────────────────────
1696
1697    #[test]
1698    fn roundtrip_field() {
1699        let src = "field pressure: Pressure\n  unit: <qudt:KiloPascal>\n  support: point\n  representation: grid;\n";
1700        let prog = parse_program(src).expect("parse");
1701        let projected = project_program(&prog, &ProjectOptions::default());
1702        let reprog = parse_program(&projected).expect("re-parse");
1703        assert_eq!(prog.items.len(), reprog.items.len());
1704        // Both should be fields with the same name
1705        match (&prog.items[0], &reprog.items[0]) {
1706            (Item::Field(a), Item::Field(b)) => {
1707                assert_eq!(a.name, b.name);
1708                assert_eq!(a.unit, b.unit);
1709                assert_eq!(a.support, b.support);
1710                assert_eq!(a.representation, b.representation);
1711            }
1712            _ => panic!("expected fields"),
1713        }
1714    }
1715
1716    #[test]
1717    fn roundtrip_material() {
1718        let src = "material steel: Material\n  yield: 250.0,\n  density: 7850.0;\n";
1719        let prog = parse_program(src).expect("parse");
1720        let projected = project_program(&prog, &ProjectOptions::default());
1721        let reprog = parse_program(&projected).expect("re-parse");
1722        assert_eq!(prog.items.len(), reprog.items.len());
1723        match (&prog.items[0], &reprog.items[0]) {
1724            (Item::Material(a), Item::Material(b)) => {
1725                assert_eq!(a.name, b.name);
1726                assert_eq!(a.properties.len(), b.properties.len());
1727            }
1728            _ => panic!("expected materials"),
1729        }
1730    }
1731
1732    #[test]
1733    fn roundtrip_law() {
1734        let src = "law crush\n  when pressure > steel.yield\n  => 1;\n";
1735        let prog = parse_program(src).expect("parse");
1736        let projected = project_program(&prog, &ProjectOptions::default());
1737        let reprog = parse_program(&projected).expect("re-parse");
1738        assert_eq!(prog.items.len(), reprog.items.len());
1739        match (&prog.items[0], &reprog.items[0]) {
1740            (Item::Law(a), Item::Law(b)) => {
1741                assert_eq!(a.name, b.name);
1742            }
1743            _ => panic!("expected laws"),
1744        }
1745    }
1746
1747    #[test]
1748    fn roundtrip_function() {
1749        let src = "pure fn add(a: i64, b: i64) -> i64 {\n  return a + b;\n}\n";
1750        let prog = parse_program(src).expect("parse");
1751        let projected = project_program(&prog, &ProjectOptions::default());
1752        let reprog = parse_program(&projected).expect("re-parse");
1753        assert_eq!(prog.items.len(), reprog.items.len());
1754        match (&prog.items[0], &reprog.items[0]) {
1755            (Item::Function(a), Item::Function(b)) => {
1756                assert_eq!(a.name, b.name);
1757                assert_eq!(a.params.len(), b.params.len());
1758                assert_eq!(a.effect, b.effect);
1759            }
1760            _ => panic!("expected functions"),
1761        }
1762    }
1763
1764    #[test]
1765    fn roundtrip_const() {
1766        let src = "const PI: f64 = 3.14159;\n";
1767        let prog = parse_program(src).expect("parse");
1768        let projected = project_program(&prog, &ProjectOptions::default());
1769        let reprog = parse_program(&projected).expect("re-parse");
1770        assert_eq!(prog.items.len(), reprog.items.len());
1771        match (&prog.items[0], &reprog.items[0]) {
1772            (Item::Const(a), Item::Const(b)) => {
1773                assert_eq!(a.name, b.name);
1774            }
1775            _ => panic!("expected consts"),
1776        }
1777    }
1778
1779    #[test]
1780    fn roundtrip_enum() {
1781        let src = "enum Shape {\n  Circle(f64),\n  Point,\n}\n";
1782        let prog = parse_program(src).expect("parse");
1783        let projected = project_program(&prog, &ProjectOptions::default());
1784        let reprog = parse_program(&projected).expect("re-parse");
1785        assert_eq!(prog.items.len(), reprog.items.len());
1786        match (&prog.items[0], &reprog.items[0]) {
1787            (Item::Enum(a), Item::Enum(b)) => {
1788                assert_eq!(a.name, b.name);
1789                assert_eq!(a.variants.len(), b.variants.len());
1790                assert_eq!(a.variants[0].name, b.variants[0].name);
1791            }
1792            _ => panic!("expected enums"),
1793        }
1794    }
1795
1796    // ── structural edit tests ──────────────────────────────────────
1797
1798    #[test]
1799    fn edit_add_item() {
1800        let prog = Program {
1801            span: crate::span::Span::point(0),
1802            module: None,
1803            imports: Vec::new(),
1804            prefixes: Vec::new(),
1805            locales: Vec::new(),
1806            requires: Vec::new(),
1807            items: vec![make_field(
1808                "a",
1809                "A",
1810                None,
1811                FieldSupport::Region,
1812                FieldRepresentation::Grid,
1813            )],
1814        };
1815        let new_item = make_field(
1816            "b",
1817            "B",
1818            None,
1819            FieldSupport::Region,
1820            FieldRepresentation::Grid,
1821        );
1822        let edited = apply_edit(
1823            &prog,
1824            &Edit::AddItem {
1825                item: new_item,
1826                index: None,
1827            },
1828        );
1829        assert_eq!(edited.items.len(), 2);
1830        match &edited.items[1] {
1831            Item::Field(fd) => assert_eq!(fd.name, "b"),
1832            _ => panic!("expected field"),
1833        }
1834    }
1835
1836    #[test]
1837    fn edit_remove_item() {
1838        let prog = Program {
1839            span: crate::span::Span::point(0),
1840            module: None,
1841            imports: Vec::new(),
1842            prefixes: Vec::new(),
1843            locales: Vec::new(),
1844            requires: Vec::new(),
1845            items: vec![
1846                make_field(
1847                    "a",
1848                    "A",
1849                    None,
1850                    FieldSupport::Region,
1851                    FieldRepresentation::Grid,
1852                ),
1853                make_field(
1854                    "b",
1855                    "B",
1856                    None,
1857                    FieldSupport::Region,
1858                    FieldRepresentation::Grid,
1859                ),
1860            ],
1861        };
1862        let edited = apply_edit(&prog, &Edit::RemoveItem { index: 0 });
1863        assert_eq!(edited.items.len(), 1);
1864        match &edited.items[0] {
1865            Item::Field(fd) => assert_eq!(fd.name, "b"),
1866            _ => panic!("expected field"),
1867        }
1868    }
1869
1870    #[test]
1871    fn edit_rename_item() {
1872        let prog = Program {
1873            span: crate::span::Span::point(0),
1874            module: None,
1875            imports: Vec::new(),
1876            prefixes: Vec::new(),
1877            locales: Vec::new(),
1878            requires: Vec::new(),
1879            items: vec![make_field(
1880                "old_name",
1881                "A",
1882                None,
1883                FieldSupport::Region,
1884                FieldRepresentation::Grid,
1885            )],
1886        };
1887        let edited = apply_edit(
1888            &prog,
1889            &Edit::RenameItem {
1890                index: 0,
1891                new_name: "new_name".into(),
1892            },
1893        );
1894        match &edited.items[0] {
1895            Item::Field(fd) => assert_eq!(fd.name, "new_name"),
1896            _ => panic!("expected field"),
1897        }
1898    }
1899
1900    #[test]
1901    fn edit_set_field_unit() {
1902        let prog = Program {
1903            span: crate::span::Span::point(0),
1904            module: None,
1905            imports: Vec::new(),
1906            prefixes: Vec::new(),
1907            locales: Vec::new(),
1908            requires: Vec::new(),
1909            items: vec![make_field(
1910                "temp",
1911                "Temperature",
1912                None,
1913                FieldSupport::Region,
1914                FieldRepresentation::Grid,
1915            )],
1916        };
1917        let edited = apply_edit(
1918            &prog,
1919            &Edit::SetFieldUnit {
1920                index: 0,
1921                unit: Some("qudt:Kelvin".into()),
1922            },
1923        );
1924        match &edited.items[0] {
1925            Item::Field(fd) => assert_eq!(fd.unit.as_deref(), Some("qudt:Kelvin")),
1926            _ => panic!("expected field"),
1927        }
1928    }
1929
1930    #[test]
1931    fn edit_set_field_support() {
1932        let prog = Program {
1933            span: crate::span::Span::point(0),
1934            module: None,
1935            imports: Vec::new(),
1936            prefixes: Vec::new(),
1937            locales: Vec::new(),
1938            requires: Vec::new(),
1939            items: vec![make_field(
1940                "temp",
1941                "Temperature",
1942                None,
1943                FieldSupport::Region,
1944                FieldRepresentation::Grid,
1945            )],
1946        };
1947        let edited = apply_edit(
1948            &prog,
1949            &Edit::SetFieldSupport {
1950                index: 0,
1951                support: FieldSupport::Stream,
1952            },
1953        );
1954        match &edited.items[0] {
1955            Item::Field(fd) => assert_eq!(fd.support, FieldSupport::Stream),
1956            _ => panic!("expected field"),
1957        }
1958    }
1959
1960    #[test]
1961    fn edit_add_material_property() {
1962        let prog = Program {
1963            span: crate::span::Span::point(0),
1964            module: None,
1965            imports: Vec::new(),
1966            prefixes: Vec::new(),
1967            locales: Vec::new(),
1968            requires: Vec::new(),
1969            items: vec![make_material("steel", vec![("yield", make_float(250.0))])],
1970        };
1971        let edited = apply_edit(
1972            &prog,
1973            &Edit::AddMaterialProperty {
1974                index: 0,
1975                property: NamedArg {
1976                    span: crate::span::Span::point(0),
1977                    name: "density".into(),
1978                    value: make_float(7850.0),
1979                },
1980            },
1981        );
1982        match &edited.items[0] {
1983            Item::Material(md) => {
1984                assert_eq!(md.properties.len(), 2);
1985                assert_eq!(md.properties[1].name, "density");
1986            }
1987            _ => panic!("expected material"),
1988        }
1989    }
1990
1991    #[test]
1992    fn edit_remove_material_property() {
1993        let prog = Program {
1994            span: crate::span::Span::point(0),
1995            module: None,
1996            imports: Vec::new(),
1997            prefixes: Vec::new(),
1998            locales: Vec::new(),
1999            requires: Vec::new(),
2000            items: vec![make_material(
2001                "steel",
2002                vec![
2003                    ("yield", make_float(250.0)),
2004                    ("density", make_float(7850.0)),
2005                ],
2006            )],
2007        };
2008        let edited = apply_edit(
2009            &prog,
2010            &Edit::RemoveMaterialProperty {
2011                index: 0,
2012                name: "yield".into(),
2013            },
2014        );
2015        match &edited.items[0] {
2016            Item::Material(md) => {
2017                assert_eq!(md.properties.len(), 1);
2018                assert_eq!(md.properties[0].name, "density");
2019            }
2020            _ => panic!("expected material"),
2021        }
2022    }
2023
2024    #[test]
2025    fn edit_add_prefix() {
2026        let prog = Program {
2027            span: crate::span::Span::point(0),
2028            module: None,
2029            imports: Vec::new(),
2030            prefixes: Vec::new(),
2031            locales: Vec::new(),
2032            requires: Vec::new(),
2033            items: Vec::new(),
2034        };
2035        let edited = apply_edit(
2036            &prog,
2037            &Edit::AddPrefix {
2038                prefix: "qudt".into(),
2039                iri: "http://qudt.org/".into(),
2040            },
2041        );
2042        assert_eq!(edited.prefixes.len(), 1);
2043        assert_eq!(edited.prefixes[0].prefix, "qudt");
2044    }
2045
2046    #[test]
2047    fn edit_remove_prefix() {
2048        let prog = Program {
2049            span: crate::span::Span::point(0),
2050            module: None,
2051            imports: Vec::new(),
2052            prefixes: vec![
2053                crate::ast::PrefixDecl {
2054                    span: crate::span::Span::point(0),
2055                    prefix: "qudt".into(),
2056                    iri: "http://qudt.org/".into(),
2057                },
2058                crate::ast::PrefixDecl {
2059                    span: crate::span::Span::point(0),
2060                    prefix: "ex".into(),
2061                    iri: "http://example.org/".into(),
2062                },
2063            ],
2064            locales: Vec::new(),
2065            requires: Vec::new(),
2066            items: Vec::new(),
2067        };
2068        let edited = apply_edit(
2069            &prog,
2070            &Edit::RemovePrefix {
2071                prefix: "qudt".into(),
2072            },
2073        );
2074        assert_eq!(edited.prefixes.len(), 1);
2075        assert_eq!(edited.prefixes[0].prefix, "ex");
2076    }
2077
2078    #[test]
2079    fn edit_apply_sequence() {
2080        let prog = Program {
2081            span: crate::span::Span::point(0),
2082            module: None,
2083            imports: Vec::new(),
2084            prefixes: Vec::new(),
2085            locales: Vec::new(),
2086            requires: Vec::new(),
2087            items: Vec::new(),
2088        };
2089        let edits = vec![
2090            Edit::AddPrefix {
2091                prefix: "qudt".into(),
2092                iri: "http://qudt.org/".into(),
2093            },
2094            Edit::AddItem {
2095                item: make_field(
2096                    "temp",
2097                    "Temperature",
2098                    Some("qudt:Kelvin"),
2099                    FieldSupport::Point,
2100                    FieldRepresentation::Sampled,
2101                ),
2102                index: None,
2103            },
2104            Edit::AddItem {
2105                item: make_material("steel", vec![("yield", make_float(250.0))]),
2106                index: None,
2107            },
2108        ];
2109        let edited = apply_edits(&prog, &edits);
2110        assert_eq!(edited.prefixes.len(), 1);
2111        assert_eq!(edited.items.len(), 2);
2112    }
2113
2114    // ── edit + project integration ─────────────────────────────────
2115
2116    #[test]
2117    fn edit_then_project_produces_valid_source() {
2118        let src = "field pressure: Pressure\n  unit: <qudt:KiloPascal>;\n";
2119        let prog = parse_program(src).expect("parse");
2120        let edited = apply_edit(
2121            &prog,
2122            &Edit::SetFieldSupport {
2123                index: 0,
2124                support: FieldSupport::Stream,
2125            },
2126        );
2127        let projected = project_program(&edited, &ProjectOptions::default());
2128        // Should be re-parseable
2129        let reprog = parse_program(&projected).expect("re-parse");
2130        match &reprog.items[0] {
2131            Item::Field(fd) => {
2132                assert_eq!(fd.support, FieldSupport::Stream);
2133                assert_eq!(fd.unit.as_deref(), Some("qudt:KiloPascal"));
2134            }
2135            _ => panic!("expected field"),
2136        }
2137    }
2138
2139    #[test]
2140    fn edit_add_field_then_project() {
2141        let src = "material steel: Material\n  yield: 250.0;\n";
2142        let prog = parse_program(src).expect("parse");
2143        let new_field = make_field(
2144            "temp",
2145            "Temperature",
2146            Some("qudt:Kelvin"),
2147            FieldSupport::Point,
2148            FieldRepresentation::Grid,
2149        );
2150        let edited = apply_edit(
2151            &prog,
2152            &Edit::AddItem {
2153                item: new_field,
2154                index: Some(0),
2155            },
2156        );
2157        let projected = project_program(&edited, &ProjectOptions::default());
2158        let reprog = parse_program(&projected).expect("re-parse");
2159        assert_eq!(reprog.items.len(), 2);
2160        // Field should be first (inserted at index 0)
2161        match &reprog.items[0] {
2162            Item::Field(fd) => assert_eq!(fd.name, "temp"),
2163            _ => panic!("expected field at index 0"),
2164        }
2165        match &reprog.items[1] {
2166            Item::Material(md) => assert_eq!(md.name, "steel"),
2167            _ => panic!("expected material at index 1"),
2168        }
2169    }
2170
2171    // ── expression projection tests ────────────────────────────────
2172
2173    #[test]
2174    fn project_expr_list() {
2175        let e = Expr {
2176            span: crate::span::Span::point(0),
2177            kind: ExprKind::List(vec![make_int(1), make_int(2), make_int(3)]),
2178        };
2179        let mut out = String::new();
2180        project_expr(&e, &ProjectOptions::default(), &mut out);
2181        assert_eq!(out, "[1, 2, 3]");
2182    }
2183
2184    #[test]
2185    fn project_expr_record() {
2186        let e = Expr {
2187            span: crate::span::Span::point(0),
2188            kind: ExprKind::Record(vec![
2189                NamedArg {
2190                    span: crate::span::Span::point(0),
2191                    name: "x".into(),
2192                    value: make_int(1),
2193                },
2194                NamedArg {
2195                    span: crate::span::Span::point(0),
2196                    name: "y".into(),
2197                    value: make_int(2),
2198                },
2199            ]),
2200        };
2201        let mut out = String::new();
2202        project_expr(&e, &ProjectOptions::default(), &mut out);
2203        assert_eq!(out, "{ x: 1, y: 2 }");
2204    }
2205
2206    #[test]
2207    fn project_expr_binary() {
2208        let e = make_binary(BinOp::Add, make_int(1), make_int(2));
2209        let mut out = String::new();
2210        project_expr(&e, &ProjectOptions::default(), &mut out);
2211        assert_eq!(out, "1 + 2");
2212    }
2213
2214    #[test]
2215    fn project_expr_call() {
2216        let e = make_call("math.max", vec![make_int(0), make_int(100)]);
2217        let mut out = String::new();
2218        project_expr(&e, &ProjectOptions::default(), &mut out);
2219        assert_eq!(out, "math.max(0, 100)");
2220    }
2221
2222    #[test]
2223    fn project_expr_member() {
2224        let e = make_member("steel", "yield");
2225        let mut out = String::new();
2226        project_expr(&e, &ProjectOptions::default(), &mut out);
2227        assert_eq!(out, "steel.yield");
2228    }
2229
2230    #[test]
2231    fn project_expr_string() {
2232        let e = make_string("hello");
2233        let mut out = String::new();
2234        project_expr(&e, &ProjectOptions::default(), &mut out);
2235        assert_eq!(out, "\"hello\"");
2236    }
2237
2238    #[test]
2239    fn project_expr_iri() {
2240        let e = Expr {
2241            span: crate::span::Span::point(0),
2242            kind: ExprKind::Iri("https://example.org/foo".to_string()),
2243        };
2244        let mut out = String::new();
2245        project_expr(&e, &ProjectOptions::default(), &mut out);
2246        assert_eq!(out, "<https://example.org/foo>");
2247    }
2248
2249    // ── trivia-aware projection ────────────────────────────────────
2250
2251    #[test]
2252    fn project_with_trivia_preserves_comments() {
2253        let cst_items = vec![CstNode::new(
2254            make_field(
2255                "temp",
2256                "Temperature",
2257                Some("qudt:Kelvin"),
2258                FieldSupport::Region,
2259                FieldRepresentation::Grid,
2260            ),
2261            vec![Trivia::line_comment(
2262                "// This is a field",
2263                crate::span::Span::point(0),
2264            )],
2265            vec![],
2266        )];
2267        let prog = Program {
2268            span: crate::span::Span::point(0),
2269            module: None,
2270            imports: Vec::new(),
2271            prefixes: Vec::new(),
2272            locales: Vec::new(),
2273            requires: Vec::new(),
2274            items: vec![make_field(
2275                "temp",
2276                "Temperature",
2277                Some("qudt:Kelvin"),
2278                FieldSupport::Region,
2279                FieldRepresentation::Grid,
2280            )],
2281        };
2282        let out = project_with_trivia(&prog, &cst_items, &ProjectOptions::default());
2283        assert!(out.contains("// This is a field"));
2284        assert!(out.contains("field temp: Temperature"));
2285    }
2286}