harn-lint 0.10.124

Linter for the Harn programming language
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
//! Checks for results that are computed and then dropped on the floor.
//!
//! Harn has no implicit block return, so a bare expression statement is a
//! discarded value everywhere except the tail of a value-producing block
//! (closure body, `match` arm, `if`/`else` branch, `try`, `block { … }`) —
//! see [`BlockKind`].

use harn_parser::{DiagnosticCode as Code, Node, SNode};

use super::Linter;
use crate::diagnostic::{LintDiagnostic, LintSeverity};

/// Whether a block's trailing expression is its value or just its last
/// statement. Harn `fn` / `for` / `while` bodies do **not** implicitly return
/// their tail, so a trailing expression there is discarded like any other
/// statement; a closure body or `match` arm *does* yield its tail.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum BlockKind {
    /// Tail expression is discarded (`fn`, `for`, `while`, `finally`, …).
    Statement,
    /// Tail expression is the block's value (closure, `match` arm, `if`,
    /// `try`, `block { … }`).
    Value,
}

/// Methods on `list` / `dict` / `set` / `string` that compute a new value and
/// leave the receiver untouched. Every method on Harn's built-in collections
/// is pure — they are persistent, copy-on-write values — so this list is a
/// *precision* filter rather than a semantic one: it holds the names whose
/// results are worth flagging when dropped, excluding names common enough to
/// collide with an effectful host or connector method of the same name
/// (`get`, `add`, `remove`, `merge`, `count`, `find`, …).
///
/// Keep sorted.
const PURE_COLLECTION_METHODS: &[&str] = &[
    "adding",
    "appending",
    "char_at",
    "chars",
    "chunk",
    "compact",
    "dropping_last",
    "each_cons",
    "each_slice",
    "enumerate",
    "flatten",
    "lines",
    "lower",
    "lowercase",
    "map_keys",
    "map_values",
    "merging",
    "pad_left",
    "pad_right",
    "partition",
    "rekeyed",
    "removing",
    "repeat",
    "reversed",
    "skip",
    "slice",
    "sliding_window",
    "sorted",
    "sorted_by",
    "split",
    "substring",
    "tally",
    "to_dict",
    "to_list",
    "to_set",
    "trim",
    "trim_end",
    "trim_start",
    "unique",
    "upper",
    "uppercase",
    "window",
    "zip",
];

fn is_pure_collection_method(method: &str) -> bool {
    PURE_COLLECTION_METHODS.binary_search(&method).is_ok()
}

impl Linter<'_> {
    /// Record every method name declared in an `impl` block so
    /// [`Self::check_discarded_pure_result`] can stand down on a receiver that
    /// might be a user type with a same-named, effectful method. Runs as a
    /// pre-pass because a call can precede the `impl` that defines it.
    pub(super) fn collect_impl_method_names(&mut self, nodes: &[SNode]) {
        for node in nodes {
            let inner = match &node.node {
                Node::AttributedDecl { inner, .. } => &inner.node,
                other => other,
            };
            let Node::ImplBlock { methods, .. } = inner else {
                continue;
            };
            for method in methods {
                if let Node::FnDecl { name, .. } = &method.node {
                    self.impl_method_names.insert(name.clone());
                }
            }
        }
    }

    /// Flag a pure collection/string method call whose result is discarded
    /// (`l.appending(1)` as a statement).
    ///
    /// `appending` clones the receiver, appends, and returns a *new* list rather
    /// than mutating `l`, so dropping the return value drops the entire point
    /// of the call and leaves `l` unchanged — a silent no-op that otherwise
    /// typechecks clean. This is an error rather than a warning because there
    /// is no legitimate reason to call one of these and discard the result.
    ///
    /// Three guards keep it exact:
    /// - a closure argument (`.map({ … })`) can perform effects, so the
    ///   statement is not provably inert;
    /// - a receiver rooted at `harness` is a host method, which exists for its
    ///   effects;
    /// - a name the file also declares in an `impl` block may be a
    ///   user-defined method with effects of its own.
    pub(super) fn check_discarded_pure_result(&mut self, node: &SNode) {
        let (object, method, args) = match &node.node {
            Node::MethodCall {
                object,
                method,
                args,
            }
            | Node::OptionalMethodCall {
                object,
                method,
                args,
            } => (object, method, args),
            _ => return,
        };
        if !is_pure_collection_method(method)
            || args.iter().any(|a| matches!(&a.node, Node::Closure { .. }))
            || self.impl_method_names.contains(method.as_str())
        {
            return;
        }
        let receiver = Self::method_receiver_root(object);
        if receiver == Some("harness") {
            return;
        }
        // Name the receiver only when it is a plain binding that could be
        // assigned back to. `[1, 2].tally()` has no name to suggest.
        let (message, suggestion) = match receiver {
            Some(name) => (
                format!(
                    "the result of `{method}` is discarded, so this statement leaves `{name}` unchanged"
                ),
                format!(
                    "`{method}` returns a new value instead of modifying `{name}` — assign it back, \
                     as in `{name} = {name}.{method}(...)`, which needs `{name}` declared `let`. \
                     To call `{method}` purely for its errors, discard the result explicitly with \
                     `const _ = {name}.{method}(...)`"
                ),
            ),
            None => (
                format!("the result of `{method}` is discarded, so this statement has no effect"),
                format!(
                    "`{method}` returns a new value rather than modifying its receiver — bind the \
                     result, or discard it explicitly with `const _ = ...{method}(...)` if the call \
                     is made only for its errors"
                ),
            ),
        };
        self.diagnostics.push(LintDiagnostic {
            code: Code::LintDiscardedPureResult,
            rule: "discarded-pure-result".into(),
            message,
            span: node.span,
            severity: LintSeverity::Error,
            suggestion: Some(suggestion),
            fix: None,
        });
    }

    /// The root identifier of a method receiver: `a.b.c` and `a[0]` both root
    /// at `a`. `None` when the receiver is not rooted in a plain name.
    fn method_receiver_root(object: &SNode) -> Option<&str> {
        match &object.node {
            Node::Identifier(name) => Some(name.as_str()),
            Node::PropertyAccess { object, .. }
            | Node::OptionalPropertyAccess { object, .. }
            | Node::SubscriptAccess { object, .. }
            | Node::MethodCall { object, .. }
            | Node::OptionalMethodCall { object, .. } => Self::method_receiver_root(object),
            _ => None,
        }
    }

    pub(super) fn check_discarded_approval_result(&mut self, node: &SNode) {
        // The canonical shape is the capability method
        // `harness.interaction.request_approval(...)`. The bare
        // `request_approval(...)` call is the removed ambient builtin: it is
        // still matched so that a script mid-migration keeps this warning
        // alongside the HARN-LNT-071 that tells it to move, rather than going
        // quiet on the way from one spelling to the other.
        let name = match &node.node {
            Node::FunctionCall { name, .. } if Self::is_approval_record_builtin(name) => {
                name.as_str()
            }
            Node::MethodCall { object, method, .. }
            | Node::OptionalMethodCall { object, method, .. }
                if Self::is_approval_record_builtin(method)
                    && self.harness_capability_of(object) == Some("interaction") =>
            {
                method.as_str()
            }
            _ => return,
        };
        self.diagnostics.push(LintDiagnostic {
            code: Code::LintUnhandledApprovalResult,
            rule: "unhandled-approval-result".into(),
            message: format!("approval result from `{name}` is discarded"),
            span: node.span,
            severity: LintSeverity::Warning,
            suggestion: Some(
                "bind the result, inspect its signed approver receipts, or explicitly assign it to `_`"
                    .to_string(),
            ),
            fix: None,
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use harn_lexer::Lexer;
    use harn_parser::Parser;

    /// The methods HARN-LNT-066 flags in `source`, in order.
    fn flagged(source: &str) -> Vec<String> {
        let tokens = Lexer::new(source).tokenize().expect("lex");
        let program = Parser::new(tokens).parse().expect("parse");
        crate::lint(&program)
            .into_iter()
            .filter(|d| d.code == Code::LintDiscardedPureResult)
            .map(|d| {
                assert_eq!(d.severity, LintSeverity::Error, "LNT-066 is error-grade");
                // Messages lead with "the result of `<method>`".
                d.message
                    .split('`')
                    .nth(1)
                    .expect("method name in backticks")
                    .to_string()
            })
            .collect()
    }

    #[test]
    fn flags_discarded_appending_in_statement_position() {
        assert_eq!(
            flagged("fn main(h: Harness) {\n  const l = []\n  l.appending(1)\n  log(l)\n}"),
            vec!["appending"]
        );
    }

    #[test]
    fn flags_discarded_appending_as_the_tail_of_a_fn_body() {
        // Harn has no implicit block return, so a `fn` tail is discarded too.
        assert_eq!(
            flagged("fn build(l: list<int>) {\n  l.appending(1)\n}"),
            vec!["appending"]
        );
    }

    #[test]
    fn flags_discarded_appending_in_a_loop_body() {
        // The classic builder bug: the tail of a `for` body is not a value.
        assert_eq!(
            flagged(
                "fn main(h: Harness) {\n  let out = []\n  for i in [1] {\n    out.appending(i)\n  }\n}"
            ),
            vec!["appending"]
        );
    }

    #[test]
    fn allows_the_result_being_assigned_back() {
        assert!(flagged("fn main(h: Harness) {\n  let l = []\n  l = l.appending(1)\n}").is_empty());
    }

    #[test]
    fn allows_an_explicit_discard() {
        assert!(flagged("fn main(h: Harness) {\n  const _ = [1].sorted()\n}").is_empty());
    }

    #[test]
    fn allows_a_call_taking_a_closure() {
        // The closure may carry effects, so the statement is not provably inert.
        assert!(flagged(
            "fn main(h: Harness) {\n  const l = [1]\n  l.sorted_by({ a, b -> a - b })\n  log(l)\n}"
        )
        .is_empty());
    }

    #[test]
    fn allows_a_same_named_user_impl_method() {
        // A user method may exist for its effects, unlike the built-ins.
        assert!(flagged(
            "struct Basket { items: list<int> }\nimpl Basket {\n  fn appending(self, i: int) -> Basket { return self }\n}\nfn main(h: Harness) {\n  const b = Basket { items: [] }\n  b.appending(1)\n}"
        )
        .is_empty());
    }

    #[test]
    fn allows_a_harness_rooted_receiver() {
        // Host methods exist for their effects.
        assert!(flagged("fn main(h: Harness) {\n  harness.stdio.split(\"a\")\n}").is_empty());
    }

    #[test]
    fn allows_the_tail_of_every_value_producing_block() {
        // Closure body, `match` arm, `if` branch, `try`, and `block { … }` all
        // yield their tail, so the tail is a result rather than a discard.
        for source in [
            "fn main(h: Harness) {\n  const f = { -> [1].sorted() }\n  log(f())\n}",
            "fn main(h: Harness) {\n  const m = match 1 {\n    1 -> { [1].sorted() }\n    _ -> { [] }\n  }\n  log(m)\n}",
            "fn main(h: Harness) {\n  const i = if true { [1].sorted() } else { [] }\n  log(i)\n}",
            "fn main(h: Harness) {\n  const t = try { [1].sorted() } catch (e) { [] }\n  log(t)\n}",
        ] {
            assert!(
                flagged(source).is_empty(),
                "value-block tail must not be flagged: {source}"
            );
        }
    }

    #[test]
    fn flags_a_non_tail_statement_inside_a_value_block() {
        // Only the *tail* of a value block is a result; earlier statements in
        // it are discarded like any other.
        assert_eq!(
            flagged("fn main(h: Harness) {\n  const f = { -> \n    [1].sorted()\n    42\n  }\n  log(f())\n}"),
            vec!["sorted"]
        );
    }

    #[test]
    fn pure_collection_methods_are_sorted_and_unique() {
        let mut sorted = PURE_COLLECTION_METHODS.to_vec();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(
            sorted.as_slice(),
            PURE_COLLECTION_METHODS,
            "PURE_COLLECTION_METHODS must stay sorted and duplicate-free for binary_search"
        );
    }

    #[test]
    fn ambiguous_host_verbs_are_not_listed() {
        // These are pure on the built-in collections but collide with
        // plausible effectful methods on other receivers, so they stay out.
        for name in ["get", "add", "remove", "delete", "merge", "count", "find"] {
            assert!(
                !is_pure_collection_method(name),
                "`{name}` is too ambiguous to flag as a discarded pure result"
            );
        }
    }

    /// The spans HARN-LNT-013 flags in `source`, as the names it names.
    fn approvals_flagged(source: &str) -> Vec<String> {
        let tokens = Lexer::new(source).tokenize().expect("lex");
        let program = Parser::new(tokens).parse().expect("parse");
        crate::lint(&program)
            .into_iter()
            .filter(|d| d.code == Code::LintUnhandledApprovalResult)
            .map(|d| {
                d.message
                    .split('`')
                    .nth(1)
                    .expect("approval name in backticks")
                    .to_string()
            })
            .collect()
    }

    #[test]
    fn flags_a_discarded_approval_on_the_canonical_harness_path() {
        // The regression this check exists to prevent: HARN-LNT-071 tells
        // callers to move from `request_approval(...)` to the capability
        // method, so the guard has to survive the move. A silent approval
        // lint is worse than none — it reads as "this code was checked".
        assert_eq!(
            approvals_flagged(
                "fn main(harness: Harness) {\n  harness.interaction.request_approval(\"ship\", {})\n}"
            ),
            vec!["request_approval"]
        );
    }

    #[test]
    fn still_flags_the_legacy_ambient_call() {
        // Mid-migration scripts keep both diagnostics rather than trading
        // one for the other.
        assert_eq!(
            approvals_flagged("fn main(harness: Harness) {\n  request_approval(\"ship\", {})\n}"),
            vec!["request_approval"]
        );
    }

    #[test]
    fn allows_a_bound_approval_result() {
        assert!(
            approvals_flagged(
                "fn main(harness: Harness) {\n  const r = harness.interaction.request_approval(\"ship\", {})\n  log(r)\n}"
            )
            .is_empty()
        );
    }

    #[test]
    fn ignores_request_approval_on_a_receiver_that_is_not_the_harness() {
        // A user-defined object may legitimately own a method by this name;
        // only the host capability carries the approver receipts.
        assert!(
            approvals_flagged(
                "fn main(harness: Harness) {\n  const q = my_queue()\n  q.interaction.request_approval(\"ship\", {})\n}"
            )
            .is_empty()
        );
    }
}