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
use std::convert::Infallible;

use full_moon::{ast, visitors::Visitor};

use crate::ast_util::{name_paths::*, scopes::ScopeManager};

use super::{super::standard_library::*, *};

pub struct DeprecatedLint;

impl Rule for DeprecatedLint {
    type Config = ();
    type Error = Infallible;

    fn new(_: Self::Config) -> Result<Self, Self::Error> {
        Ok(DeprecatedLint)
    }

    fn pass(&self, ast: &full_moon::ast::Ast, context: &Context) -> Vec<Diagnostic> {
        let mut visitor = DeprecatedVisitor {
            diagnostics: Vec::new(),
            scope_manager: ScopeManager::new(ast),
            standard_library: &context.standard_library,
        };

        visitor.visit_ast(ast);

        visitor.diagnostics
    }

    fn rule_type(&self) -> RuleType {
        RuleType::Correctness
    }

    fn severity(&self) -> Severity {
        Severity::Warning
    }
}

struct DeprecatedVisitor<'a> {
    diagnostics: Vec<Diagnostic>,
    scope_manager: ScopeManager,
    standard_library: &'a StandardLibrary,
}

impl DeprecatedVisitor<'_> {
    fn check_name_path<N: Node>(
        &mut self,
        node: &N,
        what: &str,
        name_path: &[String],
        parameters: &[String],
    ) {
        assert!(!name_path.is_empty());

        for bound in 1..=name_path.len() {
            let deprecated = match self.standard_library.find_global(&name_path[0..bound]) {
                Some(Field {
                    deprecated: Some(deprecated),
                    ..
                }) => deprecated,

                _ => continue,
            };

            let mut notes = vec![deprecated.message.to_owned()];

            if let Some(replace_with) = deprecated.try_instead(parameters) {
                notes.push(format!("try: {replace_with}"));
            }

            self.diagnostics.push(Diagnostic::new_complete(
                "deprecated",
                format!(
                    "standard library {what} `{}` is deprecated",
                    name_path.join(".")
                ),
                Label::from_node(node, None),
                notes,
                Vec::new(),
            ));
        }
    }
}

impl Visitor for DeprecatedVisitor<'_> {
    fn visit_expression(&mut self, expression: &ast::Expression) {
        if let Some(reference) = self
            .scope_manager
            .reference_at_byte(expression.start_position().unwrap().bytes())
        {
            if reference.resolved.is_some() {
                return;
            }
        }

        let name_path = match name_path(expression) {
            Some(name_path) => name_path,
            None => return,
        };

        self.check_name_path(expression, "expression", &name_path, &[]);
    }

    fn visit_function_call(&mut self, call: &ast::FunctionCall) {
        if let Some(reference) = self
            .scope_manager
            .reference_at_byte(call.start_position().unwrap().bytes())
        {
            if reference.resolved.is_some() {
                return;
            }
        }

        let mut keep_going = true;
        let mut suffixes: Vec<&ast::Suffix> = call
            .suffixes()
            .take_while(|suffix| take_while_keep_going(suffix, &mut keep_going))
            .collect();

        let name_path = match name_path_from_prefix_suffix(call.prefix(), suffixes.iter().copied())
        {
            Some(name_path) => name_path,
            None => return,
        };

        let call_suffix = suffixes.pop().unwrap();

        let function_args = match call_suffix {
            #[cfg_attr(
                feature = "force_exhaustive_checks",
                deny(non_exhaustive_omitted_patterns)
            )]
            ast::Suffix::Call(call) => match call {
                ast::Call::AnonymousCall(args) => args,
                ast::Call::MethodCall(method_call) => method_call.args(),
                _ => return,
            },

            _ => unreachable!("function_call.call_suffix != ast::Suffix::Call"),
        };

        #[cfg_attr(
            feature = "force_exhaustive_checks",
            deny(non_exhaustive_omitted_patterns)
        )]
        let argument_displays = match function_args {
            ast::FunctionArgs::Parentheses { arguments, .. } => arguments
                .iter()
                .map(|argument| argument.to_string())
                .collect(),

            ast::FunctionArgs::String(token) => vec![token.to_string()],
            ast::FunctionArgs::TableConstructor(table_constructor) => {
                vec![table_constructor.to_string()]
            }

            _ => Vec::new(),
        };

        self.check_name_path(call, "function", &name_path, &argument_displays);
    }
}

#[cfg(test)]
mod tests {
    use super::{super::test_util::*, *};

    #[test]
    fn test_deprecated_fields() {
        test_lint(
            DeprecatedLint::new(()).unwrap(),
            "deprecated",
            "deprecated_fields",
        );
    }

    #[test]
    fn test_deprecated_functions() {
        test_lint(
            DeprecatedLint::new(()).unwrap(),
            "deprecated",
            "deprecated_functions",
        );
    }

    #[test]
    fn test_toml_forwards_compatibility() {
        test_lint(
            DeprecatedLint::new(()).unwrap(),
            "deprecated",
            "toml_forwards_compatibility",
        );
    }
}