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

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

664 lines
21 KiB
Rust
Raw Normal View History

2019-11-10 03:03:24 +00:00
//! Builtin macro
2019-11-11 06:15:09 +00:00
use base_db::{
span::{SpanAnchor, ROOT_ERASED_FILE_AST_ID},
AnchoredPath, Edition, FileId,
};
2021-03-10 18:43:03 +00:00
use cfg::CfgExpr;
2020-03-02 06:05:15 +00:00
use either::Either;
use mbe::{parse_exprs_with_sep, parse_to_token_tree};
use syntax::{
ast::{self, AstToken},
SmolStr,
};
2019-11-10 03:03:24 +00:00
2023-02-13 11:55:14 +00:00
use crate::{
db::ExpandDatabase,
name, quote,
tt::{self, Span},
EagerCallInfo, ExpandError, ExpandResult, HirFileIdExt, MacroCallId, MacroCallLoc,
2023-02-13 11:55:14 +00:00
};
2019-11-22 17:47:35 +00:00
macro_rules! register_builtin {
2020-03-02 06:05:15 +00:00
( LAZY: $(($name:ident, $kind: ident) => $expand:ident),* , EAGER: $(($e_name:ident, $e_kind: ident) => $e_expand:ident),* ) => {
2019-11-23 14:48:34 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BuiltinFnLikeExpander {
$($kind),*
}
2020-03-02 06:05:15 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EagerExpander {
$($e_kind),*
}
2019-11-23 14:48:34 +00:00
impl BuiltinFnLikeExpander {
pub fn expand(
&self,
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
id: MacroCallId,
2019-11-23 14:48:34 +00:00
tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
2019-11-23 14:48:34 +00:00
let expander = match *self {
$( BuiltinFnLikeExpander::$kind => $expand, )*
};
expander(db, id, tt)
}
2020-03-02 06:05:15 +00:00
}
2020-03-02 06:05:15 +00:00
impl EagerExpander {
pub fn expand(
&self,
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
arg_id: MacroCallId,
2020-03-02 06:05:15 +00:00
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
2020-03-02 06:05:15 +00:00
let expander = match *self {
$( EagerExpander::$e_kind => $e_expand, )*
};
expander(db, arg_id, tt)
}
2019-11-23 14:48:34 +00:00
}
2020-03-02 06:05:15 +00:00
fn find_by_name(ident: &name::Name) -> Option<Either<BuiltinFnLikeExpander, EagerExpander>> {
match ident {
$( id if id == &name::name![$name] => Some(Either::Left(BuiltinFnLikeExpander::$kind)), )*
$( id if id == &name::name![$e_name] => Some(Either::Right(EagerExpander::$e_kind)), )*
_ => return None,
}
2019-11-23 14:48:34 +00:00
}
2019-11-22 17:47:35 +00:00
};
}
2023-06-07 09:20:10 +00:00
impl EagerExpander {
pub fn is_include(&self) -> bool {
matches!(self, EagerExpander::Include)
}
}
2020-03-02 06:05:15 +00:00
pub fn find_builtin_macro(
ident: &name::Name,
) -> Option<Either<BuiltinFnLikeExpander, EagerExpander>> {
find_by_name(ident)
2020-03-02 06:05:15 +00:00
}
2019-11-22 17:47:35 +00:00
register_builtin! {
2020-03-02 06:05:15 +00:00
LAZY:
2023-11-15 11:41:14 +00:00
(column, Column) => line_expand,
2019-12-13 20:43:53 +00:00
(file, File) => file_expand,
(line, Line) => line_expand,
2020-12-14 15:38:53 +00:00
(module_path, ModulePath) => module_path_expand,
2020-03-11 15:08:12 +00:00
(assert, Assert) => assert_expand,
2019-12-13 20:43:53 +00:00
(stringify, Stringify) => stringify_expand,
(llvm_asm, LlvmAsm) => asm_expand,
(asm, Asm) => asm_expand,
2021-04-18 16:43:45 +00:00
(global_asm, GlobalAsm) => global_asm_expand,
2021-03-10 18:43:03 +00:00
(cfg, Cfg) => cfg_expand,
(core_panic, CorePanic) => panic_expand,
(std_panic, StdPanic) => panic_expand,
(unreachable, Unreachable) => unreachable_expand,
(log_syntax, LogSyntax) => log_syntax_expand,
(trace_macros, TraceMacros) => trace_macros_expand,
(format_args, FormatArgs) => format_args_expand,
(const_format_args, ConstFormatArgs) => format_args_expand,
(format_args_nl, FormatArgsNl) => format_args_nl_expand,
EAGER:
(compile_error, CompileError) => compile_error_expand,
2020-03-06 14:58:45 +00:00
(concat, Concat) => concat_expand,
2021-05-13 22:42:10 +00:00
(concat_idents, ConcatIdents) => concat_idents_expand,
2022-02-25 10:46:11 +00:00
(concat_bytes, ConcatBytes) => concat_bytes_expand,
2020-03-10 14:01:08 +00:00
(include, Include) => include_expand,
2020-06-27 18:02:47 +00:00
(include_bytes, IncludeBytes) => include_bytes_expand,
2020-06-27 12:31:19 +00:00
(include_str, IncludeStr) => include_str_expand,
2020-03-10 14:01:08 +00:00
(env, Env) => env_expand,
(option_env, OptionEnv) => option_env_expand
2019-11-22 17:47:35 +00:00
}
2022-03-06 16:56:02 +00:00
const DOLLAR_CRATE: tt::Ident =
tt::Ident { text: SmolStr::new_inline("$crate"), span: tt::SpanData::DUMMY };
2022-03-06 16:56:02 +00:00
2020-12-14 15:38:53 +00:00
fn module_path_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
2020-12-14 15:38:53 +00:00
_tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
// Just return a dummy result.
ExpandResult::ok(quote! { "module::path" })
}
2019-11-11 06:15:09 +00:00
fn line_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
2019-11-11 06:15:09 +00:00
_tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
// dummy implementation for type-checking purposes
2023-11-15 11:41:14 +00:00
ExpandResult::ok(tt::Subtree {
delimiter: tt::Delimiter::unspecified(),
token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
text: "0u32".into(),
span: tt::SpanData::DUMMY,
2023-11-15 11:41:14 +00:00
}))],
})
2019-11-11 06:15:09 +00:00
}
fn log_syntax_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
_id: MacroCallId,
_tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
ExpandResult::ok(quote! {})
}
fn trace_macros_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
_id: MacroCallId,
_tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
ExpandResult::ok(quote! {})
}
fn stringify_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
_id: MacroCallId,
tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
2023-02-13 11:55:14 +00:00
let pretty = ::tt::pretty(&tt.token_trees);
let expanded = quote! {
#pretty
};
ExpandResult::ok(expanded)
}
2019-11-22 15:05:04 +00:00
2020-03-11 15:08:12 +00:00
fn assert_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
2020-03-11 15:08:12 +00:00
tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
2021-02-28 12:46:24 +00:00
let args = parse_exprs_with_sep(tt, ',');
2021-09-30 14:26:41 +00:00
let expanded = match &*args {
[cond, panic_args @ ..] => {
2021-09-30 14:37:12 +00:00
let comma = tt::Subtree {
2023-02-13 11:55:14 +00:00
delimiter: tt::Delimiter::unspecified(),
2021-09-30 14:26:41 +00:00
token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct {
char: ',',
spacing: tt::Spacing::Alone,
span: tt::SpanData::DUMMY,
2021-09-30 14:26:41 +00:00
}))],
2021-09-30 14:37:12 +00:00
};
let cond = cond.clone();
let panic_args = itertools::Itertools::intersperse(panic_args.iter().cloned(), comma);
2021-09-30 14:26:41 +00:00
quote! {{
2023-03-13 08:42:24 +00:00
if !(#cond) {
2022-03-06 16:56:02 +00:00
#DOLLAR_CRATE::panic!(##panic_args);
2021-09-30 14:26:41 +00:00
}
}}
}
[] => quote! {{}},
2020-03-11 15:08:12 +00:00
};
2021-09-30 14:26:41 +00:00
ExpandResult::ok(expanded)
2020-03-11 15:08:12 +00:00
}
2019-11-22 15:05:04 +00:00
fn file_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
2019-11-22 15:05:04 +00:00
_tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
2019-11-22 15:05:04 +00:00
// FIXME: RA purposefully lacks knowledge of absolute file names
// so just return "".
let file_name = "";
let expanded = quote! {
#file_name
};
ExpandResult::ok(expanded)
2019-11-22 15:05:04 +00:00
}
2019-11-22 17:47:35 +00:00
fn format_args_expand(
db: &dyn ExpandDatabase,
id: MacroCallId,
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
format_args_expand_general(db, id, tt, "")
}
fn format_args_nl_expand(
db: &dyn ExpandDatabase,
id: MacroCallId,
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
format_args_expand_general(db, id, tt, "\\n")
}
fn format_args_expand_general(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
2019-12-06 18:30:01 +00:00
tt: &tt::Subtree,
// FIXME: Make use of this so that mir interpretation works properly
_end_string: &str,
) -> ExpandResult<tt::Subtree> {
let pound = quote! {@PUNCT '#'};
let mut tt = tt.clone();
tt.delimiter.kind = tt::DelimiterKind::Parenthesis;
return ExpandResult::ok(quote! {
builtin #pound format_args #tt
});
}
fn asm_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
2021-10-01 10:33:18 +00:00
tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
2021-10-01 10:33:18 +00:00
// We expand all assembly snippets to `format_args!` invocations to get format syntax
// highlighting for them.
let mut literals = Vec::new();
for tt in tt.token_trees.chunks(2) {
match tt {
[tt::TokenTree::Leaf(tt::Leaf::Literal(lit))]
2023-02-13 11:55:14 +00:00
| [tt::TokenTree::Leaf(tt::Leaf::Literal(lit)), tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: ',', span: _, spacing: _ }))] =>
2021-10-01 10:33:18 +00:00
{
2022-03-06 16:56:02 +00:00
let krate = DOLLAR_CRATE.clone();
2021-10-01 10:33:18 +00:00
literals.push(quote!(#krate::format_args!(#lit);));
}
_ => break,
}
}
2023-09-05 08:36:35 +00:00
let pound = quote! {@PUNCT '#'};
let expanded = quote! {
builtin #pound asm (
{##literals}
)
2023-09-05 08:36:35 +00:00
};
ExpandResult::ok(expanded)
}
2021-04-18 16:43:45 +00:00
fn global_asm_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
2021-04-18 16:43:45 +00:00
_tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
// Expand to nothing (at item-level)
ExpandResult::ok(quote! {})
}
2021-03-10 18:43:03 +00:00
fn cfg_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
id: MacroCallId,
2021-03-10 18:43:03 +00:00
tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
let loc = db.lookup_intern_macro_call(id);
2021-03-10 18:43:03 +00:00
let expr = CfgExpr::parse(tt);
let enabled = db.crate_graph()[loc.krate].cfg_options.check(&expr) != Some(false);
let expanded = if enabled { quote!(true) } else { quote!(false) };
ExpandResult::ok(expanded)
}
fn panic_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
id: MacroCallId,
tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
// Expand to a macro call `$crate::panic::panic_{edition}`
let mut call = if db.crate_graph()[loc.krate].edition >= Edition::Edition2021 {
2022-03-06 16:56:02 +00:00
quote!(#DOLLAR_CRATE::panic::panic_2021!)
} else {
2022-03-06 16:56:02 +00:00
quote!(#DOLLAR_CRATE::panic::panic_2015!)
};
// Pass the original arguments
call.token_trees.push(tt::TokenTree::Subtree(tt.clone()));
ExpandResult::ok(call)
}
fn unreachable_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
id: MacroCallId,
tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
// Expand to a macro call `$crate::panic::unreachable_{edition}`
let mut call = if db.crate_graph()[loc.krate].edition >= Edition::Edition2021 {
2022-03-06 16:56:02 +00:00
quote!(#DOLLAR_CRATE::panic::unreachable_2021!)
} else {
2022-03-06 16:56:02 +00:00
quote!(#DOLLAR_CRATE::panic::unreachable_2015!)
};
// Pass the original arguments
call.token_trees.push(tt::TokenTree::Subtree(tt.clone()));
ExpandResult::ok(call)
}
2020-03-02 06:05:15 +00:00
fn unquote_str(lit: &tt::Literal) -> Option<String> {
let lit = ast::make::tokens::literal(&lit.to_string());
let token = ast::String::cast(lit)?;
token.value().map(|it| it.into_owned())
}
2022-08-16 08:24:50 +00:00
fn unquote_char(lit: &tt::Literal) -> Option<char> {
let lit = ast::make::tokens::literal(&lit.to_string());
let token = ast::Char::cast(lit)?;
token.value()
}
fn unquote_byte_string(lit: &tt::Literal) -> Option<Vec<u8>> {
let lit = ast::make::tokens::literal(&lit.to_string());
let token = ast::ByteString::cast(lit)?;
2022-02-25 10:46:11 +00:00
token.value().map(|it| it.into_owned())
}
fn compile_error_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_id: MacroCallId,
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
let err = match &*tt.token_trees {
[tt::TokenTree::Leaf(tt::Leaf::Literal(it))] => match unquote_str(it) {
2023-06-07 09:20:10 +00:00
Some(unquoted) => ExpandError::other(unquoted),
None => ExpandError::other("`compile_error!` argument must be a string"),
},
2023-06-07 09:20:10 +00:00
_ => ExpandError::other("`compile_error!` argument must be a string"),
};
2023-06-07 09:20:10 +00:00
ExpandResult { value: quote! {}, err: Some(err) }
}
2020-03-06 14:58:45 +00:00
fn concat_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_arg_id: MacroCallId,
2020-03-06 14:58:45 +00:00
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
2020-12-08 19:06:41 +00:00
let mut err = None;
2020-03-02 06:05:15 +00:00
let mut text = String::new();
2021-12-10 14:17:31 +00:00
for (i, mut t) in tt.token_trees.iter().enumerate() {
// FIXME: hack on top of a hack: `$e:expr` captures get surrounded in parentheses
// to ensure the right parsing order, so skip the parentheses here. Ideally we'd
2022-07-08 13:44:49 +00:00
// implement rustc's model. cc https://github.com/rust-lang/rust-analyzer/pull/10623
2023-02-13 11:55:14 +00:00
if let tt::TokenTree::Subtree(tt::Subtree { delimiter: delim, token_trees }) = t {
2021-12-10 14:17:31 +00:00
if let [tt] = &**token_trees {
if delim.kind == tt::DelimiterKind::Parenthesis {
t = tt;
}
}
}
2020-03-02 06:05:15 +00:00
match t {
tt::TokenTree::Leaf(tt::Leaf::Literal(it)) if i % 2 == 0 => {
2020-12-08 19:06:41 +00:00
// concat works with string and char literals, so remove any quotes.
// It also works with integer, float and boolean literals, so just use the rest
// as-is.
2022-08-16 08:24:50 +00:00
if let Some(c) = unquote_char(it) {
text.push(c);
} else {
let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
text.push_str(&component);
}
}
// handle boolean literals
tt::TokenTree::Leaf(tt::Leaf::Ident(id))
if i % 2 == 0 && (id.text == "true" || id.text == "false") =>
{
text.push_str(id.text.as_str());
2020-03-02 06:05:15 +00:00
}
tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
2020-12-08 19:06:41 +00:00
_ => {
err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
2020-12-08 19:06:41 +00:00
}
2020-03-02 06:05:15 +00:00
}
}
2023-06-07 09:20:10 +00:00
ExpandResult { value: quote!(#text), err }
2020-03-02 06:05:15 +00:00
}
2022-02-25 10:46:11 +00:00
fn concat_bytes_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2022-02-25 10:46:11 +00:00
_arg_id: MacroCallId,
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
2022-02-25 10:46:11 +00:00
let mut bytes = Vec::new();
let mut err = None;
for (i, t) in tt.token_trees.iter().enumerate() {
match t {
tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => {
let token = ast::make::tokens::literal(&lit.to_string());
match token.kind() {
syntax::SyntaxKind::BYTE => bytes.push(token.text().to_string()),
syntax::SyntaxKind::BYTE_STRING => {
let components = unquote_byte_string(lit).unwrap_or_default();
2023-07-06 14:03:17 +00:00
components.into_iter().for_each(|it| bytes.push(it.to_string()));
2022-02-25 10:46:11 +00:00
}
_ => {
err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
break;
}
}
}
tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
2023-02-13 11:55:14 +00:00
tt::TokenTree::Subtree(tree) if tree.delimiter.kind == tt::DelimiterKind::Bracket => {
2022-02-25 10:46:11 +00:00
if let Err(e) = concat_bytes_expand_subtree(tree, &mut bytes) {
err.get_or_insert(e);
break;
}
}
_ => {
err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
break;
}
}
}
let ident = tt::Ident { text: bytes.join(", ").into(), span: tt::SpanData::DUMMY };
2023-06-07 09:20:10 +00:00
ExpandResult { value: quote!([#ident]), err }
2022-02-25 10:46:11 +00:00
}
fn concat_bytes_expand_subtree(
tree: &tt::Subtree,
bytes: &mut Vec<String>,
) -> Result<(), ExpandError> {
for (ti, tt) in tree.token_trees.iter().enumerate() {
match tt {
tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => {
let lit = ast::make::tokens::literal(&lit.to_string());
2022-02-25 10:46:11 +00:00
match lit.kind() {
syntax::SyntaxKind::BYTE | syntax::SyntaxKind::INT_NUMBER => {
bytes.push(lit.text().to_string())
2022-02-25 10:46:11 +00:00
}
_ => {
return Err(mbe::ExpandError::UnexpectedToken.into());
}
}
}
tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if ti % 2 == 1 && punct.char == ',' => (),
_ => {
return Err(mbe::ExpandError::UnexpectedToken.into());
}
}
}
Ok(())
}
2021-05-13 22:42:10 +00:00
fn concat_idents_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_arg_id: MacroCallId,
2021-05-13 22:42:10 +00:00
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
2021-05-13 22:42:10 +00:00
let mut err = None;
let mut ident = String::new();
for (i, t) in tt.token_trees.iter().enumerate() {
match t {
tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => {
ident.push_str(id.text.as_str());
}
tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
_ => {
err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
2021-05-13 22:42:10 +00:00
}
}
}
let ident = tt::Ident { text: ident.into(), span: tt::SpanData::DUMMY };
2023-06-07 09:20:10 +00:00
ExpandResult { value: quote!(#ident), err }
2021-05-13 22:42:10 +00:00
}
2020-06-27 12:31:19 +00:00
fn relative_file(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2020-06-27 12:31:19 +00:00
call_id: MacroCallId,
path_str: &str,
2020-06-27 12:31:19 +00:00
allow_recursion: bool,
) -> Result<FileId, ExpandError> {
2020-03-06 14:58:45 +00:00
let call_site = call_id.as_file().original_file(db);
let path = AnchoredPath { anchor: call_site, path: path_str };
let res = db
.resolve_path(path)
2023-06-07 09:20:10 +00:00
.ok_or_else(|| ExpandError::other(format!("failed to load file `{path_str}`")))?;
2020-06-05 14:45:20 +00:00
// Prevent include itself
2020-06-27 12:31:19 +00:00
if res == call_site && !allow_recursion {
2023-06-07 09:20:10 +00:00
Err(ExpandError::other(format!("recursive inclusion of `{path_str}`")))
2020-06-05 14:45:20 +00:00
} else {
Ok(res)
2020-03-07 08:25:43 +00:00
}
2020-03-06 14:58:45 +00:00
}
fn parse_string(tt: &tt::Subtree) -> Result<String, ExpandError> {
2020-03-10 14:01:08 +00:00
tt.token_trees
2020-03-06 14:58:45 +00:00
.get(0)
.and_then(|tt| match tt {
2021-06-13 03:54:16 +00:00
tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(it),
2020-03-06 14:58:45 +00:00
_ => None,
})
.ok_or(mbe::ExpandError::ConversionError.into())
2020-03-10 14:01:08 +00:00
}
2020-03-06 14:58:45 +00:00
2020-03-10 14:01:08 +00:00
fn include_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
arg_id: MacroCallId,
2023-06-07 09:20:10 +00:00
_tt: &tt::Subtree,
) -> ExpandResult<tt::Subtree> {
match db.include_expand(arg_id) {
Ok((res, _)) => ExpandResult::ok(res.as_ref().clone()),
2023-06-07 09:20:10 +00:00
Err(e) => ExpandResult::new(tt::Subtree::empty(), e),
}
2020-03-06 14:58:45 +00:00
}
// FIXME: Check if this is still needed now after the token map rewrite
2023-06-07 09:20:10 +00:00
pub(crate) fn include_arg_to_tt(
db: &dyn ExpandDatabase,
arg_id: MacroCallId,
) -> Result<(triomphe::Arc<tt::Subtree>, FileId), ExpandError> {
2023-06-07 09:20:10 +00:00
let loc = db.lookup_intern_macro_call(arg_id);
2023-08-25 14:38:36 +00:00
let Some(EagerCallInfo { arg, arg_id, .. }) = loc.eager.as_deref() else {
2023-06-07 09:20:10 +00:00
panic!("include_arg_to_tt called on non include macro call: {:?}", &loc.eager);
};
let path = parse_string(&arg.0)?;
let file_id = relative_file(db, *arg_id, &path, false)?;
let subtree = parse_to_token_tree(
&db.file_text(file_id),
SpanAnchor { file_id: file_id.into(), ast_id: ROOT_ERASED_FILE_AST_ID },
)
.ok_or(mbe::ExpandError::ConversionError)?;
Ok((triomphe::Arc::new(subtree), file_id))
2023-06-07 09:20:10 +00:00
}
2020-06-27 18:02:47 +00:00
fn include_bytes_expand(
2023-03-20 06:31:01 +00:00
_db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
_arg_id: MacroCallId,
2020-06-27 18:02:47 +00:00
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
if let Err(e) = parse_string(tt) {
2023-06-07 09:20:10 +00:00
return ExpandResult::new(tt::Subtree::empty(), e);
}
2020-06-27 18:02:47 +00:00
// FIXME: actually read the file here if the user asked for macro expansion
let res = tt::Subtree {
2023-02-13 11:55:14 +00:00
delimiter: tt::Delimiter::unspecified(),
2020-06-27 18:02:47 +00:00
token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
text: r#"b"""#.into(),
span: tt::SpanData::DUMMY,
2020-06-27 18:02:47 +00:00
}))],
};
2023-06-07 09:20:10 +00:00
ExpandResult::ok(res)
2020-06-27 18:02:47 +00:00
}
2020-06-27 12:31:19 +00:00
fn include_str_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
arg_id: MacroCallId,
2020-06-27 12:31:19 +00:00
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
let path = match parse_string(tt) {
Ok(it) => it,
2023-06-07 09:20:10 +00:00
Err(e) => return ExpandResult::new(tt::Subtree::empty(), e),
};
2020-06-27 12:31:19 +00:00
// FIXME: we're not able to read excluded files (which is most of them because
// it's unusual to `include_str!` a Rust file), but we can return an empty string.
// Ideally, we'd be able to offer a precise expansion if the user asks for macro
// expansion.
2021-06-13 03:55:55 +00:00
let file_id = match relative_file(db, arg_id, &path, true) {
Ok(file_id) => file_id,
Err(_) => {
2023-06-07 09:20:10 +00:00
return ExpandResult::ok(quote!(""));
2020-06-27 12:31:19 +00:00
}
};
let text = db.file_text(file_id);
let text = &*text;
2023-06-07 09:20:10 +00:00
ExpandResult::ok(quote!(#text))
2020-06-27 12:31:19 +00:00
}
2023-03-20 06:31:01 +00:00
fn get_env_inner(db: &dyn ExpandDatabase, arg_id: MacroCallId, key: &str) -> Option<String> {
let krate = db.lookup_intern_macro_call(arg_id).krate;
2020-03-10 14:01:08 +00:00
db.crate_graph()[krate].env.get(key)
}
fn env_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
arg_id: MacroCallId,
2020-03-10 14:01:08 +00:00
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
let key = match parse_string(tt) {
Ok(it) => it,
2023-06-07 09:20:10 +00:00
Err(e) => return ExpandResult::new(tt::Subtree::empty(), e),
};
2020-03-10 14:01:08 +00:00
let mut err = None;
let s = get_env_inner(db, arg_id, &key).unwrap_or_else(|| {
// The only variable rust-analyzer ever sets is `OUT_DIR`, so only diagnose that to avoid
// unnecessary diagnostics for eg. `CARGO_PKG_NAME`.
if key == "OUT_DIR" {
2023-06-07 09:20:10 +00:00
err = Some(ExpandError::other(r#"`OUT_DIR` not set, enable "build scripts" to fix"#));
}
// If the variable is unset, still return a dummy string to help type inference along.
// We cannot use an empty string here, because for
// `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
// `include!("foo.rs"), which might go to infinite loop
2023-06-07 09:20:10 +00:00
"UNRESOLVED_ENV_VAR".to_string()
});
2020-03-10 14:01:08 +00:00
let expanded = quote! { #s };
2023-06-07 09:20:10 +00:00
ExpandResult { value: expanded, err }
2020-03-10 14:01:08 +00:00
}
fn option_env_expand(
2023-03-20 06:31:01 +00:00
db: &dyn ExpandDatabase,
2021-05-19 18:19:08 +00:00
arg_id: MacroCallId,
2020-03-10 14:01:08 +00:00
tt: &tt::Subtree,
2023-06-07 09:20:10 +00:00
) -> ExpandResult<tt::Subtree> {
let key = match parse_string(tt) {
Ok(it) => it,
2023-06-07 09:20:10 +00:00
Err(e) => return ExpandResult::new(tt::Subtree::empty(), e),
};
// FIXME: Use `DOLLAR_CRATE` when that works in eager macros.
2020-03-10 14:01:08 +00:00
let expanded = match get_env_inner(db, arg_id, &key) {
None => quote! { ::core::option::Option::None::<&str> },
Some(s) => quote! { ::core::option::Option::Some(#s) },
2020-03-10 14:01:08 +00:00
};
2023-06-07 09:20:10 +00:00
ExpandResult::ok(expanded)
2020-03-10 14:01:08 +00:00
}