]>
Commit | Line | Data |
---|---|---|
1 | //! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate | |
2 | //! that fragment into the module structures that are already partially built. | |
3 | //! | |
4 | //! Items from the fragment are placed into modules, | |
5 | //! unexpanded macros in the fragment are visited and registered. | |
6 | //! Imports are also considered items and placed into modules here, but not resolved yet. | |
7 | ||
8 | use crate::def_collector::collect_definitions; | |
9 | use crate::imports::{Import, ImportKind}; | |
10 | use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; | |
11 | use crate::Namespace::{self, MacroNS, TypeNS, ValueNS}; | |
12 | use crate::{errors, BindingKey, MacroData}; | |
13 | use crate::{Determinacy, ExternPreludeEntry, Finalize, Module, ModuleKind, ModuleOrUniformRoot}; | |
14 | use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, PerNS, ResolutionError}; | |
15 | use crate::{Resolver, ResolverArenas, Segment, ToNameBinding, VisResolutionError}; | |
16 | ||
17 | use rustc_ast::visit::{self, AssocCtxt, Visitor}; | |
18 | use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind}; | |
19 | use rustc_ast::{Block, Fn, ForeignItem, ForeignItemKind, Impl, Item, ItemKind, NodeId}; | |
20 | use rustc_attr as attr; | |
21 | use rustc_data_structures::sync::Lrc; | |
22 | use rustc_errors::{struct_span_err, Applicability}; | |
23 | use rustc_expand::expand::AstFragment; | |
24 | use rustc_hir::def::{self, *}; | |
25 | use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; | |
26 | use rustc_metadata::creader::LoadedMacro; | |
27 | use rustc_middle::metadata::ModChild; | |
28 | use rustc_middle::{bug, ty}; | |
29 | use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind}; | |
30 | use rustc_span::symbol::{kw, sym, Ident, Symbol}; | |
31 | use rustc_span::Span; | |
32 | ||
33 | use std::cell::Cell; | |
34 | use std::ptr; | |
35 | ||
36 | type Res = def::Res<NodeId>; | |
37 | ||
38 | impl<'a, Id: Into<DefId>> ToNameBinding<'a> | |
39 | for (Module<'a>, ty::Visibility<Id>, Span, LocalExpnId) | |
40 | { | |
41 | fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { | |
42 | arenas.alloc_name_binding(NameBinding { | |
43 | kind: NameBindingKind::Module(self.0), | |
44 | ambiguity: None, | |
45 | vis: self.1.to_def_id(), | |
46 | span: self.2, | |
47 | expansion: self.3, | |
48 | }) | |
49 | } | |
50 | } | |
51 | ||
52 | impl<'a, Id: Into<DefId>> ToNameBinding<'a> for (Res, ty::Visibility<Id>, Span, LocalExpnId) { | |
53 | fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> { | |
54 | arenas.alloc_name_binding(NameBinding { | |
55 | kind: NameBindingKind::Res(self.0), | |
56 | ambiguity: None, | |
57 | vis: self.1.to_def_id(), | |
58 | span: self.2, | |
59 | expansion: self.3, | |
60 | }) | |
61 | } | |
62 | } | |
63 | ||
64 | impl<'a, 'tcx> Resolver<'a, 'tcx> { | |
65 | /// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined; | |
66 | /// otherwise, reports an error. | |
67 | pub(crate) fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T) | |
68 | where | |
69 | T: ToNameBinding<'a>, | |
70 | { | |
71 | let binding = def.to_name_binding(self.arenas); | |
72 | let key = self.new_disambiguated_key(ident, ns); | |
73 | if let Err(old_binding) = self.try_define(parent, key, binding) { | |
74 | self.report_conflict(parent, ident, ns, old_binding, &binding); | |
75 | } | |
76 | } | |
77 | ||
78 | /// Walks up the tree of definitions starting at `def_id`, | |
79 | /// stopping at the first encountered module. | |
80 | /// Parent block modules for arbitrary def-ids are not recorded for the local crate, | |
81 | /// and are not preserved in metadata for foreign crates, so block modules are never | |
82 | /// returned by this function. | |
83 | /// | |
84 | /// For the local crate ignoring block modules may be incorrect, so use this method with care. | |
85 | /// | |
86 | /// For foreign crates block modules can be ignored without introducing observable differences, | |
87 | /// moreover they has to be ignored right now because they are not kept in metadata. | |
88 | /// Foreign parent modules are used for resolving names used by foreign macros with def-site | |
89 | /// hygiene, therefore block module ignorability relies on macros with def-site hygiene and | |
90 | /// block module parents being unreachable from other crates. | |
91 | /// Reachable macros with block module parents exist due to `#[macro_export] macro_rules!`, | |
92 | /// but they cannot use def-site hygiene, so the assumption holds | |
93 | /// (<https://github.com/rust-lang/rust/pull/77984#issuecomment-712445508>). | |
94 | pub(crate) fn get_nearest_non_block_module(&mut self, mut def_id: DefId) -> Module<'a> { | |
95 | loop { | |
96 | match self.get_module(def_id) { | |
97 | Some(module) => return module, | |
98 | None => def_id = self.tcx.parent(def_id), | |
99 | } | |
100 | } | |
101 | } | |
102 | ||
103 | pub(crate) fn expect_module(&mut self, def_id: DefId) -> Module<'a> { | |
104 | self.get_module(def_id).expect("argument `DefId` is not a module") | |
105 | } | |
106 | ||
107 | /// If `def_id` refers to a module (in resolver's sense, i.e. a module item, crate root, enum, | |
108 | /// or trait), then this function returns that module's resolver representation, otherwise it | |
109 | /// returns `None`. | |
110 | pub(crate) fn get_module(&mut self, def_id: DefId) -> Option<Module<'a>> { | |
111 | if let module @ Some(..) = self.module_map.get(&def_id) { | |
112 | return module.copied(); | |
113 | } | |
114 | ||
115 | if !def_id.is_local() { | |
116 | // Query `def_kind` is not used because query system overhead is too expensive here. | |
117 | let def_kind = self.cstore().def_kind_untracked(def_id); | |
118 | if let DefKind::Mod | DefKind::Enum | DefKind::Trait = def_kind { | |
119 | let parent = self | |
120 | .tcx | |
121 | .opt_parent(def_id) | |
122 | .map(|parent_id| self.get_nearest_non_block_module(parent_id)); | |
123 | // Query `expn_that_defined` is not used because | |
124 | // hashing spans in its result is expensive. | |
125 | let expn_id = self.cstore().expn_that_defined_untracked(def_id, &self.tcx.sess); | |
126 | return Some(self.new_module( | |
127 | parent, | |
128 | ModuleKind::Def(def_kind, def_id, self.tcx.item_name(def_id)), | |
129 | expn_id, | |
130 | self.def_span(def_id), | |
131 | // FIXME: Account for `#[no_implicit_prelude]` attributes. | |
132 | parent.is_some_and(|module| module.no_implicit_prelude), | |
133 | )); | |
134 | } | |
135 | } | |
136 | ||
137 | None | |
138 | } | |
139 | ||
140 | pub(crate) fn expn_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> { | |
141 | match expn_id.expn_data().macro_def_id { | |
142 | Some(def_id) => self.macro_def_scope(def_id), | |
143 | None => expn_id | |
144 | .as_local() | |
145 | .and_then(|expn_id| self.ast_transform_scopes.get(&expn_id)) | |
146 | .unwrap_or(&self.graph_root), | |
147 | } | |
148 | } | |
149 | ||
150 | pub(crate) fn macro_def_scope(&mut self, def_id: DefId) -> Module<'a> { | |
151 | if let Some(id) = def_id.as_local() { | |
152 | self.local_macro_def_scopes[&id] | |
153 | } else { | |
154 | self.get_nearest_non_block_module(def_id) | |
155 | } | |
156 | } | |
157 | ||
158 | pub(crate) fn get_macro(&mut self, res: Res) -> Option<MacroData> { | |
159 | match res { | |
160 | Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)), | |
161 | Res::NonMacroAttr(_) => { | |
162 | Some(MacroData { ext: self.non_macro_attr.clone(), macro_rules: false }) | |
163 | } | |
164 | _ => None, | |
165 | } | |
166 | } | |
167 | ||
168 | pub(crate) fn get_macro_by_def_id(&mut self, def_id: DefId) -> MacroData { | |
169 | if let Some(macro_data) = self.macro_map.get(&def_id) { | |
170 | return macro_data.clone(); | |
171 | } | |
172 | ||
173 | let load_macro_untracked = self.cstore().load_macro_untracked(def_id, &self.tcx.sess); | |
174 | let (ext, macro_rules) = match load_macro_untracked { | |
175 | LoadedMacro::MacroDef(item, edition) => ( | |
176 | Lrc::new(self.compile_macro(&item, edition).0), | |
177 | matches!(item.kind, ItemKind::MacroDef(def) if def.macro_rules), | |
178 | ), | |
179 | LoadedMacro::ProcMacro(extz) => (Lrc::new(extz), false), | |
180 | }; | |
181 | ||
182 | let macro_data = MacroData { ext, macro_rules }; | |
183 | self.macro_map.insert(def_id, macro_data.clone()); | |
184 | macro_data | |
185 | } | |
186 | ||
187 | pub(crate) fn build_reduced_graph( | |
188 | &mut self, | |
189 | fragment: &AstFragment, | |
190 | parent_scope: ParentScope<'a>, | |
191 | ) -> MacroRulesScopeRef<'a> { | |
192 | collect_definitions(self, fragment, parent_scope.expansion); | |
193 | let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope }; | |
194 | fragment.visit_with(&mut visitor); | |
195 | visitor.parent_scope.macro_rules | |
196 | } | |
197 | ||
198 | pub(crate) fn build_reduced_graph_external(&mut self, module: Module<'a>) { | |
199 | for child in self.tcx.module_children(module.def_id()) { | |
200 | let parent_scope = ParentScope::module(module, self); | |
201 | BuildReducedGraphVisitor { r: self, parent_scope } | |
202 | .build_reduced_graph_for_external_crate_res(child); | |
203 | } | |
204 | } | |
205 | } | |
206 | ||
207 | struct BuildReducedGraphVisitor<'a, 'b, 'tcx> { | |
208 | r: &'b mut Resolver<'a, 'tcx>, | |
209 | parent_scope: ParentScope<'a>, | |
210 | } | |
211 | ||
212 | impl<'a, 'tcx> AsMut<Resolver<'a, 'tcx>> for BuildReducedGraphVisitor<'a, '_, 'tcx> { | |
213 | fn as_mut(&mut self) -> &mut Resolver<'a, 'tcx> { | |
214 | self.r | |
215 | } | |
216 | } | |
217 | ||
218 | impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> { | |
219 | fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility { | |
220 | self.try_resolve_visibility(vis, true).unwrap_or_else(|err| { | |
221 | self.r.report_vis_error(err); | |
222 | ty::Visibility::Public | |
223 | }) | |
224 | } | |
225 | ||
226 | fn try_resolve_visibility<'ast>( | |
227 | &mut self, | |
228 | vis: &'ast ast::Visibility, | |
229 | finalize: bool, | |
230 | ) -> Result<ty::Visibility, VisResolutionError<'ast>> { | |
231 | let parent_scope = &self.parent_scope; | |
232 | match vis.kind { | |
233 | ast::VisibilityKind::Public => Ok(ty::Visibility::Public), | |
234 | ast::VisibilityKind::Inherited => { | |
235 | Ok(match self.parent_scope.module.kind { | |
236 | // Any inherited visibility resolved directly inside an enum or trait | |
237 | // (i.e. variants, fields, and trait items) inherits from the visibility | |
238 | // of the enum or trait. | |
239 | ModuleKind::Def(DefKind::Enum | DefKind::Trait, def_id, _) => { | |
240 | self.r.visibilities[&def_id.expect_local()] | |
241 | } | |
242 | // Otherwise, the visibility is restricted to the nearest parent `mod` item. | |
243 | _ => ty::Visibility::Restricted( | |
244 | self.parent_scope.module.nearest_parent_mod().expect_local(), | |
245 | ), | |
246 | }) | |
247 | } | |
248 | ast::VisibilityKind::Restricted { ref path, id, .. } => { | |
249 | // Make `PRIVATE_IN_PUBLIC` lint a hard error. | |
250 | self.r.has_pub_restricted = true; | |
251 | // For visibilities we are not ready to provide correct implementation of "uniform | |
252 | // paths" right now, so on 2018 edition we only allow module-relative paths for now. | |
253 | // On 2015 edition visibilities are resolved as crate-relative by default, | |
254 | // so we are prepending a root segment if necessary. | |
255 | let ident = path.segments.get(0).expect("empty path in visibility").ident; | |
256 | let crate_root = if ident.is_path_segment_keyword() { | |
257 | None | |
258 | } else if ident.span.is_rust_2015() { | |
259 | Some(Segment::from_ident(Ident::new( | |
260 | kw::PathRoot, | |
261 | path.span.shrink_to_lo().with_ctxt(ident.span.ctxt()), | |
262 | ))) | |
263 | } else { | |
264 | return Err(VisResolutionError::Relative2018(ident.span, path)); | |
265 | }; | |
266 | ||
267 | let segments = crate_root | |
268 | .into_iter() | |
269 | .chain(path.segments.iter().map(|seg| seg.into())) | |
270 | .collect::<Vec<_>>(); | |
271 | let expected_found_error = |res| { | |
272 | Err(VisResolutionError::ExpectedFound( | |
273 | path.span, | |
274 | Segment::names_to_string(&segments), | |
275 | res, | |
276 | )) | |
277 | }; | |
278 | match self.r.resolve_path( | |
279 | &segments, | |
280 | Some(TypeNS), | |
281 | parent_scope, | |
282 | finalize.then(|| Finalize::new(id, path.span)), | |
283 | None, | |
284 | ) { | |
285 | PathResult::Module(ModuleOrUniformRoot::Module(module)) => { | |
286 | let res = module.res().expect("visibility resolved to unnamed block"); | |
287 | if finalize { | |
288 | self.r.record_partial_res(id, PartialRes::new(res)); | |
289 | } | |
290 | if module.is_normal() { | |
291 | match res { | |
292 | Res::Err => Ok(ty::Visibility::Public), | |
293 | _ => { | |
294 | let vis = ty::Visibility::Restricted(res.def_id()); | |
295 | if self.r.is_accessible_from(vis, parent_scope.module) { | |
296 | Ok(vis.expect_local()) | |
297 | } else { | |
298 | Err(VisResolutionError::AncestorOnly(path.span)) | |
299 | } | |
300 | } | |
301 | } | |
302 | } else { | |
303 | expected_found_error(res) | |
304 | } | |
305 | } | |
306 | PathResult::Module(..) => Err(VisResolutionError::ModuleOnly(path.span)), | |
307 | PathResult::NonModule(partial_res) => { | |
308 | expected_found_error(partial_res.expect_full_res()) | |
309 | } | |
310 | PathResult::Failed { span, label, suggestion, .. } => { | |
311 | Err(VisResolutionError::FailedToResolve(span, label, suggestion)) | |
312 | } | |
313 | PathResult::Indeterminate => Err(VisResolutionError::Indeterminate(path.span)), | |
314 | } | |
315 | } | |
316 | } | |
317 | } | |
318 | ||
319 | fn insert_field_def_ids(&mut self, def_id: LocalDefId, vdata: &ast::VariantData) { | |
320 | if vdata.fields().iter().any(|field| field.is_placeholder) { | |
321 | // The fields are not expanded yet. | |
322 | return; | |
323 | } | |
324 | let def_ids = vdata.fields().iter().map(|field| self.r.local_def_id(field.id).to_def_id()); | |
325 | self.r.field_def_ids.insert(def_id, self.r.tcx.arena.alloc_from_iter(def_ids)); | |
326 | } | |
327 | ||
328 | fn insert_field_visibilities_local(&mut self, def_id: DefId, vdata: &ast::VariantData) { | |
329 | let field_vis = vdata | |
330 | .fields() | |
331 | .iter() | |
332 | .map(|field| field.vis.span.until(field.ident.map_or(field.ty.span, |i| i.span))) | |
333 | .collect(); | |
334 | self.r.field_visibility_spans.insert(def_id, field_vis); | |
335 | } | |
336 | ||
337 | fn block_needs_anonymous_module(&mut self, block: &Block) -> bool { | |
338 | // If any statements are items, we need to create an anonymous module | |
339 | block | |
340 | .stmts | |
341 | .iter() | |
342 | .any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_))) | |
343 | } | |
344 | ||
345 | // Add an import to the current module. | |
346 | fn add_import( | |
347 | &mut self, | |
348 | module_path: Vec<Segment>, | |
349 | kind: ImportKind<'a>, | |
350 | span: Span, | |
351 | item: &ast::Item, | |
352 | root_span: Span, | |
353 | root_id: NodeId, | |
354 | vis: ty::Visibility, | |
355 | ) { | |
356 | let current_module = self.parent_scope.module; | |
357 | let import = self.r.arenas.alloc_import(Import { | |
358 | kind, | |
359 | parent_scope: self.parent_scope, | |
360 | module_path, | |
361 | imported_module: Cell::new(None), | |
362 | span, | |
363 | use_span: item.span, | |
364 | use_span_with_attributes: item.span_with_attributes(), | |
365 | has_attributes: !item.attrs.is_empty(), | |
366 | root_span, | |
367 | root_id, | |
368 | vis: Cell::new(Some(vis)), | |
369 | used: Cell::new(false), | |
370 | }); | |
371 | ||
372 | self.r.indeterminate_imports.push(import); | |
373 | match import.kind { | |
374 | // Don't add unresolved underscore imports to modules | |
375 | ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {} | |
376 | ImportKind::Single { target, type_ns_only, .. } => { | |
377 | self.r.per_ns(|this, ns| { | |
378 | if !type_ns_only || ns == TypeNS { | |
379 | let key = BindingKey::new(target, ns); | |
380 | let mut resolution = this.resolution(current_module, key).borrow_mut(); | |
381 | resolution.add_single_import(import); | |
382 | } | |
383 | }); | |
384 | } | |
385 | // We don't add prelude imports to the globs since they only affect lexical scopes, | |
386 | // which are not relevant to import resolution. | |
387 | ImportKind::Glob { is_prelude: true, .. } => {} | |
388 | ImportKind::Glob { .. } => current_module.globs.borrow_mut().push(import), | |
389 | _ => unreachable!(), | |
390 | } | |
391 | } | |
392 | ||
393 | fn build_reduced_graph_for_use_tree( | |
394 | &mut self, | |
395 | // This particular use tree | |
396 | use_tree: &ast::UseTree, | |
397 | id: NodeId, | |
398 | parent_prefix: &[Segment], | |
399 | nested: bool, | |
400 | // The whole `use` item | |
401 | item: &Item, | |
402 | vis: ty::Visibility, | |
403 | root_span: Span, | |
404 | ) { | |
405 | debug!( | |
406 | "build_reduced_graph_for_use_tree(parent_prefix={:?}, use_tree={:?}, nested={})", | |
407 | parent_prefix, use_tree, nested | |
408 | ); | |
409 | ||
410 | let mut prefix_iter = parent_prefix | |
411 | .iter() | |
412 | .cloned() | |
413 | .chain(use_tree.prefix.segments.iter().map(|seg| seg.into())) | |
414 | .peekable(); | |
415 | ||
416 | // On 2015 edition imports are resolved as crate-relative by default, | |
417 | // so prefixes are prepended with crate root segment if necessary. | |
418 | // The root is prepended lazily, when the first non-empty prefix or terminating glob | |
419 | // appears, so imports in braced groups can have roots prepended independently. | |
420 | let is_glob = matches!(use_tree.kind, ast::UseTreeKind::Glob); | |
421 | let crate_root = match prefix_iter.peek() { | |
422 | Some(seg) if !seg.ident.is_path_segment_keyword() && seg.ident.span.is_rust_2015() => { | |
423 | Some(seg.ident.span.ctxt()) | |
424 | } | |
425 | None if is_glob && use_tree.span.is_rust_2015() => Some(use_tree.span.ctxt()), | |
426 | _ => None, | |
427 | } | |
428 | .map(|ctxt| { | |
429 | Segment::from_ident(Ident::new( | |
430 | kw::PathRoot, | |
431 | use_tree.prefix.span.shrink_to_lo().with_ctxt(ctxt), | |
432 | )) | |
433 | }); | |
434 | ||
435 | let prefix = crate_root.into_iter().chain(prefix_iter).collect::<Vec<_>>(); | |
436 | debug!("build_reduced_graph_for_use_tree: prefix={:?}", prefix); | |
437 | ||
438 | let empty_for_self = |prefix: &[Segment]| { | |
439 | prefix.is_empty() || prefix.len() == 1 && prefix[0].ident.name == kw::PathRoot | |
440 | }; | |
441 | match use_tree.kind { | |
442 | ast::UseTreeKind::Simple(rename) => { | |
443 | let mut ident = use_tree.ident(); | |
444 | let mut module_path = prefix; | |
445 | let mut source = module_path.pop().unwrap(); | |
446 | let mut type_ns_only = false; | |
447 | ||
448 | self.r.visibilities.insert(self.r.local_def_id(id), vis); | |
449 | ||
450 | if nested { | |
451 | // Correctly handle `self` | |
452 | if source.ident.name == kw::SelfLower { | |
453 | type_ns_only = true; | |
454 | ||
455 | if empty_for_self(&module_path) { | |
456 | self.r.report_error( | |
457 | use_tree.span, | |
458 | ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix, | |
459 | ); | |
460 | return; | |
461 | } | |
462 | ||
463 | // Replace `use foo::{ self };` with `use foo;` | |
464 | let self_span = source.ident.span; | |
465 | source = module_path.pop().unwrap(); | |
466 | if rename.is_none() { | |
467 | // Keep the span of `self`, but the name of `foo` | |
468 | ident = Ident { name: source.ident.name, span: self_span }; | |
469 | } | |
470 | } | |
471 | } else { | |
472 | // Disallow `self` | |
473 | if source.ident.name == kw::SelfLower { | |
474 | let parent = module_path.last(); | |
475 | ||
476 | let span = match parent { | |
477 | // only `::self` from `use foo::self as bar` | |
478 | Some(seg) => seg.ident.span.shrink_to_hi().to(source.ident.span), | |
479 | None => source.ident.span, | |
480 | }; | |
481 | let span_with_rename = match rename { | |
482 | // only `self as bar` from `use foo::self as bar` | |
483 | Some(rename) => source.ident.span.to(rename.span), | |
484 | None => source.ident.span, | |
485 | }; | |
486 | self.r.report_error( | |
487 | span, | |
488 | ResolutionError::SelfImportsOnlyAllowedWithin { | |
489 | root: parent.is_none(), | |
490 | span_with_rename, | |
491 | }, | |
492 | ); | |
493 | ||
494 | // Error recovery: replace `use foo::self;` with `use foo;` | |
495 | if let Some(parent) = module_path.pop() { | |
496 | source = parent; | |
497 | if rename.is_none() { | |
498 | ident = source.ident; | |
499 | } | |
500 | } | |
501 | } | |
502 | ||
503 | // Disallow `use $crate;` | |
504 | if source.ident.name == kw::DollarCrate && module_path.is_empty() { | |
505 | let crate_root = self.r.resolve_crate_root(source.ident); | |
506 | let crate_name = match crate_root.kind { | |
507 | ModuleKind::Def(.., name) => name, | |
508 | ModuleKind::Block => unreachable!(), | |
509 | }; | |
510 | // HACK(eddyb) unclear how good this is, but keeping `$crate` | |
511 | // in `source` breaks `tests/ui/imports/import-crate-var.rs`, | |
512 | // while the current crate doesn't have a valid `crate_name`. | |
513 | if crate_name != kw::Empty { | |
514 | // `crate_name` should not be interpreted as relative. | |
515 | module_path.push(Segment::from_ident_and_id( | |
516 | Ident { name: kw::PathRoot, span: source.ident.span }, | |
517 | self.r.next_node_id(), | |
518 | )); | |
519 | source.ident.name = crate_name; | |
520 | } | |
521 | if rename.is_none() { | |
522 | ident.name = crate_name; | |
523 | } | |
524 | ||
525 | self.r.tcx.sess.emit_err(errors::CrateImported { span: item.span }); | |
526 | } | |
527 | } | |
528 | ||
529 | if ident.name == kw::Crate { | |
530 | self.r.tcx.sess.span_err( | |
531 | ident.span, | |
532 | "crate root imports need to be explicitly named: \ | |
533 | `use crate as name;`", | |
534 | ); | |
535 | } | |
536 | ||
537 | let kind = ImportKind::Single { | |
538 | source: source.ident, | |
539 | target: ident, | |
540 | source_bindings: PerNS { | |
541 | type_ns: Cell::new(Err(Determinacy::Undetermined)), | |
542 | value_ns: Cell::new(Err(Determinacy::Undetermined)), | |
543 | macro_ns: Cell::new(Err(Determinacy::Undetermined)), | |
544 | }, | |
545 | target_bindings: PerNS { | |
546 | type_ns: Cell::new(None), | |
547 | value_ns: Cell::new(None), | |
548 | macro_ns: Cell::new(None), | |
549 | }, | |
550 | type_ns_only, | |
551 | nested, | |
552 | id, | |
553 | }; | |
554 | ||
555 | self.add_import(module_path, kind, use_tree.span, item, root_span, item.id, vis); | |
556 | } | |
557 | ast::UseTreeKind::Glob => { | |
558 | let kind = ImportKind::Glob { | |
559 | is_prelude: attr::contains_name(&item.attrs, sym::prelude_import), | |
560 | max_vis: Cell::new(None), | |
561 | id, | |
562 | }; | |
563 | self.r.visibilities.insert(self.r.local_def_id(id), vis); | |
564 | self.add_import(prefix, kind, use_tree.span, item, root_span, item.id, vis); | |
565 | } | |
566 | ast::UseTreeKind::Nested(ref items) => { | |
567 | // Ensure there is at most one `self` in the list | |
568 | let self_spans = items | |
569 | .iter() | |
570 | .filter_map(|(use_tree, _)| { | |
571 | if let ast::UseTreeKind::Simple(..) = use_tree.kind { | |
572 | if use_tree.ident().name == kw::SelfLower { | |
573 | return Some(use_tree.span); | |
574 | } | |
575 | } | |
576 | ||
577 | None | |
578 | }) | |
579 | .collect::<Vec<_>>(); | |
580 | if self_spans.len() > 1 { | |
581 | let mut e = self.r.into_struct_error( | |
582 | self_spans[0], | |
583 | ResolutionError::SelfImportCanOnlyAppearOnceInTheList, | |
584 | ); | |
585 | ||
586 | for other_span in self_spans.iter().skip(1) { | |
587 | e.span_label(*other_span, "another `self` import appears here"); | |
588 | } | |
589 | ||
590 | e.emit(); | |
591 | } | |
592 | ||
593 | for &(ref tree, id) in items { | |
594 | self.build_reduced_graph_for_use_tree( | |
595 | // This particular use tree | |
596 | tree, id, &prefix, true, // The whole `use` item | |
597 | item, vis, root_span, | |
598 | ); | |
599 | } | |
600 | ||
601 | // Empty groups `a::b::{}` are turned into synthetic `self` imports | |
602 | // `a::b::c::{self as _}`, so that their prefixes are correctly | |
603 | // resolved and checked for privacy/stability/etc. | |
604 | if items.is_empty() && !empty_for_self(&prefix) { | |
605 | let new_span = prefix[prefix.len() - 1].ident.span; | |
606 | let tree = ast::UseTree { | |
607 | prefix: ast::Path::from_ident(Ident::new(kw::SelfLower, new_span)), | |
608 | kind: ast::UseTreeKind::Simple(Some(Ident::new(kw::Underscore, new_span))), | |
609 | span: use_tree.span, | |
610 | }; | |
611 | self.build_reduced_graph_for_use_tree( | |
612 | // This particular use tree | |
613 | &tree, | |
614 | id, | |
615 | &prefix, | |
616 | true, | |
617 | // The whole `use` item | |
618 | item, | |
619 | ty::Visibility::Restricted( | |
620 | self.parent_scope.module.nearest_parent_mod().expect_local(), | |
621 | ), | |
622 | root_span, | |
623 | ); | |
624 | } | |
625 | } | |
626 | } | |
627 | } | |
628 | ||
629 | /// Constructs the reduced graph for one item. | |
630 | fn build_reduced_graph_for_item(&mut self, item: &'b Item) { | |
631 | let parent_scope = &self.parent_scope; | |
632 | let parent = parent_scope.module; | |
633 | let expansion = parent_scope.expansion; | |
634 | let ident = item.ident; | |
635 | let sp = item.span; | |
636 | let vis = self.resolve_visibility(&item.vis); | |
637 | let local_def_id = self.r.local_def_id(item.id); | |
638 | let def_id = local_def_id.to_def_id(); | |
639 | ||
640 | self.r.visibilities.insert(local_def_id, vis); | |
641 | ||
642 | match item.kind { | |
643 | ItemKind::Use(ref use_tree) => { | |
644 | self.build_reduced_graph_for_use_tree( | |
645 | // This particular use tree | |
646 | use_tree, | |
647 | item.id, | |
648 | &[], | |
649 | false, | |
650 | // The whole `use` item | |
651 | item, | |
652 | vis, | |
653 | use_tree.span, | |
654 | ); | |
655 | } | |
656 | ||
657 | ItemKind::ExternCrate(orig_name) => { | |
658 | self.build_reduced_graph_for_extern_crate( | |
659 | orig_name, | |
660 | item, | |
661 | local_def_id, | |
662 | vis, | |
663 | parent, | |
664 | ); | |
665 | } | |
666 | ||
667 | ItemKind::Mod(..) => { | |
668 | let module = self.r.new_module( | |
669 | Some(parent), | |
670 | ModuleKind::Def(DefKind::Mod, def_id, ident.name), | |
671 | expansion.to_expn_id(), | |
672 | item.span, | |
673 | parent.no_implicit_prelude | |
674 | || attr::contains_name(&item.attrs, sym::no_implicit_prelude), | |
675 | ); | |
676 | self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); | |
677 | ||
678 | // Descend into the module. | |
679 | self.parent_scope.module = module; | |
680 | } | |
681 | ||
682 | // These items live in the value namespace. | |
683 | ItemKind::Static(box ast::StaticItem { mutability, .. }) => { | |
684 | let res = Res::Def(DefKind::Static(mutability), def_id); | |
685 | self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); | |
686 | } | |
687 | ItemKind::Const(..) => { | |
688 | let res = Res::Def(DefKind::Const, def_id); | |
689 | self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); | |
690 | } | |
691 | ItemKind::Fn(..) => { | |
692 | let res = Res::Def(DefKind::Fn, def_id); | |
693 | self.r.define(parent, ident, ValueNS, (res, vis, sp, expansion)); | |
694 | ||
695 | // Functions introducing procedural macros reserve a slot | |
696 | // in the macro namespace as well (see #52225). | |
697 | self.define_macro(item); | |
698 | } | |
699 | ||
700 | // These items live in the type namespace. | |
701 | ItemKind::TyAlias(..) => { | |
702 | let res = Res::Def(DefKind::TyAlias, def_id); | |
703 | self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); | |
704 | } | |
705 | ||
706 | ItemKind::Enum(_, _) => { | |
707 | let module = self.r.new_module( | |
708 | Some(parent), | |
709 | ModuleKind::Def(DefKind::Enum, def_id, ident.name), | |
710 | expansion.to_expn_id(), | |
711 | item.span, | |
712 | parent.no_implicit_prelude, | |
713 | ); | |
714 | self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); | |
715 | self.parent_scope.module = module; | |
716 | } | |
717 | ||
718 | ItemKind::TraitAlias(..) => { | |
719 | let res = Res::Def(DefKind::TraitAlias, def_id); | |
720 | self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); | |
721 | } | |
722 | ||
723 | // These items live in both the type and value namespaces. | |
724 | ItemKind::Struct(ref vdata, _) => { | |
725 | // Define a name in the type namespace. | |
726 | let res = Res::Def(DefKind::Struct, def_id); | |
727 | self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); | |
728 | ||
729 | // Record field names for error reporting. | |
730 | self.insert_field_def_ids(local_def_id, vdata); | |
731 | self.insert_field_visibilities_local(def_id, vdata); | |
732 | ||
733 | // If this is a tuple or unit struct, define a name | |
734 | // in the value namespace as well. | |
735 | if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(vdata) { | |
736 | // If the structure is marked as non_exhaustive then lower the visibility | |
737 | // to within the crate. | |
738 | let mut ctor_vis = if vis.is_public() | |
739 | && attr::contains_name(&item.attrs, sym::non_exhaustive) | |
740 | { | |
741 | ty::Visibility::Restricted(CRATE_DEF_ID) | |
742 | } else { | |
743 | vis | |
744 | }; | |
745 | ||
746 | let mut ret_fields = Vec::with_capacity(vdata.fields().len()); | |
747 | ||
748 | for field in vdata.fields() { | |
749 | // NOTE: The field may be an expansion placeholder, but expansion sets | |
750 | // correct visibilities for unnamed field placeholders specifically, so the | |
751 | // constructor visibility should still be determined correctly. | |
752 | let field_vis = self | |
753 | .try_resolve_visibility(&field.vis, false) | |
754 | .unwrap_or(ty::Visibility::Public); | |
755 | if ctor_vis.is_at_least(field_vis, self.r.tcx) { | |
756 | ctor_vis = field_vis; | |
757 | } | |
758 | ret_fields.push(field_vis.to_def_id()); | |
759 | } | |
760 | let ctor_def_id = self.r.local_def_id(ctor_node_id); | |
761 | let ctor_res = | |
762 | Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id.to_def_id()); | |
763 | self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion)); | |
764 | self.r.visibilities.insert(ctor_def_id, ctor_vis); | |
765 | // We need the field visibility spans also for the constructor for E0603. | |
766 | self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata); | |
767 | ||
768 | self.r | |
769 | .struct_constructors | |
770 | .insert(local_def_id, (ctor_res, ctor_vis.to_def_id(), ret_fields)); | |
771 | } | |
772 | } | |
773 | ||
774 | ItemKind::Union(ref vdata, _) => { | |
775 | let res = Res::Def(DefKind::Union, def_id); | |
776 | self.r.define(parent, ident, TypeNS, (res, vis, sp, expansion)); | |
777 | ||
778 | // Record field names for error reporting. | |
779 | self.insert_field_def_ids(local_def_id, vdata); | |
780 | self.insert_field_visibilities_local(def_id, vdata); | |
781 | } | |
782 | ||
783 | ItemKind::Trait(..) => { | |
784 | // Add all the items within to a new module. | |
785 | let module = self.r.new_module( | |
786 | Some(parent), | |
787 | ModuleKind::Def(DefKind::Trait, def_id, ident.name), | |
788 | expansion.to_expn_id(), | |
789 | item.span, | |
790 | parent.no_implicit_prelude, | |
791 | ); | |
792 | self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion)); | |
793 | self.parent_scope.module = module; | |
794 | } | |
795 | ||
796 | // These items do not add names to modules. | |
797 | ItemKind::Impl(box Impl { of_trait: Some(..), .. }) => { | |
798 | self.r.trait_impl_items.insert(local_def_id); | |
799 | } | |
800 | ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {} | |
801 | ||
802 | ItemKind::MacroDef(..) | ItemKind::MacCall(_) => unreachable!(), | |
803 | } | |
804 | } | |
805 | ||
806 | fn build_reduced_graph_for_extern_crate( | |
807 | &mut self, | |
808 | orig_name: Option<Symbol>, | |
809 | item: &Item, | |
810 | local_def_id: LocalDefId, | |
811 | vis: ty::Visibility, | |
812 | parent: Module<'a>, | |
813 | ) { | |
814 | let ident = item.ident; | |
815 | let sp = item.span; | |
816 | let parent_scope = self.parent_scope; | |
817 | let expansion = parent_scope.expansion; | |
818 | ||
819 | let (used, module, binding) = if orig_name.is_none() && ident.name == kw::SelfLower { | |
820 | self.r | |
821 | .tcx | |
822 | .sess | |
823 | .struct_span_err(item.span, "`extern crate self;` requires renaming") | |
824 | .span_suggestion( | |
825 | item.span, | |
826 | "rename the `self` crate to be able to import it", | |
827 | "extern crate self as name;", | |
828 | Applicability::HasPlaceholders, | |
829 | ) | |
830 | .emit(); | |
831 | return; | |
832 | } else if orig_name == Some(kw::SelfLower) { | |
833 | Some(self.r.graph_root) | |
834 | } else { | |
835 | let tcx = self.r.tcx; | |
836 | let crate_id = self.r.crate_loader(|c| { | |
837 | c.process_extern_crate(item, local_def_id, &tcx.definitions_untracked()) | |
838 | }); | |
839 | crate_id.map(|crate_id| { | |
840 | self.r.extern_crate_map.insert(local_def_id, crate_id); | |
841 | self.r.expect_module(crate_id.as_def_id()) | |
842 | }) | |
843 | } | |
844 | .map(|module| { | |
845 | let used = self.process_macro_use_imports(item, module); | |
846 | let vis = ty::Visibility::<LocalDefId>::Public; | |
847 | let binding = (module, vis, sp, expansion).to_name_binding(self.r.arenas); | |
848 | (used, Some(ModuleOrUniformRoot::Module(module)), binding) | |
849 | }) | |
850 | .unwrap_or((true, None, self.r.dummy_binding)); | |
851 | let import = self.r.arenas.alloc_import(Import { | |
852 | kind: ImportKind::ExternCrate { source: orig_name, target: ident, id: item.id }, | |
853 | root_id: item.id, | |
854 | parent_scope: self.parent_scope, | |
855 | imported_module: Cell::new(module), | |
856 | has_attributes: !item.attrs.is_empty(), | |
857 | use_span_with_attributes: item.span_with_attributes(), | |
858 | use_span: item.span, | |
859 | root_span: item.span, | |
860 | span: item.span, | |
861 | module_path: Vec::new(), | |
862 | vis: Cell::new(Some(vis)), | |
863 | used: Cell::new(used), | |
864 | }); | |
865 | self.r.potentially_unused_imports.push(import); | |
866 | let imported_binding = self.r.import(binding, import); | |
867 | if ptr::eq(parent, self.r.graph_root) { | |
868 | if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0()) { | |
869 | if expansion != LocalExpnId::ROOT | |
870 | && orig_name.is_some() | |
871 | && entry.extern_crate_item.is_none() | |
872 | { | |
873 | let msg = "macro-expanded `extern crate` items cannot \ | |
874 | shadow names passed with `--extern`"; | |
875 | self.r.tcx.sess.span_err(item.span, msg); | |
876 | // `return` is intended to discard this binding because it's an | |
877 | // unregistered ambiguity error which would result in a panic | |
878 | // caused by inconsistency `path_res` | |
879 | // more details: https://github.com/rust-lang/rust/pull/111761 | |
880 | return; | |
881 | } | |
882 | } | |
883 | let entry = self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert( | |
884 | ExternPreludeEntry { extern_crate_item: None, introduced_by_item: true }, | |
885 | ); | |
886 | entry.extern_crate_item = Some(imported_binding); | |
887 | if orig_name.is_some() { | |
888 | entry.introduced_by_item = true; | |
889 | } | |
890 | } | |
891 | self.r.define(parent, ident, TypeNS, imported_binding); | |
892 | } | |
893 | ||
894 | /// Constructs the reduced graph for one foreign item. | |
895 | fn build_reduced_graph_for_foreign_item(&mut self, item: &ForeignItem) { | |
896 | let local_def_id = self.r.local_def_id(item.id); | |
897 | let def_id = local_def_id.to_def_id(); | |
898 | let (def_kind, ns) = match item.kind { | |
899 | ForeignItemKind::Fn(..) => (DefKind::Fn, ValueNS), | |
900 | ForeignItemKind::Static(_, mt, _) => (DefKind::Static(mt), ValueNS), | |
901 | ForeignItemKind::TyAlias(..) => (DefKind::ForeignTy, TypeNS), | |
902 | ForeignItemKind::MacCall(_) => unreachable!(), | |
903 | }; | |
904 | let parent = self.parent_scope.module; | |
905 | let expansion = self.parent_scope.expansion; | |
906 | let vis = self.resolve_visibility(&item.vis); | |
907 | let res = Res::Def(def_kind, def_id); | |
908 | self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion)); | |
909 | self.r.visibilities.insert(local_def_id, vis); | |
910 | } | |
911 | ||
912 | fn build_reduced_graph_for_block(&mut self, block: &Block) { | |
913 | let parent = self.parent_scope.module; | |
914 | let expansion = self.parent_scope.expansion; | |
915 | if self.block_needs_anonymous_module(block) { | |
916 | let module = self.r.new_module( | |
917 | Some(parent), | |
918 | ModuleKind::Block, | |
919 | expansion.to_expn_id(), | |
920 | block.span, | |
921 | parent.no_implicit_prelude, | |
922 | ); | |
923 | self.r.block_map.insert(block.id, module); | |
924 | self.parent_scope.module = module; // Descend into the block. | |
925 | } | |
926 | } | |
927 | ||
928 | /// Builds the reduced graph for a single item in an external crate. | |
929 | fn build_reduced_graph_for_external_crate_res(&mut self, child: &ModChild) { | |
930 | let parent = self.parent_scope.module; | |
931 | let ModChild { ident, res, vis, ref reexport_chain } = *child; | |
932 | let span = self.r.def_span( | |
933 | reexport_chain | |
934 | .first() | |
935 | .and_then(|reexport| reexport.id()) | |
936 | .unwrap_or_else(|| res.def_id()), | |
937 | ); | |
938 | let res = res.expect_non_local(); | |
939 | let expansion = self.parent_scope.expansion; | |
940 | // Record primary definitions. | |
941 | match res { | |
942 | Res::Def(DefKind::Mod | DefKind::Enum | DefKind::Trait, def_id) => { | |
943 | let module = self.r.expect_module(def_id); | |
944 | self.r.define(parent, ident, TypeNS, (module, vis, span, expansion)); | |
945 | } | |
946 | Res::Def( | |
947 | DefKind::Struct | |
948 | | DefKind::Union | |
949 | | DefKind::Variant | |
950 | | DefKind::TyAlias | |
951 | | DefKind::ForeignTy | |
952 | | DefKind::OpaqueTy | |
953 | | DefKind::ImplTraitPlaceholder | |
954 | | DefKind::TraitAlias | |
955 | | DefKind::AssocTy, | |
956 | _, | |
957 | ) | |
958 | | Res::PrimTy(..) | |
959 | | Res::ToolMod => self.r.define(parent, ident, TypeNS, (res, vis, span, expansion)), | |
960 | Res::Def( | |
961 | DefKind::Fn | |
962 | | DefKind::AssocFn | |
963 | | DefKind::Static(_) | |
964 | | DefKind::Const | |
965 | | DefKind::AssocConst | |
966 | | DefKind::Ctor(..), | |
967 | _, | |
968 | ) => self.r.define(parent, ident, ValueNS, (res, vis, span, expansion)), | |
969 | Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => { | |
970 | self.r.define(parent, ident, MacroNS, (res, vis, span, expansion)) | |
971 | } | |
972 | Res::Def( | |
973 | DefKind::TyParam | |
974 | | DefKind::ConstParam | |
975 | | DefKind::ExternCrate | |
976 | | DefKind::Use | |
977 | | DefKind::ForeignMod | |
978 | | DefKind::AnonConst | |
979 | | DefKind::InlineConst | |
980 | | DefKind::Field | |
981 | | DefKind::LifetimeParam | |
982 | | DefKind::GlobalAsm | |
983 | | DefKind::Closure | |
984 | | DefKind::Impl { .. } | |
985 | | DefKind::Generator, | |
986 | _, | |
987 | ) | |
988 | | Res::Local(..) | |
989 | | Res::SelfTyParam { .. } | |
990 | | Res::SelfTyAlias { .. } | |
991 | | Res::SelfCtor(..) | |
992 | | Res::Err => bug!("unexpected resolution: {:?}", res), | |
993 | } | |
994 | } | |
995 | ||
996 | fn add_macro_use_binding( | |
997 | &mut self, | |
998 | name: Symbol, | |
999 | binding: &'a NameBinding<'a>, | |
1000 | span: Span, | |
1001 | allow_shadowing: bool, | |
1002 | ) { | |
1003 | if self.r.macro_use_prelude.insert(name, binding).is_some() && !allow_shadowing { | |
1004 | let msg = format!("`{}` is already in scope", name); | |
1005 | let note = | |
1006 | "macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)"; | |
1007 | self.r.tcx.sess.struct_span_err(span, msg).note(note).emit(); | |
1008 | } | |
1009 | } | |
1010 | ||
1011 | /// Returns `true` if we should consider the underlying `extern crate` to be used. | |
1012 | fn process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool { | |
1013 | let mut import_all = None; | |
1014 | let mut single_imports = Vec::new(); | |
1015 | for attr in &item.attrs { | |
1016 | if attr.has_name(sym::macro_use) { | |
1017 | if self.parent_scope.module.parent.is_some() { | |
1018 | struct_span_err!( | |
1019 | self.r.tcx.sess, | |
1020 | item.span, | |
1021 | E0468, | |
1022 | "an `extern crate` loading macros must be at the crate root" | |
1023 | ) | |
1024 | .emit(); | |
1025 | } | |
1026 | if let ItemKind::ExternCrate(Some(orig_name)) = item.kind { | |
1027 | if orig_name == kw::SelfLower { | |
1028 | self.r | |
1029 | .tcx | |
1030 | .sess | |
1031 | .emit_err(errors::MacroUseExternCrateSelf { span: attr.span }); | |
1032 | } | |
1033 | } | |
1034 | let ill_formed = |span| { | |
1035 | struct_span_err!(self.r.tcx.sess, span, E0466, "bad macro import").emit(); | |
1036 | }; | |
1037 | match attr.meta() { | |
1038 | Some(meta) => match meta.kind { | |
1039 | MetaItemKind::Word => { | |
1040 | import_all = Some(meta.span); | |
1041 | break; | |
1042 | } | |
1043 | MetaItemKind::List(nested_metas) => { | |
1044 | for nested_meta in nested_metas { | |
1045 | match nested_meta.ident() { | |
1046 | Some(ident) if nested_meta.is_word() => { | |
1047 | single_imports.push(ident) | |
1048 | } | |
1049 | _ => ill_formed(nested_meta.span()), | |
1050 | } | |
1051 | } | |
1052 | } | |
1053 | MetaItemKind::NameValue(..) => ill_formed(meta.span), | |
1054 | }, | |
1055 | None => ill_formed(attr.span), | |
1056 | } | |
1057 | } | |
1058 | } | |
1059 | ||
1060 | let macro_use_import = |this: &Self, span| { | |
1061 | this.r.arenas.alloc_import(Import { | |
1062 | kind: ImportKind::MacroUse, | |
1063 | root_id: item.id, | |
1064 | parent_scope: this.parent_scope, | |
1065 | imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))), | |
1066 | use_span_with_attributes: item.span_with_attributes(), | |
1067 | has_attributes: !item.attrs.is_empty(), | |
1068 | use_span: item.span, | |
1069 | root_span: span, | |
1070 | span, | |
1071 | module_path: Vec::new(), | |
1072 | vis: Cell::new(Some(ty::Visibility::Restricted(CRATE_DEF_ID))), | |
1073 | used: Cell::new(false), | |
1074 | }) | |
1075 | }; | |
1076 | ||
1077 | let allow_shadowing = self.parent_scope.expansion == LocalExpnId::ROOT; | |
1078 | if let Some(span) = import_all { | |
1079 | let import = macro_use_import(self, span); | |
1080 | self.r.potentially_unused_imports.push(import); | |
1081 | module.for_each_child(self, |this, ident, ns, binding| { | |
1082 | if ns == MacroNS { | |
1083 | let imported_binding = this.r.import(binding, import); | |
1084 | this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing); | |
1085 | } | |
1086 | }); | |
1087 | } else { | |
1088 | for ident in single_imports.iter().cloned() { | |
1089 | let result = self.r.maybe_resolve_ident_in_module( | |
1090 | ModuleOrUniformRoot::Module(module), | |
1091 | ident, | |
1092 | MacroNS, | |
1093 | &self.parent_scope, | |
1094 | ); | |
1095 | if let Ok(binding) = result { | |
1096 | let import = macro_use_import(self, ident.span); | |
1097 | self.r.potentially_unused_imports.push(import); | |
1098 | let imported_binding = self.r.import(binding, import); | |
1099 | self.add_macro_use_binding( | |
1100 | ident.name, | |
1101 | imported_binding, | |
1102 | ident.span, | |
1103 | allow_shadowing, | |
1104 | ); | |
1105 | } else { | |
1106 | struct_span_err!( | |
1107 | self.r.tcx.sess, | |
1108 | ident.span, | |
1109 | E0469, | |
1110 | "imported macro not found" | |
1111 | ) | |
1112 | .emit(); | |
1113 | } | |
1114 | } | |
1115 | } | |
1116 | import_all.is_some() || !single_imports.is_empty() | |
1117 | } | |
1118 | ||
1119 | /// Returns `true` if this attribute list contains `macro_use`. | |
1120 | fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool { | |
1121 | for attr in attrs { | |
1122 | if attr.has_name(sym::macro_escape) { | |
1123 | let msg = "`#[macro_escape]` is a deprecated synonym for `#[macro_use]`"; | |
1124 | let mut err = self.r.tcx.sess.struct_span_warn(attr.span, msg); | |
1125 | if let ast::AttrStyle::Inner = attr.style { | |
1126 | err.help("try an outer attribute: `#[macro_use]`").emit(); | |
1127 | } else { | |
1128 | err.emit(); | |
1129 | } | |
1130 | } else if !attr.has_name(sym::macro_use) { | |
1131 | continue; | |
1132 | } | |
1133 | ||
1134 | if !attr.is_word() { | |
1135 | self.r | |
1136 | .tcx | |
1137 | .sess | |
1138 | .span_err(attr.span, "arguments to `macro_use` are not allowed here"); | |
1139 | } | |
1140 | return true; | |
1141 | } | |
1142 | ||
1143 | false | |
1144 | } | |
1145 | ||
1146 | fn visit_invoc(&mut self, id: NodeId) -> LocalExpnId { | |
1147 | let invoc_id = id.placeholder_to_expn_id(); | |
1148 | let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope); | |
1149 | assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation"); | |
1150 | invoc_id | |
1151 | } | |
1152 | ||
1153 | /// Visit invocation in context in which it can emit a named item (possibly `macro_rules`) | |
1154 | /// directly into its parent scope's module. | |
1155 | fn visit_invoc_in_module(&mut self, id: NodeId) -> MacroRulesScopeRef<'a> { | |
1156 | let invoc_id = self.visit_invoc(id); | |
1157 | self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id); | |
1158 | self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Invocation(invoc_id)) | |
1159 | } | |
1160 | ||
1161 | fn proc_macro_stub(&self, item: &ast::Item) -> Option<(MacroKind, Ident, Span)> { | |
1162 | if attr::contains_name(&item.attrs, sym::proc_macro) { | |
1163 | return Some((MacroKind::Bang, item.ident, item.span)); | |
1164 | } else if attr::contains_name(&item.attrs, sym::proc_macro_attribute) { | |
1165 | return Some((MacroKind::Attr, item.ident, item.span)); | |
1166 | } else if let Some(attr) = attr::find_by_name(&item.attrs, sym::proc_macro_derive) { | |
1167 | if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) { | |
1168 | if let Some(ident) = nested_meta.ident() { | |
1169 | return Some((MacroKind::Derive, ident, ident.span)); | |
1170 | } | |
1171 | } | |
1172 | } | |
1173 | None | |
1174 | } | |
1175 | ||
1176 | // Mark the given macro as unused unless its name starts with `_`. | |
1177 | // Macro uses will remove items from this set, and the remaining | |
1178 | // items will be reported as `unused_macros`. | |
1179 | fn insert_unused_macro( | |
1180 | &mut self, | |
1181 | ident: Ident, | |
1182 | def_id: LocalDefId, | |
1183 | node_id: NodeId, | |
1184 | rule_spans: &[(usize, Span)], | |
1185 | ) { | |
1186 | if !ident.as_str().starts_with('_') { | |
1187 | self.r.unused_macros.insert(def_id, (node_id, ident)); | |
1188 | for (rule_i, rule_span) in rule_spans.iter() { | |
1189 | self.r.unused_macro_rules.insert((def_id, *rule_i), (ident, *rule_span)); | |
1190 | } | |
1191 | } | |
1192 | } | |
1193 | ||
1194 | fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScopeRef<'a> { | |
1195 | let parent_scope = self.parent_scope; | |
1196 | let expansion = parent_scope.expansion; | |
1197 | let def_id = self.r.local_def_id(item.id); | |
1198 | let (ext, ident, span, macro_rules, rule_spans) = match &item.kind { | |
1199 | ItemKind::MacroDef(def) => { | |
1200 | let (ext, rule_spans) = self.r.compile_macro(item, self.r.tcx.sess.edition()); | |
1201 | let ext = Lrc::new(ext); | |
1202 | (ext, item.ident, item.span, def.macro_rules, rule_spans) | |
1203 | } | |
1204 | ItemKind::Fn(..) => match self.proc_macro_stub(item) { | |
1205 | Some((macro_kind, ident, span)) => { | |
1206 | self.r.proc_macro_stubs.insert(def_id); | |
1207 | (self.r.dummy_ext(macro_kind), ident, span, false, Vec::new()) | |
1208 | } | |
1209 | None => return parent_scope.macro_rules, | |
1210 | }, | |
1211 | _ => unreachable!(), | |
1212 | }; | |
1213 | ||
1214 | let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id.to_def_id()); | |
1215 | self.r.macro_map.insert(def_id.to_def_id(), MacroData { ext, macro_rules }); | |
1216 | self.r.local_macro_def_scopes.insert(def_id, parent_scope.module); | |
1217 | ||
1218 | if macro_rules { | |
1219 | let ident = ident.normalize_to_macros_2_0(); | |
1220 | self.r.macro_names.insert(ident); | |
1221 | let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export); | |
1222 | let vis = if is_macro_export { | |
1223 | ty::Visibility::Public | |
1224 | } else { | |
1225 | ty::Visibility::Restricted(CRATE_DEF_ID) | |
1226 | }; | |
1227 | let binding = (res, vis, span, expansion).to_name_binding(self.r.arenas); | |
1228 | self.r.set_binding_parent_module(binding, parent_scope.module); | |
1229 | self.r.all_macro_rules.insert(ident.name, res); | |
1230 | if is_macro_export { | |
1231 | let import = self.r.arenas.alloc_import(Import { | |
1232 | kind: ImportKind::MacroExport, | |
1233 | root_id: item.id, | |
1234 | parent_scope: self.parent_scope, | |
1235 | imported_module: Cell::new(None), | |
1236 | has_attributes: false, | |
1237 | use_span_with_attributes: span, | |
1238 | use_span: span, | |
1239 | root_span: span, | |
1240 | span: span, | |
1241 | module_path: Vec::new(), | |
1242 | vis: Cell::new(Some(vis)), | |
1243 | used: Cell::new(true), | |
1244 | }); | |
1245 | let import_binding = self.r.import(binding, import); | |
1246 | self.r.define(self.r.graph_root, ident, MacroNS, import_binding); | |
1247 | } else { | |
1248 | self.r.check_reserved_macro_name(ident, res); | |
1249 | self.insert_unused_macro(ident, def_id, item.id, &rule_spans); | |
1250 | } | |
1251 | self.r.visibilities.insert(def_id, vis); | |
1252 | let scope = self.r.arenas.alloc_macro_rules_scope(MacroRulesScope::Binding( | |
1253 | self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding { | |
1254 | parent_macro_rules_scope: parent_scope.macro_rules, | |
1255 | binding, | |
1256 | ident, | |
1257 | }), | |
1258 | )); | |
1259 | self.r.macro_rules_scopes.insert(def_id, scope); | |
1260 | scope | |
1261 | } else { | |
1262 | let module = parent_scope.module; | |
1263 | let vis = match item.kind { | |
1264 | // Visibilities must not be resolved non-speculatively twice | |
1265 | // and we already resolved this one as a `fn` item visibility. | |
1266 | ItemKind::Fn(..) => { | |
1267 | self.try_resolve_visibility(&item.vis, false).unwrap_or(ty::Visibility::Public) | |
1268 | } | |
1269 | _ => self.resolve_visibility(&item.vis), | |
1270 | }; | |
1271 | if !vis.is_public() { | |
1272 | self.insert_unused_macro(ident, def_id, item.id, &rule_spans); | |
1273 | } | |
1274 | self.r.define(module, ident, MacroNS, (res, vis, span, expansion)); | |
1275 | self.r.visibilities.insert(def_id, vis); | |
1276 | self.parent_scope.macro_rules | |
1277 | } | |
1278 | } | |
1279 | } | |
1280 | ||
1281 | macro_rules! method { | |
1282 | ($visit:ident: $ty:ty, $invoc:path, $walk:ident) => { | |
1283 | fn $visit(&mut self, node: &'b $ty) { | |
1284 | if let $invoc(..) = node.kind { | |
1285 | self.visit_invoc(node.id); | |
1286 | } else { | |
1287 | visit::$walk(self, node); | |
1288 | } | |
1289 | } | |
1290 | }; | |
1291 | } | |
1292 | ||
1293 | impl<'a, 'b, 'tcx> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b, 'tcx> { | |
1294 | method!(visit_expr: ast::Expr, ast::ExprKind::MacCall, walk_expr); | |
1295 | method!(visit_pat: ast::Pat, ast::PatKind::MacCall, walk_pat); | |
1296 | method!(visit_ty: ast::Ty, ast::TyKind::MacCall, walk_ty); | |
1297 | ||
1298 | fn visit_item(&mut self, item: &'b Item) { | |
1299 | let orig_module_scope = self.parent_scope.module; | |
1300 | self.parent_scope.macro_rules = match item.kind { | |
1301 | ItemKind::MacroDef(..) => { | |
1302 | let macro_rules_scope = self.define_macro(item); | |
1303 | visit::walk_item(self, item); | |
1304 | macro_rules_scope | |
1305 | } | |
1306 | ItemKind::MacCall(..) => { | |
1307 | let macro_rules_scope = self.visit_invoc_in_module(item.id); | |
1308 | visit::walk_item(self, item); | |
1309 | macro_rules_scope | |
1310 | } | |
1311 | _ => { | |
1312 | let orig_macro_rules_scope = self.parent_scope.macro_rules; | |
1313 | self.build_reduced_graph_for_item(item); | |
1314 | visit::walk_item(self, item); | |
1315 | match item.kind { | |
1316 | ItemKind::Mod(..) if self.contains_macro_use(&item.attrs) => { | |
1317 | self.parent_scope.macro_rules | |
1318 | } | |
1319 | _ => orig_macro_rules_scope, | |
1320 | } | |
1321 | } | |
1322 | }; | |
1323 | self.parent_scope.module = orig_module_scope; | |
1324 | } | |
1325 | ||
1326 | fn visit_stmt(&mut self, stmt: &'b ast::Stmt) { | |
1327 | if let ast::StmtKind::MacCall(..) = stmt.kind { | |
1328 | self.parent_scope.macro_rules = self.visit_invoc_in_module(stmt.id); | |
1329 | } else { | |
1330 | visit::walk_stmt(self, stmt); | |
1331 | } | |
1332 | } | |
1333 | ||
1334 | fn visit_foreign_item(&mut self, foreign_item: &'b ForeignItem) { | |
1335 | if let ForeignItemKind::MacCall(_) = foreign_item.kind { | |
1336 | self.visit_invoc_in_module(foreign_item.id); | |
1337 | return; | |
1338 | } | |
1339 | ||
1340 | self.build_reduced_graph_for_foreign_item(foreign_item); | |
1341 | visit::walk_foreign_item(self, foreign_item); | |
1342 | } | |
1343 | ||
1344 | fn visit_block(&mut self, block: &'b Block) { | |
1345 | let orig_current_module = self.parent_scope.module; | |
1346 | let orig_current_macro_rules_scope = self.parent_scope.macro_rules; | |
1347 | self.build_reduced_graph_for_block(block); | |
1348 | visit::walk_block(self, block); | |
1349 | self.parent_scope.module = orig_current_module; | |
1350 | self.parent_scope.macro_rules = orig_current_macro_rules_scope; | |
1351 | } | |
1352 | ||
1353 | fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) { | |
1354 | if let AssocItemKind::MacCall(_) = item.kind { | |
1355 | match ctxt { | |
1356 | AssocCtxt::Trait => { | |
1357 | self.visit_invoc_in_module(item.id); | |
1358 | } | |
1359 | AssocCtxt::Impl => { | |
1360 | self.visit_invoc(item.id); | |
1361 | } | |
1362 | } | |
1363 | return; | |
1364 | } | |
1365 | ||
1366 | let vis = self.resolve_visibility(&item.vis); | |
1367 | let local_def_id = self.r.local_def_id(item.id); | |
1368 | let def_id = local_def_id.to_def_id(); | |
1369 | ||
1370 | if !(ctxt == AssocCtxt::Impl | |
1371 | && matches!(item.vis.kind, ast::VisibilityKind::Inherited) | |
1372 | && self.r.trait_impl_items.contains(&self.r.tcx.local_parent(local_def_id))) | |
1373 | { | |
1374 | // Trait impl item visibility is inherited from its trait when not specified | |
1375 | // explicitly. In that case we cannot determine it here in early resolve, | |
1376 | // so we leave a hole in the visibility table to be filled later. | |
1377 | self.r.visibilities.insert(local_def_id, vis); | |
1378 | } | |
1379 | ||
1380 | if ctxt == AssocCtxt::Trait { | |
1381 | let (def_kind, ns) = match item.kind { | |
1382 | AssocItemKind::Const(..) => (DefKind::AssocConst, ValueNS), | |
1383 | AssocItemKind::Fn(box Fn { ref sig, .. }) => { | |
1384 | if sig.decl.has_self() { | |
1385 | self.r.has_self.insert(local_def_id); | |
1386 | } | |
1387 | (DefKind::AssocFn, ValueNS) | |
1388 | } | |
1389 | AssocItemKind::Type(..) => (DefKind::AssocTy, TypeNS), | |
1390 | AssocItemKind::MacCall(_) => bug!(), // handled above | |
1391 | }; | |
1392 | ||
1393 | let parent = self.parent_scope.module; | |
1394 | let expansion = self.parent_scope.expansion; | |
1395 | let res = Res::Def(def_kind, def_id); | |
1396 | self.r.define(parent, item.ident, ns, (res, vis, item.span, expansion)); | |
1397 | } | |
1398 | ||
1399 | visit::walk_assoc_item(self, item, ctxt); | |
1400 | } | |
1401 | ||
1402 | fn visit_attribute(&mut self, attr: &'b ast::Attribute) { | |
1403 | if !attr.is_doc_comment() && attr::is_builtin_attr(attr) { | |
1404 | self.r | |
1405 | .builtin_attrs | |
1406 | .push((attr.get_normal_item().path.segments[0].ident, self.parent_scope)); | |
1407 | } | |
1408 | visit::walk_attribute(self, attr); | |
1409 | } | |
1410 | ||
1411 | fn visit_arm(&mut self, arm: &'b ast::Arm) { | |
1412 | if arm.is_placeholder { | |
1413 | self.visit_invoc(arm.id); | |
1414 | } else { | |
1415 | visit::walk_arm(self, arm); | |
1416 | } | |
1417 | } | |
1418 | ||
1419 | fn visit_expr_field(&mut self, f: &'b ast::ExprField) { | |
1420 | if f.is_placeholder { | |
1421 | self.visit_invoc(f.id); | |
1422 | } else { | |
1423 | visit::walk_expr_field(self, f); | |
1424 | } | |
1425 | } | |
1426 | ||
1427 | fn visit_pat_field(&mut self, fp: &'b ast::PatField) { | |
1428 | if fp.is_placeholder { | |
1429 | self.visit_invoc(fp.id); | |
1430 | } else { | |
1431 | visit::walk_pat_field(self, fp); | |
1432 | } | |
1433 | } | |
1434 | ||
1435 | fn visit_generic_param(&mut self, param: &'b ast::GenericParam) { | |
1436 | if param.is_placeholder { | |
1437 | self.visit_invoc(param.id); | |
1438 | } else { | |
1439 | visit::walk_generic_param(self, param); | |
1440 | } | |
1441 | } | |
1442 | ||
1443 | fn visit_param(&mut self, p: &'b ast::Param) { | |
1444 | if p.is_placeholder { | |
1445 | self.visit_invoc(p.id); | |
1446 | } else { | |
1447 | visit::walk_param(self, p); | |
1448 | } | |
1449 | } | |
1450 | ||
1451 | fn visit_field_def(&mut self, sf: &'b ast::FieldDef) { | |
1452 | if sf.is_placeholder { | |
1453 | self.visit_invoc(sf.id); | |
1454 | } else { | |
1455 | let vis = self.resolve_visibility(&sf.vis); | |
1456 | self.r.visibilities.insert(self.r.local_def_id(sf.id), vis); | |
1457 | visit::walk_field_def(self, sf); | |
1458 | } | |
1459 | } | |
1460 | ||
1461 | // Constructs the reduced graph for one variant. Variants exist in the | |
1462 | // type and value namespaces. | |
1463 | fn visit_variant(&mut self, variant: &'b ast::Variant) { | |
1464 | if variant.is_placeholder { | |
1465 | self.visit_invoc_in_module(variant.id); | |
1466 | return; | |
1467 | } | |
1468 | ||
1469 | let parent = self.parent_scope.module; | |
1470 | let expn_id = self.parent_scope.expansion; | |
1471 | let ident = variant.ident; | |
1472 | ||
1473 | // Define a name in the type namespace. | |
1474 | let def_id = self.r.local_def_id(variant.id); | |
1475 | let res = Res::Def(DefKind::Variant, def_id.to_def_id()); | |
1476 | let vis = self.resolve_visibility(&variant.vis); | |
1477 | self.r.define(parent, ident, TypeNS, (res, vis, variant.span, expn_id)); | |
1478 | self.r.visibilities.insert(def_id, vis); | |
1479 | ||
1480 | // If the variant is marked as non_exhaustive then lower the visibility to within the crate. | |
1481 | let ctor_vis = | |
1482 | if vis.is_public() && attr::contains_name(&variant.attrs, sym::non_exhaustive) { | |
1483 | ty::Visibility::Restricted(CRATE_DEF_ID) | |
1484 | } else { | |
1485 | vis | |
1486 | }; | |
1487 | ||
1488 | // Define a constructor name in the value namespace. | |
1489 | if let Some((ctor_kind, ctor_node_id)) = CtorKind::from_ast(&variant.data) { | |
1490 | let ctor_def_id = self.r.local_def_id(ctor_node_id); | |
1491 | let ctor_res = | |
1492 | Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id.to_def_id()); | |
1493 | self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, variant.span, expn_id)); | |
1494 | self.r.visibilities.insert(ctor_def_id, ctor_vis); | |
1495 | } | |
1496 | ||
1497 | // Record field names for error reporting. | |
1498 | self.insert_field_def_ids(def_id, &variant.data); | |
1499 | self.insert_field_visibilities_local(def_id.to_def_id(), &variant.data); | |
1500 | ||
1501 | visit::walk_variant(self, variant); | |
1502 | } | |
1503 | ||
1504 | fn visit_crate(&mut self, krate: &'b ast::Crate) { | |
1505 | if krate.is_placeholder { | |
1506 | self.visit_invoc_in_module(krate.id); | |
1507 | } else { | |
1508 | visit::walk_crate(self, krate); | |
1509 | self.contains_macro_use(&krate.attrs); | |
1510 | } | |
1511 | } | |
1512 | } |