daml-lint 0.9.4

Static analysis scanner for Daml smart contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
//! Lowering: typed AST (from the `daml-parser` crate) → rule-facing IR
//! (src/ir.rs).
//!
//! This replaces the old line-based keyword shim. The IR shapes are the
//! stable contract with rule scripts; structured `Expr` and `TypeNode`
//! payloads carry the actual parse tree.

use crate::ir::{
    BranchArm, CaseAlt, CaseBranch, CaseGuard, Choice, Consuming, DamlModule, EnsureClause, Expr,
    Field, Function, Import, ImportStyle, Interface, InterfaceInstance, InterfaceMethod,
    LetBinding, LiteralKind, RecordField, Span, SrcPos, Statement, Template, TypeNode,
};
use daml_parser::ast::{
    self, Consuming as ParserConsuming, Decl, DiagnosticCategory as ParserDiagnosticCategory,
    DoStmt, ImportStyle as ParserImportStyle, TemplateBodyDecl,
};
use daml_syntax::{CharColumn, DiagnosticEndColumn, LineNumber, SourceFile};
use std::error::Error;
use std::fmt;
use std::path::Path;

#[cfg(all(test, feature = "js-runtime"))]
pub(crate) fn parse_daml(source: &str, file: &Path) -> DamlModule {
    parse_daml_with_diagnostics(source, file).module
}

/// A parse diagnostic for the caller to report.
///
/// `end_column` is present when the offending span sits on a single line (most
/// tokens); `category` is the parser's recovery classification.
#[derive(Debug)]
#[non_exhaustive]
pub struct ParseDiagnostic {
    /// 1-based diagnostic start line.
    pub line: LineNumber,
    /// 1-based Unicode-scalar diagnostic start column.
    pub column: CharColumn,
    /// Exclusive 1-based Unicode-scalar end column for non-empty single-line
    /// diagnostics; `None` for multi-line or zero-width diagnostics.
    pub end_column: Option<CharColumn>,
    /// Human-readable diagnostic message from the parser.
    pub message: String,
    /// Stable recovery category for machine-readable reporting.
    pub category: ParseDiagnosticCategory,
}

/// Stable, machine-readable parse-diagnostic categories.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseDiagnosticCategory {
    /// A declaration could not be parsed and was skipped to the next item.
    SkippedDeclaration,
    /// A malformed expression, pattern, or expected-token error inside an
    /// otherwise-recognized construct.
    Malformed,
    /// A construct the parser intentionally does not support, e.g. legacy
    /// `controller ... can` choice syntax.
    UnsupportedSyntax,
    /// Expression/pattern nesting exceeded the recursion bound and was degraded
    /// to raw text.
    RecursionLimit,
    /// A lexical error (unterminated string/comment, stray character).
    LexicalError,
    /// The parser reported an unknown or forward-compatible diagnostic category.
    Unknown,
}

impl ParseDiagnosticCategory {
    /// Stable kebab-case tag used by JSON/SARIF output and external tooling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SkippedDeclaration => "skipped-declaration",
            Self::Malformed => "malformed",
            Self::UnsupportedSyntax => "unsupported-syntax",
            Self::RecursionLimit => "recursion-limit",
            Self::LexicalError => "lexical-error",
            Self::Unknown => "unknown",
        }
    }
}

impl fmt::Display for ParseDiagnosticCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<ParserDiagnosticCategory> for ParseDiagnosticCategory {
    fn from(category: ParserDiagnosticCategory) -> Self {
        match category {
            ParserDiagnosticCategory::SkippedDecl => Self::SkippedDeclaration,
            ParserDiagnosticCategory::Malformed => Self::Malformed,
            ParserDiagnosticCategory::UnsupportedSyntax => Self::UnsupportedSyntax,
            ParserDiagnosticCategory::RecursionLimit => Self::RecursionLimit,
            ParserDiagnosticCategory::Lex => Self::LexicalError,
            _ => Self::Unknown,
        }
    }
}

/// Error returned when parsing an unsupported parse-diagnostic category tag.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseDiagnosticCategoryParseError {
    value: String,
}

impl ParseDiagnosticCategoryParseError {
    fn new(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
        }
    }
}

impl fmt::Display for ParseDiagnosticCategoryParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid parse diagnostic category: {}", self.value)
    }
}

impl Error for ParseDiagnosticCategoryParseError {}

impl std::str::FromStr for ParseDiagnosticCategory {
    type Err = ParseDiagnosticCategoryParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "skipped-declaration" => Ok(Self::SkippedDeclaration),
            "malformed" => Ok(Self::Malformed),
            "unsupported-syntax" => Ok(Self::UnsupportedSyntax),
            "recursion-limit" => Ok(Self::RecursionLimit),
            "lexical-error" => Ok(Self::LexicalError),
            "unknown" => Ok(Self::Unknown),
            _ => Err(ParseDiagnosticCategoryParseError::new(s)),
        }
    }
}

/// Result of loss-tolerant parser lowering.
///
/// `module` is always returned and may be partial when `diagnostics` is
/// non-empty. Callers that require authoritative scans should reject results
/// with diagnostics before running or accepting detector output.
#[derive(Debug)]
#[non_exhaustive]
pub struct ParseResult {
    /// Lowered rule-facing module, possibly partial if parse recovery occurred.
    pub module: DamlModule,
    /// Recoverable parse and lexical diagnostics in source order.
    pub diagnostics: Vec<ParseDiagnostic>,
}

/// Parse DAML source into the lint IR plus parse diagnostics.
///
/// Parsing is loss-tolerant: a `DamlModule` is returned even when `diags` is
/// non-empty.
///
/// # API note
///
/// `ParseResult` is the supported return type (`{ module, diagnostics }`) and
/// replaces the previous tuple-shaped return. This is a breaking API shape
/// change in favor of clearer, named-field access.
#[must_use]
pub fn parse_daml_with_diagnostics(source: &str, file: &Path) -> ParseResult {
    let source_file = SourceFile::parse(source);
    let module = source_file.module();
    let imports = module
        .imports
        .iter()
        .map(|i| Import {
            module_name: i.module_name.to_string(),
            qualified: if i.style == ParserImportStyle::Qualified {
                ImportStyle::Qualified
            } else {
                ImportStyle::Unqualified
            },
            alias: i.alias.clone().map(|alias| alias.to_string()),
            package_label: i.package_label.as_ref().map(|label| label.value.clone()),
            span: span_at(file, i.pos),
        })
        .collect();

    let mut templates = Vec::new();
    let mut interfaces = Vec::new();
    let mut functions = Vec::new();

    for decl in &module.decls {
        match decl {
            Decl::Template(t) => templates.push(lower_template(t, file, &source_file)),
            Decl::Interface(i) => interfaces.push(lower_interface(i, file, &source_file)),
            Decl::Function(f) => {
                if f.equations.is_empty() {
                    continue; // type signature without a body
                }
                functions.push(lower_function(f, file, &source_file));
            }
            _ => {}
        }
    }

    let module = DamlModule {
        ir_version: 8,
        name: module.name.to_string(),
        file: file.to_path_buf(),
        source: source.to_string(),
        imports,
        templates,
        interfaces,
        functions,
    };
    let diags = source_file
        .diagnostics()
        .iter()
        .map(|d| ParseDiagnostic {
            line: d.line(),
            column: d.column(),
            end_column: if let DiagnosticEndColumn::SameLineEnd(end_column) = d.end_column() {
                Some(end_column)
            } else {
                None
            },
            message: d.message().to_owned(),
            category: d.category().into(),
        })
        .collect();
    ParseResult {
        module,
        diagnostics: diags,
    }
}

fn span_at(file: &Path, pos: ast::Pos) -> Span {
    Span {
        file: file.to_path_buf(),
        line: LineNumber::new(pos.line),
        column: CharColumn::new(pos.column),
    }
}

const fn src_pos(pos: ast::Pos) -> SrcPos {
    SrcPos {
        line: LineNumber::new(pos.line),
        column: CharColumn::new(pos.column),
    }
}

// ----- expressions -------------------------------------------------------

fn lower_case_guard(guard: &ast::GuardQualifier) -> CaseGuard {
    match guard {
        ast::GuardQualifier::Bool { expr, .. } => CaseGuard::Bool {
            expr: lower_expr(expr),
        },
        ast::GuardQualifier::Pattern { pat, expr, .. } => CaseGuard::Pattern {
            pattern: pat.render(),
            expr: lower_expr(expr),
        },
        _ => CaseGuard::Bool {
            expr: Expr::Unknown {
                raw: String::new(),
                span: src_pos(guard.pos()),
            },
        },
    }
}

fn lower_case_alt(alt: &ast::Alt) -> CaseAlt {
    CaseAlt {
        pattern: alt.pat.render(),
        body: lower_expr(&alt.body),
        branches: alt
            .branches
            .iter()
            .map(|branch| CaseBranch {
                guards: branch.guards.iter().map(lower_case_guard).collect(),
                body: lower_expr(&branch.body),
            })
            .collect(),
        where_bindings: alt
            .where_bindings
            .iter()
            .map(|b| LetBinding {
                name: binding_name(b),
                value: lower_expr(&b.expr),
            })
            .collect(),
    }
}

fn lower_expr(e: &ast::Expr) -> Expr {
    let span = src_pos(e.pos());
    match e {
        ast::Expr::Var {
            qualifier, name, ..
        } => Expr::Var {
            name: name.to_string(),
            qualifier: qualifier.to_owned().map(String::from),
            span,
        },
        ast::Expr::Con {
            qualifier, name, ..
        } => Expr::Con {
            name: name.to_string(),
            qualifier: qualifier.to_owned().map(String::from),
            span,
        },
        ast::Expr::Lit { kind, text, .. } => Expr::Lit {
            kind: match kind {
                ast::LitKind::Int => LiteralKind::Int,
                ast::LitKind::Decimal => LiteralKind::Decimal,
                ast::LitKind::Char => LiteralKind::Char,
                _ => LiteralKind::Text,
            },
            value: text.clone(),
            span,
        },
        ast::Expr::App { func, args, .. } => Expr::App {
            func: Box::new(lower_expr(func)),
            args: args.iter().map(lower_expr).collect(),
            span,
        },
        ast::Expr::BinOp { op, lhs, rhs, .. } => Expr::BinOp {
            op: op.to_string(),
            lhs: Box::new(lower_expr(lhs)),
            rhs: Box::new(lower_expr(rhs)),
            span,
        },
        ast::Expr::Neg { expr, .. } => Expr::Neg {
            expr: Box::new(lower_expr(expr)),
            span,
        },
        ast::Expr::Lambda { params, body, .. } => Expr::Lambda {
            params: params.iter().map(|p| p.render()).collect(),
            body: Box::new(lower_expr(body)),
            span,
        },
        ast::Expr::If {
            cond,
            then_branch,
            else_branch,
            ..
        } => Expr::If {
            cond: Box::new(lower_expr(cond)),
            then_branch: Box::new(lower_expr(then_branch)),
            else_branch: Box::new(lower_expr(else_branch)),
            span,
        },
        ast::Expr::Case {
            scrutinee, alts, ..
        } => Expr::Case {
            scrutinee: Box::new(lower_expr(scrutinee)),
            alts: alts.iter().map(lower_case_alt).collect(),
            span,
        },
        ast::Expr::Do { stmts, .. } => Expr::DoBlock {
            statements: lower_do(stmts),
            span,
        },
        ast::Expr::LetIn { bindings, body, .. } => Expr::LetIn {
            bindings: bindings
                .iter()
                .map(|b| LetBinding {
                    name: binding_name(b),
                    value: lower_expr(&b.expr),
                })
                .collect(),
            body: Box::new(lower_expr(body)),
            span,
        },
        ast::Expr::Record { base, fields, .. } => Expr::Record {
            base: Box::new(lower_expr(base)),
            fields: fields
                .iter()
                .map(|f| match f {
                    ast::FieldAssign::Assign { name, value, .. } => RecordField {
                        name: name.to_string(),
                        value: Some(lower_expr(value)),
                    },
                    ast::FieldAssign::Pun { name, .. } => RecordField {
                        name: name.to_string(),
                        value: None,
                    },
                    ast::FieldAssign::Wildcard { .. } => RecordField {
                        name: "..".to_string(),
                        value: None,
                    },
                    _ => RecordField {
                        name: String::new(),
                        value: None,
                    },
                })
                .collect(),
            span,
        },
        ast::Expr::Tuple { items, .. } => Expr::Tuple {
            items: items.iter().map(lower_expr).collect(),
            span,
        },
        ast::Expr::List { items, .. } => Expr::List {
            items: items.iter().map(lower_expr).collect(),
            span,
        },
        // No structured rule-facing encoding (yet): sections, try-in-
        // expression-position, recovered parse errors.
        _ => Expr::Unknown {
            raw: e.render(),
            span,
        },
    }
}

fn binding_name(b: &ast::Binding) -> String {
    let mut name = b.pat.render();
    for p in &b.params {
        name.push(' ');
        name.push_str(&p.render());
    }
    name
}

// ----- declarations ------------------------------------------------------

fn lower_template(t: &ast::TemplateDecl, file: &Path, source_file: &SourceFile) -> Template {
    let fields = t
        .fields
        .iter()
        .map(|f| Field {
            name: f.name.to_string(),
            type_: f
                .ty
                .as_type()
                .map(|ty| TypeNode::from_type(ty, file, source_file)),
            span: span_at(file, f.pos),
        })
        .collect();

    let mut signatory_exprs = Vec::new();
    let mut observer_exprs = Vec::new();
    let mut ensure_clause = None;
    let mut key_expr = None;
    let mut key_type = None;
    let mut maintainer_exprs = Vec::new();
    let mut choices = Vec::new();
    let mut interface_instances = Vec::new();

    for item in &t.body {
        match item {
            TemplateBodyDecl::Signatory { parties, .. } => {
                signatory_exprs.extend(parties.iter().map(lower_expr));
            }
            TemplateBodyDecl::Observer { parties, .. } => {
                observer_exprs.extend(parties.iter().map(lower_expr));
            }
            TemplateBodyDecl::Ensure { expr, pos, .. } => {
                ensure_clause = Some(EnsureClause {
                    expr: lower_expr(expr),
                    span: span_at(file, *pos),
                });
            }
            TemplateBodyDecl::Key { expr, ty, .. } => {
                key_expr = Some(lower_expr(expr));
                key_type = ty
                    .as_type()
                    .map(|ty| TypeNode::from_type(ty, file, source_file));
            }
            TemplateBodyDecl::Maintainer { expr, .. } => {
                maintainer_exprs.push(lower_expr(expr));
            }
            TemplateBodyDecl::Choice(c) => choices.push(lower_choice(c, file, source_file)),
            TemplateBodyDecl::InterfaceInstance(ii) => {
                let mut methods = Vec::new();
                let mut view_expr = None;
                for item in &ii.items {
                    match item {
                        ast::InterfaceInstanceBodyItem::View { expr, .. } => {
                            view_expr = Some(lower_expr(expr));
                        }
                        ast::InterfaceInstanceBodyItem::Method(binding) => {
                            methods.push(binding_name(binding));
                        }
                        _ => {}
                    }
                }
                interface_instances.push(InterfaceInstance {
                    interface_name: ii.interface_name.to_string(),
                    view_expr,
                    methods,
                    span: span_at(file, ii.pos),
                });
            }
            _ => {}
        }
    }

    Template {
        name: t.name.to_string(),
        fields,
        signatory_exprs,
        observer_exprs,
        ensure_clause,
        key_expr,
        key_type,
        maintainer_exprs,
        choices,
        interface_instances,
        span: span_at(file, t.pos),
    }
}

fn lower_interface(i: &ast::InterfaceDecl, file: &Path, source_file: &SourceFile) -> Interface {
    Interface {
        name: i.name.to_string(),
        requires: i.requires.iter().map(ToString::to_string).collect(),
        viewtype: i.viewtype.to_owned().map(String::from),
        methods: i
            .methods
            .iter()
            .map(|m| InterfaceMethod {
                name: m.name.to_string(),
                type_: m
                    .ty
                    .as_type()
                    .map(|ty| TypeNode::from_type(ty, file, source_file)),
                span: span_at(file, m.pos),
            })
            .collect(),
        choices: i
            .choices
            .iter()
            .map(|c| lower_choice(c, file, source_file))
            .collect(),
        span: span_at(file, i.pos),
    }
}

fn lower_choice(c: &ast::ChoiceDecl, file: &Path, source_file: &SourceFile) -> Choice {
    let parameters = c
        .params
        .iter()
        .map(|f| Field {
            name: f.name.to_string(),
            type_: f
                .ty
                .as_type()
                .map(|ty| TypeNode::from_type(ty, file, source_file)),
            span: span_at(file, f.pos),
        })
        .collect();

    let body = c.body.as_ref().map_or_else(Vec::new, statements_of_expr);

    Choice {
        name: c.name.to_string(),
        // pre/postconsuming choices archive the contract just like the default
        // consuming form; only NonConsuming leaves it live.
        consuming: if c.consuming == ParserConsuming::NonConsuming {
            Consuming::NonConsuming
        } else {
            Consuming::Consuming
        },
        controller_exprs: c.controllers.iter().map(lower_expr).collect(),
        observer_exprs: c.observers.iter().map(lower_expr).collect(),
        authority_exprs: c.authority_exprs.iter().map(lower_expr).collect(),
        parameters,
        return_type: c
            .return_ty
            .as_type()
            .map(|ty| TypeNode::from_type(ty, file, source_file)),
        body,
        span: span_at(file, c.pos),
    }
}

fn lower_function(f: &ast::FunctionDecl, file: &Path, source_file: &SourceFile) -> Function {
    let mut body = Vec::new();
    for eq in &f.equations {
        if eq.guards.is_empty() {
            body.extend(statements_of_expr(&eq.body));
        } else {
            for (_, guard_body) in &eq.guards {
                body.extend(statements_of_expr(guard_body));
            }
        }
        // `where` helpers can perform ledger actions when invoked; surface
        // their actions like the line shim did.
        for b in &eq.where_bindings {
            let mut acts = Vec::new();
            collect_actions(&b.expr, None, &mut acts);
            body.extend(acts);
        }
    }

    Function {
        name: f.name.to_string(),
        type_signature: f
            .ty
            .as_type()
            .map(|ty| TypeNode::from_type(ty, file, source_file)),
        body,
        span: span_at(file, f.pos),
    }
}

// ----- statements --------------------------------------------------------

/// Statements of a choice/function body expression: a do block yields its
/// statements; any other expression is a single statement.
fn statements_of_expr(expr: &ast::Expr) -> Vec<Statement> {
    match expr {
        ast::Expr::Do { stmts, .. } => lower_do(stmts),
        other => {
            let mut acts = Vec::new();
            if collect_actions(other, None, &mut acts) {
                acts
            } else {
                vec![other_statement(other, None)]
            }
        }
    }
}

fn other_statement(expr: &ast::Expr, binder: Option<&ast::Pat>) -> Statement {
    let raw = binder.map_or_else(
        || expr.render(),
        |p| format!("{} <- {}", p.render(), expr.render()),
    );
    Statement::Other {
        raw,
        expr: lower_expr(expr),
        binder: binder.map(|p| p.render()),
        span: src_pos(expr.pos()),
    }
}

fn case_branch_guard_statements(branch: &ast::AltBranch) -> Vec<Statement> {
    branch
        .guards
        .iter()
        .filter_map(|guard| {
            let (ast::GuardQualifier::Bool { expr, .. }
            | ast::GuardQualifier::Pattern { expr, .. }) = guard
            else {
                return None;
            };
            Some(other_statement(expr, None))
        })
        .collect()
}

fn lower_do(stmts: &[DoStmt]) -> Vec<Statement> {
    let mut out = Vec::new();
    let mut helpers: std::collections::HashMap<String, Helper<'_>> =
        std::collections::HashMap::new();
    for stmt in stmts {
        match stmt {
            DoStmt::Let { bindings, .. } => {
                for b in bindings {
                    let name = binding_name(b);
                    out.push(Statement::Let {
                        name: name.clone(),
                        value: lower_expr(&b.expr),
                        span: src_pos(b.pos),
                    });
                    // A let-bound local helper (`let go x = archive x`) only
                    // DEFINES its actions; they execute at the CALL site (or
                    // never), not at the definition. Record it under its bare
                    // name (without the parameters that `binding_name` appends)
                    // for expansion there, and do NOT surface its archive at the
                    // `let` line.
                    if let Some(params) = formal_param_names(b) {
                        helpers.insert(
                            b.pat.render(),
                            Helper {
                                params,
                                body: &b.expr,
                            },
                        );
                    }
                }
            }
            DoStmt::Bind { pat, expr, .. } => {
                let mut acts = Vec::new();
                if expand_helper_call(expr, Some(pat), &helpers, &mut out) {
                    // expanded in place at the call site
                } else if collect_actions(expr, Some(pat), &mut acts) {
                    out.extend(acts);
                } else {
                    out.push(other_statement(expr, Some(pat)));
                }
            }
            DoStmt::Expr { expr, .. } => {
                let mut acts = Vec::new();
                if expand_helper_call(expr, None, &helpers, &mut out) {
                    // expanded in place at the call site
                } else if collect_actions(expr, None, &mut acts) {
                    out.extend(acts);
                } else {
                    out.push(other_statement(expr, None));
                }
            }
            _ => {}
        }
    }
    out
}

/// A let-bound local helper (`let f x = archive x`): its formal parameter names
/// and body. Its ledger actions run at each CALL site (or never), so they are
/// expanded where it is invoked, not recorded at the definition.
struct Helper<'a> {
    params: Vec<String>,
    body: &'a ast::Expr,
}

/// The simple variable names of a function binding's formal parameters
/// (`let f x y = ...` → `["x", "y"]`). None when the binding takes no parameters
/// (a plain value, not a helper) or any parameter is a non-trivial pattern we
/// cannot substitute by name.
fn formal_param_names(b: &ast::Binding) -> Option<Vec<String>> {
    if b.params.is_empty() {
        return None;
    }
    b.params
        .iter()
        .map(|p| match p {
            ast::Pat::Var { name, .. } => Some(name.to_string()),
            _ => None,
        })
        .collect()
}

/// If `expr` invokes a known local helper with a matching argument count, expand
/// the helper body with the actual arguments substituted for its formal
/// parameters, re-point every node to the CALL site, and lower the result there
/// (so the archive/effect lands on the invocation line with the real argument).
/// Returns true when an action was expanded. A partial application (arity
/// mismatch) is left for normal lowering.
fn expand_helper_call(
    expr: &ast::Expr,
    binder: Option<&ast::Pat>,
    helpers: &std::collections::HashMap<String, Helper<'_>>,
    out: &mut Vec<Statement>,
) -> bool {
    let ast::Expr::App { func, args, .. } = expr else {
        return false;
    };
    let ast::Expr::Var {
        qualifier: None,
        name,
        ..
    } = func.as_ref()
    else {
        return false;
    };
    let Some(helper) = helpers.get(name.as_str()) else {
        return false;
    };
    if helper.params.len() != args.len() {
        return false;
    }
    let subst: std::collections::HashMap<&str, &ast::Expr> = helper
        .params
        .iter()
        .map(|p| p.as_str())
        .zip(args.iter())
        .collect();
    let call_pos = expr.pos();
    let expanded = subst_expr(helper.body, &subst, call_pos);
    collect_actions(&expanded, binder, out)
}

/// Substitute actual arguments for a helper's formal parameters throughout
/// `expr`, re-pointing every rebuilt node to `call_pos` (the invocation site) so
/// a finding cites the call, not the definition. A bare `Var` naming a formal is
/// replaced by the actual argument; everything else is rebuilt structurally, and
/// any node we do not rebuild is repointed as-is. The realistic helper is a
/// single ledger action over its arguments.
fn subst_expr(
    expr: &ast::Expr,
    subst: &std::collections::HashMap<&str, &ast::Expr>,
    call_pos: ast::Pos,
) -> ast::Expr {
    use ast::Expr as E;
    match expr {
        E::Var {
            qualifier: None,
            name,
            span,
            ..
        } => subst.get(name.as_str()).map_or_else(
            || E::Var {
                qualifier: None,
                name: name.clone(),
                pos: call_pos,
                span: *span,
            },
            |arg| repoint(arg, call_pos),
        ),
        E::App {
            func, args, span, ..
        } => E::App {
            func: Box::new(subst_expr(func, subst, call_pos)),
            args: args
                .iter()
                .map(|a| subst_expr(a, subst, call_pos))
                .collect(),
            pos: call_pos,
            span: *span,
        },
        E::BinOp {
            op, lhs, rhs, span, ..
        } => E::BinOp {
            op: op.clone(),
            lhs: Box::new(subst_expr(lhs, subst, call_pos)),
            rhs: Box::new(subst_expr(rhs, subst, call_pos)),
            pos: call_pos,
            span: *span,
        },
        E::Neg { expr, span, .. } => E::Neg {
            expr: Box::new(subst_expr(expr, subst, call_pos)),
            pos: call_pos,
            span: *span,
        },
        E::Record {
            base, fields, span, ..
        } => E::Record {
            base: Box::new(subst_expr(base, subst, call_pos)),
            fields: fields
                .iter()
                .map(|f| match f {
                    ast::FieldAssign::Assign {
                        name,
                        value,
                        pos,
                        span,
                    } => ast::FieldAssign::Assign {
                        name: name.clone(),
                        value: subst_expr(value, subst, call_pos),
                        pos: *pos,
                        span: *span,
                    },
                    ast::FieldAssign::Pun { name, pos, span } => ast::FieldAssign::Pun {
                        name: name.clone(),
                        pos: *pos,
                        span: *span,
                    },
                    ast::FieldAssign::Wildcard { pos, span } => ast::FieldAssign::Wildcard {
                        pos: *pos,
                        span: *span,
                    },
                    _ => f.clone(),
                })
                .collect(),
            pos: call_pos,
            span: *span,
        },
        E::Tuple { items, span, .. } => E::Tuple {
            items: items
                .iter()
                .map(|i| subst_expr(i, subst, call_pos))
                .collect(),
            pos: call_pos,
            span: *span,
        },
        E::List { items, span, .. } => E::List {
            items: items
                .iter()
                .map(|i| subst_expr(i, subst, call_pos))
                .collect(),
            pos: call_pos,
            span: *span,
        },
        // A helper body that is itself a do-block / conditional / lambda is
        // beyond this targeted substitution; repoint what we can and lower it
        // as-is.
        other => repoint(other, call_pos),
    }
}

/// Shallowly re-point an expression's top-level position to `call_pos` so a
/// substituted argument or unhandled body reports the invocation line. Nested
/// positions are left as-is.
fn repoint(expr: &ast::Expr, call_pos: ast::Pos) -> ast::Expr {
    use ast::Expr as E;
    let mut e = expr.clone();
    match &mut e {
        E::Var { pos, .. }
        | E::Con { pos, .. }
        | E::Lit { pos, .. }
        | E::App { pos, .. }
        | E::BinOp { pos, .. }
        | E::Neg { pos, .. }
        | E::Lambda { pos, .. }
        | E::If { pos, .. }
        | E::Case { pos, .. }
        | E::Do { pos, .. }
        | E::LetIn { pos, .. }
        | E::Record { pos, .. }
        | E::Tuple { pos, .. }
        | E::List { pos, .. }
        | E::Try { pos, .. }
        | E::OperatorRef { pos, .. }
        | E::LeftSection { pos, .. }
        | E::RightSection { pos, .. }
        | E::Error { pos, .. } => *pos = call_pos,
        _ => {}
    }
    e
}

/// Walk an expression collecting ledger-action statements (create,
/// exercise, fetch, archive, assert, try/catch). Returns true if anything
/// was collected. Only unqualified applications count: `Lifecycle.exercise`
/// is a user function, not the ledger action.
///
/// External callers are all statement-position, where an `if`/`case` is its own
/// set of mutually-exclusive scopes and an `assert` is an unconditional guard.
fn collect_actions(expr: &ast::Expr, binder: Option<&ast::Pat>, out: &mut Vec<Statement>) -> bool {
    collect_actions_inner(expr, binder, out, true, false)
}

/// `stmt_pos` is true when `expr` is in statement position (a do-statement or an
/// `if`/`case` arm). A statement-position `if`/`case` is lowered to a single
/// `Statement::Branch` whose arms are independent scopes; an `if`/`case` reached
/// by descending into a sub-expression (an application argument, an operand, a
/// lambda body) is left in the `Expr` tree for the enclosing statement to carry,
/// so a value-level guard like `if denom /= 0 then x / denom` stays analyzable.
///
/// `conditional` is true once we are inside a branch / iteration / lambda
/// argument that runs only on some paths or zero-or-more times. An `assert`
/// lifted from there is not a guarantee, so it is recorded as a plain
/// `Statement::Other` (scannable, but never a guard) rather than a
/// `Statement::Assert`.
fn collect_actions_inner(
    expr: &ast::Expr,
    binder: Option<&ast::Pat>,
    out: &mut Vec<Statement>,
    stmt_pos: bool,
    conditional: bool,
) -> bool {
    let before = out.len();
    match expr {
        ast::Expr::Do { stmts, .. } => {
            out.extend(lower_do(stmts));
        }
        ast::Expr::Try { body, handlers, .. } => {
            let try_body = statements_of_expr(body);
            let mut catch_body = Vec::new();
            for h in handlers {
                for branch in &h.branches {
                    catch_body.extend(statements_of_expr(&branch.body));
                }
            }
            out.push(Statement::TryCatch {
                try_body,
                catch_body,
                span: src_pos(expr.pos()),
            });
        }
        ast::Expr::If {
            cond,
            then_branch,
            else_branch,
            ..
        } => {
            if stmt_pos {
                // The condition rides along as the Branch scrutinee so a defensive
                // guard (`if amount <= 0 then abort`) stays analyzable; the arms
                // (then, else) carry no pattern.
                push_branch(
                    Some(cond),
                    &[then_branch, else_branch],
                    &[None, None],
                    expr,
                    out,
                );
            } else {
                // Expression-position `if`: surface only ledger actions inside,
                // leaving the `Expr::If` (and its condition guard) for the
                // enclosing statement.
                collect_actions_inner(then_branch, None, out, false, conditional);
                collect_actions_inner(else_branch, None, out, false, conditional);
            }
        }
        ast::Expr::Case {
            scrutinee, alts, ..
        } => {
            if stmt_pos {
                let arms: Vec<BranchArm> = alts
                    .iter()
                    .flat_map(|alt| {
                        let where_body: Vec<Statement> = alt
                            .where_bindings
                            .iter()
                            .map(|b| Statement::Let {
                                name: binding_name(b),
                                value: lower_expr(&b.expr),
                                span: src_pos(b.pos),
                            })
                            .collect();
                        if alt.branches.is_empty() {
                            let mut arm_body = statements_of_expr(&alt.body);
                            arm_body.extend(where_body);
                            vec![BranchArm {
                                pattern: Some(alt.pat.render()),
                                body: arm_body,
                            }]
                        } else {
                            let branch_count = alt.branches.len();
                            alt.branches
                                .iter()
                                .enumerate()
                                .map(|(index, branch)| {
                                    let mut arm_body = case_branch_guard_statements(branch);
                                    arm_body.extend(statements_of_expr(&branch.body));
                                    if index + 1 == branch_count {
                                        arm_body.extend(where_body.clone());
                                    }
                                    BranchArm {
                                        pattern: Some(alt.pat.render()),
                                        body: arm_body,
                                    }
                                })
                                .collect()
                        }
                    })
                    .collect();
                out.push(Statement::Branch {
                    scrutinee: Some(lower_expr(scrutinee)),
                    arms,
                    span: src_pos(expr.pos()),
                });
            } else {
                for alt in alts {
                    for branch in &alt.branches {
                        collect_actions_inner(&branch.body, None, out, false, conditional);
                    }
                    for b in &alt.where_bindings {
                        collect_actions_inner(&b.expr, None, out, false, conditional);
                    }
                }
            }
        }
        ast::Expr::LetIn { body, .. } => {
            collect_actions_inner(body, None, out, stmt_pos, conditional);
        }
        ast::Expr::Lambda { body, .. } => {
            // A lambda body runs in a deferred / zero-or-more context, so an
            // assert inside it is not an unconditional guarantee.
            collect_actions_inner(body, None, out, false, true);
        }
        ast::Expr::Neg { expr, .. } => {
            collect_actions_inner(expr, None, out, false, conditional);
        }
        ast::Expr::BinOp {
            op,
            lhs,
            rhs,
            pos,
            span,
        } => {
            // `create $ Foo with ...` — `$` is application.
            if op.as_str() == "$" {
                let as_app = ast::Expr::App {
                    func: lhs.clone(),
                    args: vec![(**rhs).clone()],
                    pos: *pos,
                    span: *span,
                };
                if classify_app(&as_app, binder, out, conditional) {
                    return out.len() > before;
                }
            }
            collect_actions_inner(lhs, None, out, false, conditional);
            collect_actions_inner(rhs, None, out, false, conditional);
        }
        ast::Expr::App { args, .. } => {
            if !classify_app(expr, binder, out, conditional) {
                // `when c act` / `forA_ xs f` run their action argument only on
                // some paths or zero-or-more times: an assert lifted from inside
                // is conditional, not a guard.
                let arg_conditional =
                    conditional || is_conditional_combinator(expr.application_head());
                for a in args {
                    collect_actions_inner(a, None, out, false, arg_conditional);
                }
            }
        }
        ast::Expr::Tuple { items, .. } | ast::Expr::List { items, .. } => {
            for i in items {
                collect_actions_inner(i, None, out, false, conditional);
            }
        }
        _ => {}
    }
    out.len() > before
}

/// Lower each branch of a statement-position `if`/`case` into its own scope and
/// push one `Statement::Branch`. `scrutinee` is the case scrutinee (None for
/// `if`); `patterns[i]` is arm i's source pattern (None for the `if` then/else
/// arms). Always pushes the Branch: the case shape (scrutinee + patterns) must
/// survive even when the arms perform no ledger action, so a detector can read
/// it structurally.
fn push_branch(
    scrutinee: Option<&ast::Expr>,
    branches: &[&ast::Expr],
    patterns: &[Option<String>],
    whole: &ast::Expr,
    out: &mut Vec<Statement>,
) {
    let arms = branches
        .iter()
        .enumerate()
        .map(|(i, b)| BranchArm {
            pattern: patterns.get(i).cloned().flatten(),
            body: statements_of_expr(b),
        })
        .collect();
    out.push(Statement::Branch {
        scrutinee: scrutinee.map(lower_expr),
        arms,
        span: src_pos(whole.pos()),
    });
}

/// True if `head` is a combinator that runs its action argument conditionally or
/// zero-or-more times (`when`, `unless`, `forA_`, `mapA_`, …), so an `assert`
/// lifted from that argument is not an unconditional guard. Matched on the
/// trailing identifier at any qualifier.
fn is_conditional_combinator(head: &ast::Expr) -> bool {
    matches!(
        head,
        ast::Expr::Var { name, .. } if matches!(
            name.as_str(),
            "when"
                | "unless"
                | "forA_"
                | "forA"
                | "forM_"
                | "forM"
                | "mapA_"
                | "mapA"
                | "mapM_"
                | "mapM"
        )
    )
}

/// If `expr` is an application of a ledger-action head, push the matching
/// statement(s) and return true.
fn classify_app(
    expr: &ast::Expr,
    binder: Option<&ast::Pat>,
    out: &mut Vec<Statement>,
    conditional: bool,
) -> bool {
    let args = expr.application_args();
    if args.is_empty() {
        return false;
    }
    let (head_name, qualified) = match expr.application_head() {
        ast::Expr::Var {
            qualifier, name, ..
        } => (name.as_str(), qualifier.is_some()),
        _ => return false,
    };
    // The ledger actions are the UNQUALIFIED primitives (`Lifecycle.exercise` is
    // a user function, not the ledger action). The one exception is the assert
    // guard, which is routinely written qualified (`DA.Assert.assertMsg`).
    if qualified && head_name != "assert" && head_name != "assertMsg" {
        return false;
    }
    let arg_expr = |i: usize| {
        args.get(i)
            .map(lower_expr)
            .unwrap_or_else(|| Expr::Unknown {
                raw: String::new(),
                span: src_pos(expr.pos()),
            })
    };
    let binder_name = binder.map(|p| p.render());
    let span = src_pos(expr.pos());
    match head_name {
        "create" | "createCmd" => {
            out.push(Statement::Create {
                template_name: template_name_of(args.first()),
                argument: arg_expr(0),
                binder: binder_name,
                span,
            });
            true
        }
        "exercise" | "exerciseByKey" | "exerciseCmd" | "exerciseByKeyCmd" => {
            out.push(Statement::Exercise {
                choice_name: choice_name_of(args.get(1)),
                cid: arg_expr(0),
                argument: choice_argument_of(args.get(1)),
                binder: binder_name,
                span,
            });
            true
        }
        "createAndExerciseCmd" => {
            out.push(Statement::Create {
                template_name: template_name_of(args.first()),
                argument: arg_expr(0),
                binder: binder_name.clone(),
                span,
            });
            out.push(Statement::Exercise {
                choice_name: choice_name_of(args.get(1)),
                cid: arg_expr(0),
                argument: choice_argument_of(args.get(1)),
                binder: binder_name,
                span,
            });
            true
        }
        "fetch" => {
            out.push(Statement::Fetch {
                cid: arg_expr(0),
                binder: binder_name,
                span,
            });
            true
        }
        "fetchAndArchive" => {
            out.push(Statement::Archive {
                cid: arg_expr(0),
                span,
            });
            out.push(Statement::Fetch {
                cid: arg_expr(0),
                binder: binder_name,
                span,
            });
            true
        }
        "archive" => {
            out.push(Statement::Archive {
                cid: arg_expr(0),
                span,
            });
            true
        }
        "assert" | "assertMsg" => {
            if conditional {
                // An assert that runs only on some paths (inside an `if`/`case`
                // arm, a `when`, or a `forA_` lambda) guarantees nothing. Keep it
                // scannable but deny it guard status: record it as a plain Other.
                out.push(Statement::Other {
                    raw: expr.render(),
                    expr: lower_expr(expr),
                    binder: None,
                    span,
                });
            } else {
                // The condition is the assert's argument (after the message for
                // assertMsg), not the whole call.
                let cond_idx = if head_name == "assertMsg" { 1 } else { 0 };
                let condition_expr = args
                    .get(cond_idx)
                    .map(lower_expr)
                    .unwrap_or_else(|| lower_expr(expr));
                out.push(Statement::Assert {
                    condition_expr,
                    span,
                });
            }
            true
        }
        _ => false,
    }
}

fn template_name_of(arg: Option<&ast::Expr>) -> String {
    match arg {
        Some(ast::Expr::Record { base, .. }) => template_name_of(Some(base)),
        Some(ast::Expr::Con {
            qualifier, name, ..
        }) => qualifier
            .as_ref()
            .map_or_else(|| name.to_string(), |q| format!("{q}.{name}")),
        Some(ast::Expr::Var { name, .. }) if name.as_str() == "this" => "this".to_string(),
        _ => String::new(),
    }
}

fn choice_name_of(arg: Option<&ast::Expr>) -> String {
    match arg {
        Some(ast::Expr::Record { base, .. }) => choice_name_of(Some(base)),
        Some(ast::Expr::Con {
            qualifier, name, ..
        }) => qualifier
            .as_ref()
            .map_or_else(|| name.to_string(), |q| format!("{q}.{name}")),
        Some(ast::Expr::App { func, .. }) => choice_name_of(Some(func)),
        _ => String::new(),
    }
}

fn choice_argument_of(arg: Option<&ast::Expr>) -> Option<Expr> {
    match arg {
        Some(expr @ ast::Expr::Record { .. }) => Some(lower_expr(expr)),
        _ => None,
    }
}