rust-analyzer/crates/hir-expand/src/eager.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

213 lines
7.8 KiB
Rust
Raw Normal View History

2020-03-02 06:05:15 +00:00
//! Eager expansion related utils
//!
//! Here is a dump of a discussion from Vadim Petrochenkov about Eager Expansion and
//! Its name resolution :
//!
//! > Eagerly expanded macros (and also macros eagerly expanded by eagerly expanded macros,
//! > which actually happens in practice too!) are resolved at the location of the "root" macro
//! > that performs the eager expansion on its arguments.
//! > If some name cannot be resolved at the eager expansion time it's considered unresolved,
//! > even if becomes available later (e.g. from a glob import or other macro).
//!
//! > Eagerly expanded macros don't add anything to the module structure of the crate and
//! > don't build any speculative module structures, i.e. they are expanded in a "flat"
//! > way even if tokens in them look like modules.
//!
//! > In other words, it kinda works for simple cases for which it was originally intended,
//! > and we need to live with it because it's available on stable and widely relied upon.
//!
//!
//! See the full discussion : <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Eager.20expansion.20of.20built-in.20macros>
use base_db::CrateId;
use syntax::{ted, Parse, SyntaxNode};
use triomphe::Arc;
2020-03-02 06:05:15 +00:00
use crate::{
ast::{self, AstNode},
2023-03-20 06:31:01 +00:00
db::ExpandDatabase,
2022-01-26 17:31:07 +00:00
hygiene::Hygiene,
mod_path::ModPath,
EagerCallInfo, ExpandError, ExpandResult, ExpandTo, InFile, MacroCallId, MacroCallKind,
MacroCallLoc, MacroDefId, MacroDefKind, UnresolvedMacro,
2020-03-02 06:05:15 +00:00
};
pub fn expand_eager_macro_input(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2020-06-11 10:08:24 +00:00
krate: CrateId,
2020-03-03 17:13:20 +00:00
macro_call: InFile<ast::MacroCall>,
def: MacroDefId,
2022-01-26 17:31:07 +00:00
resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
) -> Result<ExpandResult<Option<MacroCallId>>, UnresolvedMacro> {
assert!(matches!(def.kind, MacroDefKind::BuiltInEager(..)));
let token_tree = macro_call.value.token_tree();
let Some(token_tree) = token_tree else {
return Ok(ExpandResult { value: None, err:
Some(ExpandError::other(
"invalid token tree"
)),
});
};
let (parsed_args, arg_token_map) = mbe::syntax_node_to_token_tree(token_tree.syntax());
2020-03-03 17:13:20 +00:00
2020-12-22 13:42:28 +00:00
let ast_map = db.ast_id_map(macro_call.file_id);
let call_id = InFile::new(macro_call.file_id, ast_map.ast_id(&macro_call.value));
let expand_to = ExpandTo::from_call_site(&macro_call.value);
2020-12-22 13:42:28 +00:00
2020-03-03 18:41:33 +00:00
// Note:
// When `lazy_expand` is called, its *parent* file must already exist.
// Here we store an eager macro id for the argument expanded subtree
2020-03-03 18:41:33 +00:00
// for that purpose.
let arg_id = db.intern_macro_call(MacroCallLoc {
2021-05-19 18:19:08 +00:00
def,
krate,
eager: Some(Box::new(EagerCallInfo {
arg: Arc::new((parsed_args, arg_token_map)),
arg_id: None,
error: None,
})),
kind: MacroCallKind::FnLike { ast_id: call_id, expand_to: ExpandTo::Expr },
2020-03-06 14:58:45 +00:00
});
let arg_as_expr = match db.macro_arg_text(arg_id) {
Some(it) => it,
None => {
return Ok(ExpandResult {
value: None,
err: Some(ExpandError::other("invalid token tree")),
})
}
};
let ExpandResult { value: expanded_eager_input, err } = eager_macro_recur(
2020-03-06 14:58:45 +00:00
db,
&Hygiene::new(db, macro_call.file_id),
InFile::new(arg_id.as_file(), SyntaxNode::new_root(arg_as_expr)),
2020-06-11 10:08:24 +00:00
krate,
2020-03-06 14:58:45 +00:00
resolver,
)?;
let Some(expanded_eager_input) = expanded_eager_input else {
return Ok(ExpandResult { value: None, err })
};
let (mut subtree, token_map) = mbe::syntax_node_to_token_tree(&expanded_eager_input);
subtree.delimiter = crate::tt::Delimiter::unspecified();
2020-03-03 17:13:20 +00:00
let loc = MacroCallLoc {
def,
krate,
eager: Some(Box::new(EagerCallInfo {
arg: Arc::new((subtree, token_map)),
arg_id: Some(arg_id),
error: err.clone(),
})),
kind: MacroCallKind::FnLike { ast_id: call_id, expand_to },
};
Ok(ExpandResult { value: Some(db.intern_macro_call(loc)), err })
2020-03-02 06:05:15 +00:00
}
fn lazy_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2020-03-02 06:05:15 +00:00
def: &MacroDefId,
macro_call: InFile<ast::MacroCall>,
2020-06-11 10:08:24 +00:00
krate: CrateId,
) -> ExpandResult<InFile<Parse<SyntaxNode>>> {
2020-03-02 06:05:15 +00:00
let ast_id = db.ast_id_map(macro_call.file_id).ast_id(&macro_call.value);
let expand_to = ExpandTo::from_call_site(&macro_call.value);
2021-06-07 11:59:01 +00:00
let id = def.as_lazy_macro(
2021-06-13 04:18:15 +00:00
db,
krate,
MacroCallKind::FnLike { ast_id: macro_call.with_value(ast_id), expand_to },
2021-06-13 04:18:15 +00:00
);
2020-03-02 06:05:15 +00:00
let macro_file = id.as_macro_file();
db.parse_macro_expansion(macro_file).map(|parse| InFile::new(macro_file.into(), parse.0))
2020-03-02 06:05:15 +00:00
}
fn eager_macro_recur(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
hygiene: &Hygiene,
2020-03-02 06:05:15 +00:00
curr: InFile<SyntaxNode>,
2020-06-11 10:08:24 +00:00
krate: CrateId,
2022-01-26 17:31:07 +00:00
macro_resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
) -> Result<ExpandResult<Option<SyntaxNode>>, UnresolvedMacro> {
2021-05-26 15:34:50 +00:00
let original = curr.value.clone_for_update();
2020-03-02 06:05:15 +00:00
let children = original.descendants().filter_map(ast::MacroCall::cast);
let mut replacements = Vec::new();
2020-03-02 06:05:15 +00:00
// Note: We only report a single error inside of eager expansions
let mut error = None;
2020-03-02 06:05:15 +00:00
// Collect replacement
for child in children {
2022-03-12 12:04:13 +00:00
let def = match child.path().and_then(|path| ModPath::from_src(db, path, hygiene)) {
Some(path) => macro_resolver(path.clone()).ok_or(UnresolvedMacro { path })?,
2022-01-26 17:31:07 +00:00
None => {
error = Some(ExpandError::other("malformed macro invocation"));
2022-01-26 17:31:07 +00:00
continue;
}
};
let ExpandResult { value, err } = match def.kind {
MacroDefKind::BuiltInEager(..) => {
let ExpandResult { value, err } = match expand_eager_macro_input(
2020-06-11 10:08:24 +00:00
db,
krate,
curr.with_value(child.clone()),
def,
macro_resolver,
2022-01-26 17:31:07 +00:00
) {
Ok(it) => it,
2022-01-26 17:31:07 +00:00
Err(err) => return Err(err),
};
match value {
Some(call) => {
let ExpandResult { value, err: err2 } =
db.parse_macro_expansion(call.as_macro_file());
ExpandResult {
value: Some(value.0.syntax_node().clone_for_update()),
err: err.or(err2),
}
}
None => ExpandResult { value: None, err },
}
2020-03-02 06:05:15 +00:00
}
MacroDefKind::Declarative(_)
| MacroDefKind::BuiltIn(..)
| MacroDefKind::BuiltInAttr(..)
| MacroDefKind::BuiltInDerive(..)
2021-03-18 15:11:18 +00:00
| MacroDefKind::ProcMacro(..) => {
let ExpandResult { value, err } =
lazy_expand(db, &def, curr.with_value(child.clone()), krate);
2020-12-02 15:52:14 +00:00
2020-03-02 06:05:15 +00:00
// replace macro inside
let hygiene = Hygiene::new(db, value.file_id);
let ExpandResult { value, err: error } = eager_macro_recur(
db,
&hygiene,
// FIXME: We discard parse errors here
value.map(|it| it.syntax_node()),
krate,
macro_resolver,
)?;
let err = err.or(error);
ExpandResult { value, err }
2020-03-02 06:05:15 +00:00
}
};
if err.is_some() {
error = err;
}
// check if the whole original syntax is replaced
2021-01-03 09:56:59 +00:00
if child.syntax() == &original {
return Ok(ExpandResult { value, err: error });
2021-01-03 09:56:59 +00:00
}
if let Some(insert) = value {
replacements.push((child, insert));
}
2020-03-02 06:05:15 +00:00
}
replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
Ok(ExpandResult { value: Some(original), err: error })
2020-03-02 06:05:15 +00:00
}