3 use base_db::{AnchoredPath, Edition, FileId};
6 use mbe::{parse_exprs_with_sep, parse_to_token_tree};
7 use syntax::ast::{self, AstToken};
10 db::AstDatabase, name, quote, AstId, CrateId, ExpandError, ExpandResult, MacroCallId,
11 MacroCallLoc, MacroDefId, MacroDefKind,
14 macro_rules! register_builtin {
15 ( LAZY: $(($name:ident, $kind: ident) => $expand:ident),* , EAGER: $(($e_name:ident, $e_kind: ident) => $e_expand:ident),* ) => {
16 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17 pub enum BuiltinFnLikeExpander {
21 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22 pub enum EagerExpander {
26 impl BuiltinFnLikeExpander {
32 ) -> ExpandResult<tt::Subtree> {
33 let expander = match *self {
34 $( BuiltinFnLikeExpander::$kind => $expand, )*
46 ) -> ExpandResult<ExpandedEager> {
47 let expander = match *self {
48 $( EagerExpander::$e_kind => $e_expand, )*
50 expander(db, arg_id, tt)
54 fn find_by_name(ident: &name::Name) -> Option<Either<BuiltinFnLikeExpander, EagerExpander>> {
56 $( id if id == &name::name![$name] => Some(Either::Left(BuiltinFnLikeExpander::$kind)), )*
57 $( id if id == &name::name![$e_name] => Some(Either::Right(EagerExpander::$e_kind)), )*
64 #[derive(Debug, Default)]
65 pub struct ExpandedEager {
66 pub(crate) subtree: tt::Subtree,
67 /// The included file ID of the include macro.
68 pub(crate) included_file: Option<FileId>,
72 fn new(subtree: tt::Subtree) -> Self {
73 ExpandedEager { subtree, included_file: None }
77 pub fn find_builtin_macro(
80 ast_id: AstId<ast::Macro>,
81 ) -> Option<MacroDefId> {
82 let kind = find_by_name(ident)?;
85 Either::Left(kind) => Some(MacroDefId {
87 kind: MacroDefKind::BuiltIn(kind, ast_id),
90 Either::Right(kind) => Some(MacroDefId {
92 kind: MacroDefKind::BuiltInEager(kind, ast_id),
100 (column, Column) => column_expand,
101 (file, File) => file_expand,
102 (line, Line) => line_expand,
103 (module_path, ModulePath) => module_path_expand,
104 (assert, Assert) => assert_expand,
105 (stringify, Stringify) => stringify_expand,
106 (format_args, FormatArgs) => format_args_expand,
107 (const_format_args, ConstFormatArgs) => format_args_expand,
108 // format_args_nl only differs in that it adds a newline in the end,
109 // so we use the same stub expansion for now
110 (format_args_nl, FormatArgsNl) => format_args_expand,
111 (llvm_asm, LlvmAsm) => asm_expand,
112 (asm, Asm) => asm_expand,
113 (global_asm, GlobalAsm) => global_asm_expand,
114 (cfg, Cfg) => cfg_expand,
115 (core_panic, CorePanic) => panic_expand,
116 (std_panic, StdPanic) => panic_expand,
117 (log_syntax, LogSyntax) => log_syntax_expand,
118 (trace_macros, TraceMacros) => trace_macros_expand,
121 (compile_error, CompileError) => compile_error_expand,
122 (concat, Concat) => concat_expand,
123 (concat_idents, ConcatIdents) => concat_idents_expand,
124 (include, Include) => include_expand,
125 (include_bytes, IncludeBytes) => include_bytes_expand,
126 (include_str, IncludeStr) => include_str_expand,
127 (env, Env) => env_expand,
128 (option_env, OptionEnv) => option_env_expand
131 fn module_path_expand(
132 _db: &dyn AstDatabase,
135 ) -> ExpandResult<tt::Subtree> {
136 // Just return a dummy result.
137 ExpandResult::ok(quote! { "module::path" })
141 _db: &dyn AstDatabase,
144 ) -> ExpandResult<tt::Subtree> {
145 // dummy implementation for type-checking purposes
147 let expanded = quote! {
151 ExpandResult::ok(expanded)
154 fn log_syntax_expand(
155 _db: &dyn AstDatabase,
158 ) -> ExpandResult<tt::Subtree> {
159 ExpandResult::ok(quote! {})
162 fn trace_macros_expand(
163 _db: &dyn AstDatabase,
166 ) -> ExpandResult<tt::Subtree> {
167 ExpandResult::ok(quote! {})
171 _db: &dyn AstDatabase,
174 ) -> ExpandResult<tt::Subtree> {
175 let pretty = tt::pretty(&tt.token_trees);
177 let expanded = quote! {
181 ExpandResult::ok(expanded)
185 _db: &dyn AstDatabase,
188 ) -> ExpandResult<tt::Subtree> {
189 // dummy implementation for type-checking purposes
191 let expanded = quote! {
195 ExpandResult::ok(expanded)
199 _db: &dyn AstDatabase,
202 ) -> ExpandResult<tt::Subtree> {
203 let krate = tt::Ident { text: "$crate".into(), id: tt::TokenId::unspecified() };
204 let args = parse_exprs_with_sep(tt, ',');
205 let expanded = match &*args {
206 [cond, panic_args @ ..] => {
207 let comma = tt::Subtree {
209 token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct {
211 spacing: tt::Spacing::Alone,
212 id: tt::TokenId::unspecified(),
215 let cond = cond.clone();
216 let panic_args = itertools::Itertools::intersperse(panic_args.iter().cloned(), comma);
219 #krate::panic!(##panic_args);
226 ExpandResult::ok(expanded)
230 _db: &dyn AstDatabase,
233 ) -> ExpandResult<tt::Subtree> {
234 // FIXME: RA purposefully lacks knowledge of absolute file names
235 // so just return "".
238 let expanded = quote! {
242 ExpandResult::ok(expanded)
245 fn format_args_expand(
246 _db: &dyn AstDatabase,
249 ) -> ExpandResult<tt::Subtree> {
250 // We expand `format_args!("", a1, a2)` to
252 // std::fmt::Arguments::new_v1(&[], &[
253 // std::fmt::ArgumentV1::new(&arg1,std::fmt::Display::fmt),
254 // std::fmt::ArgumentV1::new(&arg2,std::fmt::Display::fmt),
257 // which is still not really correct, but close enough for now
258 let mut args = parse_exprs_with_sep(tt, ',');
261 return ExpandResult::only_err(mbe::ExpandError::NoMatchingRule.into());
263 for arg in &mut args {
265 if matches!(arg.token_trees.get(1), Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p))) if p.char == '=' && p.spacing != tt::Spacing::Joint)
267 arg.token_trees.drain(..2);
270 let _format_string = args.remove(0);
271 let arg_tts = args.into_iter().flat_map(|arg| {
272 quote! { std::fmt::ArgumentV1::new(&(#arg), std::fmt::Display::fmt), }
274 let expanded = quote! {
275 // It's unsafe since https://github.com/rust-lang/rust/pull/83302
276 // Wrap an unsafe block to avoid false-positive `missing-unsafe` lint.
277 // FIXME: Currently we don't have `unused_unsafe` lint so an extra unsafe block won't cause issues on early
280 std::fmt::Arguments::new_v1(&[], &[##arg_tts])
283 ExpandResult::ok(expanded)
287 _db: &dyn AstDatabase,
290 ) -> ExpandResult<tt::Subtree> {
291 // We expand all assembly snippets to `format_args!` invocations to get format syntax
292 // highlighting for them.
294 let krate = tt::Ident { text: "$crate".into(), id: tt::TokenId::unspecified() };
296 let mut literals = Vec::new();
297 for tt in tt.token_trees.chunks(2) {
299 [tt::TokenTree::Leaf(tt::Leaf::Literal(lit))]
300 | [tt::TokenTree::Leaf(tt::Leaf::Literal(lit)), tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: ',', id: _, spacing: _ }))] =>
302 let krate = krate.clone();
303 literals.push(quote!(#krate::format_args!(#lit);));
309 let expanded = quote! {{
313 ExpandResult::ok(expanded)
316 fn global_asm_expand(
317 _db: &dyn AstDatabase,
320 ) -> ExpandResult<tt::Subtree> {
321 // Expand to nothing (at item-level)
322 ExpandResult::ok(quote! {})
326 db: &dyn AstDatabase,
329 ) -> ExpandResult<tt::Subtree> {
330 let loc = db.lookup_intern_macro_call(id);
331 let expr = CfgExpr::parse(tt);
332 let enabled = db.crate_graph()[loc.krate].cfg_options.check(&expr) != Some(false);
333 let expanded = if enabled { quote!(true) } else { quote!(false) };
334 ExpandResult::ok(expanded)
338 db: &dyn AstDatabase,
341 ) -> ExpandResult<tt::Subtree> {
342 let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
343 // Expand to a macro call `$crate::panic::panic_{edition}`
344 let krate = tt::Ident { text: "$crate".into(), id: tt::TokenId::unspecified() };
345 let mut call = if db.crate_graph()[loc.krate].edition == Edition::Edition2021 {
346 quote!(#krate::panic::panic_2021!)
348 quote!(#krate::panic::panic_2015!)
351 // Pass the original arguments
352 call.token_trees.push(tt::TokenTree::Subtree(tt.clone()));
353 ExpandResult::ok(call)
356 fn unquote_str(lit: &tt::Literal) -> Option<String> {
357 let lit = ast::make::tokens::literal(&lit.to_string());
358 let token = ast::String::cast(lit)?;
359 token.value().map(|it| it.into_owned())
362 fn compile_error_expand(
363 _db: &dyn AstDatabase,
366 ) -> ExpandResult<ExpandedEager> {
367 let err = match &*tt.token_trees {
368 [tt::TokenTree::Leaf(tt::Leaf::Literal(it))] => {
369 let text = it.text.as_str();
370 if text.starts_with('"') && text.ends_with('"') {
371 // FIXME: does not handle raw strings
372 ExpandError::Other(text[1..text.len() - 1].into())
374 ExpandError::Other("`compile_error!` argument must be a string".into())
377 _ => ExpandError::Other("`compile_error!` argument must be a string".into()),
380 ExpandResult { value: ExpandedEager::new(quote! {}), err: Some(err) }
384 _db: &dyn AstDatabase,
385 _arg_id: MacroCallId,
387 ) -> ExpandResult<ExpandedEager> {
389 let mut text = String::new();
390 for (i, mut t) in tt.token_trees.iter().enumerate() {
391 // FIXME: hack on top of a hack: `$e:expr` captures get surrounded in parentheses
392 // to ensure the right parsing order, so skip the parentheses here. Ideally we'd
393 // implement rustc's model. cc https://github.com/rust-analyzer/rust-analyzer/pull/10623
394 if let tt::TokenTree::Subtree(tt::Subtree { delimiter: Some(delim), token_trees }) = t {
395 if let [tt] = &**token_trees {
396 if delim.kind == tt::DelimiterKind::Parenthesis {
403 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) if i % 2 == 0 => {
404 // concat works with string and char literals, so remove any quotes.
405 // It also works with integer, float and boolean literals, so just use the rest
407 let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
408 text.push_str(&component);
410 // handle boolean literals
411 tt::TokenTree::Leaf(tt::Leaf::Ident(id))
412 if i % 2 == 0 && (id.text == "true" || id.text == "false") =>
414 text.push_str(id.text.as_str());
416 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
418 err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
422 ExpandResult { value: ExpandedEager::new(quote!(#text)), err }
425 fn concat_idents_expand(
426 _db: &dyn AstDatabase,
427 _arg_id: MacroCallId,
429 ) -> ExpandResult<ExpandedEager> {
431 let mut ident = String::new();
432 for (i, t) in tt.token_trees.iter().enumerate() {
434 tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => {
435 ident.push_str(id.text.as_str());
437 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
439 err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
443 let ident = tt::Ident { text: ident.into(), id: tt::TokenId::unspecified() };
444 ExpandResult { value: ExpandedEager::new(quote!(#ident)), err }
448 db: &dyn AstDatabase,
449 call_id: MacroCallId,
451 allow_recursion: bool,
452 ) -> Result<FileId, ExpandError> {
453 let call_site = call_id.as_file().original_file(db);
454 let path = AnchoredPath { anchor: call_site, path: path_str };
457 .ok_or_else(|| ExpandError::Other(format!("failed to load file `{path_str}`").into()))?;
458 // Prevent include itself
459 if res == call_site && !allow_recursion {
460 Err(ExpandError::Other(format!("recursive inclusion of `{path_str}`").into()))
466 fn parse_string(tt: &tt::Subtree) -> Result<String, ExpandError> {
469 .and_then(|tt| match tt {
470 tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(it),
473 .ok_or(mbe::ExpandError::ConversionError.into())
477 db: &dyn AstDatabase,
480 ) -> ExpandResult<ExpandedEager> {
482 let path = parse_string(tt)?;
483 let file_id = relative_file(db, arg_id, &path, false)?;
486 parse_to_token_tree(&db.file_text(file_id)).ok_or(mbe::ExpandError::ConversionError)?.0;
487 Ok((subtree, file_id))
491 Ok((subtree, file_id)) => {
492 ExpandResult::ok(ExpandedEager { subtree, included_file: Some(file_id) })
494 Err(e) => ExpandResult::only_err(e),
498 fn include_bytes_expand(
499 _db: &dyn AstDatabase,
500 _arg_id: MacroCallId,
502 ) -> ExpandResult<ExpandedEager> {
503 if let Err(e) = parse_string(tt) {
504 return ExpandResult::only_err(e);
507 // FIXME: actually read the file here if the user asked for macro expansion
508 let res = tt::Subtree {
510 token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
511 text: r#"b"""#.into(),
512 id: tt::TokenId::unspecified(),
515 ExpandResult::ok(ExpandedEager::new(res))
518 fn include_str_expand(
519 db: &dyn AstDatabase,
522 ) -> ExpandResult<ExpandedEager> {
523 let path = match parse_string(tt) {
525 Err(e) => return ExpandResult::only_err(e),
528 // FIXME: we're not able to read excluded files (which is most of them because
529 // it's unusual to `include_str!` a Rust file), but we can return an empty string.
530 // Ideally, we'd be able to offer a precise expansion if the user asks for macro
532 let file_id = match relative_file(db, arg_id, &path, true) {
533 Ok(file_id) => file_id,
535 return ExpandResult::ok(ExpandedEager::new(quote!("")));
539 let text = db.file_text(file_id);
542 ExpandResult::ok(ExpandedEager::new(quote!(#text)))
545 fn get_env_inner(db: &dyn AstDatabase, arg_id: MacroCallId, key: &str) -> Option<String> {
546 let krate = db.lookup_intern_macro_call(arg_id).krate;
547 db.crate_graph()[krate].env.get(key)
551 db: &dyn AstDatabase,
554 ) -> ExpandResult<ExpandedEager> {
555 let key = match parse_string(tt) {
557 Err(e) => return ExpandResult::only_err(e),
561 let s = get_env_inner(db, arg_id, &key).unwrap_or_else(|| {
562 // The only variable rust-analyzer ever sets is `OUT_DIR`, so only diagnose that to avoid
563 // unnecessary diagnostics for eg. `CARGO_PKG_NAME`.
564 if key == "OUT_DIR" {
565 err = Some(ExpandError::Other(
566 r#"`OUT_DIR` not set, enable "run build scripts" to fix"#.into(),
570 // If the variable is unset, still return a dummy string to help type inference along.
571 // We cannot use an empty string here, because for
572 // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
573 // `include!("foo.rs"), which might go to infinite loop
574 "__RA_UNIMPLEMENTED__".to_string()
576 let expanded = quote! { #s };
578 ExpandResult { value: ExpandedEager::new(expanded), err }
581 fn option_env_expand(
582 db: &dyn AstDatabase,
585 ) -> ExpandResult<ExpandedEager> {
586 let key = match parse_string(tt) {
588 Err(e) => return ExpandResult::only_err(e),
591 let expanded = match get_env_inner(db, arg_id, &key) {
592 None => quote! { std::option::Option::None::<&str> },
593 Some(s) => quote! { std::option::Some(#s) },
596 ExpandResult::ok(ExpandedEager::new(expanded))