about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorTimothée Delabrouille <timothee.delabrouille@musicworldmedia.com>2021-04-23 22:15:13 +0200
committerTimothée Delabrouille <timothee.delabrouille@musicworldmedia.com>2021-04-27 10:17:59 +0200
commitb4f1dfd2c57985a4cbb74fb34073ba04fd6f5f63 (patch)
tree574a6b0f39e26251ab3354f22d86575146726755 /src
parent5da10c01214a3d3ebec65b8ba6effada92a0673f (diff)
downloadrust-b4f1dfd2c57985a4cbb74fb34073ba04fd6f5f63.tar.gz
rust-b4f1dfd2c57985a4cbb74fb34073ba04fd6f5f63.zip
Removed usage of Attributes in FnDecl and ExternalCrate. Relocate part of the fields in Attributes, as functions in AttributesExt.
refacto use from_def_id_and_attrs_and_parts instead of an old trick

most of josha suggestions + check if def_id is not fake before using it in a query

Removed usage of Attributes in FnDecl and ExternalCrate. Relocate part of the Attributes fields as functions in AttributesExt.
Diffstat (limited to 'src')
-rw-r--r--src/librustdoc/clean/inline.rs3
-rw-r--r--src/librustdoc/clean/mod.rs7
-rw-r--r--src/librustdoc/clean/types.rs50
-rw-r--r--src/librustdoc/core.rs2
-rw-r--r--src/librustdoc/doctest.rs11
-rw-r--r--src/librustdoc/formats/cache.rs8
-rw-r--r--src/librustdoc/html/render/cache.rs9
-rw-r--r--src/librustdoc/html/render/context.rs2
-rw-r--r--src/librustdoc/json/conversions.rs2
-rw-r--r--src/librustdoc/passes/collect_intra_doc_links.rs19
-rw-r--r--src/librustdoc/passes/strip_hidden.rs4
11 files changed, 64 insertions, 53 deletions
diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs
index e88a739d042..0f74639cbc6 100644
--- a/src/librustdoc/clean/inline.rs
+++ b/src/librustdoc/clean/inline.rs
@@ -124,8 +124,7 @@ crate fn try_inline(
     let attrs = box merge_attrs(cx, Some(parent_module), target_attrs, attrs_clone);
 
     cx.inlined.insert(did);
-    let what_rustc_thinks = clean::Item::from_def_id_and_parts(did, Some(name), kind, cx);
-    ret.push(clean::Item { attrs, ..what_rustc_thinks });
+    ret.push(clean::Item::from_def_id_and_attrs_and_parts(did, Some(name), kind, attrs, cx));
     Some(ret)
 }
 
diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs
index c0a8c88bdeb..d1a6f8d0c24 100644
--- a/src/librustdoc/clean/mod.rs
+++ b/src/librustdoc/clean/mod.rs
@@ -84,9 +84,8 @@ impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
 }
 
 impl Clean<ExternalCrate> for CrateNum {
-    fn clean(&self, cx: &mut DocContext<'_>) -> ExternalCrate {
-        let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
-        ExternalCrate { crate_num: *self, attrs: cx.tcx.get_attrs(root).clean(cx) }
+    fn clean(&self, _cx: &mut DocContext<'_>) -> ExternalCrate {
+        ExternalCrate { crate_num: *self }
     }
 }
 
@@ -850,7 +849,6 @@ where
             inputs: (self.0.inputs, self.1).clean(cx),
             output: self.0.output.clean(cx),
             c_variadic: self.0.c_variadic,
-            attrs: Attributes::default(),
         }
     }
 }
@@ -862,7 +860,6 @@ impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
 
         FnDecl {
             output: Return(sig.skip_binder().output().clean(cx)),
-            attrs: Attributes::default(),
             c_variadic: sig.skip_binder().c_variadic,
             inputs: Arguments {
                 values: sig
diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs
index 607a634c1bc..788b421c7ca 100644
--- a/src/librustdoc/clean/types.rs
+++ b/src/librustdoc/clean/types.rs
@@ -73,7 +73,6 @@ crate struct TraitWithExtraInfo {
 #[derive(Clone, Debug)]
 crate struct ExternalCrate {
     crate crate_num: CrateNum,
-    crate attrs: Attributes,
 }
 
 impl ExternalCrate {
@@ -663,12 +662,35 @@ impl<'a> Iterator for ListAttributesIter<'a> {
 crate trait AttributesExt {
     /// Finds an attribute as List and returns the list of attributes nested inside.
     fn lists(&self, name: Symbol) -> ListAttributesIter<'_>;
+
+    fn span(&self) -> Option<rustc_span::Span>;
+
+    fn inner_docs(&self) -> bool;
+
+    fn other_attrs(&self) -> Vec<ast::Attribute>;
 }
 
 impl AttributesExt for [ast::Attribute] {
     fn lists(&self, name: Symbol) -> ListAttributesIter<'_> {
         ListAttributesIter { attrs: self.iter(), current_list: Vec::new().into_iter(), name }
     }
+
+    /// Return the span of the first doc-comment, if it exists.
+    fn span(&self) -> Option<rustc_span::Span> {
+        self.iter().find(|attr| attr.doc_str().is_some()).map(|attr| attr.span)
+    }
+
+    /// Returns whether the first doc-comment is an inner attribute.
+    ///
+    //// If there are no doc-comments, return true.
+    /// FIXME(#78591): Support both inner and outer attributes on the same item.
+    fn inner_docs(&self) -> bool {
+        self.iter().find(|a| a.doc_str().is_some()).map_or(true, |a| a.style == AttrStyle::Inner)
+    }
+
+    fn other_attrs(&self) -> Vec<ast::Attribute> {
+        self.iter().filter(|attr| attr.doc_str().is_none()).cloned().collect()
+    }
 }
 
 crate trait NestedAttributesExt {
@@ -778,8 +800,6 @@ crate struct Attributes {
     crate doc_strings: Vec<DocFragment>,
     crate other_attrs: Vec<ast::Attribute>,
     crate cfg: Option<Arc<Cfg>>,
-    crate span: Option<rustc_span::Span>,
-    crate inner_docs: bool,
 }
 
 #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
@@ -811,6 +831,10 @@ pub struct RenderedLink {
 }
 
 impl Attributes {
+    crate fn lists(&self, name: Symbol) -> ListAttributesIter<'_> {
+        self.other_attrs.lists(name)
+    }
+
     /// Extracts the content from an attribute `#[doc(cfg(content))]`.
     crate fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> {
         use rustc_ast::NestedMetaItem::MetaItem;
@@ -895,7 +919,6 @@ impl Attributes {
         additional_attrs: Option<(&[ast::Attribute], DefId)>,
     ) -> Attributes {
         let mut doc_strings: Vec<DocFragment> = vec![];
-        let mut sp = None;
         let mut cfg = Cfg::True;
         let mut doc_line = 0;
 
@@ -940,9 +963,6 @@ impl Attributes {
 
                 doc_strings.push(frag);
 
-                if sp.is_none() {
-                    sp = Some(attr.span);
-                }
                 None
             } else {
                 if attr.has_name(sym::doc) {
@@ -1001,17 +1021,10 @@ impl Attributes {
             }
         }
 
-        let inner_docs = attrs
-            .iter()
-            .find(|a| a.doc_str().is_some())
-            .map_or(true, |a| a.style == AttrStyle::Inner);
-
         Attributes {
             doc_strings,
             other_attrs,
             cfg: if cfg == Cfg::True { None } else { Some(Arc::new(cfg)) },
-            span: sp,
-            inner_docs,
         }
     }
 
@@ -1079,7 +1092,6 @@ impl PartialEq for Attributes {
     fn eq(&self, rhs: &Self) -> bool {
         self.doc_strings == rhs.doc_strings
             && self.cfg == rhs.cfg
-            && self.span == rhs.span
             && self
                 .other_attrs
                 .iter()
@@ -1094,19 +1106,12 @@ impl Hash for Attributes {
     fn hash<H: Hasher>(&self, hasher: &mut H) {
         self.doc_strings.hash(hasher);
         self.cfg.hash(hasher);
-        self.span.hash(hasher);
         for attr in &self.other_attrs {
             attr.id.hash(hasher);
         }
     }
 }
 
-impl AttributesExt for Attributes {
-    fn lists(&self, name: Symbol) -> ListAttributesIter<'_> {
-        self.other_attrs.lists(name)
-    }
-}
-
 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
 crate enum GenericBound {
     TraitBound(PolyTrait, hir::TraitBoundModifier),
@@ -1269,7 +1274,6 @@ crate struct FnDecl {
     crate inputs: Arguments,
     crate output: FnRetTy,
     crate c_variadic: bool,
-    crate attrs: Attributes,
 }
 
 impl FnDecl {
diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs
index be7bff1a29c..212aac0e5b4 100644
--- a/src/librustdoc/core.rs
+++ b/src/librustdoc/core.rs
@@ -32,7 +32,7 @@ use std::rc::Rc;
 
 use crate::clean;
 use crate::clean::inline::build_external_trait;
-use crate::clean::{AttributesExt, TraitWithExtraInfo, MAX_DEF_IDX};
+use crate::clean::{TraitWithExtraInfo, MAX_DEF_IDX};
 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
 use crate::formats::cache::Cache;
 use crate::passes::{self, Condition::*, ConditionalPass};
diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs
index 6f6ed0eb684..b51655ea203 100644
--- a/src/librustdoc/doctest.rs
+++ b/src/librustdoc/doctest.rs
@@ -26,7 +26,7 @@ use std::str;
 use std::sync::atomic::{AtomicUsize, Ordering};
 use std::sync::{Arc, Mutex};
 
-use crate::clean::Attributes;
+use crate::clean::{types::AttributesExt, Attributes};
 use crate::config::Options;
 use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
 use crate::lint::init_lints;
@@ -1092,8 +1092,9 @@ impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
         sp: Span,
         nested: F,
     ) {
-        let attrs = self.tcx.hir().attrs(hir_id);
-        let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs, None);
+        let ast_attrs = self.tcx.hir().attrs(hir_id);
+
+        let mut attrs = Attributes::from_ast(self.sess.diagnostic(), ast_attrs, None);
         if let Some(ref cfg) = attrs.cfg {
             if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
                 return;
@@ -1110,8 +1111,8 @@ impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> {
         // anything else, this will combine them for us.
         if let Some(doc) = attrs.collapsed_doc_value() {
             // Use the outermost invocation, so that doctest names come from where the docs were written.
-            let span = attrs
-                .span
+            let span = ast_attrs
+                .span()
                 .map(|span| span.ctxt().outer_expn().expansion_cause().unwrap_or(span))
                 .unwrap_or(DUMMY_SP);
             self.collector.set_position(span);
diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs
index 9a61f963a3e..8f8bca64e14 100644
--- a/src/librustdoc/formats/cache.rs
+++ b/src/librustdoc/formats/cache.rs
@@ -164,10 +164,12 @@ impl Cache {
             };
             let name = e.name(tcx);
             let extern_url = extern_html_root_urls.get(&*name.as_str()).map(|u| &**u);
-            self.extern_locations
-                .insert(n, (name, src_root, extern_location(e, extern_url, &dst, tcx)));
-
             let did = DefId { krate: n, index: CRATE_DEF_INDEX };
+            self.extern_locations.insert(
+                n,
+                (name, src_root, extern_location(e, extern_url, tcx.get_attrs(did), &dst, tcx)),
+            );
+
             self.external_paths.insert(did, (vec![name.to_string()], ItemType::Module));
         }
 
diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs
index f93a0d4fc2d..d1aa6fba463 100644
--- a/src/librustdoc/html/render/cache.rs
+++ b/src/librustdoc/html/render/cache.rs
@@ -1,15 +1,17 @@
 use std::collections::BTreeMap;
 use std::path::Path;
 
+use rustc_ast::ast;
 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
 use rustc_middle::ty::TyCtxt;
 use rustc_span::symbol::{sym, Symbol};
 use serde::ser::{Serialize, SerializeStruct, Serializer};
 
+use crate::clean;
 use crate::clean::types::{
-    FnDecl, FnRetTy, GenericBound, Generics, GetDefId, Type, WherePredicate,
+    AttributesExt, FnDecl, FnRetTy, GenericBound, Generics, GetDefId, Type, TypeKind,
+    WherePredicate,
 };
-use crate::clean::{self, AttributesExt};
 use crate::formats::cache::Cache;
 use crate::formats::item_type::ItemType;
 use crate::html::markdown::short_markdown_summary;
@@ -30,6 +32,7 @@ crate enum ExternalLocation {
 crate fn extern_location(
     e: &clean::ExternalCrate,
     extern_url: Option<&str>,
+    ast_attrs: &[ast::Attribute],
     dst: &Path,
     tcx: TyCtxt<'_>,
 ) -> ExternalLocation {
@@ -50,7 +53,7 @@ crate fn extern_location(
 
     // Failing that, see if there's an attribute specifying where to find this
     // external crate
-    e.attrs
+    ast_attrs
         .lists(sym::doc)
         .filter(|a| a.has_name(sym::html_root_url))
         .filter_map(|a| a.value_str())
diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs
index 6d45ed69c12..4c8ba0e7b49 100644
--- a/src/librustdoc/html/render/context.rs
+++ b/src/librustdoc/html/render/context.rs
@@ -18,7 +18,7 @@ use super::print_item::{full_path, item_path, print_item};
 use super::write_shared::write_shared;
 use super::{print_sidebar, settings, AllTypes, NameDoc, StylePath, BASIC_KEYWORDS};
 
-use crate::clean::{self, AttributesExt};
+use crate::clean;
 use crate::config::RenderOptions;
 use crate::docfs::{DocFS, PathError};
 use crate::error::Error;
diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs
index 42cd765c294..3d5dc7dbec0 100644
--- a/src/librustdoc/json/conversions.rs
+++ b/src/librustdoc/json/conversions.rs
@@ -421,7 +421,7 @@ impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
 
 impl FromWithTcx<clean::FnDecl> for FnDecl {
     fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self {
-        let clean::FnDecl { inputs, output, c_variadic, attrs: _ } = decl;
+        let clean::FnDecl { inputs, output, c_variadic } = decl;
         FnDecl {
             inputs: inputs
                 .values
diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs
index dad6593248d..7f479b62c90 100644
--- a/src/librustdoc/passes/collect_intra_doc_links.rs
+++ b/src/librustdoc/passes/collect_intra_doc_links.rs
@@ -2,6 +2,7 @@
 //!
 //! [RFC 1946]: https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md
 
+use clean::AttributesExt;
 use rustc_ast as ast;
 use rustc_data_structures::{fx::FxHashMap, stable_set::FxHashSet};
 use rustc_errors::{Applicability, DiagnosticBuilder};
@@ -853,7 +854,12 @@ impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
             }
         });
 
-        if item.is_mod() && item.attrs.inner_docs {
+        let inner_docs = match self_id {
+            Some(did) => self.cx.tcx.get_attrs(did).inner_docs(),
+            None => false,
+        };
+
+        if item.is_mod() && inner_docs {
             self.mod_ids.push(item.def_id);
         }
 
@@ -880,7 +886,7 @@ impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
         }
 
         Some(if item.is_mod() {
-            if !item.attrs.inner_docs {
+            if !inner_docs {
                 self.mod_ids.push(item.def_id);
             }
 
@@ -1050,6 +1056,8 @@ impl LinkCollector<'_, '_> {
             };
         let mut path_str = &*path_str;
 
+        let inner_docs = self.cx.tcx.get_attrs(item.def_id).inner_docs();
+
         // In order to correctly resolve intra-doc links we need to
         // pick a base AST node to work from.  If the documentation for
         // this module came from an inner comment (//!) then we anchor
@@ -1061,11 +1069,8 @@ impl LinkCollector<'_, '_> {
         // we've already pushed this node onto the resolution stack but
         // for outer comments we explicitly try and resolve against the
         // parent_node first.
-        let base_node = if item.is_mod() && item.attrs.inner_docs {
-            self.mod_ids.last().copied()
-        } else {
-            parent_node
-        };
+        let base_node =
+            if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
 
         let mut module_id = if let Some(id) = base_node {
             id
diff --git a/src/librustdoc/passes/strip_hidden.rs b/src/librustdoc/passes/strip_hidden.rs
index c742d32cb62..54c4ed22f1c 100644
--- a/src/librustdoc/passes/strip_hidden.rs
+++ b/src/librustdoc/passes/strip_hidden.rs
@@ -2,8 +2,8 @@ use rustc_hir::def_id::DefIdSet;
 use rustc_span::symbol::sym;
 use std::mem;
 
-use crate::clean::Item;
-use crate::clean::{self, AttributesExt, NestedAttributesExt};
+use crate::clean;
+use crate::clean::{Item, NestedAttributesExt};
 use crate::core::DocContext;
 use crate::fold::{DocFolder, StripItem};
 use crate::passes::{ImplStripper, Pass};