Debian Codegraph @

gcc/rust/resolve/rust-early-name-resolver-2.0.cc

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #include "rust-early-name-resolver-2.0.h"
20 #include "rust-ast-full.h"
21 #include "rust-diagnostics.h"
22 #include "rust-toplevel-name-resolver-2.0.h"
23 #include "rust-attributes.h"
24 #include "rust-finalize-imports-2.0.h"
25 #include "rust-attribute-values.h"
26
27 namespace Rust {
28 namespace Resolver2_0 {
29
30 Early::Early (NameResolutionContext &ctx)
31 : DefaultResolver (ctx), toplevel (TopLevel (ctx)), dirty (false)
32 {}
33
34 void
35 Early::insert_once (AST::MacroInvocation &invocation, NodeId resolved)
36 {
37 // TODO: Should we use `ctx.mark_resolved()`?
38 auto definition = ctx.mappings.lookup_macro_def (resolved);
39
40 if (!ctx.mappings.lookup_macro_invocation (invocation))
41 ctx.mappings.insert_macro_invocation (invocation, definition.value ());
42 }
43
44 void
45 Early::insert_once (AST::MacroRulesDefinition &def)
46 {
47 // TODO: Should we use `ctx.mark_resolved()`?
48 if (!ctx.mappings.lookup_macro_def (def.get_node_id ()))
49 ctx.mappings.insert_macro_def (&def);
50 }
51
52 void
53 Early::go (AST::Crate &crate)
54 {
55 // First we go through TopLevel resolution to get all our declared items
56 toplevel.go (crate);
57
58 // We start with resolving the list of imports that `TopLevel` has built for
59 // us
60
61 dirty = toplevel.is_dirty ();
62 // We now proceed with resolving macros, which can be nested in almost any
63 // items
64 textual_scope.push ();
65 for (auto &item : crate.items)
66 item->accept_vis (*this);
67 textual_scope.pop ();
68 }
69
70 bool
71 Early::resolve_glob_import (NodeId use_dec_id, TopLevel::ImportKind &&glob)
72 {
73 auto resolved
74 = ctx.resolve_path (glob.to_resolve.get_segments (), Namespace::Types);
75 if (!resolved.has_value ())
76 return false;
77
78 auto result
79 = Analysis::Mappings::get ().lookup_ast_module (resolved->get_node_id ());
80 if (!result)
81 return false;
82
83 // here, we insert the module's NodeId into the import_mappings and will look
84 // up the module proper in `FinalizeImports`
85 // The namespace does not matter here since we are dealing with a glob
86 // TODO: Ugly
87 import_mappings.insert (use_dec_id,
88 ImportPair (std::move (glob),
89 ImportData::Glob (*resolved)));
90
91 return true;
92 }
93
94 bool
95 Early::resolve_simple_import (NodeId use_dec_id, TopLevel::ImportKind &&import)
96 {
97 auto definitions = resolve_path_in_all_ns (import.to_resolve);
98
99 // if we've found at least one definition, then we're good
100 if (definitions.empty ())
101 return false;
102
103 auto &imports = import_mappings.new_or_access (use_dec_id);
104
105 imports.emplace_back (
106 ImportPair (std::move (import),
107 ImportData::Simple (std::move (definitions))));
108
109 return true;
110 }
111
112 bool
113 Early::resolve_rebind_import (NodeId use_dec_id,
114 TopLevel::ImportKind &&rebind_import)
115 {
116 auto definitions = resolve_path_in_all_ns (rebind_import.to_resolve);
117
118 // if we've found at least one definition, then we're good
119 if (definitions.empty ())
120 return false;
121
122 auto &imports = import_mappings.new_or_access (use_dec_id);
123
124 imports.emplace_back (
125 ImportPair (std::move (rebind_import),
126 ImportData::Rebind (std::move (definitions))));
127
128 return true;
129 }
130
131 void
132 Early::build_import_mapping (
133 std::pair<NodeId, std::vector<TopLevel::ImportKind>> &&use_import)
134 {
135 auto found = false;
136 auto use_dec_id = use_import.first;
137
138 for (auto &&import : use_import.second)
139 {
140 // We create a copy of the path in case of errors, since the `import` will
141 // be moved into the newly created import mappings
142 auto path = import.to_resolve;
143
144 switch (import.kind)
145 {
146 case TopLevel::ImportKind::Kind::Glob:
147 found = resolve_glob_import (use_dec_id, std::move (import));
148 break;
149 case TopLevel::ImportKind::Kind::Simple:
150 found = resolve_simple_import (use_dec_id, std::move (import));
151 break;
152 case TopLevel::ImportKind::Kind::Rebind:
153 found = resolve_rebind_import (use_dec_id, std::move (import));
154 break;
155 }
156
157 if (!found)
158 collect_error (Error (path.get_final_segment ().get_locus (),
159 ErrorCode::E0433, "unresolved import %qs",
160 path.as_string ().c_str ()));
161 }
162 }
163
164 void
165 Early::TextualScope::push ()
166 {
167 // push a new empty scope
168 scopes.emplace_back ();
169 }
170
171 void
172 Early::TextualScope::pop ()
173 {
174 rust_assert (!scopes.empty ());
175
176 scopes.pop_back ();
177 }
178
179 void
180 Early::TextualScope::insert (std::string name, NodeId id)
181 {
182 rust_assert (!scopes.empty ());
183
184 // we can ignore the return value as we always want the latest defined macro
185 // to shadow a previous one - so if two macros have the same name and get
186 // inserted with the same key, it's not a bug
187 scopes.back ().insert ({name, id});
188 }
189
190 tl::optional<NodeId>
191 Early::TextualScope::get (const std::string &name)
192 {
193 for (auto iterator = scopes.rbegin (); iterator != scopes.rend (); iterator++)
194 {
195 auto scope = *iterator;
196 auto found = scope.find (name);
197 if (found != scope.end ())
198 return found->second;
199 }
200
201 return tl::nullopt;
202 }
203
204 void
205 Early::visit (AST::MacroRulesDefinition &def)
206 {
207 DefaultResolver::visit (def);
208
209 textual_scope.insert (def.get_rule_name ().as_string (), def.get_node_id ());
210 insert_once (def);
211 }
212
213 void
214 Early::visit (AST::BlockExpr &block)
215 {
216 textual_scope.push ();
217
218 DefaultResolver::visit (block);
219
220 textual_scope.pop ();
221 }
222
223 void
224 Early::visit (AST::Module &module)
225 {
226 bool is_macro_use = false;
227
228 for (const auto &attr : module.get_outer_attrs ())
229 {
230 if (attr.get_path ().as_string () == Values::Attributes::MACRO_USE)
231 {
232 is_macro_use = true;
233 break;
234 }
235 }
236
237 if (!is_macro_use)
238 textual_scope.push ();
239
240 DefaultResolver::visit (module);
241
242 if (!is_macro_use)
243 textual_scope.pop ();
244 }
245
246 void
247 Early::visit (AST::MacroInvocation &invoc)
248 {
249 auto path = invoc.get_invoc_data ().get_path ();
250
251 if (invoc.get_kind () == AST::MacroInvocation::InvocKind::Builtin)
252 for (auto &pending_invoc : invoc.get_pending_eager_invocations ())
253 pending_invoc->accept_vis (*this);
254
255 // When a macro is invoked by an unqualified identifier (not part of a
256 // multi-part path), it is first looked up in textual scoping. If this does
257 // not yield any results, then it is looked up in path-based scoping. If the
258 // macro's name is qualified with a path, then it is only looked up in
259 // path-based scoping.
260
261 // https://doc.rust-lang.org/reference/macros-by-example.html#path-based-scope
262
263 tl::optional<Rib::Definition> definition = tl::nullopt;
264 if (path.get_segments ().size () == 1)
265 definition
266 = textual_scope.get (path.get_final_segment ().as_string ())
267 .map ([] (NodeId id) { return Rib::Definition::NonShadowable (id); });
268
269 // we won't have changed `definition` from `nullopt` if there are more
270 // than one segments in our path
271 if (!definition.has_value ())
272 definition = ctx.resolve_path (path.get_segments (), Namespace::Macros);
273
274 // if the definition still does not have a value, then it's an error
275 if (!definition.has_value ())
276 {
277 collect_error (Error (invoc.get_locus (), ErrorCode::E0433,
278 "could not resolve macro invocation %qs",
279 path.as_string ().c_str ()));
280 return;
281 }
282
283 insert_once (invoc, definition->get_node_id ());
284
285 // now do we need to keep mappings or something? or insert "uses" into our
286 // ForeverStack? can we do that? are mappings simpler?
287 auto &mappings = Analysis::Mappings::get ();
288 auto rules_def = mappings.lookup_macro_def (definition->get_node_id ());
289
290 // Macro definition not found, maybe it is not expanded yet.
291 if (!rules_def)
292 return;
293
294 if (mappings.lookup_macro_invocation (invoc))
295 return;
296
297 mappings.insert_macro_invocation (invoc, rules_def.value ());
298 }
299
300 void
301 Early::visit_attributes (std::vector<AST::Attribute> &attrs)
302 {
303 auto &mappings = Analysis::Mappings::get ();
304
305 for (auto &attr : attrs)
306 {
307 auto name = attr.get_path ().get_segments ().at (0).get_segment_name ();
308
309 if (attr.is_derive ())
310 {
311 auto traits = attr.get_traits_to_derive ();
312 for (auto &trait : traits)
313 {
314 auto definition = ctx.resolve_path (trait.get ().get_segments (),
315 Namespace::Macros);
316 if (!definition.has_value ())
317 {
318 // FIXME: Change to proper error message
319 collect_error (Error (trait.get ().get_locus (),
320 "could not resolve trait %qs",
321 trait.get ().as_string ().c_str ()));
322 continue;
323 }
324
325 auto pm_def = mappings.lookup_derive_proc_macro_def (
326 definition->get_node_id ());
327
328 if (pm_def.has_value ())
329 mappings.insert_derive_proc_macro_invocation (trait,
330 pm_def.value ());
331 }
332 }
333 else if (Analysis::BuiltinAttributeMappings::get ()
334 ->lookup_builtin (name)
335 .is_error ()) // Do not resolve builtins
336 {
337 auto definition = ctx.resolve_path (attr.get_path ().get_segments (),
338 Namespace::Macros);
339 if (!definition.has_value ())
340 {
341 // FIXME: Change to proper error message
342 collect_error (
343 Error (attr.get_locus (),
344 "could not resolve attribute macro invocation"));
345 return;
346 }
347 auto pm_def = mappings.lookup_attribute_proc_macro_def (
348 definition->get_node_id ());
349
350 rust_assert (pm_def.has_value ());
351
352 mappings.insert_attribute_proc_macro_invocation (attr.get_path (),
353 pm_def.value ());
354 }
355 }
356 }
357
358 void
359 Early::visit (AST::Function &fn)
360 {
361 visit_attributes (fn.get_outer_attrs ());
362 DefaultResolver::visit (fn);
363 }
364
365 void
366 Early::visit (AST::StructStruct &s)
367 {
368 visit_attributes (s.get_outer_attrs ());
369 DefaultResolver::visit (s);
370 }
371
372 void
373 Early::finalize_simple_import (const Early::ImportPair &mapping)
374 {
375 // FIXME: We probably need to store namespace information
376
377 auto locus = mapping.import_kind.to_resolve.get_locus ();
378 auto data = mapping.data;
379 auto identifier
380 = mapping.import_kind.to_resolve.get_final_segment ().get_segment_name ();
381
382 for (auto &&definition : data.definitions ())
383 toplevel
384 .insert_or_error_out (
385 identifier, locus, definition.first.get_node_id (), definition.second /* TODO: This isn't clear - it would be better if it was called .ns or something */);
386 }
387
388 void
389 Early::finalize_glob_import (NameResolutionContext &ctx,
390 const Early::ImportPair &mapping)
391 {
392 auto module = Analysis::Mappings::get ().lookup_ast_module (
393 mapping.data.module ().get_node_id ());
394 rust_assert (module);
395
396 GlobbingVisitor glob_visitor (ctx);
397 glob_visitor.go (module.value ());
398 }
399
400 void
401 Early::finalize_rebind_import (const Early::ImportPair &mapping)
402 {
403 // We can fetch the value here as `resolve_rebind` will only be called on
404 // imports of the right kind
405 auto &path = mapping.import_kind.to_resolve;
406 auto &rebind = mapping.import_kind.rebind.value ();
407 auto data = mapping.data;
408
409 location_t locus = UNKNOWN_LOCATION;
410 std::string declared_name;
411
412 // FIXME: This needs to be done in `FinalizeImports`
413 switch (rebind.get_new_bind_type ())
414 {
415 case AST::UseTreeRebind::NewBindType::IDENTIFIER:
416 declared_name = rebind.get_identifier ().as_string ();
417 locus = rebind.get_identifier ().get_locus ();
418 break;
419 case AST::UseTreeRebind::NewBindType::NONE: {
420 const auto &segments = path.get_segments ();
421 // We don't want to insert `self` with `use module::self`
422 if (path.get_final_segment ().is_lower_self_seg ())
423 {
424 rust_assert (segments.size () > 1);
425 declared_name = segments[segments.size () - 2].as_string ();
426 }
427 else
428 declared_name = path.get_final_segment ().as_string ();
429 locus = path.get_final_segment ().get_locus ();
430 break;
431 }
432 case AST::UseTreeRebind::NewBindType::WILDCARD:
433 rust_unreachable ();
434 break;
435 }
436
437 for (auto &&definition : data.definitions ())
438 toplevel.insert_or_error_out (
439 declared_name, locus, definition.first.get_node_id (), definition.second /* TODO: This isn't clear - it would be better if it was called .ns or something */);
440 }
441
442 void
443 Early::visit (AST::UseDeclaration &decl)
444 {
445 auto &imports = toplevel.get_imports_to_resolve ();
446 auto current_import = imports.find (decl.get_node_id ());
447 if (current_import != imports.end ())
448 {
449 build_import_mapping (*current_import);
450 }
451
452 // Once this is done, we finalize their resolution
453 for (const auto &mapping : import_mappings.get (decl.get_node_id ()))
454 switch (mapping.import_kind.kind)
455 {
456 case TopLevel::ImportKind::Kind::Glob:
457 finalize_glob_import (ctx, mapping);
458 break;
459 case TopLevel::ImportKind::Kind::Simple:
460 finalize_simple_import (mapping);
461 break;
462 case TopLevel::ImportKind::Kind::Rebind:
463 finalize_rebind_import (mapping);
464 break;
465 }
466
467 DefaultResolver::visit (decl);
468 }
469
470 } // namespace Resolver2_0
471 } // namespace Rust