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
use super::*;
use crate::ast_util::range;
use std::{collections::HashSet, convert::Infallible};

use full_moon::{
    ast::{self, Ast},
    tokenizer::{TokenReference, TokenType},
    visitors::Visitor,
};
use if_chain::if_chain;

pub struct IncorrectRoactUsageLint;

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

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

    fn pass(&self, ast: &Ast, context: &Context) -> Vec<Diagnostic> {
        if !context.is_roblox() {
            return Vec::new();
        }

        let mut visitor = IncorrectRoactUsageVisitor::default();
        visitor.visit_ast(ast);

        let mut diagnostics = Vec::new();

        for invalid_property in visitor.invalid_properties {
            diagnostics.push(Diagnostic::new(
                "roblox_incorrect_roact_usage",
                format!(
                    "`{}` is not a property of `{}`",
                    invalid_property.property_name, invalid_property.class_name
                ),
                Label::new(invalid_property.range),
            ));
        }

        for unknown_class in visitor.unknown_class {
            diagnostics.push(Diagnostic::new(
                "roblox_incorrect_roact_usage",
                format!("`{}` is not a valid class", unknown_class.name),
                Label::new(unknown_class.range),
            ));
        }

        diagnostics
    }

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

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

fn is_roact_create_element(prefix: &ast::Prefix, suffixes: &[&ast::Suffix]) -> bool {
    if_chain! {
        if let ast::Prefix::Name(prefix_token) = prefix;
        if prefix_token.token().to_string() == "Roact";
        if suffixes.len() == 1;
        if let ast::Suffix::Index(ast::Index::Dot { name, .. }) = suffixes[0];
        then {
            name.token().to_string() == "createElement"
        } else {
            false
        }
    }
}

#[derive(Debug, Default)]
struct IncorrectRoactUsageVisitor {
    definitions_of_create_element: HashSet<String>,
    invalid_properties: Vec<InvalidProperty>,
    unknown_class: Vec<UnknownClass>,
}

#[derive(Debug)]
struct InvalidProperty {
    class_name: String,
    property_name: String,
    range: (usize, usize),
}

#[derive(Debug)]
struct UnknownClass {
    name: String,
    range: (usize, usize),
}

impl IncorrectRoactUsageVisitor {
    fn check_class_name(
        &mut self,
        token: &TokenReference,
    ) -> Option<&'static rbx_reflection::RbxClassDescriptor> {
        let name = if let TokenType::StringLiteral { literal, .. } = &*token.token_type() {
            literal.to_string()
        } else {
            return None;
        };

        match rbx_reflection::get_class_descriptor(&name) {
            option @ Some(_) => option,

            None => {
                self.unknown_class.push(UnknownClass {
                    name,
                    range: range(token),
                });

                None
            }
        }
    }
}

impl Visitor for IncorrectRoactUsageVisitor {
    fn visit_function_call(&mut self, call: &ast::FunctionCall) {
        // Check if caller is Roact.createElement or a variable defined to it
        let mut suffixes = call.suffixes().collect::<Vec<_>>();
        let call_suffix = suffixes.pop();

        let mut check = false;

        if suffixes.is_empty() {
            // Call is foo(), not foo.bar()
            // Check if foo is a variable for Roact.createElement
            if let ast::Prefix::Name(name) = call.prefix() {
                if self
                    .definitions_of_create_element
                    .contains(&name.token().to_string())
                {
                    check = true;
                }
            }
        } else if suffixes.len() == 1 {
            // Call is foo.bar()
            // Check if foo.bar is Roact.createElement
            check = is_roact_create_element(call.prefix(), &suffixes);
        }

        if !check {
            return;
        }

        let (mut class, arguments) = if_chain! {
            if let Some(ast::Suffix::Call(ast::Call::AnonymousCall(
                ast::FunctionArgs::Parentheses { arguments, .. }
            ))) = call_suffix;
            if arguments.len() >= 2;
            let mut iter = arguments.iter();

            // Get first argument, check if it is a Roblox class
            let name_arg = iter.next().unwrap();
            if let ast::Expression::Value { value, .. } = name_arg;
            if let ast::Value::String(token) = &**value;
            if let Some(class) = self.check_class_name(token);

            // Get second argument, check if it is a table
            let arg = iter.next().unwrap();
            if let ast::Expression::Value { value, .. } = arg;
            if let ast::Value::TableConstructor(table) = &**value;

            then {
                (class, table)
            } else {
                return;
            }
        };

        let mut valid_properties = HashSet::new();

        loop {
            for (property, descriptor) in class.iter_property_descriptors() {
                if descriptor.is_canonical() {
                    valid_properties.insert(property);
                }
            }

            if let Some(superclass) = class.superclass() {
                class = rbx_reflection::get_class_descriptor(superclass).unwrap();
            } else {
                break;
            }
        }

        for field in arguments.fields() {
            if let ast::Field::NameKey { key, .. } = field {
                let property_name = key.token().to_string();
                if !valid_properties.contains(property_name.as_str()) {
                    self.invalid_properties.push(InvalidProperty {
                        class_name: class.name().to_string(),
                        property_name,
                        range: range(key),
                    });
                }
            }
        }
    }

    fn visit_local_assignment(&mut self, node: &ast::LocalAssignment) {
        for (name, expr) in node.names().iter().zip(node.expressions().iter()) {
            if_chain! {
                if let ast::Expression::Value { value, .. } = expr;
                if let ast::Value::Var(ast::Var::Expression(var_expr)) = &**value;
                if is_roact_create_element(var_expr.prefix(), &var_expr.suffixes().collect::<Vec<_>>());
                then {
                    self.definitions_of_create_element.insert(name.token().to_string());
                }
            };
        }
    }
}

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

    #[test]
    fn test_roblox_incorrect_roact_usage() {
        test_lint(
            IncorrectRoactUsageLint::new(()).unwrap(),
            "roblox_incorrect_roact_usage",
            "roblox_incorrect_roact_usage",
        );
    }
}