]> git.lizzy.rs Git - rust.git/commitdiff
Update `krate_attrs` and `get_module`
authorJohn Kåre Alsaker <john.kare.alsaker@gmail.com>
Fri, 7 Feb 2020 15:43:36 +0000 (16:43 +0100)
committerJohn Kåre Alsaker <john.kare.alsaker@gmail.com>
Sat, 14 Mar 2020 21:52:29 +0000 (22:52 +0100)
20 files changed:
src/librustc/hir/map/collector.rs
src/librustc/hir/map/mod.rs
src/librustc_ast_lowering/lib.rs
src/librustc_codegen_ssa/back/write.rs
src/librustc_hir/hir.rs
src/librustc_hir/intravisit.rs
src/librustc_hir/print.rs
src/librustc_incremental/assert_dep_graph.rs
src/librustc_incremental/assert_module_sources.rs
src/librustc_lint/builtin.rs
src/librustc_lint/late.rs
src/librustc_lint/levels.rs
src/librustc_metadata/link_args.rs
src/librustc_metadata/rmeta/encoder.rs
src/librustc_passes/entry.rs
src/librustc_passes/stability.rs
src/librustc_trait_selection/traits/error_reporting/suggestions.rs
src/librustdoc/clean/mod.rs
src/librustdoc/test.rs
src/librustdoc/visit_ast.rs

index 0ac8f403cb7c983a1edaf890786a16d17dac54a4..7e626f79c0c9db75436e1ea45ac2b762f93366c2 100644 (file)
@@ -133,11 +133,7 @@ pub(super) fn root(
         // Allocate `DepNode`s for the root module.
         let (root_mod_sig_dep_index, root_mod_full_dep_index) = {
             let Crate {
-                ref module,
-                // Crate attributes are not copied over to the root `Mod`, so hash
-                // them explicitly here.
-                ref attrs,
-                span,
+                ref item,
                 // These fields are handled separately:
                 exported_macros: _,
                 non_exported_macro_attrs: _,
@@ -155,7 +151,7 @@ pub(super) fn root(
                 dep_graph,
                 &mut hcx,
                 root_mod_def_path_hash,
-                (module, attrs, span),
+                item,
                 &mut hir_body_nodes,
             )
         };
@@ -191,7 +187,7 @@ pub(super) fn root(
             Entry {
                 parent: hir::CRATE_HIR_ID,
                 dep_node: root_mod_sig_dep_index,
-                node: Node::Crate,
+                node: Node::Crate(&krate.item),
             },
         );
 
index 38260eac890b8fcd315151a194a74f5d9dfe24f6..106475e5e1337b308dec5a7f7e5333e1946934e4 100644 (file)
@@ -13,7 +13,7 @@
 use rustc_data_structures::fx::FxHashMap;
 use rustc_data_structures::svh::Svh;
 use rustc_hir::def::{DefKind, Res};
-use rustc_hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
+use rustc_hir::def_id::{DefId, DefIndex, LocalDefId};
 use rustc_hir::intravisit;
 use rustc_hir::itemlikevisit::ItemLikeVisitor;
 use rustc_hir::print::Nested;
@@ -41,7 +41,7 @@ pub struct Entry<'hir> {
 impl<'hir> Entry<'hir> {
     fn parent_node(self) -> Option<HirId> {
         match self.node {
-            Node::Crate | Node::MacroDef(_) => None,
+            Node::Crate(_) | Node::MacroDef(_) => None,
             _ => Some(self.parent),
         }
     }
@@ -389,7 +389,7 @@ pub fn def_kind(&self, hir_id: HirId) -> Option<DefKind> {
             | Node::Lifetime(_)
             | Node::Visibility(_)
             | Node::Block(_)
-            | Node::Crate => return None,
+            | Node::Crate(_) => return None,
             Node::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
             Node::GenericParam(param) => match param.kind {
                 GenericParamKind::Lifetime { .. } => return None,
@@ -403,6 +403,21 @@ fn find_entry(&self, id: HirId) -> Option<Entry<'hir>> {
         self.lookup(id).cloned()
     }
 
+    fn get_entry(&self, id: HirId) -> Entry<'hir> {
+        if id.local_id == ItemLocalId::from_u32_const(0) {
+            let owner = self.tcx.hir_owner(id.owner_def_id());
+            Entry { parent: owner.parent, node: owner.node, dep_node: DepNodeIndex::INVALID }
+        } else {
+            let owner = self.tcx.hir_owner_items(id.owner_def_id());
+            let item = owner.items[id.local_id].as_ref().unwrap();
+            Entry {
+                parent: HirId { owner: id.owner, local_id: item.parent },
+                node: item.node,
+                dep_node: DepNodeIndex::INVALID,
+            }
+        }
+    }
+
     pub fn item(&self, id: HirId) -> &'hir Item<'hir> {
         match self.find(id).unwrap() {
             Node::Item(item) => item,
@@ -528,18 +543,17 @@ pub fn trait_impls(&self, trait_did: DefId) -> &'hir [HirId] {
     /// invoking `krate.attrs` because it registers a tighter
     /// dep-graph access.
     pub fn krate_attrs(&self) -> &'hir [ast::Attribute] {
-        let def_path_hash = self.definitions.def_path_hash(CRATE_DEF_INDEX);
-
-        self.dep_graph.read(def_path_hash.to_dep_node(DepKind::Hir));
-        &self.krate.attrs
+        match self.get_entry(CRATE_HIR_ID).node {
+            Node::Crate(item) => item.attrs,
+            _ => bug!(),
+        }
     }
 
     pub fn get_module(&self, module: DefId) -> (&'hir Mod<'hir>, Span, HirId) {
         let hir_id = self.as_local_hir_id(module).unwrap();
-        self.read(hir_id);
-        match self.find_entry(hir_id).unwrap().node {
+        match self.get_entry(hir_id).node {
             Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
-            Node::Crate => (&self.krate.module, self.krate.span, hir_id),
+            Node::Crate(item) => (&item.module, item.span, hir_id),
             node => panic!("not a module: {:?}", node),
         }
     }
@@ -602,9 +616,9 @@ pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
 
     /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
     pub fn find(&self, hir_id: HirId) -> Option<Node<'hir>> {
-        let result = self
-            .find_entry(hir_id)
-            .and_then(|entry| if let Node::Crate = entry.node { None } else { Some(entry.node) });
+        let result = self.find_entry(hir_id).and_then(|entry| {
+            if let Node::Crate(..) = entry.node { None } else { Some(entry.node) }
+        });
         if result.is_some() {
             self.read(hir_id);
         }
@@ -675,7 +689,7 @@ pub fn is_const_context(&self, hir_id: HirId) -> bool {
     pub fn is_hir_id_module(&self, hir_id: HirId) -> bool {
         match self.lookup(hir_id) {
             Some(Entry { node: Node::Item(Item { kind: ItemKind::Mod(_), .. }), .. })
-            | Some(Entry { node: Node::Crate, .. }) => true,
+            | Some(Entry { node: Node::Crate(..), .. }) => true,
             _ => false,
         }
     }
@@ -752,7 +766,7 @@ pub fn get_return_block(&self, id: HirId) -> Option<HirId> {
     pub fn get_parent_item(&self, hir_id: HirId) -> HirId {
         for (hir_id, node) in self.parent_iter(hir_id) {
             match node {
-                Node::Crate
+                Node::Crate(_)
                 | Node::Item(_)
                 | Node::ForeignItem(_)
                 | Node::TraitItem(_)
@@ -973,7 +987,7 @@ pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] {
             // Unit/tuple structs/variants take the attributes straight from
             // the struct/variant definition.
             Some(Node::Ctor(..)) => return self.attrs(self.get_parent_item(id)),
-            Some(Node::Crate) => Some(&self.krate.attrs[..]),
+            Some(Node::Crate(item)) => Some(&item.attrs[..]),
             _ => None,
         };
         attrs.unwrap_or(&[])
@@ -1013,7 +1027,7 @@ pub fn span(&self, hir_id: HirId) -> Span {
             Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
             Some(Node::Local(local)) => local.span,
             Some(Node::MacroDef(macro_def)) => macro_def.span,
-            Some(Node::Crate) => self.krate.span,
+            Some(Node::Crate(item)) => item.span,
             None => bug!("hir::map::Map::span: id not in map: {:?}", hir_id),
         }
     }
@@ -1255,7 +1269,7 @@ fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String {
         Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str),
         Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str),
         Some(Node::MacroDef(_)) => format!("macro {}{}", path_str(), id_str),
-        Some(Node::Crate) => String::from("root_crate"),
+        Some(Node::Crate(..)) => String::from("root_crate"),
         None => format!("unknown node{}", id_str),
     }
 }
index dd9526ccee41aec02be1cbd974f91020d45d2520..748b9b7fb40e2883b667e06117acd053b885ea44 100644 (file)
@@ -535,9 +535,7 @@ fn visit_ty(&mut self, t: &'tcx Ty) {
         self.resolver.definitions().init_node_id_to_hir_id_mapping(self.node_id_to_hir_id);
 
         hir::Crate {
-            module,
-            attrs,
-            span: c.span,
+            item: hir::CrateItem { module, attrs, span: c.span },
             exported_macros: self.arena.alloc_from_iter(self.exported_macros),
             non_exported_macro_attrs: self.arena.alloc_from_iter(self.non_exported_macro_attrs),
             items: self.items,
index 3afa4758253d919f4c1f0f3a74f4e7383596d759..dbc2ef6f2b05e1b938739e1a1571b055f9645c7d 100644 (file)
@@ -341,9 +341,9 @@ pub fn start_async_codegen<B: ExtraBackendMethods>(
 
     let crate_name = tcx.crate_name(LOCAL_CRATE);
     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
-    let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
+    let no_builtins = attr::contains_name(&tcx.hir().krate().item.attrs, sym::no_builtins);
     let subsystem =
-        attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs, sym::windows_subsystem);
+        attr::first_attr_value_str_by_name(&tcx.hir().krate().item.attrs, sym::windows_subsystem);
     let windows_subsystem = subsystem.map(|subsystem| {
         if subsystem != sym::windows && subsystem != sym::console {
             tcx.sess.fatal(&format!(
index ed06aeb60bb18d42421ca34dcf025c7888806460..65bb4b9a6a1f2bcdc08a697acaf1d46b1e23a23d 100644 (file)
@@ -606,6 +606,14 @@ pub struct ModuleItems {
     pub impl_items: BTreeSet<ImplItemId>,
 }
 
+/// A type representing only the top-level module.
+#[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
+pub struct CrateItem<'hir> {
+    pub module: Mod<'hir>,
+    pub attrs: &'hir [Attribute],
+    pub span: Span,
+}
+
 /// The top-level data structure that stores the entire contents of
 /// the crate currently being compiled.
 ///
@@ -614,9 +622,7 @@ pub struct ModuleItems {
 /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/hir.html
 #[derive(RustcEncodable, RustcDecodable, Debug)]
 pub struct Crate<'hir> {
-    pub module: Mod<'hir>,
-    pub attrs: &'hir [Attribute],
-    pub span: Span,
+    pub item: CrateItem<'hir>,
     pub exported_macros: &'hir [MacroDef<'hir>],
     // Attributes from non-exported macros, kept only for collecting the library feature list.
     pub non_exported_macro_attrs: &'hir [Attribute],
@@ -2683,7 +2689,7 @@ pub enum Node<'hir> {
     GenericParam(&'hir GenericParam<'hir>),
     Visibility(&'hir Visibility<'hir>),
 
-    Crate,
+    Crate(&'hir CrateItem<'hir>),
 }
 
 impl Node<'_> {
index f8bd40d380d754a3c9e51d26d5787c64dbdb1ab2..5f31ddeae95d1a3517b720c7f778f2884f11e580 100644 (file)
@@ -438,8 +438,8 @@ fn visit_defaultness(&mut self, defaultness: &'v Defaultness) {
 
 /// Walks the contents of a crate. See also `Crate::visit_all_items`.
 pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate<'v>) {
-    visitor.visit_mod(&krate.module, krate.span, CRATE_HIR_ID);
-    walk_list!(visitor, visit_attribute, krate.attrs);
+    visitor.visit_mod(&krate.item.module, krate.item.span, CRATE_HIR_ID);
+    walk_list!(visitor, visit_attribute, krate.item.attrs);
     walk_list!(visitor, visit_macro_def, krate.exported_macros);
 }
 
index 7eb5cc417b7e6463b3de7476b7079ae20596e71f..1a2c3a38565c8e17ae59197f19729b337579645f 100644 (file)
@@ -102,7 +102,7 @@ pub fn print_node(&mut self, node: Node<'_>) {
             Node::Ctor(..) => panic!("cannot print isolated Ctor"),
             Node::Local(a) => self.print_local_decl(&a),
             Node::MacroDef(_) => panic!("cannot print MacroDef"),
-            Node::Crate => panic!("cannot print Crate"),
+            Node::Crate(..) => panic!("cannot print Crate"),
         }
     }
 }
@@ -151,7 +151,7 @@ pub fn print_crate<'a>(
     // When printing the AST, we sometimes need to inject `#[no_std]` here.
     // Since you can't compile the HIR, it's not necessary.
 
-    s.print_mod(&krate.module, &krate.attrs);
+    s.print_mod(&krate.item.module, &krate.item.attrs);
     s.print_remaining_comments();
     s.s.eof()
 }
index c2b62f9670c8bd84db80722cbdd619c12214e3e8..5f186f0e1b2bd4ca68488671219e54102c96a1c5 100644 (file)
@@ -68,7 +68,7 @@ pub fn assert_dep_graph(tcx: TyCtxt<'_>) {
         let (if_this_changed, then_this_would_need) = {
             let mut visitor =
                 IfThisChanged { tcx, if_this_changed: vec![], then_this_would_need: vec![] };
-            visitor.process_attrs(hir::CRATE_HIR_ID, &tcx.hir().krate().attrs);
+            visitor.process_attrs(hir::CRATE_HIR_ID, &tcx.hir().krate().item.attrs);
             tcx.hir().krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
             (visitor.if_this_changed, visitor.then_this_would_need)
         };
index 261540abcad5d85d1fe7bb5cf5a56a0a61070164..54d7e0ece503185dfcd241023521c5d556e2c56c 100644 (file)
@@ -44,7 +44,7 @@ pub fn assert_module_sources(tcx: TyCtxt<'_>) {
 
         let ams = AssertModuleSource { tcx, available_cgus };
 
-        for attr in tcx.hir().krate().attrs {
+        for attr in tcx.hir().krate().item.attrs {
             ams.check_attr(attr);
         }
     })
index 50c2c6f95522890db46ab6677588a5379c45ae81..852998c9e7da38a42204baf3bfade3fd269d7d0c 100644 (file)
@@ -399,7 +399,7 @@ fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]
     }
 
     fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate<'_>) {
-        self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
+        self.check_missing_docs_attrs(cx, None, &krate.item.attrs, krate.item.span, "crate");
 
         for macro_def in krate.exported_macros {
             let has_doc = macro_def.attrs.iter().any(|a| has_doc(a));
index 0964dfa28998eaa6673b0c11a6aecf8b542a153f..839057a75a655deef6496354d8da2b3f03966a86 100644 (file)
@@ -419,7 +419,7 @@ fn late_lint_pass_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tc
     let mut cx = LateContextAndPass { context, pass };
 
     // Visit the whole crate.
-    cx.with_lint_attrs(hir::CRATE_HIR_ID, &krate.attrs, |cx| {
+    cx.with_lint_attrs(hir::CRATE_HIR_ID, &krate.item.attrs, |cx| {
         // since the root module isn't visited as an item (because it isn't an
         // item), warn for it here.
         lint_callback!(cx, check_crate, krate);
index 0e85b8d2a39edf482ee0de20823b0cb16e038962..6fddf1535c9c5a4713e5ae44831f86a96805b242 100644 (file)
@@ -29,7 +29,7 @@ fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap {
     let mut builder = LintLevelMapBuilder { levels, tcx, store };
     let krate = tcx.hir().krate();
 
-    let push = builder.levels.push(&krate.attrs, &store);
+    let push = builder.levels.push(&krate.item.attrs, &store);
     builder.levels.register_id(hir::CRATE_HIR_ID);
     for macro_def in krate.exported_macros {
         builder.levels.register_id(macro_def.hir_id);
index 8d018b9bb94ddb653ff61a69c4f4bb33de0c5cc1..13668b2423fddf27452bdda804d8b2be7eb7d6e5 100644 (file)
@@ -8,7 +8,7 @@
     let mut collector = Collector { args: Vec::new() };
     tcx.hir().krate().visit_all_item_likes(&mut collector);
 
-    for attr in tcx.hir().krate().attrs.iter() {
+    for attr in tcx.hir().krate().item.attrs.iter() {
         if attr.has_name(sym::link_args) {
             if let Some(linkarg) = attr.value_str() {
                 collector.add_link_args(&linkarg.as_str());
index ce62f15f85d93683ebfffd6962352d682f52ea81..e69b4fd619599afe7d71dcdeaf035b5064c00ec2 100644 (file)
@@ -331,7 +331,7 @@ fn lazy<T: ?Sized + LazyMeta>(&mut self, value: impl EncodeContentsForLazy<T>) -
     fn encode_info_for_items(&mut self) {
         let krate = self.tcx.hir().krate();
         let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
-        self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis);
+        self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs, &vis);
         krate.visit_all_item_likes(&mut self.as_deep_visitor());
         for macro_def in krate.exported_macros {
             self.visit_macro_def(macro_def);
index 86596e205562ed034919e2a15ac8567caecfe548..c29c552202aa1b681f79d5bc6836007be0e45070 100644 (file)
@@ -59,7 +59,7 @@ fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
     }
 
     // If the user wants no main function at all, then stop here.
-    if attr::contains_name(&tcx.hir().krate().attrs, sym::no_main) {
+    if attr::contains_name(&tcx.hir().krate().item.attrs, sym::no_main) {
         return None;
     }
 
@@ -157,7 +157,7 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(De
 }
 
 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
-    let sp = tcx.hir().krate().span;
+    let sp = tcx.hir().krate().item.span;
     if *tcx.sess.parse_sess.reached_eof.borrow() {
         // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
         // the missing `fn main()` then as it might have been hidden inside an unclosed block.
index d056d9f0562a323e834b617ff62147fc4871f063..84ba245998ce742d084c5acc3e42bd4ac45f0557 100644 (file)
@@ -459,8 +459,8 @@ fn new_index(tcx: TyCtxt<'tcx>) -> Index<'tcx> {
 
         annotator.annotate(
             hir::CRATE_HIR_ID,
-            &krate.attrs,
-            krate.span,
+            &krate.item.attrs,
+            krate.item.span,
             AnnotationKind::Required,
             |v| intravisit::walk_crate(v, krate),
         );
@@ -585,7 +585,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
     if tcx.stability().staged_api[&LOCAL_CRATE] {
         let krate = tcx.hir().krate();
         let mut missing = MissingStabilityAnnotations { tcx, access_levels };
-        missing.check_missing_stability(hir::CRATE_HIR_ID, krate.span, "crate");
+        missing.check_missing_stability(hir::CRATE_HIR_ID, krate.item.span, "crate");
         intravisit::walk_crate(&mut missing, krate);
         krate.visit_all_item_likes(&mut missing.as_deep_visitor());
     }
index 351e557d40b302d1f804c7305393429e3278c111..0e0cb8ccb0c61020c27a269d2d3c1e5aaa7c33b9 100644 (file)
@@ -282,7 +282,7 @@ fn suggest_restricting_param_bound(
                     }
                 }
 
-                hir::Node::Crate => return,
+                hir::Node::Crate(..) => return,
 
                 _ => {}
             }
index 661666b6637f124d8698637845616dad8babc3cd..e2fca8f39a3983d922646ffc8eb50a878729a1c6 100644 (file)
@@ -141,6 +141,7 @@ fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
             cx.tcx
                 .hir()
                 .krate()
+                .item
                 .module
                 .item_ids
                 .iter()
@@ -194,6 +195,7 @@ fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
             cx.tcx
                 .hir()
                 .krate()
+                .item
                 .module
                 .item_ids
                 .iter()
index b63dbbf80d86421939f50ec0e37f72ea093aaefa..85ccb55333b321d9ad03303ce53c21c15a88c004 100644 (file)
@@ -112,7 +112,7 @@ pub fn run(options: Options) -> i32 {
                         compiler.session().opts.unstable_features.is_nightly_build(),
                     ),
                 };
-                hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
+                hir_collector.visit_testable("".to_string(), &krate.item.attrs, |this| {
                     intravisit::walk_crate(this, krate);
                 });
             });
@@ -146,6 +146,7 @@ fn scrape_test_config(krate: &::rustc_hir::Crate) -> TestOptions {
         TestOptions { no_crate_inject: false, display_warnings: false, attrs: Vec::new() };
 
     let test_attrs: Vec<_> = krate
+        .item
         .attrs
         .iter()
         .filter(|a| a.check_name(sym::doc))
index 8f2f88d08bf7a94727d76d9619b8c112ab47ed73..6e34f731e3bd0c8e1c00f75d95342c262dbaa859 100644 (file)
@@ -64,11 +64,11 @@ fn store_path(&mut self, did: DefId) {
 
     pub fn visit(mut self, krate: &'tcx hir::Crate) -> Module<'tcx> {
         let mut module = self.visit_mod_contents(
-            krate.span,
-            krate.attrs,
+            krate.item.span,
+            krate.item.attrs,
             &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
             hir::CRATE_HIR_ID,
-            &krate.module,
+            &krate.item.module,
             None,
         );
         // Attach the crate's exported macros to the top-level module: