aboutsummaryrefslogtreecommitdiff
path: root/lib/src/lints/legacy_let_syntax.rs
blob: cdd012dd6718ef2420a9f17b1aad477da8dd29c4 (plain)
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
use crate::{make, Metadata, Report, Rule, Suggestion};

use if_chain::if_chain;
use macros::lint;
use rnix::{
    types::{EntryHolder, Ident, Key, LegacyLet, TokenWrapper, TypedNode},
    NodeOrToken, SyntaxElement, SyntaxKind,
};

/// ## What it does
/// Checks for legacy-let syntax that was never formalized.
///
/// ## Why is this bad?
/// This syntax construct is undocumented, refrain from using it.
///
/// ## Example
///
/// Legacy let syntax makes use of an attribute set annotated with
/// `let` and expects a `body` attribute.
/// ```nix
/// let {
///   body = x + y;
///   x = 2;
///   y = 3;
/// }
/// ```
///
/// This is trivially representible via `rec`, which is documented
/// and more widely known:
///
/// ```nix
/// rec {
///   body = x + y;
///   x = 2;
///   y = 3;
/// }.body
/// ```
#[lint(
    name = "legacy let syntax",
    note = "Using undocumented `let` syntax",
    code = 5,
    match_with = SyntaxKind::NODE_LEGACY_LET
)]
struct ManualInherit;

impl Rule for ManualInherit {
    fn validate(&self, node: &SyntaxElement) -> Option<Report> {
        if_chain! {
            if let NodeOrToken::Node(node) = node;
            if let Some(legacy_let) = LegacyLet::cast(node.clone());

            if legacy_let
                .entries()
                .any(|kv| matches!(kv.key(), Some(k) if key_is_ident(&k, "body")));

            then {
                let inherits = legacy_let.inherits();
                let entries = legacy_let.entries();
                let attrset = make::attrset(inherits, entries, true);
                let parenthesized = make::parenthesize(attrset.node());
                let selected = make::select(parenthesized.node(), make::ident("body").node());

                let at = node.text_range();
                let message = "Prefer `rec` over undocumented `let` syntax";
                let replacement = selected.node().clone();

                Some(self.report().suggest(at, message, Suggestion::new(at, replacement)))
            } else {
                None
            }
        }
    }
}

fn key_is_ident(key_path: &Key, ident: &str) -> bool {
    if let Some(key_node) = key_path.path().next() {
        if let Some(key) = Ident::cast(key_node) {
            return key.as_str() == ident;
        }
    }
    false
}