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
use crate::packs::file_utils::file_read_contents;
use crate::packs::{
    parsing::{
        ruby::parse_utils::{
            fetch_const_const_name, fetch_const_name, fetch_node_location,
            get_constant_assignment_definition, get_definition_from,
            get_reference_from_active_record_association, loc_to_range,
        },
        ParsedDefinition, UnresolvedReference,
    },
    Configuration, ProcessedFile,
};
use lib_ruby_parser::{
    nodes, traverse::visitor::Visitor, Node, Parser, ParserOptions,
};
use line_col::LineColLookup;
use std::path::Path;

struct ReferenceCollector<'a> {
    pub references: Vec<UnresolvedReference>,
    pub definitions: Vec<ParsedDefinition>,
    pub current_namespaces: Vec<String>,
    pub line_col_lookup: LineColLookup<'a>,
    pub behavioral_change_in_namespace: bool,
    pub custom_associations: Vec<String>,
}

impl<'a> Visitor for ReferenceCollector<'a> {
    fn on_class(&mut self, node: &nodes::Class) {
        // We're not collecting definitions, so no need to visit the class definitioname);
        let namespace_result = fetch_const_name(&node.name);
        // For now, we simply exit and stop traversing if we encounter an error when fetching the constant name of a class
        // We can iterate on this if this is different than the packwerk implementation
        if namespace_result.is_err() {
            return;
        }

        let namespace = namespace_result.unwrap();

        if let Some(inner) = node.superclass.as_ref() {
            self.visit(inner);
        }
        let definition_loc = fetch_node_location(&node.name).unwrap();
        let location = loc_to_range(definition_loc, &self.line_col_lookup);

        let definition = get_definition_from(
            &namespace,
            &self.current_namespaces,
            &location,
        );

        // Note – is there a way to use lifetime specifiers to get rid of this and
        // just keep current namespaces as a vector of string references or something else
        // more efficient?
        self.current_namespaces.push(namespace);

        // Each time we open up a new class/module, we reset the behavioral change flag
        let previous_behavioral_change = self.behavioral_change_in_namespace;
        self.behavioral_change_in_namespace = false;

        if let Some(inner) = &node.body {
            self.visit(inner);
        }

        if self.behavioral_change_in_namespace {
            self.definitions.push(definition);
        }

        // When we're done visiting the class/module, we restore the previous behavioral change flag
        // to account for nested class/module definitions
        self.behavioral_change_in_namespace = previous_behavioral_change;

        self.current_namespaces.pop();
    }

    fn on_send(&mut self, node: &nodes::Send) {
        if node.method_name == "private_constant" {
            // `private_constant` is not considered to be a behavioral change
        } else {
            self.behavioral_change_in_namespace = true;

            let association_reference =
                get_reference_from_active_record_association(
                    node,
                    &self.current_namespaces,
                    &self.line_col_lookup,
                    &self.custom_associations,
                );

            if let Some(association_reference) = association_reference {
                self.references.push(association_reference);
            }
        }
        lib_ruby_parser::traverse::visitor::visit_send(self, node);
    }

    fn on_casgn(&mut self, node: &nodes::Casgn) {
        let definition = get_constant_assignment_definition(
            node,
            self.current_namespaces.to_owned(),
            &self.line_col_lookup,
        );

        if let Some(definition) = definition {
            self.definitions.push(definition);
        }

        if let Some(v) = node.value.to_owned() {
            self.visit(&v);
        } else {
            // We don't handle constant assignments as part of a multi-assignment yet,
            // e.g. A, B = 1, 2
            // See the documentation for nodes::Casgn#value for more info.
        }
    }

    fn on_module(&mut self, node: &nodes::Module) {
        let namespace = fetch_const_name(&node.name).unwrap_or("".to_owned());
        let definition_loc = fetch_node_location(&node.name).unwrap();
        let location = loc_to_range(definition_loc, &self.line_col_lookup);

        let definition = get_definition_from(
            &namespace,
            &self.current_namespaces,
            &location,
        );

        // Note – is there a way to use lifetime specifiers to get rid of this and
        // just keep current namespaces as a vector of string references or something else
        // more efficient?
        self.current_namespaces.push(namespace);

        // Each time we open up a new class/module, we reset the behavioral change flag
        let previous_behavioral_change = self.behavioral_change_in_namespace;
        self.behavioral_change_in_namespace = false;

        if let Some(inner) = &node.body {
            self.visit(inner);
        }

        if self.behavioral_change_in_namespace {
            self.definitions.push(definition);
        }

        // When we're done visiting the class/module, we restore the previous behavioral change flag
        // to account for nested class/module definitions
        self.behavioral_change_in_namespace = previous_behavioral_change;

        self.current_namespaces.pop();
    }

    fn on_const(&mut self, node: &nodes::Const) {
        let Ok(name) = fetch_const_const_name(node) else {
            return;
        };

        let namespace_path = self
            .current_namespaces
            .clone()
            .into_iter()
            .filter(|namespace| namespace != &name)
            .collect::<Vec<String>>();

        self.references.push(UnresolvedReference {
            name,
            namespace_path,
            location: loc_to_range(&node.expression_l, &self.line_col_lookup),
        })
    }

    fn on_def(&mut self, node: &nodes::Def) {
        self.behavioral_change_in_namespace = true;
        lib_ruby_parser::traverse::visitor::visit_def(self, node);
    }

    fn on_defs(&mut self, node: &nodes::Defs) {
        self.behavioral_change_in_namespace = true;
        lib_ruby_parser::traverse::visitor::visit_defs(self, node);
    }
}

pub(crate) fn process_from_path(
    path: &Path,
    configuration: &Configuration,
) -> ProcessedFile {
    let contents = file_read_contents(path, configuration);
    process_from_contents(contents, path, configuration)
}

pub(crate) fn process_from_contents(
    contents: String,
    path: &Path,
    configuration: &Configuration,
) -> ProcessedFile {
    let options = ParserOptions {
        buffer_name: "".to_string(),
        ..Default::default()
    };

    let lookup = LineColLookup::new(&contents);
    let parser = Parser::new(contents.clone(), options);
    let parse_result = parser.do_parse();

    let ast_option: Option<Box<Node>> = parse_result.ast;

    let ast = match ast_option {
        Some(some_ast) => some_ast,
        None => {
            return ProcessedFile {
                absolute_path: path.to_owned(),
                unresolved_references: vec![],
                definitions: vec![],
            }
        }
    };

    let mut collector = ReferenceCollector {
        references: vec![],
        current_namespaces: vec![],
        definitions: vec![],
        line_col_lookup: lookup,
        behavioral_change_in_namespace: false,
        custom_associations: configuration.custom_associations.clone(),
    };

    collector.visit(&ast);

    let unresolved_references = collector.references;

    let absolute_path = path.to_owned();

    // The packwerk parser uses a ConstantResolver constructed by constants inferred from the file system
    // see zeitwerk_utils for more.
    // For a parser that uses parsed constants, see the experimental parser
    let definitions = collector.definitions;

    ProcessedFile {
        absolute_path,
        unresolved_references,
        definitions,
    }
}