Debian Codegraph @

gcc/rust/resolve/rust-toplevel-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-toplevel-name-resolver-2.0.h"
20 #include "input.h"
21 #include "optional.h"
22 #include "rust-ast-full.h"
23 #include "rust-hir-map.h"
24 #include "rust-attribute-values.h"
25
26 namespace Rust {
27 namespace Resolver2_0 {
28
29 TopLevel::TopLevel (NameResolutionContext &resolver)
30 : DefaultResolver (resolver), dirty (false)
31 {}
32
33 template <typename T>
34 void
35 TopLevel::insert_enum_variant_or_error_out (const Identifier &identifier,
36 const T &node)
37 {
38 insert_enum_variant_or_error_out (identifier, node.get_locus (),
39 node.get_node_id ());
40 }
41
42 void
43 TopLevel::check_multiple_insertion_error (
44 tl::expected<NodeId, DuplicateNameError> result, const Identifier &identifier,
45 const location_t &locus, const NodeId node_id)
46 {
47 if (result)
48 dirty = true;
49 else if (result.error ().existing != node_id)
50 {
51 rich_location rich_loc (line_table, locus);
52 rich_loc.add_range (node_locations[result.error ().existing]);
53
54 rust_error_at (rich_loc, ErrorCode::E0428, "%qs defined multiple times",
55 identifier.as_string ().c_str ());
56 }
57 }
58 void
59 TopLevel::insert_enum_variant_or_error_out (const Identifier &identifier,
60 const location_t &locus,
61 const NodeId node_id)
62 {
63 // keep track of each node's location to provide useful errors
64 node_locations.emplace (node_id, locus);
65
66 auto result = ctx.insert_variant (identifier, node_id);
67 check_multiple_insertion_error (result, identifier, locus, node_id);
68 }
69
70 template <typename T>
71 void
72 TopLevel::insert_or_error_out (const Identifier &identifier, const T &node,
73 Namespace ns)
74 {
75 insert_or_error_out (identifier, node.get_locus (), node.get_node_id (), ns);
76 }
77
78 void
79 TopLevel::insert_or_error_out (const Identifier &identifier,
80 const location_t &locus, const NodeId &node_id,
81 Namespace ns)
82 {
83 // keep track of each node's location to provide useful errors
84 node_locations.emplace (node_id, locus);
85
86 auto result = ctx.insert (identifier, node_id, ns);
87 check_multiple_insertion_error (result, identifier, locus, node_id);
88 }
89
90 void
91 TopLevel::go (AST::Crate &crate)
92 {
93 // we do not include builtin types in the top-level definition collector, as
94 // they are not used until `Late`. furthermore, we run this visitor multiple
95 // times in a row in a fixed-point fashion, so it would make the code
96 // responsible for this ugly and perfom a lot of error checking.
97
98 for (auto &item : crate.items)
99 item->accept_vis (*this);
100 }
101
102 void
103 TopLevel::visit (AST::Module &module)
104 {
105 insert_or_error_out (module.get_name (), module, Namespace::Types);
106
107 // Parse the module's items if they haven't been expanded and the file
108 // should be parsed (i.e isn't hidden behind an untrue or impossible cfg
109 // directive
110 // TODO: make sure this is right
111 // TODO: avoid loading items if cfg attributes are present?
112 // might not be needed if this runs after early resolution?
113 // This was copied from the old early resolver method
114 // 'accumulate_escaped_macros'
115 if (module.get_kind () == AST::Module::UNLOADED)
116 {
117 module.load_items ();
118
119 // If the module was previously unloaded, then we don't want to visit it
120 // this time around as the CfgStrip hasn't run on its inner items yet.
121 // Skip it for now, mark the visitor as dirty and try again
122
123 dirty = true;
124
125 return;
126 }
127
128 DefaultResolver::visit (module);
129
130 if (Analysis::Mappings::get ().lookup_ast_module (module.get_node_id ())
131 == tl::nullopt)
132 Analysis::Mappings::get ().insert_ast_module (&module);
133 }
134
135 void
136 TopLevel::visit (AST::Trait &trait)
137 {
138 insert_or_error_out (trait.get_identifier ().as_string (), trait,
139 Namespace::Types);
140
141 DefaultResolver::visit (trait);
142 }
143
144 void
145 TopLevel::visit (AST::InherentImpl &impl)
146 {
147 auto inner_fn = [this, &impl] () {
148 insert_or_error_out (Identifier ("Self", impl.get_type ().get_locus ()),
149 impl.get_type (), Namespace::Types);
150
151 // We do want to visit with the default visitor instead of default resolver
152 // because we don't want to insert the scope twice.
153 AST::DefaultASTVisitor::visit (impl);
154 };
155
156 ctx.scoped (Rib::Kind::TraitOrImpl, impl.get_node_id (), inner_fn);
157 }
158
159 void
160 TopLevel::visit (AST::TraitImpl &impl)
161 {
162 auto inner_fn = [this, &impl] () {
163 insert_or_error_out (Identifier ("Self", impl.get_type ().get_locus ()),
164 impl.get_type (), Namespace::Types);
165
166 // We do want to visit using the default visitor instead of default resolver
167 // because we don't want to insert the scope twice.
168 AST::DefaultASTVisitor::visit (impl);
169 };
170
171 ctx.scoped (Rib::Kind::TraitOrImpl, impl.get_node_id (), inner_fn);
172 }
173
174 void
175 TopLevel::visit (AST::TraitItemType &trait_item)
176 {
177 insert_or_error_out (trait_item.get_identifier ().as_string (), trait_item,
178 Namespace::Types);
179
180 DefaultResolver::visit (trait_item);
181 }
182
183 template <typename PROC_MACRO>
184 static void
185 insert_macros (std::vector<PROC_MACRO> &macros, NameResolutionContext &ctx)
186 {
187 for (auto &macro : macros)
188 {
189 auto res = ctx.macros.insert (macro.get_name (), macro.get_node_id ());
190
191 if (!res && res.error ().existing != macro.get_node_id ())
192 {
193 rust_error_at (UNKNOWN_LOCATION, ErrorCode::E0428,
194 "macro %qs defined multiple times",
195 macro.get_name ().c_str ());
196 }
197 }
198 }
199
200 void
201 TopLevel::visit (AST::ExternCrate &crate)
202 {
203 auto &mappings = Analysis::Mappings::get ();
204 auto num_opt = mappings.lookup_crate_name (crate.get_referenced_crate ());
205
206 if (!num_opt)
207 {
208 rust_error_at (crate.get_locus (), "unknown crate %qs",
209 crate.get_referenced_crate ().c_str ());
210 return;
211 }
212
213 CrateNum num = *num_opt;
214
215 auto attribute_macros = mappings.lookup_attribute_proc_macros (num);
216
217 auto bang_macros = mappings.lookup_bang_proc_macros (num);
218
219 auto derive_macros = mappings.lookup_derive_proc_macros (num);
220
221 auto sub_visitor = [&] () {
222 // TODO: Find a way to keep this part clean without the double dispatch.
223 if (derive_macros.has_value ())
224 {
225 insert_macros (derive_macros.value (), ctx);
226 for (auto &macro : derive_macros.value ())
227 mappings.insert_derive_proc_macro_def (macro);
228 }
229 if (attribute_macros.has_value ())
230 {
231 insert_macros (attribute_macros.value (), ctx);
232 for (auto &macro : attribute_macros.value ())
233 mappings.insert_attribute_proc_macro_def (macro);
234 }
235 if (bang_macros.has_value ())
236 {
237 insert_macros (bang_macros.value (), ctx);
238 for (auto &macro : bang_macros.value ())
239 mappings.insert_bang_proc_macro_def (macro);
240 }
241 };
242
243 if (crate.has_as_clause ())
244 ctx.scoped (Rib::Kind::Module, crate.get_node_id (), sub_visitor,
245 crate.get_as_clause ());
246 else
247 ctx.scoped (Rib::Kind::Module, crate.get_node_id (), sub_visitor,
248 crate.get_referenced_crate ());
249 }
250
251 static bool
252 is_macro_export (AST::MacroRulesDefinition &def)
253 {
254 for (const auto &attr : def.get_outer_attrs ())
255 if (attr.get_path ().as_string () == Values::Attributes::MACRO_EXPORT)
256 return true;
257
258 return false;
259 }
260
261 void
262 TopLevel::visit (AST::MacroRulesDefinition &macro)
263 {
264 // we do not insert macros in the current rib as that needs to be done in the
265 // textual scope of the Early pass. we only insert them in the root of the
266 // crate if they are marked with #[macro_export]. The execption to this is
267 // macros 2.0, which get resolved and inserted like regular items.
268
269 if (is_macro_export (macro))
270 {
271 auto res = ctx.macros.insert_at_root (macro.get_rule_name (),
272 macro.get_node_id ());
273 if (!res && res.error ().existing != macro.get_node_id ())
274 {
275 // TODO: Factor this
276 rich_location rich_loc (line_table, macro.get_locus ());
277 rich_loc.add_range (node_locations[res.error ().existing]);
278
279 rust_error_at (rich_loc, ErrorCode::E0428,
280 "macro %qs defined multiple times",
281 macro.get_rule_name ().as_string ().c_str ());
282 }
283 }
284
285 if (macro.get_kind () == AST::MacroRulesDefinition::MacroKind::DeclMacro)
286 insert_or_error_out (macro.get_rule_name (), macro, Namespace::Macros);
287
288 auto &mappings = Analysis::Mappings::get ();
289 if (mappings.lookup_macro_def (macro.get_node_id ()))
290 return;
291
292 mappings.insert_macro_def (&macro);
293 }
294
295 void
296 TopLevel::visit (AST::Function &function)
297 {
298 insert_or_error_out (function.get_function_name (), function,
299 Namespace::Values);
300
301 DefaultResolver::visit (function);
302 }
303
304 void
305 TopLevel::visit (AST::StaticItem &static_item)
306 {
307 insert_or_error_out (static_item.get_identifier (), static_item,
308 Namespace::Values);
309
310 DefaultResolver::visit (static_item);
311 }
312
313 void
314 TopLevel::visit (AST::ExternalStaticItem &static_item)
315 {
316 insert_or_error_out (static_item.get_identifier ().as_string (), static_item,
317 Namespace::Values);
318
319 DefaultResolver::visit (static_item);
320 }
321
322 void
323 TopLevel::visit (AST::StructStruct &struct_item)
324 {
325 auto generic_vis = [this, &struct_item] () {
326 for (auto &g : struct_item.get_generic_params ())
327 {
328 g->accept_vis (*this);
329 }
330 };
331
332 ctx.scoped (Rib::Kind::Item, struct_item.get_node_id (), generic_vis);
333
334 insert_or_error_out (struct_item.get_struct_name (), struct_item,
335 Namespace::Types);
336
337 // Do we need to insert the constructor in the value namespace as well?
338
339 // Do we need to do anything if the struct is a unit struct?
340 if (struct_item.is_unit_struct ())
341 insert_or_error_out (struct_item.get_struct_name (), struct_item,
342 Namespace::Values);
343 }
344
345 void
346 TopLevel::visit (AST::TypeParam &type_param)
347 {
348 insert_or_error_out (type_param.get_type_representation (), type_param,
349 Namespace::Types);
350
351 DefaultResolver::visit (type_param);
352 }
353
354 void
355 TopLevel::visit (AST::ConstGenericParam &const_param)
356 {
357 insert_or_error_out (const_param.get_name (), const_param, Namespace::Values);
358
359 DefaultResolver::visit (const_param);
360 }
361
362 void
363 TopLevel::visit (AST::TupleStruct &tuple_struct)
364 {
365 insert_or_error_out (tuple_struct.get_struct_name (), tuple_struct,
366 Namespace::Types);
367
368 insert_or_error_out (tuple_struct.get_struct_name (), tuple_struct,
369 Namespace::Values);
370
371 DefaultResolver::visit (tuple_struct);
372 }
373
374 void
375 TopLevel::visit (AST::EnumItem &variant)
376 {
377 insert_enum_variant_or_error_out (variant.get_identifier (), variant);
378 }
379
380 void
381 TopLevel::visit (AST::EnumItemTuple &variant)
382 {
383 insert_enum_variant_or_error_out (variant.get_identifier (), variant);
384 }
385
386 void
387 TopLevel::visit (AST::EnumItemStruct &variant)
388 {
389 insert_enum_variant_or_error_out (variant.get_identifier (), variant);
390 }
391
392 void
393 TopLevel::visit (AST::EnumItemDiscriminant &variant)
394 {
395 insert_or_error_out (variant.get_identifier (), variant, Namespace::Types);
396 }
397
398 void
399 TopLevel::visit (AST::Enum &enum_item)
400 {
401 insert_or_error_out (enum_item.get_identifier (), enum_item,
402 Namespace::Types);
403
404 DefaultResolver::visit (enum_item);
405 }
406
407 void
408 TopLevel::visit (AST::Union &union_item)
409 {
410 insert_or_error_out (union_item.get_identifier (), union_item,
411 Namespace::Types);
412
413 DefaultResolver::visit (union_item);
414 }
415
416 void
417 TopLevel::visit (AST::ConstantItem &const_item)
418 {
419 insert_or_error_out (const_item.get_identifier (), const_item,
420 Namespace::Values);
421
422 DefaultResolver::visit (const_item);
423 }
424
425 void
426 TopLevel::visit (AST::TypeAlias &type_item)
427 {
428 insert_or_error_out (type_item.get_new_type_name (), type_item,
429 Namespace::Types);
430
431 DefaultResolver::visit (type_item);
432 }
433
434 static void
435 flatten_rebind (
436 const AST::UseTreeRebind &glob,
437 std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> &rebind_paths);
438
439 static void
440 flatten_list (
441 const AST::UseTreeList &glob, std::vector<AST::SimplePath> &paths,
442 std::vector<AST::SimplePath> &glob_paths,
443 std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> &rebind_paths,
444 NameResolutionContext &ctx);
445 static void
446 flatten_glob (const AST::UseTreeGlob &glob,
447 std::vector<AST::SimplePath> &glob_paths,
448 NameResolutionContext &ctx);
449
450 static void
451 flatten (
452 const AST::UseTree *tree, std::vector<AST::SimplePath> &paths,
453 std::vector<AST::SimplePath> &glob_paths,
454 std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> &rebind_paths,
455 NameResolutionContext &ctx)
456 {
457 switch (tree->get_kind ())
458 {
459 case AST::UseTree::Rebind: {
460 auto rebind = static_cast<const AST::UseTreeRebind *> (tree);
461 flatten_rebind (*rebind, rebind_paths);
462 break;
463 }
464 case AST::UseTree::List: {
465 auto list = static_cast<const AST::UseTreeList *> (tree);
466 flatten_list (*list, paths, glob_paths, rebind_paths, ctx);
467 break;
468 }
469 case AST::UseTree::Glob: {
470 auto glob = static_cast<const AST::UseTreeGlob *> (tree);
471 flatten_glob (*glob, glob_paths, ctx);
472 break;
473 }
474 break;
475 }
476 }
477
478 static void
479 flatten_rebind (
480 const AST::UseTreeRebind &rebind,
481 std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> &rebind_paths)
482 {
483 rebind_paths.emplace_back (rebind.get_path (), rebind);
484 }
485
486 /** Prefix a list of subpath
487 * @param prefix A prefix for all subpath
488 * @param subs List of subpath to prefix
489 * @param size List where results should be stored
490 */
491 static void
492 prefix_subpaths (AST::SimplePath prefix, std::vector<AST::SimplePath> subs,
493 std::vector<AST::SimplePath> &results)
494 {
495 for (auto &sub : subs)
496 {
497 auto new_path = prefix;
498 std::copy (sub.get_segments ().begin (), sub.get_segments ().end (),
499 std::back_inserter (new_path.get_segments ()));
500 results.emplace_back (new_path);
501 }
502 }
503
504 static void
505 prefix_rebinds (
506 AST::SimplePath prefix,
507 std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> subs,
508 std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> &results)
509 {
510 for (auto &sub : subs)
511 {
512 auto new_path = prefix;
513 std::copy (sub.first.get_segments ().begin (),
514 sub.first.get_segments ().end (),
515 std::back_inserter (new_path.get_segments ()));
516 results.emplace_back (std::make_pair (new_path, sub.second));
517 }
518 }
519
520 static void
521 flatten_list (
522 const AST::UseTreeList &list, std::vector<AST::SimplePath> &paths,
523 std::vector<AST::SimplePath> &glob_paths,
524 std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> &rebind_paths,
525 NameResolutionContext &ctx)
526 {
527 auto prefix = AST::SimplePath::create_empty ();
528 if (list.has_path ())
529 prefix = list.get_path ();
530
531 for (const auto &tree : list.get_trees ())
532 {
533 auto sub_paths = std::vector<AST::SimplePath> ();
534 auto sub_globs = std::vector<AST::SimplePath> ();
535 auto sub_rebinds
536 = std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> ();
537 flatten (tree.get (), sub_paths, sub_globs, sub_rebinds, ctx);
538
539 prefix_subpaths (prefix, sub_paths, paths);
540 prefix_subpaths (prefix, sub_globs, glob_paths);
541 prefix_rebinds (prefix, sub_rebinds, rebind_paths);
542 }
543 }
544
545 static void
546 flatten_glob (const AST::UseTreeGlob &glob, std::vector<AST::SimplePath> &paths,
547 NameResolutionContext &ctx)
548 {
549 if (glob.has_path ())
550 paths.emplace_back (glob.get_path ());
551 }
552
553 void
554 TopLevel::visit (AST::UseDeclaration &use)
555 {
556 auto paths = std::vector<AST::SimplePath> ();
557 auto glob_path = std::vector<AST::SimplePath> ();
558 auto rebind_path
559 = std::vector<std::pair<AST::SimplePath, AST::UseTreeRebind>> ();
560
561 auto &values_rib = ctx.values.peek ();
562 auto &types_rib = ctx.types.peek ();
563 auto &macros_rib = ctx.macros.peek ();
564
565 // FIXME: How do we handle `use foo::{self}` imports? Some beforehand cleanup?
566 // How do we handle module imports in general? Should they get added to all
567 // namespaces?
568
569 const auto &tree = use.get_tree ();
570 flatten (tree.get (), paths, glob_path, rebind_path, this->ctx);
571
572 auto imports = std::vector<ImportKind> ();
573
574 for (auto &&path : paths)
575 imports.emplace_back (
576 ImportKind::Simple (std::move (path), values_rib, types_rib, macros_rib));
577
578 for (auto &&glob : glob_path)
579 imports.emplace_back (
580 ImportKind::Glob (std::move (glob), values_rib, types_rib, macros_rib));
581
582 for (auto &&rebind : rebind_path)
583 imports.emplace_back (
584 ImportKind::Rebind (std::move (rebind.first), std::move (rebind.second),
585 values_rib, types_rib, macros_rib));
586
587 imports_to_resolve.insert ({use.get_node_id (), std::move (imports)});
588 }
589
590 } // namespace Resolver2_0
591 } // namespace Rust