Skip to content

Commit

Permalink
Auto merge of #16434 - Veykril:things, r=Veykril
Browse files Browse the repository at this point in the history
internal: Restructure and cleanup hir-expand a bit
  • Loading branch information
bors committed Jan 27, 2024
2 parents 4a23744 + 8a5829c commit 27c3ed9
Show file tree
Hide file tree
Showing 62 changed files with 749 additions and 723 deletions.
2 changes: 1 addition & 1 deletion crates/base-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
#![warn(rust_2018_idioms, unused_lifetimes)]

mod input;
mod change;
mod input;

use std::panic;

Expand Down
22 changes: 0 additions & 22 deletions crates/cfg/src/cfg_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,6 @@ pub enum CfgAtom {
KeyValue { key: SmolStr, value: SmolStr },
}

impl CfgAtom {
/// Returns `true` when the atom comes from the target specification.
///
/// If this returns `true`, then changing this atom requires changing the compilation target. If
/// it returns `false`, the atom might come from a build script or the build system.
pub fn is_target_defined(&self) -> bool {
match self {
CfgAtom::Flag(flag) => matches!(&**flag, "unix" | "windows"),
CfgAtom::KeyValue { key, value: _ } => matches!(
&**key,
"target_arch"
| "target_os"
| "target_env"
| "target_family"
| "target_endian"
| "target_pointer_width"
| "target_vendor" // NOTE: `target_feature` is left out since it can be configured via `-Ctarget-feature`
),
}
}
}

impl fmt::Display for CfgAtom {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expand Down
8 changes: 3 additions & 5 deletions crates/cfg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,9 @@ impl CfgDiff {
/// of both.
pub fn new(enable: Vec<CfgAtom>, disable: Vec<CfgAtom>) -> Option<CfgDiff> {
let mut occupied = FxHashSet::default();
for item in enable.iter().chain(disable.iter()) {
if !occupied.insert(item) {
// was present
return None;
}
if enable.iter().chain(disable.iter()).any(|item| !occupied.insert(item)) {
// was present
return None;
}

Some(CfgDiff { enable, disable })
Expand Down
11 changes: 4 additions & 7 deletions crates/hir-def/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use crate::{
VariantId,
};

/// Desugared attributes of an item post `cfg_attr` expansion.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct Attrs(RawAttrs);

Expand Down Expand Up @@ -228,7 +229,6 @@ pub enum DocAtom {
KeyValue { key: SmolStr, value: SmolStr },
}

// Adapted from `CfgExpr` parsing code
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DocExpr {
Invalid,
Expand Down Expand Up @@ -448,10 +448,7 @@ impl AttrsWithOwner {
let map = db.fields_attrs_source_map(id.parent);
let file_id = id.parent.file_id(db);
let root = db.parse_or_expand(file_id);
let owner = match &map[id.local_id] {
Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
};
let owner = ast::AnyHasAttrs::new(map[id.local_id].to_node(&root));
InFile::new(file_id, owner)
}
AttrDefId::AdtId(adt) => match adt {
Expand Down Expand Up @@ -634,7 +631,7 @@ fn attrs_from_item_tree_assoc<'db, N: ItemTreeModItemNode>(
pub(crate) fn fields_attrs_source_map(
db: &dyn DefDatabase,
def: VariantId,
) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>> {
) -> Arc<ArenaMap<LocalFieldId, AstPtr<Either<ast::TupleField, ast::RecordField>>>> {
let mut res = ArenaMap::default();
let child_source = def.child_source(db);

Expand All @@ -643,7 +640,7 @@ pub(crate) fn fields_attrs_source_map(
idx,
variant
.as_ref()
.either(|l| Either::Left(AstPtr::new(l)), |r| Either::Right(AstPtr::new(r))),
.either(|l| AstPtr::new(l).wrap_left(), |r| AstPtr::new(r).wrap_right()),
);
}

Expand Down
4 changes: 2 additions & 2 deletions crates/hir-def/src/body.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Defines `Body`: a lowered representation of bodies of functions, statics and
//! consts.
mod lower;
mod pretty;
pub mod scope;
#[cfg(test)]
mod tests;
pub mod scope;
mod pretty;

use std::ops::Index;

Expand Down
2 changes: 1 addition & 1 deletion crates/hir-def/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + Upcast<dyn ExpandDataba
fn fields_attrs_source_map(
&self,
def: VariantId,
) -> Arc<ArenaMap<LocalFieldId, Either<AstPtr<ast::TupleField>, AstPtr<ast::RecordField>>>>;
) -> Arc<ArenaMap<LocalFieldId, AstPtr<Either<ast::TupleField, ast::RecordField>>>>;

#[salsa::invoke(AttrsWithOwner::attrs_query)]
fn attrs(&self, def: AttrDefId) -> Attrs;
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-def/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
//!
//! See also a neighboring `body` module.
pub mod type_ref;
pub mod format_args;
pub mod type_ref;

use std::fmt;

Expand Down
71 changes: 8 additions & 63 deletions crates/hir-def/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ extern crate ra_ap_rustc_abi as rustc_abi;
pub mod db;

pub mod attr;
pub mod path;
pub mod builtin_type;
pub mod per_ns;
pub mod item_scope;
pub mod path;
pub mod per_ns;

pub mod lower;
pub mod expander;
pub mod lower;

pub mod dyn_map;

Expand All @@ -46,24 +46,24 @@ pub use self::hir::type_ref;
pub mod body;
pub mod resolver;

mod trace;
pub mod nameres;
mod trace;

pub mod src;
pub mod child_by_source;
pub mod src;

pub mod visibility;
pub mod find_path;
pub mod import_map;
pub mod visibility;

pub use rustc_abi as layout;
use triomphe::Arc;

#[cfg(test)]
mod test_db;
#[cfg(test)]
mod macro_expansion_tests;
mod pretty;
#[cfg(test)]
mod test_db;

use std::{
hash::{Hash, Hasher},
Expand All @@ -73,7 +73,6 @@ use std::{
use base_db::{impl_intern_key, salsa, CrateId, Edition};
use hir_expand::{
ast_id_map::{AstIdNode, FileAstId},
attrs::{Attr, AttrId, AttrInput},
builtin_attr_macro::BuiltinAttrExpander,
builtin_derive_macro::BuiltinDeriveExpander,
builtin_fn_macro::{BuiltinFnLikeExpander, EagerExpander},
Expand Down Expand Up @@ -1274,60 +1273,6 @@ fn macro_call_as_call_id_with_eager(
Ok(res)
}

fn derive_macro_as_call_id(
db: &dyn DefDatabase,
item_attr: &AstIdWithPath<ast::Adt>,
derive_attr_index: AttrId,
derive_pos: u32,
call_site: Span,
krate: CrateId,
resolver: impl Fn(path::ModPath) -> Option<(MacroId, MacroDefId)>,
) -> Result<(MacroId, MacroDefId, MacroCallId), UnresolvedMacro> {
let (macro_id, def_id) = resolver(item_attr.path.clone())
.filter(|(_, def_id)| def_id.is_derive())
.ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
let call_id = def_id.as_lazy_macro(
db.upcast(),
krate,
MacroCallKind::Derive {
ast_id: item_attr.ast_id,
derive_index: derive_pos,
derive_attr_index,
},
call_site,
);
Ok((macro_id, def_id, call_id))
}

fn attr_macro_as_call_id(
db: &dyn DefDatabase,
item_attr: &AstIdWithPath<ast::Item>,
macro_attr: &Attr,
krate: CrateId,
def: MacroDefId,
) -> MacroCallId {
let arg = match macro_attr.input.as_deref() {
Some(AttrInput::TokenTree(tt)) => {
let mut tt = tt.as_ref().clone();
tt.delimiter = tt::Delimiter::invisible_spanned(macro_attr.span);
Some(tt)
}

_ => None,
};

def.as_lazy_macro(
db.upcast(),
krate,
MacroCallKind::Attr {
ast_id: item_attr.ast_id,
attr_args: arg.map(Arc::new),
invoc_attr_index: macro_attr.id,
},
macro_attr.span,
)
}

#[derive(Debug)]
pub struct UnresolvedMacro {
pub path: hir_expand::mod_path::ModPath,
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-def/src/macro_expansion_tests/mbe.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
//! Tests specific to declarative macros, aka macros by example. This covers
//! both stable `macro_rules!` macros as well as unstable `macro` macros.
mod tt_conversion;
mod matching;
mod meta_syntax;
mod metavar_expr;
mod regression;
mod tt_conversion;

use expect_test::expect;

Expand Down
4 changes: 2 additions & 2 deletions crates/hir-def/src/macro_expansion_tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
//! write unit-tests (in fact, we used to do that), but that makes tests brittle
//! and harder to understand.
mod mbe;
mod builtin_fn_macro;
mod builtin_derive_macro;
mod builtin_fn_macro;
mod mbe;
mod proc_macros;

use std::{iter, ops::Range, sync};
Expand Down
4 changes: 2 additions & 2 deletions crates/hir-def/src/nameres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@
//! the result
pub mod attr_resolution;
pub mod proc_macro;
pub mod diagnostics;
mod collector;
pub mod diagnostics;
mod mod_resolution;
mod path_resolution;
pub mod proc_macro;

#[cfg(test)]
mod tests;
Expand Down
67 changes: 63 additions & 4 deletions crates/hir-def/src/nameres/attr_resolution.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
//! Post-nameres attribute resolution.
use hir_expand::{attrs::Attr, MacroCallId};
use base_db::CrateId;
use hir_expand::{
attrs::{Attr, AttrId, AttrInput},
MacroCallId, MacroCallKind, MacroDefId,
};
use span::Span;
use syntax::{ast, SmolStr};
use triomphe::Arc;

use crate::{
attr::builtin::{find_builtin_attr_idx, TOOL_MODULES},
attr_macro_as_call_id,
db::DefDatabase,
item_scope::BuiltinShadowMode,
nameres::path_resolution::ResolveMode,
path::{ModPath, PathKind},
AstIdWithPath, LocalModuleId, UnresolvedMacro,
path::{self, ModPath, PathKind},
AstIdWithPath, LocalModuleId, MacroId, UnresolvedMacro,
};

use super::{DefMap, MacroSubNs};
Expand Down Expand Up @@ -93,3 +98,57 @@ impl DefMap {
false
}
}

pub(super) fn attr_macro_as_call_id(
db: &dyn DefDatabase,
item_attr: &AstIdWithPath<ast::Item>,
macro_attr: &Attr,
krate: CrateId,
def: MacroDefId,
) -> MacroCallId {
let arg = match macro_attr.input.as_deref() {
Some(AttrInput::TokenTree(tt)) => {
let mut tt = tt.as_ref().clone();
tt.delimiter = tt::Delimiter::invisible_spanned(macro_attr.span);
Some(tt)
}

_ => None,
};

def.as_lazy_macro(
db.upcast(),
krate,
MacroCallKind::Attr {
ast_id: item_attr.ast_id,
attr_args: arg.map(Arc::new),
invoc_attr_index: macro_attr.id,
},
macro_attr.span,
)
}

pub(super) fn derive_macro_as_call_id(
db: &dyn DefDatabase,
item_attr: &AstIdWithPath<ast::Adt>,
derive_attr_index: AttrId,
derive_pos: u32,
call_site: Span,
krate: CrateId,
resolver: impl Fn(path::ModPath) -> Option<(MacroId, MacroDefId)>,
) -> Result<(MacroId, MacroDefId, MacroCallId), UnresolvedMacro> {
let (macro_id, def_id) = resolver(item_attr.path.clone())
.filter(|(_, def_id)| def_id.is_derive())
.ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
let call_id = def_id.as_lazy_macro(
db.upcast(),
krate,
MacroCallKind::Derive {
ast_id: item_attr.ast_id,
derive_index: derive_pos,
derive_attr_index,
},
call_site,
);
Ok((macro_id, def_id, call_id))
}
Loading

0 comments on commit 27c3ed9

Please sign in to comment.