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, t) in tt.token_trees.iter().enumerate() {
391 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) if i % 2 == 0 => {
392 // concat works with string and char literals, so remove any quotes.
393 // It also works with integer, float and boolean literals, so just use the rest
395 let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
396 text.push_str(&component);
398 // handle boolean literals
399 tt::TokenTree::Leaf(tt::Leaf::Ident(id))
400 if i % 2 == 0 && (id.text == "true" || id.text == "false") =>
402 text.push_str(id.text.as_str());
404 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
406 err.get_or_insert(mbe::ExpandError::UnexpectedToken);
410 ExpandResult { value: Some(ExpandedEager::new(quote!(#text))), err }
413 fn concat_idents_expand(
414 _db: &dyn AstDatabase,
415 _arg_id: MacroCallId,
417 ) -> ExpandResult<Option<ExpandedEager>> {
419 let mut ident = String::new();
420 for (i, t) in tt.token_trees.iter().enumerate() {
422 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => {
423 ident.push_str(id.text.as_str());
425 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
427 err.get_or_insert(mbe::ExpandError::UnexpectedToken);
431 let ident = tt::Ident { text: ident.into(), id: tt::TokenId::unspecified() };
432 ExpandResult { value: Some(ExpandedEager::new(quote!(#ident))), err }
436 db: &dyn AstDatabase,
437 call_id: MacroCallId,
439 allow_recursion: bool,
440 ) -> Result<FileId, mbe::ExpandError> {
441 let call_site = call_id.as_file().original_file(db);
442 let path = AnchoredPath { anchor: call_site, path: path_str };
445 .ok_or_else(|| mbe::ExpandError::Other(format!("failed to load file `{}`", path_str)))?;
446 // Prevent include itself
447 if res == call_site && !allow_recursion {
448 Err(mbe::ExpandError::Other(format!("recursive inclusion of `{}`", path_str)))
454 fn parse_string(tt: &tt::Subtree) -> Result<String, mbe::ExpandError> {
457 .and_then(|tt| match tt {
458 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(it),
461 .ok_or(mbe::ExpandError::ConversionError)
465 db: &dyn AstDatabase,
468 ) -> ExpandResult<Option<ExpandedEager>> {
470 let path = parse_string(tt)?;
471 let file_id = relative_file(db, arg_id, &path, false)?;
474 parse_to_token_tree(&db.file_text(file_id)).ok_or(mbe::ExpandError::ConversionError)?.0;
475 Ok((subtree, file_id))
479 Ok((subtree, file_id)) => {
480 ExpandResult::ok(Some(ExpandedEager { subtree, included_file: Some(file_id) }))
482 Err(e) => ExpandResult::only_err(e),
486 fn include_bytes_expand(
487 _db: &dyn AstDatabase,
488 _arg_id: MacroCallId,
490 ) -> ExpandResult<Option<ExpandedEager>> {
491 if let Err(e) = parse_string(tt) {
492 return ExpandResult::only_err(e);
495 // FIXME: actually read the file here if the user asked for macro expansion
496 let res = tt::Subtree {
498 token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
499 text: r#"b"""#.into(),
500 id: tt::TokenId::unspecified(),
503 ExpandResult::ok(Some(ExpandedEager::new(res)))
506 fn include_str_expand(
507 db: &dyn AstDatabase,
510 ) -> ExpandResult<Option<ExpandedEager>> {
511 let path = match parse_string(tt) {
513 Err(e) => return ExpandResult::only_err(e),
516 // FIXME: we're not able to read excluded files (which is most of them because
517 // it's unusual to `include_str!` a Rust file), but we can return an empty string.
518 // Ideally, we'd be able to offer a precise expansion if the user asks for macro
520 let file_id = match relative_file(db, arg_id, &path, true) {
521 Ok(file_id) => file_id,
523 return ExpandResult::ok(Some(ExpandedEager::new(quote!(""))));
527 let text = db.file_text(file_id);
530 ExpandResult::ok(Some(ExpandedEager::new(quote!(#text))))
533 fn get_env_inner(db: &dyn AstDatabase, arg_id: MacroCallId, key: &str) -> Option<String> {
534 let krate = db.lookup_intern_macro_call(arg_id).krate;
535 db.crate_graph()[krate].env.get(key)
539 db: &dyn AstDatabase,
542 ) -> ExpandResult<Option<ExpandedEager>> {
543 let key = match parse_string(tt) {
545 Err(e) => return ExpandResult::only_err(e),
549 let s = get_env_inner(db, arg_id, &key).unwrap_or_else(|| {
550 // The only variable rust-analyzer ever sets is `OUT_DIR`, so only diagnose that to avoid
551 // unnecessary diagnostics for eg. `CARGO_PKG_NAME`.
552 if key == "OUT_DIR" {
553 err = Some(mbe::ExpandError::Other(
554 r#"`OUT_DIR` not set, enable "run build scripts" to fix"#.into(),
558 // If the variable is unset, still return a dummy string to help type inference along.
559 // We cannot use an empty string here, because for
560 // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
561 // `include!("foo.rs"), which might go to infinite loop
562 "__RA_UNIMPLEMENTED__".to_string()
564 let expanded = quote! { #s };
566 ExpandResult { value: Some(ExpandedEager::new(expanded)), err }
569 fn option_env_expand(
570 db: &dyn AstDatabase,
573 ) -> ExpandResult<Option<ExpandedEager>> {
574 let key = match parse_string(tt) {
576 Err(e) => return ExpandResult::only_err(e),
579 let expanded = match get_env_inner(db, arg_id, &key) {
580 None => quote! { std::option::Option::None::<&str> },
581 Some(s) => quote! { std::option::Some(#s) },
584 ExpandResult::ok(Some(ExpandedEager::new(expanded)))