minor: Simplify

This commit is contained in:
Lukas Wirth 2021-11-18 21:43:54 +01:00
parent f72512f1c6
commit 966cae384f
3 changed files with 91 additions and 91 deletions

View File

@ -723,20 +723,20 @@ impl Attr {
/// to derive macros. /// to derive macros.
/// ///
/// Returns `None` when the attribute does not have a well-formed `#[derive]` attribute input. /// Returns `None` when the attribute does not have a well-formed `#[derive]` attribute input.
pub(crate) fn parse_derive(&self) -> Option<impl Iterator<Item = ModPath>> { pub(crate) fn parse_derive(&self) -> Option<impl Iterator<Item = ModPath> + '_> {
if let Some(AttrInput::TokenTree(args, _)) = self.input.as_deref() { let args = match self.input.as_deref() {
Some(AttrInput::TokenTree(args, _)) => args,
_ => return None,
};
if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) { if args.delimiter_kind() != Some(DelimiterKind::Parenthesis) {
return None; return None;
} }
let mut counter = 0;
let paths = args let paths = args
.token_trees .token_trees
.iter() .iter()
.group_by(move |tt| { .group_by(|tt| {
if let tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })) = tt { matches!(tt, tt::TokenTree::Leaf(tt::Leaf::Punct(Punct { char: ',', .. })))
counter += 1;
}
counter
}) })
.into_iter() .into_iter()
.map(|(_, tts)| { .map(|(_, tts)| {
@ -750,8 +750,6 @@ impl Attr {
return Some(paths.into_iter()); return Some(paths.into_iter());
} }
None
}
pub fn string_value(&self) -> Option<&SmolStr> { pub fn string_value(&self) -> Option<&SmolStr> {
match self.input.as_deref()? { match self.input.as_deref()? {

View File

@ -226,13 +226,6 @@ enum MacroDirectiveKind {
Attr { ast_id: AstIdWithPath<ast::Item>, attr: Attr, mod_item: ModItem }, Attr { ast_id: AstIdWithPath<ast::Item>, attr: Attr, mod_item: ModItem },
} }
struct DefData<'a> {
id: ModuleDefId,
name: &'a Name,
visibility: &'a RawVisibility,
has_constructor: bool,
}
/// Walks the tree of module recursively /// Walks the tree of module recursively
struct DefCollector<'a> { struct DefCollector<'a> {
db: &'a dyn DefDatabase, db: &'a dyn DefDatabase,
@ -1353,19 +1346,18 @@ impl DefCollector<'_> {
} }
for directive in &self.unresolved_imports { for directive in &self.unresolved_imports {
if let ImportSource::Import { id: import, use_tree } = &directive.import.source { if let ImportSource::Import { id: import, use_tree } = directive.import.source {
if let (Some(krate), PathKind::Plain | PathKind::Abs) = if matches!(
(directive.import.path.segments().first(), &directive.import.path.kind) (directive.import.path.segments().first(), &directive.import.path.kind),
{ (Some(krate), PathKind::Plain | PathKind::Abs) if diagnosed_extern_crates.contains(krate)
if diagnosed_extern_crates.contains(krate) { ) {
continue; continue;
} }
}
self.def_map.diagnostics.push(DefDiagnostic::unresolved_import( self.def_map.diagnostics.push(DefDiagnostic::unresolved_import(
directive.module_id, directive.module_id,
*import, import,
*use_tree, use_tree,
)); ));
} }
} }
@ -1386,6 +1378,13 @@ struct ModCollector<'a, 'b> {
impl ModCollector<'_, '_> { impl ModCollector<'_, '_> {
fn collect(&mut self, items: &[ModItem]) { fn collect(&mut self, items: &[ModItem]) {
struct DefData<'a> {
id: ModuleDefId,
name: &'a Name,
visibility: &'a RawVisibility,
has_constructor: bool,
}
let krate = self.def_collector.def_map.krate; let krate = self.def_collector.def_map.krate;
// Note: don't assert that inserted value is fresh: it's simply not true // Note: don't assert that inserted value is fresh: it's simply not true
@ -1403,18 +1402,18 @@ impl ModCollector<'_, '_> {
// This should be processed eagerly instead of deferred to resolving. // This should be processed eagerly instead of deferred to resolving.
// `#[macro_use] extern crate` is hoisted to imports macros before collecting // `#[macro_use] extern crate` is hoisted to imports macros before collecting
// any other items. // any other items.
for item in items { for &item in items {
let attrs = self.item_tree.attrs(self.def_collector.db, krate, (*item).into()); let attrs = self.item_tree.attrs(self.def_collector.db, krate, item.into());
if attrs.cfg().map_or(true, |cfg| self.is_cfg_enabled(&cfg)) { if attrs.cfg().map_or(true, |cfg| self.is_cfg_enabled(&cfg)) {
if let ModItem::ExternCrate(id) = item { if let ModItem::ExternCrate(id) = item {
let import = self.item_tree[*id].clone(); let import = &self.item_tree[id];
let attrs = self.item_tree.attrs( let attrs = self.item_tree.attrs(
self.def_collector.db, self.def_collector.db,
krate, krate,
ModItem::from(*id).into(), ModItem::from(id).into(),
); );
if attrs.by_key("macro_use").exists() { if attrs.by_key("macro_use").exists() {
self.def_collector.import_macros_from_extern_crate(self.module_id, &import); self.def_collector.import_macros_from_extern_crate(self.module_id, import);
} }
} }
} }
@ -1656,9 +1655,7 @@ impl ModCollector<'_, '_> {
let is_enabled = item_tree let is_enabled = item_tree
.top_level_attrs(db, self.def_collector.def_map.krate) .top_level_attrs(db, self.def_collector.def_map.krate)
.cfg() .cfg()
.map_or(true, |cfg| { .map_or(true, |cfg| self.is_cfg_enabled(&cfg));
self.def_collector.cfg_options.check(&cfg) != Some(false)
});
if is_enabled { if is_enabled {
let module_id = self.push_child_module( let module_id = self.push_child_module(
module.name.clone(), module.name.clone(),
@ -1675,12 +1672,12 @@ impl ModCollector<'_, '_> {
mod_dir, mod_dir,
} }
.collect(item_tree.top_level_items()); .collect(item_tree.top_level_items());
if is_macro_use let is_macro_use = is_macro_use
|| item_tree || item_tree
.top_level_attrs(db, self.def_collector.def_map.krate) .top_level_attrs(db, self.def_collector.def_map.krate)
.by_key("macro_use") .by_key("macro_use")
.exists() .exists();
{ if is_macro_use {
self.import_all_legacy_macros(module_id); self.import_all_legacy_macros(module_id);
} }
} }
@ -1714,14 +1711,17 @@ impl ModCollector<'_, '_> {
ModuleOrigin::File { declaration, definition, is_mod_rs } ModuleOrigin::File { declaration, definition, is_mod_rs }
} }
}; };
let res = modules.alloc(ModuleData::new(origin, vis)); let res = modules.alloc(ModuleData::new(origin, vis));
modules[res].parent = Some(self.module_id); modules[res].parent = Some(self.module_id);
for (name, mac) in modules[self.module_id].scope.collect_legacy_macros() { for (name, mac) in modules[self.module_id].scope.collect_legacy_macros() {
modules[res].scope.define_legacy_macro(name, mac) modules[res].scope.define_legacy_macro(name, mac)
} }
modules[self.module_id].children.insert(name.clone(), res); modules[self.module_id].children.insert(name.clone(), res);
let module = self.def_collector.def_map.module_id(res); let module = self.def_collector.def_map.module_id(res);
let def: ModuleDefId = module.into(); let def = ModuleDefId::from(module);
self.def_collector.def_map.modules[self.module_id].scope.declare(def); self.def_collector.def_map.modules[self.module_id].scope.declare(def);
self.def_collector.update( self.def_collector.update(
self.module_id, self.module_id,
@ -1786,30 +1786,29 @@ impl ModCollector<'_, '_> {
} }
fn is_builtin_or_registered_attr(&self, path: &ModPath) -> bool { fn is_builtin_or_registered_attr(&self, path: &ModPath) -> bool {
if path.kind == PathKind::Plain { if path.kind != PathKind::Plain {
if let Some(tool_module) = path.segments().first() { return false;
let tool_module = tool_module.to_smol_str(); }
let is_tool = builtin_attr::TOOL_MODULES
.iter() let segments = path.segments();
.copied()
.chain(self.def_collector.registered_tools.iter().map(SmolStr::as_str)) if let Some(name) = segments.first() {
.any(|m| tool_module == *m); let name = name.to_smol_str();
let pred = |n: &_| *n == name;
let registered = self.def_collector.registered_tools.iter().map(SmolStr::as_str);
let is_tool = builtin_attr::TOOL_MODULES.iter().copied().chain(registered).any(pred);
if is_tool { if is_tool {
return true; return true;
} }
}
if let Some(name) = path.as_ident() { if segments.len() == 1 {
let name = name.to_smol_str(); let registered = self.def_collector.registered_attrs.iter().map(SmolStr::as_str);
let is_inert = builtin_attr::INERT_ATTRIBUTES let is_inert =
.iter() builtin_attr::INERT_ATTRIBUTES.iter().copied().chain(registered).any(pred);
.copied()
.chain(self.def_collector.registered_attrs.iter().map(SmolStr::as_str))
.any(|attr| name == *attr);
return is_inert; return is_inert;
} }
} }
false false
} }
@ -1831,7 +1830,7 @@ impl ModCollector<'_, '_> {
let is_export = export_attr.exists(); let is_export = export_attr.exists();
let is_local_inner = if is_export { let is_local_inner = if is_export {
export_attr.tt_values().map(|it| &it.token_trees).flatten().any(|it| match it { export_attr.tt_values().flat_map(|it| &it.token_trees).any(|it| match it {
tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => { tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
ident.text.contains("local_inner_macros") ident.text.contains("local_inner_macros")
} }
@ -1852,12 +1851,14 @@ impl ModCollector<'_, '_> {
&name &name
} }
None => { None => {
match attrs.by_key("rustc_builtin_macro").tt_values().next().and_then(|tt| { let explicit_name =
attrs.by_key("rustc_builtin_macro").tt_values().next().and_then(|tt| {
match tt.token_trees.first() { match tt.token_trees.first() {
Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name), Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name),
_ => None, _ => None,
} }
}) { });
match explicit_name {
Some(ident) => { Some(ident) => {
name = ident.as_name(); name = ident.as_name();
&name &name
@ -1947,7 +1948,7 @@ impl ModCollector<'_, '_> {
} }
fn collect_macro_call(&mut self, mac: &MacroCall) { fn collect_macro_call(&mut self, mac: &MacroCall) {
let ast_id = AstIdWithPath::new(self.file_id(), mac.ast_id, (*mac.path).clone()); let ast_id = AstIdWithPath::new(self.file_id(), mac.ast_id, ModPath::clone(&mac.path));
// Case 1: try to resolve in legacy scope and expand macro_rules // Case 1: try to resolve in legacy scope and expand macro_rules
let mut error = None; let mut error = None;

View File

@ -24,22 +24,13 @@ impl ModDir {
pub(super) fn root() -> ModDir { pub(super) fn root() -> ModDir {
ModDir { dir_path: DirPath::empty(), root_non_dir_owner: false, depth: 0 } ModDir { dir_path: DirPath::empty(), root_non_dir_owner: false, depth: 0 }
} }
fn child(&self, dir_path: DirPath, root_non_dir_owner: bool) -> Option<ModDir> {
let depth = self.depth + 1;
if MOD_DEPTH_LIMIT.check(depth as usize).is_err() {
tracing::error!("MOD_DEPTH_LIMIT exceeded");
cov_mark::hit!(circular_mods);
return None;
}
Some(ModDir { dir_path, root_non_dir_owner, depth })
}
pub(super) fn descend_into_definition( pub(super) fn descend_into_definition(
&self, &self,
name: &Name, name: &Name,
attr_path: Option<&SmolStr>, attr_path: Option<&SmolStr>,
) -> Option<ModDir> { ) -> Option<ModDir> {
let path = match attr_path.map(|it| it.as_str()) { let path = match attr_path.map(SmolStr::as_str) {
None => { None => {
let mut path = self.dir_path.clone(); let mut path = self.dir_path.clone();
path.push(&name.to_smol_str()); path.push(&name.to_smol_str());
@ -56,6 +47,16 @@ impl ModDir {
self.child(path, false) self.child(path, false)
} }
fn child(&self, dir_path: DirPath, root_non_dir_owner: bool) -> Option<ModDir> {
let depth = self.depth + 1;
if MOD_DEPTH_LIMIT.check(depth as usize).is_err() {
tracing::error!("MOD_DEPTH_LIMIT exceeded");
cov_mark::hit!(circular_mods);
return None;
}
Some(ModDir { dir_path, root_non_dir_owner, depth })
}
pub(super) fn resolve_declaration( pub(super) fn resolve_declaration(
&self, &self,
db: &dyn DefDatabase, db: &dyn DefDatabase,