3 db::AstDatabase, name, quote, AstId, CrateId, MacroCallId, MacroCallLoc, MacroDefId,
7 use base_db::{AnchoredPath, Edition, FileId};
10 use mbe::{parse_exprs_with_sep, parse_to_token_tree, ExpandResult};
11 use syntax::ast::{self, AstToken};
13 macro_rules! register_builtin {
14 ( LAZY: $(($name:ident, $kind: ident) => $expand:ident),* , EAGER: $(($e_name:ident, $e_kind: ident) => $e_expand:ident),* ) => {
15 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16 pub enum BuiltinFnLikeExpander {
20 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21 pub enum EagerExpander {
25 impl BuiltinFnLikeExpander {
31 ) -> ExpandResult<tt::Subtree> {
32 let expander = match *self {
33 $( BuiltinFnLikeExpander::$kind => $expand, )*
45 ) -> ExpandResult<Option<ExpandedEager>> {
46 let expander = match *self {
47 $( EagerExpander::$e_kind => $e_expand, )*
49 expander(db, arg_id, tt)
53 fn find_by_name(ident: &name::Name) -> Option<Either<BuiltinFnLikeExpander, EagerExpander>> {
55 $( id if id == &name::name![$name] => Some(Either::Left(BuiltinFnLikeExpander::$kind)), )*
56 $( id if id == &name::name![$e_name] => Some(Either::Right(EagerExpander::$e_kind)), )*
64 pub struct ExpandedEager {
65 pub(crate) subtree: tt::Subtree,
66 /// The included file ID of the include macro.
67 pub(crate) included_file: Option<FileId>,
71 fn new(subtree: tt::Subtree) -> Self {
72 ExpandedEager { subtree, included_file: None }
76 pub fn find_builtin_macro(
79 ast_id: AstId<ast::Macro>,
80 ) -> Option<MacroDefId> {
81 let kind = find_by_name(ident)?;
84 Either::Left(kind) => Some(MacroDefId {
86 kind: MacroDefKind::BuiltIn(kind, ast_id),
89 Either::Right(kind) => Some(MacroDefId {
91 kind: MacroDefKind::BuiltInEager(kind, ast_id),
99 (column, Column) => column_expand,
100 (file, File) => file_expand,
101 (line, Line) => line_expand,
102 (module_path, ModulePath) => module_path_expand,
103 (assert, Assert) => assert_expand,
104 (stringify, Stringify) => stringify_expand,
105 (format_args, FormatArgs) => format_args_expand,
106 (const_format_args, ConstFormatArgs) => format_args_expand,
107 // format_args_nl only differs in that it adds a newline in the end,
108 // so we use the same stub expansion for now
109 (format_args_nl, FormatArgsNl) => format_args_expand,
110 (llvm_asm, LlvmAsm) => asm_expand,
111 (asm, Asm) => asm_expand,
112 (global_asm, GlobalAsm) => global_asm_expand,
113 (cfg, Cfg) => cfg_expand,
114 (core_panic, CorePanic) => panic_expand,
115 (std_panic, StdPanic) => panic_expand,
116 (log_syntax, LogSyntax) => log_syntax_expand,
117 (trace_macros, TraceMacros) => trace_macros_expand,
120 (compile_error, CompileError) => compile_error_expand,
121 (concat, Concat) => concat_expand,
122 (concat_idents, ConcatIdents) => concat_idents_expand,
123 (include, Include) => include_expand,
124 (include_bytes, IncludeBytes) => include_bytes_expand,
125 (include_str, IncludeStr) => include_str_expand,
126 (env, Env) => env_expand,
127 (option_env, OptionEnv) => option_env_expand
130 fn module_path_expand(
131 _db: &dyn AstDatabase,
134 ) -> ExpandResult<tt::Subtree> {
135 // Just return a dummy result.
136 ExpandResult::ok(quote! { "module::path" })
140 _db: &dyn AstDatabase,
143 ) -> ExpandResult<tt::Subtree> {
144 // dummy implementation for type-checking purposes
146 let expanded = quote! {
150 ExpandResult::ok(expanded)
153 fn log_syntax_expand(
154 _db: &dyn AstDatabase,
157 ) -> ExpandResult<tt::Subtree> {
158 ExpandResult::ok(quote! {})
161 fn trace_macros_expand(
162 _db: &dyn AstDatabase,
165 ) -> ExpandResult<tt::Subtree> {
166 ExpandResult::ok(quote! {})
170 _db: &dyn AstDatabase,
173 ) -> ExpandResult<tt::Subtree> {
174 let pretty = tt::pretty(&tt.token_trees);
176 let expanded = quote! {
180 ExpandResult::ok(expanded)
184 _db: &dyn AstDatabase,
187 ) -> ExpandResult<tt::Subtree> {
188 // dummy implementation for type-checking purposes
190 let expanded = quote! {
194 ExpandResult::ok(expanded)
198 _db: &dyn AstDatabase,
201 ) -> ExpandResult<tt::Subtree> {
202 let krate = tt::Ident { text: "$crate".into(), id: tt::TokenId::unspecified() };
203 let args = parse_exprs_with_sep(tt, ',');
204 let expanded = match &*args {
205 [cond, panic_args @ ..] => {
206 let comma = tt::Subtree {
208 token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct {
210 spacing: tt::Spacing::Alone,
211 id: tt::TokenId::unspecified(),
214 let cond = cond.clone();
215 let panic_args = itertools::Itertools::intersperse(panic_args.iter().cloned(), comma);
218 #krate::panic!(##panic_args);
225 ExpandResult::ok(expanded)
229 _db: &dyn AstDatabase,
232 ) -> ExpandResult<tt::Subtree> {
233 // FIXME: RA purposefully lacks knowledge of absolute file names
234 // so just return "".
237 let expanded = quote! {
241 ExpandResult::ok(expanded)
244 fn format_args_expand(
245 _db: &dyn AstDatabase,
248 ) -> ExpandResult<tt::Subtree> {
249 // We expand `format_args!("", a1, a2)` to
251 // std::fmt::Arguments::new_v1(&[], &[
252 // std::fmt::ArgumentV1::new(&arg1,std::fmt::Display::fmt),
253 // std::fmt::ArgumentV1::new(&arg2,std::fmt::Display::fmt),
256 // which is still not really correct, but close enough for now
257 let mut args = parse_exprs_with_sep(tt, ',');
260 return ExpandResult::only_err(mbe::ExpandError::NoMatchingRule);
262 for arg in &mut args {
264 if matches!(arg.token_trees.get(1), Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p))) if p.char == '=' && p.spacing != tt::Spacing::Joint)
266 arg.token_trees.drain(..2);
269 let _format_string = args.remove(0);
270 let arg_tts = args.into_iter().flat_map(|arg| {
271 quote! { std::fmt::ArgumentV1::new(&(#arg), std::fmt::Display::fmt), }
273 let expanded = quote! {
274 // It's unsafe since https://github.com/rust-lang/rust/pull/83302
275 // Wrap an unsafe block to avoid false-positive `missing-unsafe` lint.
276 // FIXME: Currently we don't have `unused_unsafe` lint so an extra unsafe block won't cause issues on early
279 std::fmt::Arguments::new_v1(&[], &[##arg_tts])
282 ExpandResult::ok(expanded)
286 _db: &dyn AstDatabase,
289 ) -> ExpandResult<tt::Subtree> {
290 // We expand all assembly snippets to `format_args!` invocations to get format syntax
291 // highlighting for them.
293 let krate = tt::Ident { text: "$crate".into(), id: tt::TokenId::unspecified() };
295 let mut literals = Vec::new();
296 for tt in tt.token_trees.chunks(2) {
298 [tt::TokenTree::Leaf(tt::Leaf::Literal(lit))]
299 | [tt::TokenTree::Leaf(tt::Leaf::Literal(lit)), tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: ',', id: _, spacing: _ }))] =>
301 let krate = krate.clone();
302 literals.push(quote!(#krate::format_args!(#lit);));
308 let expanded = quote! {{
312 ExpandResult::ok(expanded)
315 fn global_asm_expand(
316 _db: &dyn AstDatabase,
319 ) -> ExpandResult<tt::Subtree> {
320 // Expand to nothing (at item-level)
321 ExpandResult::ok(quote! {})
325 db: &dyn AstDatabase,
328 ) -> ExpandResult<tt::Subtree> {
329 let loc = db.lookup_intern_macro_call(id);
330 let expr = CfgExpr::parse(tt);
331 let enabled = db.crate_graph()[loc.krate].cfg_options.check(&expr) != Some(false);
332 let expanded = if enabled { quote!(true) } else { quote!(false) };
333 ExpandResult::ok(expanded)
337 db: &dyn AstDatabase,
340 ) -> ExpandResult<tt::Subtree> {
341 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
342 // Expand to a macro call `$crate::panic::panic_{edition}`
343 let krate = tt::Ident { text: "$crate".into(), id: tt::TokenId::unspecified() };
344 let mut call = if db.crate_graph()[loc.krate].edition == Edition::Edition2021 {
345 quote!(#krate::panic::panic_2021!)
347 quote!(#krate::panic::panic_2015!)
350 // Pass the original arguments
351 call.token_trees.push(tt::TokenTree::Subtree(tt.clone()));
352 ExpandResult::ok(call)
355 fn unquote_str(lit: &tt::Literal) -> Option<String> {
356 let lit = ast::make::tokens::literal(&lit.to_string());
357 let token = ast::String::cast(lit)?;
358 token.value().map(|it| it.into_owned())
361 fn compile_error_expand(
362 _db: &dyn AstDatabase,
365 ) -> ExpandResult<Option<ExpandedEager>> {
366 let err = match &*tt.token_trees {
367 [tt::TokenTree::Leaf(tt::Leaf::Literal(it))] => {
368 let text = it.text.as_str();
369 if text.starts_with('"') && text.ends_with('"') {
370 // FIXME: does not handle raw strings
371 mbe::ExpandError::Other(text[1..text.len() - 1].to_string())
373 mbe::ExpandError::BindingError("`compile_error!` argument must be a string".into())
376 _ => mbe::ExpandError::BindingError("`compile_error!` argument must be a string".into()),
379 ExpandResult { value: Some(ExpandedEager::new(quote! {})), err: Some(err) }
383 _db: &dyn AstDatabase,
384 _arg_id: MacroCallId,
386 ) -> ExpandResult<Option<ExpandedEager>> {
388 let mut text = String::new();
389 for (i, mut t) in tt.token_trees.iter().enumerate() {
390 // FIXME: hack on top of a hack: `$e:expr` captures get surrounded in parentheses
391 // to ensure the right parsing order, so skip the parentheses here. Ideally we'd
392 // implement rustc's model. cc https://github.com/rust-analyzer/rust-analyzer/pull/10623
393 if let tt::TokenTree::Subtree(tt::Subtree { delimiter: Some(delim), token_trees }) = t {
394 if let [tt] = &**token_trees {
395 if delim.kind == tt::DelimiterKind::Parenthesis {
402 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) if i % 2 == 0 => {
403 // concat works with string and char literals, so remove any quotes.
404 // It also works with integer, float and boolean literals, so just use the rest
406 let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
407 text.push_str(&component);
409 // handle boolean literals
410 tt::TokenTree::Leaf(tt::Leaf::Ident(id))
411 if i % 2 == 0 && (id.text == "true" || id.text == "false") =>
413 text.push_str(id.text.as_str());
415 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
417 err.get_or_insert(mbe::ExpandError::UnexpectedToken);
421 ExpandResult { value: Some(ExpandedEager::new(quote!(#text))), err }
424 fn concat_idents_expand(
425 _db: &dyn AstDatabase,
426 _arg_id: MacroCallId,
428 ) -> ExpandResult<Option<ExpandedEager>> {
430 let mut ident = String::new();
431 for (i, t) in tt.token_trees.iter().enumerate() {
433 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => {
434 ident.push_str(id.text.as_str());
436 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
438 err.get_or_insert(mbe::ExpandError::UnexpectedToken);
442 let ident = tt::Ident { text: ident.into(), id: tt::TokenId::unspecified() };
443 ExpandResult { value: Some(ExpandedEager::new(quote!(#ident))), err }
447 db: &dyn AstDatabase,
448 call_id: MacroCallId,
450 allow_recursion: bool,
451 ) -> Result<FileId, mbe::ExpandError> {
452 let call_site = call_id.as_file().original_file(db);
453 let path = AnchoredPath { anchor: call_site, path: path_str };
456 .ok_or_else(|| mbe::ExpandError::Other(format!("failed to load file `{}`", path_str)))?;
457 // Prevent include itself
458 if res == call_site && !allow_recursion {
459 Err(mbe::ExpandError::Other(format!("recursive inclusion of `{}`", path_str)))
465 fn parse_string(tt: &tt::Subtree) -> Result<String, mbe::ExpandError> {
468 .and_then(|tt| match tt {
469 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(it),
472 .ok_or(mbe::ExpandError::ConversionError)
476 db: &dyn AstDatabase,
479 ) -> ExpandResult<Option<ExpandedEager>> {
481 let path = parse_string(tt)?;
482 let file_id = relative_file(db, arg_id, &path, false)?;
485 parse_to_token_tree(&db.file_text(file_id)).ok_or(mbe::ExpandError::ConversionError)?.0;
486 Ok((subtree, file_id))
490 Ok((subtree, file_id)) => {
491 ExpandResult::ok(Some(ExpandedEager { subtree, included_file: Some(file_id) }))
493 Err(e) => ExpandResult::only_err(e),
497 fn include_bytes_expand(
498 _db: &dyn AstDatabase,
499 _arg_id: MacroCallId,
501 ) -> ExpandResult<Option<ExpandedEager>> {
502 if let Err(e) = parse_string(tt) {
503 return ExpandResult::only_err(e);
506 // FIXME: actually read the file here if the user asked for macro expansion
507 let res = tt::Subtree {
509 token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
510 text: r#"b"""#.into(),
511 id: tt::TokenId::unspecified(),
514 ExpandResult::ok(Some(ExpandedEager::new(res)))
517 fn include_str_expand(
518 db: &dyn AstDatabase,
521 ) -> ExpandResult<Option<ExpandedEager>> {
522 let path = match parse_string(tt) {
524 Err(e) => return ExpandResult::only_err(e),
527 // FIXME: we're not able to read excluded files (which is most of them because
528 // it's unusual to `include_str!` a Rust file), but we can return an empty string.
529 // Ideally, we'd be able to offer a precise expansion if the user asks for macro
531 let file_id = match relative_file(db, arg_id, &path, true) {
532 Ok(file_id) => file_id,
534 return ExpandResult::ok(Some(ExpandedEager::new(quote!(""))));
538 let text = db.file_text(file_id);
541 ExpandResult::ok(Some(ExpandedEager::new(quote!(#text))))
544 fn get_env_inner(db: &dyn AstDatabase, arg_id: MacroCallId, key: &str) -> Option<String> {
545 let krate = db.lookup_intern_macro_call(arg_id).krate;
546 db.crate_graph()[krate].env.get(key)
550 db: &dyn AstDatabase,
553 ) -> ExpandResult<Option<ExpandedEager>> {
554 let key = match parse_string(tt) {
556 Err(e) => return ExpandResult::only_err(e),
560 let s = get_env_inner(db, arg_id, &key).unwrap_or_else(|| {
561 // The only variable rust-analyzer ever sets is `OUT_DIR`, so only diagnose that to avoid
562 // unnecessary diagnostics for eg. `CARGO_PKG_NAME`.
563 if key == "OUT_DIR" {
564 err = Some(mbe::ExpandError::Other(
565 r#"`OUT_DIR` not set, enable "run build scripts" to fix"#.into(),
569 // If the variable is unset, still return a dummy string to help type inference along.
570 // We cannot use an empty string here, because for
571 // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
572 // `include!("foo.rs"), which might go to infinite loop
573 "__RA_UNIMPLEMENTED__".to_string()
575 let expanded = quote! { #s };
577 ExpandResult { value: Some(ExpandedEager::new(expanded)), err }
580 fn option_env_expand(
581 db: &dyn AstDatabase,
584 ) -> ExpandResult<Option<ExpandedEager>> {
585 let key = match parse_string(tt) {
587 Err(e) => return ExpandResult::only_err(e),
590 let expanded = match get_env_inner(db, arg_id, &key) {
591 None => quote! { std::option::Option::None::<&str> },
592 Some(s) => quote! { std::option::Some(#s) },
595 ExpandResult::ok(Some(ExpandedEager::new(expanded)))