]> git.lizzy.rs Git - rust.git/blobdiff - crates/hir_def/src/data.rs
parameters.split_last()
[rust.git] / crates / hir_def / src / data.rs
index d2bb381be02b9d3578b8a859079da357a0603460..3a39a65846b54267e596c2a76d0dd44e790b0396 100644 (file)
@@ -1,31 +1,33 @@
 //! Contains basic data about various HIR declarations.
 
-use std::sync::Arc;
+use std::{mem, sync::Arc};
 
-use hir_expand::{name::Name, InFile};
+use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId};
 use syntax::ast;
 
 use crate::{
     attr::Attrs,
-    body::Expander,
+    body::{Expander, Mark},
     db::DefDatabase,
     intern::Interned,
-    item_tree::{AssocItem, FnFlags, ItemTreeId, ModItem, Param},
+    item_tree::{self, AssocItem, FnFlags, ItemTreeId, ModItem, Param, TreeId},
+    nameres::{attr_resolution::ResolvedAttr, DefMap},
     type_ref::{TraitRef, TypeBound, TypeRef},
     visibility::RawVisibility,
-    AssocContainerId, AssocItemId, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
-    Intern, Lookup, ModuleId, StaticId, TraitId, TypeAliasId, TypeAliasLoc,
+    AssocItemId, AstIdWithPath, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
+    Intern, ItemContainerId, Lookup, ModuleId, StaticId, TraitId, TypeAliasId, TypeAliasLoc,
 };
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct FunctionData {
     pub name: Name,
-    pub params: Vec<Interned<TypeRef>>,
+    pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
     pub ret_type: Interned<TypeRef>,
     pub async_ret_type: Option<Interned<TypeRef>>,
     pub attrs: Attrs,
     pub visibility: RawVisibility,
     pub abi: Option<Interned<str>>,
+    pub legacy_const_generics_indices: Vec<u32>,
     flags: FnFlags,
 }
 
@@ -54,12 +56,24 @@ pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<Funct
             flags.bits |= FnFlags::IS_VARARGS;
         }
 
+        if matches!(loc.container, ItemContainerId::ExternBlockId(_)) {
+            flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
+        }
+
+        let legacy_const_generics_indices = item_tree
+            .attrs(db, krate, ModItem::from(loc.id.value).into())
+            .by_key("rustc_legacy_const_generics")
+            .tt_values()
+            .next()
+            .map(|arg| parse_rustc_legacy_const_generics(arg))
+            .unwrap_or_default();
+
         Arc::new(FunctionData {
             name: func.name.clone(),
             params: enabled_params
                 .clone()
                 .filter_map(|id| match &item_tree[id] {
-                    Param::Normal(ty) => Some(ty.clone()),
+                    Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
                     Param::Varargs => None,
                 })
                 .collect(),
@@ -68,6 +82,7 @@ pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<Funct
             attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
             visibility: item_tree[func.visibility].clone(),
             abi: func.abi.clone(),
+            legacy_const_generics_indices,
             flags,
         })
     }
@@ -107,6 +122,28 @@ pub fn is_varargs(&self) -> bool {
     }
 }
 
+fn parse_rustc_legacy_const_generics(tt: &tt::Subtree) -> Vec<u32> {
+    let mut indices = Vec::new();
+    for args in tt.token_trees.chunks(2) {
+        match &args[0] {
+            tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
+                Ok(index) => indices.push(index),
+                Err(_) => break,
+            },
+            _ => break,
+        }
+
+        if let Some(comma) = args.get(1) {
+            match comma {
+                tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
+                _ => break,
+            }
+        }
+    }
+
+    indices
+}
+
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct TypeAliasData {
     pub name: Name,
@@ -130,7 +167,7 @@ pub(crate) fn type_alias_data_query(
             name: typ.name.clone(),
             type_ref: typ.type_ref.clone(),
             visibility: item_tree[typ.visibility].clone(),
-            is_extern: typ.is_extern,
+            is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
             bounds: typ.bounds.to_vec(),
         })
     }
@@ -143,6 +180,12 @@ pub struct TraitData {
     pub is_auto: bool,
     pub is_unsafe: bool,
     pub visibility: RawVisibility,
+    /// Whether the trait has `#[rust_skip_array_during_method_dispatch]`. `hir_ty` will ignore
+    /// method calls to this trait's methods when the receiver is an array and the crate edition is
+    /// 2015 or 2018.
+    pub skip_array_during_method_dispatch: bool,
+    // box it as the vec is usually empty anyways
+    pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
 }
 
 impl TraitData {
@@ -150,25 +193,37 @@ pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitDa
         let tr_loc = tr.lookup(db);
         let item_tree = tr_loc.id.item_tree(db);
         let tr_def = &item_tree[tr_loc.id.value];
+        let _cx = stdx::panic_context::enter(format!(
+            "trait_data_query({:?} -> {:?} -> {:?})",
+            tr, tr_loc, tr_def
+        ));
         let name = tr_def.name.clone();
         let is_auto = tr_def.is_auto;
         let is_unsafe = tr_def.is_unsafe;
         let module_id = tr_loc.container;
-        let container = AssocContainerId::TraitId(tr);
         let visibility = item_tree[tr_def.visibility].clone();
-        let mut expander = Expander::new(db, tr_loc.id.file_id(), module_id);
+        let skip_array_during_method_dispatch = item_tree
+            .attrs(db, tr_loc.container.krate(), ModItem::from(tr_loc.id.value).into())
+            .by_key("rustc_skip_array_during_method_dispatch")
+            .exists();
 
-        let items = collect_items(
+        let mut collector = AssocItemCollector::new(
             db,
             module_id,
-            &mut expander,
-            tr_def.items.iter().copied(),
             tr_loc.id.file_id(),
-            container,
-            100,
+            ItemContainerId::TraitId(tr),
         );
-
-        Arc::new(TraitData { name, items, is_auto, is_unsafe, visibility })
+        collector.collect(tr_loc.id.tree_id(), &tr_def.items);
+
+        Arc::new(TraitData {
+            name,
+            attribute_calls: collector.take_attr_calls(),
+            items: collector.items,
+            is_auto,
+            is_unsafe,
+            visibility,
+            skip_array_during_method_dispatch,
+        })
     }
 
     pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
@@ -184,6 +239,17 @@ pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
             _ => None,
         })
     }
+
+    pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
+        self.items.iter().find_map(|(item_name, item)| match item {
+            AssocItemId::FunctionId(t) if item_name == name => Some(*t),
+            _ => None,
+        })
+    }
+
+    pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
+        self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
+    }
 }
 
 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -192,6 +258,8 @@ pub struct ImplData {
     pub self_ty: Interned<TypeRef>,
     pub items: Vec<AssocItemId>,
     pub is_negative: bool,
+    // box it as the vec is usually empty anyways
+    pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
 }
 
 impl ImplData {
@@ -205,27 +273,29 @@ pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData>
         let self_ty = impl_def.self_ty.clone();
         let is_negative = impl_def.is_negative;
         let module_id = impl_loc.container;
-        let container = AssocContainerId::ImplId(id);
-        let mut expander = Expander::new(db, impl_loc.id.file_id(), module_id);
 
-        let items = collect_items(
+        let mut collector = AssocItemCollector::new(
             db,
             module_id,
-            &mut expander,
-            impl_def.items.iter().copied(),
             impl_loc.id.file_id(),
-            container,
-            100,
+            ItemContainerId::ImplId(id),
         );
-        let items = items.into_iter().map(|(_, item)| item).collect();
+        collector.collect(impl_loc.id.tree_id(), &impl_def.items);
+
+        let attribute_calls = collector.take_attr_calls();
+        let items = collector.items.into_iter().map(|(_, item)| item).collect();
 
-        Arc::new(ImplData { target_trait, self_ty, items, is_negative })
+        Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls })
+    }
+
+    pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
+        self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
     }
 }
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct ConstData {
-    /// const _: () = ();
+    /// `None` for `const _: () = ();`
     pub name: Option<Name>,
     pub type_ref: Interned<TypeRef>,
     pub visibility: RawVisibility,
@@ -247,7 +317,7 @@ pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<Cons
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct StaticData {
-    pub name: Option<Name>,
+    pub name: Name,
     pub type_ref: Interned<TypeRef>,
     pub visibility: RawVisibility,
     pub mutable: bool,
@@ -256,93 +326,142 @@ pub struct StaticData {
 
 impl StaticData {
     pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
-        let node = konst.lookup(db);
-        let item_tree = node.id.item_tree(db);
-        let statik = &item_tree[node.id.value];
+        let loc = konst.lookup(db);
+        let item_tree = loc.id.item_tree(db);
+        let statik = &item_tree[loc.id.value];
 
         Arc::new(StaticData {
-            name: Some(statik.name.clone()),
+            name: statik.name.clone(),
             type_ref: statik.type_ref.clone(),
             visibility: item_tree[statik.visibility].clone(),
             mutable: statik.mutable,
-            is_extern: statik.is_extern,
+            is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
         })
     }
 }
 
-fn collect_items(
-    db: &dyn DefDatabase,
-    module: ModuleId,
-    expander: &mut Expander,
-    assoc_items: impl Iterator<Item = AssocItem>,
-    file_id: crate::HirFileId,
-    container: AssocContainerId,
-    limit: usize,
-) -> Vec<(Name, AssocItemId)> {
-    if limit == 0 {
-        return Vec::new();
-    }
+struct AssocItemCollector<'a> {
+    db: &'a dyn DefDatabase,
+    module_id: ModuleId,
+    def_map: Arc<DefMap>,
+    container: ItemContainerId,
+    expander: Expander,
 
-    let item_tree = db.file_item_tree(file_id);
-    let crate_graph = db.crate_graph();
-    let cfg_options = &crate_graph[module.krate].cfg_options;
+    items: Vec<(Name, AssocItemId)>,
+    attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
+}
 
-    let mut items = Vec::new();
-    for item in assoc_items {
-        let attrs = item_tree.attrs(db, module.krate, ModItem::from(item).into());
-        if !attrs.is_cfg_enabled(cfg_options) {
-            continue;
+impl<'a> AssocItemCollector<'a> {
+    fn new(
+        db: &'a dyn DefDatabase,
+        module_id: ModuleId,
+        file_id: HirFileId,
+        container: ItemContainerId,
+    ) -> Self {
+        Self {
+            db,
+            module_id,
+            def_map: module_id.def_map(db),
+            container,
+            expander: Expander::new(db, file_id, module_id),
+
+            items: Vec::new(),
+            attr_calls: Vec::new(),
         }
+    }
 
-        match item {
-            AssocItem::Function(id) => {
-                let item = &item_tree[id];
-                let def = FunctionLoc { container, id: ItemTreeId::new(file_id, id) }.intern(db);
-                items.push((item.name.clone(), def.into()));
-            }
-            AssocItem::Const(id) => {
-                let item = &item_tree[id];
-                let name = match item.name.clone() {
-                    Some(name) => name,
-                    None => continue,
-                };
-                let def = ConstLoc { container, id: ItemTreeId::new(file_id, id) }.intern(db);
-                items.push((name, def.into()));
+    fn take_attr_calls(&mut self) -> Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>> {
+        let attribute_calls = mem::take(&mut self.attr_calls);
+        if attribute_calls.is_empty() {
+            None
+        } else {
+            Some(Box::new(attribute_calls))
+        }
+    }
+
+    fn collect(&mut self, tree_id: TreeId, assoc_items: &[AssocItem]) {
+        let item_tree = tree_id.item_tree(self.db);
+
+        'items: for &item in assoc_items {
+            let attrs = item_tree.attrs(self.db, self.module_id.krate, ModItem::from(item).into());
+            if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
+                continue;
             }
-            AssocItem::TypeAlias(id) => {
-                let item = &item_tree[id];
-                let def = TypeAliasLoc { container, id: ItemTreeId::new(file_id, id) }.intern(db);
-                items.push((item.name.clone(), def.into()));
+
+            for attr in &*attrs {
+                let ast_id =
+                    AstId::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast());
+                let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
+
+                if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(
+                    self.db,
+                    self.module_id.local_id,
+                    ast_id_with_path,
+                    attr,
+                ) {
+                    self.attr_calls.push((ast_id, call_id));
+                    let res = self.expander.enter_expand_id(self.db, call_id);
+                    self.collect_macro_items(res);
+                    continue 'items;
+                }
             }
-            AssocItem::MacroCall(call) => {
-                let call = &item_tree[call];
-                let ast_id_map = db.ast_id_map(file_id);
-                let root = db.parse_or_expand(file_id).unwrap();
-                let call = ast_id_map.get(call.ast_id).to_node(&root);
-                let res = expander.enter_expand(db, call);
-
-                if let Ok(res) = res {
-                    if let Some((mark, mac)) = res.value {
-                        let src: InFile<ast::MacroItems> = expander.to_source(mac);
-                        let item_tree = db.file_item_tree(src.file_id);
-                        let iter =
-                            item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item);
-                        items.extend(collect_items(
-                            db,
-                            module,
-                            expander,
-                            iter,
-                            src.file_id,
-                            container,
-                            limit - 1,
-                        ));
-
-                        expander.exit(db, mark);
+
+            match item {
+                AssocItem::Function(id) => {
+                    let item = &item_tree[id];
+                    let def =
+                        FunctionLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
+                            .intern(self.db);
+                    self.items.push((item.name.clone(), def.into()));
+                }
+                AssocItem::Const(id) => {
+                    let item = &item_tree[id];
+                    let name = match item.name.clone() {
+                        Some(name) => name,
+                        None => continue,
+                    };
+                    let def =
+                        ConstLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
+                            .intern(self.db);
+                    self.items.push((name, def.into()));
+                }
+                AssocItem::TypeAlias(id) => {
+                    let item = &item_tree[id];
+                    let def = TypeAliasLoc {
+                        container: self.container,
+                        id: ItemTreeId::new(tree_id, id),
+                    }
+                    .intern(self.db);
+                    self.items.push((item.name.clone(), def.into()));
+                }
+                AssocItem::MacroCall(call) => {
+                    let call = &item_tree[call];
+                    let ast_id_map = self.db.ast_id_map(self.expander.current_file_id());
+                    let root = self.db.parse_or_expand(self.expander.current_file_id()).unwrap();
+                    let call = ast_id_map.get(call.ast_id).to_node(&root);
+                    let _cx =
+                        stdx::panic_context::enter(format!("collect_items MacroCall: {}", call));
+                    let res = self.expander.enter_expand(self.db, call);
+
+                    if let Ok(res) = res {
+                        self.collect_macro_items(res);
                     }
                 }
             }
         }
     }
 
-    items
+    fn collect_macro_items(&mut self, res: ExpandResult<Option<(Mark, ast::MacroItems)>>) {
+        if let Some((mark, mac)) = res.value {
+            let src: InFile<ast::MacroItems> = self.expander.to_source(mac);
+            let tree_id = item_tree::TreeId::new(src.file_id, None);
+            let item_tree = tree_id.item_tree(self.db);
+            let iter: Vec<_> =
+                item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
+
+            self.collect(tree_id, &iter);
+
+            self.expander.exit(self.db, mark);
+        }
+    }
 }