Skip to content

Commit

Permalink
Auto merge of rust-lang#114576 - lnicola:sync-from-ra, r=lnicola
Browse files Browse the repository at this point in the history
⬆️ `rust-analyzer`

r? `@ghost`
  • Loading branch information
bors committed Aug 7, 2023
2 parents adb15a2 + a42f832 commit 139b49b
Show file tree
Hide file tree
Showing 139 changed files with 4,248 additions and 1,042 deletions.
2 changes: 2 additions & 0 deletions src/tools/rust-analyzer/crates/hir-def/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,7 @@ impl AttrsWithOwner {
},
AttrDefId::ExternBlockId(it) => attrs_from_item_tree_loc(db, it),
AttrDefId::ExternCrateId(it) => attrs_from_item_tree_loc(db, it),
AttrDefId::UseId(it) => attrs_from_item_tree_loc(db, it),
};

let attrs = raw_attrs.filter(db.upcast(), def.krate(db));
Expand Down Expand Up @@ -570,6 +571,7 @@ impl AttrsWithOwner {
},
AttrDefId::ExternBlockId(id) => any_has_attrs(db, id),
AttrDefId::ExternCrateId(id) => any_has_attrs(db, id),
AttrDefId::UseId(id) => any_has_attrs(db, id),
};

AttrSourceMap::new(owner.as_ref().map(|node| node as &dyn HasAttrs))
Expand Down
39 changes: 29 additions & 10 deletions src/tools/rust-analyzer/crates/hir-def/src/body/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,13 +313,7 @@ impl ExprCollector<'_> {
let body = self.collect_labelled_block_opt(label, e.loop_body());
self.alloc_expr(Expr::Loop { body, label }, syntax_ptr)
}
ast::Expr::WhileExpr(e) => {
let label = e.label().map(|label| self.collect_label(label));
let body = self.collect_labelled_block_opt(label, e.loop_body());
let condition = self.collect_expr_opt(e.condition());

self.alloc_expr(Expr::While { condition, body, label }, syntax_ptr)
}
ast::Expr::WhileExpr(e) => self.collect_while_loop(syntax_ptr, e),
ast::Expr::ForExpr(e) => self.collect_for_loop(syntax_ptr, e),
ast::Expr::CallExpr(e) => {
let is_rustc_box = {
Expand Down Expand Up @@ -731,6 +725,32 @@ impl ExprCollector<'_> {
expr_id
}

/// Desugar `ast::WhileExpr` from: `[opt_ident]: while <cond> <body>` into:
/// ```ignore (pseudo-rust)
/// [opt_ident]: loop {
/// if <cond> {
/// <body>
/// }
/// else {
/// break;
/// }
/// }
/// ```
/// FIXME: Rustc wraps the condition in a construct equivalent to `{ let _t = <cond>; _t }`
/// to preserve drop semantics. We should probably do the same in future.
fn collect_while_loop(&mut self, syntax_ptr: AstPtr<ast::Expr>, e: ast::WhileExpr) -> ExprId {
let label = e.label().map(|label| self.collect_label(label));
let body = self.collect_labelled_block_opt(label, e.loop_body());
let condition = self.collect_expr_opt(e.condition());
let break_expr =
self.alloc_expr(Expr::Break { expr: None, label: None }, syntax_ptr.clone());
let if_expr = self.alloc_expr(
Expr::If { condition, then_branch: body, else_branch: Some(break_expr) },
syntax_ptr.clone(),
);
self.alloc_expr(Expr::Loop { body: if_expr, label }, syntax_ptr)
}

/// Desugar `ast::ForExpr` from: `[opt_ident]: for <pat> in <head> <body>` into:
/// ```ignore (pseudo-rust)
/// match IntoIterator::into_iter(<head>) {
Expand Down Expand Up @@ -893,15 +913,14 @@ impl ExprCollector<'_> {
self.alloc_expr(Expr::Match { expr, arms }, syntax_ptr)
}

fn collect_macro_call<F, T, U>(
fn collect_macro_call<T, U>(
&mut self,
mcall: ast::MacroCall,
syntax_ptr: AstPtr<ast::MacroCall>,
record_diagnostics: bool,
collector: F,
collector: impl FnOnce(&mut Self, Option<T>) -> U,
) -> U
where
F: FnOnce(&mut Self, Option<T>) -> U,
T: ast::AstNode,
{
// File containing the macro call. Expansion errors will be attached here.
Expand Down
8 changes: 0 additions & 8 deletions src/tools/rust-analyzer/crates/hir-def/src/body/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,14 +178,6 @@ impl Printer<'_> {
w!(self, "loop ");
self.print_expr(*body);
}
Expr::While { condition, body, label } => {
if let Some(lbl) = label {
w!(self, "{}: ", self.body[*lbl].name.display(self.db));
}
w!(self, "while ");
self.print_expr(*condition);
self.print_expr(*body);
}
Expr::Call { callee, args, is_assignee_expr: _ } => {
self.print_expr(*callee);
w!(self, "(");
Expand Down
5 changes: 0 additions & 5 deletions src/tools/rust-analyzer/crates/hir-def/src/body/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,6 @@ fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope
scopes.set_scope(expr, scope);
compute_block_scopes(statements, *tail, body, scopes, &mut scope);
}
Expr::While { condition, body: body_expr, label } => {
let mut scope = scopes.new_labeled_scope(*scope, make_label(label));
compute_expr_scopes(*condition, body, scopes, &mut scope);
compute_expr_scopes(*body_expr, body, scopes, &mut scope);
}
Expr::Loop { body: body_expr, label } => {
let mut scope = scopes.new_labeled_scope(*scope, make_label(label));
compute_expr_scopes(*body_expr, body, scopes, &mut scope);
Expand Down
23 changes: 21 additions & 2 deletions src/tools/rust-analyzer/crates/hir-def/src/child_by_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ use crate::{
item_scope::ItemScope,
nameres::DefMap,
src::{HasChildSource, HasSource},
AdtId, AssocItemId, DefWithBodyId, EnumId, EnumVariantId, FieldId, ImplId, Lookup, MacroId,
ModuleDefId, ModuleId, TraitId, VariantId,
AdtId, AssocItemId, DefWithBodyId, EnumId, EnumVariantId, ExternCrateId, FieldId, ImplId,
Lookup, MacroId, ModuleDefId, ModuleId, TraitId, UseId, VariantId,
};

pub trait ChildBySource {
Expand Down Expand Up @@ -91,6 +91,8 @@ impl ChildBySource for ItemScope {
fn child_by_source_to(&self, db: &dyn DefDatabase, res: &mut DynMap, file_id: HirFileId) {
self.declarations().for_each(|item| add_module_def(db, res, file_id, item));
self.impls().for_each(|imp| add_impl(db, res, file_id, imp));
self.extern_crate_decls().for_each(|ext| add_extern_crate(db, res, file_id, ext));
self.use_decls().for_each(|ext| add_use(db, res, file_id, ext));
self.unnamed_consts().for_each(|konst| {
let loc = konst.lookup(db);
if loc.id.file_id() == file_id {
Expand Down Expand Up @@ -167,6 +169,23 @@ impl ChildBySource for ItemScope {
map[keys::IMPL].insert(loc.source(db).value, imp)
}
}
fn add_extern_crate(
db: &dyn DefDatabase,
map: &mut DynMap,
file_id: HirFileId,
ext: ExternCrateId,
) {
let loc = ext.lookup(db);
if loc.id.file_id() == file_id {
map[keys::EXTERN_CRATE].insert(loc.source(db).value, ext)
}
}
fn add_use(db: &dyn DefDatabase, map: &mut DynMap, file_id: HirFileId, ext: UseId) {
let loc = ext.lookup(db);
if loc.id.file_id() == file_id {
map[keys::USE].insert(loc.source(db).value, ext)
}
}
}
}

Expand Down
13 changes: 13 additions & 0 deletions src/tools/rust-analyzer/crates/hir-def/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

pub mod adt;

use base_db::CrateId;
use hir_expand::{
name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefKind,
};
Expand Down Expand Up @@ -467,6 +468,7 @@ pub struct ExternCrateDeclData {
pub name: Name,
pub alias: Option<ImportAlias>,
pub visibility: RawVisibility,
pub crate_id: Option<CrateId>,
}

impl ExternCrateDeclData {
Expand All @@ -478,10 +480,21 @@ impl ExternCrateDeclData {
let item_tree = loc.id.item_tree(db);
let extern_crate = &item_tree[loc.id.value];

let name = extern_crate.name.clone();
let crate_id = if name == hir_expand::name![self] {
Some(loc.container.krate())
} else {
db.crate_def_map(loc.container.krate())
.extern_prelude()
.find(|&(prelude_name, ..)| *prelude_name == name)
.map(|(_, root)| root.krate())
};

Arc::new(Self {
name: extern_crate.name.clone(),
visibility: item_tree[extern_crate.visibility].clone(),
alias: extern_crate.alias.clone(),
crate_id,
})
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/tools/rust-analyzer/crates/hir-def/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ use crate::{
visibility::{self, Visibility},
AttrDefId, BlockId, BlockLoc, ConstBlockId, ConstBlockLoc, ConstId, ConstLoc, DefWithBodyId,
EnumId, EnumLoc, ExternBlockId, ExternBlockLoc, ExternCrateId, ExternCrateLoc, FunctionId,
FunctionLoc, GenericDefId, ImplId, ImplLoc, ImportId, ImportLoc, InTypeConstId, InTypeConstLoc,
LocalEnumVariantId, LocalFieldId, Macro2Id, Macro2Loc, MacroRulesId, MacroRulesLoc,
ProcMacroId, ProcMacroLoc, StaticId, StaticLoc, StructId, StructLoc, TraitAliasId,
TraitAliasLoc, TraitId, TraitLoc, TypeAliasId, TypeAliasLoc, UnionId, UnionLoc, VariantId,
FunctionLoc, GenericDefId, ImplId, ImplLoc, InTypeConstId, InTypeConstLoc, LocalEnumVariantId,
LocalFieldId, Macro2Id, Macro2Loc, MacroRulesId, MacroRulesLoc, ProcMacroId, ProcMacroLoc,
StaticId, StaticLoc, StructId, StructLoc, TraitAliasId, TraitAliasLoc, TraitId, TraitLoc,
TypeAliasId, TypeAliasLoc, UnionId, UnionLoc, UseId, UseLoc, VariantId,
};

#[salsa::query_group(InternDatabaseStorage)]
pub trait InternDatabase: SourceDatabase {
// region: items
#[salsa::interned]
fn intern_import(&self, loc: ImportLoc) -> ImportId;
fn intern_use(&self, loc: UseLoc) -> UseId;
#[salsa::interned]
fn intern_extern_crate(&self, loc: ExternCrateLoc) -> ExternCrateId;
#[salsa::interned]
Expand Down
3 changes: 2 additions & 1 deletion src/tools/rust-analyzer/crates/hir-def/src/dyn_map/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
dyn_map::{DynMap, Policy},
ConstId, EnumId, EnumVariantId, ExternCrateId, FieldId, FunctionId, ImplId, LifetimeParamId,
Macro2Id, MacroRulesId, ProcMacroId, StaticId, StructId, TraitAliasId, TraitId, TypeAliasId,
TypeOrConstParamId, UnionId,
TypeOrConstParamId, UnionId, UseId,
};

pub type Key<K, V> = crate::dyn_map::Key<K, V, AstPtrPolicy<K, V>>;
Expand All @@ -26,6 +26,7 @@ pub const STRUCT: Key<ast::Struct, StructId> = Key::new();
pub const UNION: Key<ast::Union, UnionId> = Key::new();
pub const ENUM: Key<ast::Enum, EnumId> = Key::new();
pub const EXTERN_CRATE: Key<ast::ExternCrate, ExternCrateId> = Key::new();
pub const USE: Key<ast::Use, UseId> = Key::new();

pub const VARIANT: Key<ast::Variant, EnumVariantId> = Key::new();
pub const TUPLE_FIELD: Key<ast::TupleField, FieldId> = Key::new();
Expand Down
32 changes: 20 additions & 12 deletions src/tools/rust-analyzer/crates/hir-def/src/expander.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,18 +164,26 @@ impl Expander {
return ExpandResult { value: None, err };
};

Self::enter_expand_inner(db, call_id, err).map(|value| {
value.and_then(|InFile { file_id, value }| {
let parse = value.cast::<T>()?;

self.recursion_depth += 1;
self.hygiene = Hygiene::new(db.upcast(), file_id);
let old_file_id = std::mem::replace(&mut self.current_file_id, file_id);
let mark =
Mark { file_id: old_file_id, bomb: DropBomb::new("expansion mark dropped") };
Some((mark, parse))
})
})
let res = Self::enter_expand_inner(db, call_id, err);
match res.err {
// If proc-macro is disabled or unresolved, we want to expand to a missing expression
// instead of an empty tree which might end up in an empty block.
Some(ExpandError::UnresolvedProcMacro(_)) => res.map(|_| None),
_ => res.map(|value| {
value.and_then(|InFile { file_id, value }| {
let parse = value.cast::<T>()?;

self.recursion_depth += 1;
self.hygiene = Hygiene::new(db.upcast(), file_id);
let old_file_id = std::mem::replace(&mut self.current_file_id, file_id);
let mark = Mark {
file_id: old_file_id,
bomb: DropBomb::new("expansion mark dropped"),
};
Some((mark, parse))
})
}),
}
}
}

Expand Down
9 changes: 0 additions & 9 deletions src/tools/rust-analyzer/crates/hir-def/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,11 +191,6 @@ pub enum Expr {
body: ExprId,
label: Option<LabelId>,
},
While {
condition: ExprId,
body: ExprId,
label: Option<LabelId>,
},
Call {
callee: ExprId,
args: Box<[ExprId]>,
Expand Down Expand Up @@ -379,10 +374,6 @@ impl Expr {
}
}
Expr::Loop { body, .. } => f(*body),
Expr::While { condition, body, .. } => {
f(*condition);
f(*body);
}
Expr::Call { callee, args, .. } => {
f(*callee);
args.iter().copied().for_each(f);
Expand Down
12 changes: 12 additions & 0 deletions src/tools/rust-analyzer/crates/hir-def/src/item_scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use syntax::ast;
use crate::{
db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType, ConstId,
ExternCrateId, HasModule, ImplId, LocalModuleId, MacroId, ModuleDefId, ModuleId, TraitId,
UseId,
};

#[derive(Copy, Clone, Debug)]
Expand Down Expand Up @@ -113,6 +114,17 @@ impl ItemScope {
self.declarations.iter().copied()
}

pub fn extern_crate_decls(
&self,
) -> impl Iterator<Item = ExternCrateId> + ExactSizeIterator + '_ {
self.extern_crate_decls.iter().copied()
}

pub fn use_decls(&self) -> impl Iterator<Item = UseId> + ExactSizeIterator + '_ {
// FIXME: to be implemented
std::iter::empty()
}

pub fn impls(&self) -> impl Iterator<Item = ImplId> + ExactSizeIterator + '_ {
self.impls.iter().copied()
}
Expand Down
16 changes: 8 additions & 8 deletions src/tools/rust-analyzer/crates/hir-def/src/item_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ impl ItemTree {
fn shrink_to_fit(&mut self) {
if let Some(data) = &mut self.data {
let ItemTreeData {
imports,
uses,
extern_crates,
extern_blocks,
functions,
Expand All @@ -211,7 +211,7 @@ impl ItemTree {
vis,
} = &mut **data;

imports.shrink_to_fit();
uses.shrink_to_fit();
extern_crates.shrink_to_fit();
extern_blocks.shrink_to_fit();
functions.shrink_to_fit();
Expand Down Expand Up @@ -262,7 +262,7 @@ static VIS_PUB_CRATE: RawVisibility = RawVisibility::Module(ModPath::from_kind(P

#[derive(Default, Debug, Eq, PartialEq)]
struct ItemTreeData {
imports: Arena<Import>,
uses: Arena<Use>,
extern_crates: Arena<ExternCrate>,
extern_blocks: Arena<ExternBlock>,
functions: Arena<Function>,
Expand Down Expand Up @@ -486,7 +486,7 @@ macro_rules! mod_items {
}

mod_items! {
Import in imports -> ast::Use,
Use in uses -> ast::Use,
ExternCrate in extern_crates -> ast::ExternCrate,
ExternBlock in extern_blocks -> ast::ExternBlock,
Function in functions -> ast::Fn,
Expand Down Expand Up @@ -541,7 +541,7 @@ impl<N: ItemTreeNode> Index<FileItemTreeId<N>> for ItemTree {
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Import {
pub struct Use {
pub visibility: RawVisibilityId,
pub ast_id: FileAstId<ast::Use>,
pub use_tree: UseTree,
Expand Down Expand Up @@ -744,7 +744,7 @@ pub struct MacroDef {
pub ast_id: FileAstId<ast::MacroDef>,
}

impl Import {
impl Use {
/// Maps a `UseTree` contained in this import back to its AST node.
pub fn use_tree_to_ast(
&self,
Expand Down Expand Up @@ -870,7 +870,7 @@ macro_rules! impl_froms {
impl ModItem {
pub fn as_assoc_item(&self) -> Option<AssocItem> {
match self {
ModItem::Import(_)
ModItem::Use(_)
| ModItem::ExternCrate(_)
| ModItem::ExternBlock(_)
| ModItem::Struct(_)
Expand All @@ -892,7 +892,7 @@ impl ModItem {

pub fn ast_id(&self, tree: &ItemTree) -> FileAstId<ast::Item> {
match self {
ModItem::Import(it) => tree[it.index].ast_id().upcast(),
ModItem::Use(it) => tree[it.index].ast_id().upcast(),
ModItem::ExternCrate(it) => tree[it.index].ast_id().upcast(),
ModItem::ExternBlock(it) => tree[it.index].ast_id().upcast(),
ModItem::Function(it) => tree[it.index].ast_id().upcast(),
Expand Down
Loading

0 comments on commit 139b49b

Please sign in to comment.