]> git.lizzy.rs Git - rust.git/blob - crates/hir_expand/src/builtin_fn_macro.rs
internal: Split unresolve proc-macro error out of mbe
[rust.git] / crates / hir_expand / src / builtin_fn_macro.rs
1 //! Builtin macro
2
3 use base_db::{AnchoredPath, Edition, FileId};
4 use cfg::CfgExpr;
5 use either::Either;
6 use mbe::{parse_exprs_with_sep, parse_to_token_tree};
7 use syntax::ast::{self, AstToken};
8
9 use crate::{
10     db::AstDatabase, name, quote, AstId, CrateId, ExpandError, ExpandResult, MacroCallId,
11     MacroCallLoc, MacroDefId, MacroDefKind,
12 };
13
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 {
18             $($kind),*
19         }
20
21         #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22         pub enum EagerExpander {
23             $($e_kind),*
24         }
25
26         impl BuiltinFnLikeExpander {
27             pub fn expand(
28                 &self,
29                 db: &dyn AstDatabase,
30                 id: MacroCallId,
31                 tt: &tt::Subtree,
32             ) -> ExpandResult<tt::Subtree> {
33                 let expander = match *self {
34                     $( BuiltinFnLikeExpander::$kind => $expand, )*
35                 };
36                 expander(db, id, tt)
37             }
38         }
39
40         impl EagerExpander {
41             pub fn expand(
42                 &self,
43                 db: &dyn AstDatabase,
44                 arg_id: MacroCallId,
45                 tt: &tt::Subtree,
46             ) -> ExpandResult<ExpandedEager> {
47                 let expander = match *self {
48                     $( EagerExpander::$e_kind => $e_expand, )*
49                 };
50                 expander(db, arg_id, tt)
51             }
52         }
53
54         fn find_by_name(ident: &name::Name) -> Option<Either<BuiltinFnLikeExpander, EagerExpander>> {
55             match ident {
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)), )*
58                 _ => return None,
59             }
60         }
61     };
62 }
63
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>,
69 }
70
71 impl ExpandedEager {
72     fn new(subtree: tt::Subtree) -> Self {
73         ExpandedEager { subtree, included_file: None }
74     }
75 }
76
77 pub fn find_builtin_macro(
78     ident: &name::Name,
79     krate: CrateId,
80     ast_id: AstId<ast::Macro>,
81 ) -> Option<MacroDefId> {
82     let kind = find_by_name(ident)?;
83
84     match kind {
85         Either::Left(kind) => Some(MacroDefId {
86             krate,
87             kind: MacroDefKind::BuiltIn(kind, ast_id),
88             local_inner: false,
89         }),
90         Either::Right(kind) => Some(MacroDefId {
91             krate,
92             kind: MacroDefKind::BuiltInEager(kind, ast_id),
93             local_inner: false,
94         }),
95     }
96 }
97
98 register_builtin! {
99     LAZY:
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,
119
120     EAGER:
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
129 }
130
131 fn module_path_expand(
132     _db: &dyn AstDatabase,
133     _id: MacroCallId,
134     _tt: &tt::Subtree,
135 ) -> ExpandResult<tt::Subtree> {
136     // Just return a dummy result.
137     ExpandResult::ok(quote! { "module::path" })
138 }
139
140 fn line_expand(
141     _db: &dyn AstDatabase,
142     _id: MacroCallId,
143     _tt: &tt::Subtree,
144 ) -> ExpandResult<tt::Subtree> {
145     // dummy implementation for type-checking purposes
146     let line_num = 0;
147     let expanded = quote! {
148         #line_num
149     };
150
151     ExpandResult::ok(expanded)
152 }
153
154 fn log_syntax_expand(
155     _db: &dyn AstDatabase,
156     _id: MacroCallId,
157     _tt: &tt::Subtree,
158 ) -> ExpandResult<tt::Subtree> {
159     ExpandResult::ok(quote! {})
160 }
161
162 fn trace_macros_expand(
163     _db: &dyn AstDatabase,
164     _id: MacroCallId,
165     _tt: &tt::Subtree,
166 ) -> ExpandResult<tt::Subtree> {
167     ExpandResult::ok(quote! {})
168 }
169
170 fn stringify_expand(
171     _db: &dyn AstDatabase,
172     _id: MacroCallId,
173     tt: &tt::Subtree,
174 ) -> ExpandResult<tt::Subtree> {
175     let pretty = tt::pretty(&tt.token_trees);
176
177     let expanded = quote! {
178         #pretty
179     };
180
181     ExpandResult::ok(expanded)
182 }
183
184 fn column_expand(
185     _db: &dyn AstDatabase,
186     _id: MacroCallId,
187     _tt: &tt::Subtree,
188 ) -> ExpandResult<tt::Subtree> {
189     // dummy implementation for type-checking purposes
190     let col_num = 0;
191     let expanded = quote! {
192         #col_num
193     };
194
195     ExpandResult::ok(expanded)
196 }
197
198 fn assert_expand(
199     _db: &dyn AstDatabase,
200     _id: MacroCallId,
201     tt: &tt::Subtree,
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 {
208                 delimiter: None,
209                 token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct {
210                     char: ',',
211                     spacing: tt::Spacing::Alone,
212                     id: tt::TokenId::unspecified(),
213                 }))],
214             };
215             let cond = cond.clone();
216             let panic_args = itertools::Itertools::intersperse(panic_args.iter().cloned(), comma);
217             quote! {{
218                 if !#cond {
219                     #krate::panic!(##panic_args);
220                 }
221             }}
222         }
223         [] => quote! {{}},
224     };
225
226     ExpandResult::ok(expanded)
227 }
228
229 fn file_expand(
230     _db: &dyn AstDatabase,
231     _id: MacroCallId,
232     _tt: &tt::Subtree,
233 ) -> ExpandResult<tt::Subtree> {
234     // FIXME: RA purposefully lacks knowledge of absolute file names
235     // so just return "".
236     let file_name = "";
237
238     let expanded = quote! {
239         #file_name
240     };
241
242     ExpandResult::ok(expanded)
243 }
244
245 fn format_args_expand(
246     _db: &dyn AstDatabase,
247     _id: MacroCallId,
248     tt: &tt::Subtree,
249 ) -> ExpandResult<tt::Subtree> {
250     // We expand `format_args!("", a1, a2)` to
251     // ```
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),
255     // ])
256     // ```,
257     // which is still not really correct, but close enough for now
258     let mut args = parse_exprs_with_sep(tt, ',');
259
260     if args.is_empty() {
261         return ExpandResult::only_err(mbe::ExpandError::NoMatchingRule.into());
262     }
263     for arg in &mut args {
264         // Remove `key =`.
265         if matches!(arg.token_trees.get(1), Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p))) if p.char == '=' && p.spacing != tt::Spacing::Joint)
266         {
267             arg.token_trees.drain(..2);
268         }
269     }
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), }
273     }.token_trees);
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
278         // stable rust-src.
279         unsafe {
280             std::fmt::Arguments::new_v1(&[], &[##arg_tts])
281         }
282     };
283     ExpandResult::ok(expanded)
284 }
285
286 fn asm_expand(
287     _db: &dyn AstDatabase,
288     _id: MacroCallId,
289     tt: &tt::Subtree,
290 ) -> ExpandResult<tt::Subtree> {
291     // We expand all assembly snippets to `format_args!` invocations to get format syntax
292     // highlighting for them.
293
294     let krate = tt::Ident { text: "$crate".into(), id: tt::TokenId::unspecified() };
295
296     let mut literals = Vec::new();
297     for tt in tt.token_trees.chunks(2) {
298         match tt {
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: _ }))] =>
301             {
302                 let krate = krate.clone();
303                 literals.push(quote!(#krate::format_args!(#lit);));
304             }
305             _ => break,
306         }
307     }
308
309     let expanded = quote! {{
310         ##literals
311         ()
312     }};
313     ExpandResult::ok(expanded)
314 }
315
316 fn global_asm_expand(
317     _db: &dyn AstDatabase,
318     _id: MacroCallId,
319     _tt: &tt::Subtree,
320 ) -> ExpandResult<tt::Subtree> {
321     // Expand to nothing (at item-level)
322     ExpandResult::ok(quote! {})
323 }
324
325 fn cfg_expand(
326     db: &dyn AstDatabase,
327     id: MacroCallId,
328     tt: &tt::Subtree,
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)
335 }
336
337 fn panic_expand(
338     db: &dyn AstDatabase,
339     id: MacroCallId,
340     tt: &tt::Subtree,
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!)
347     } else {
348         quote!(#krate::panic::panic_2015!)
349     };
350
351     // Pass the original arguments
352     call.token_trees.push(tt::TokenTree::Subtree(tt.clone()));
353     ExpandResult::ok(call)
354 }
355
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())
360 }
361
362 fn compile_error_expand(
363     _db: &dyn AstDatabase,
364     _id: MacroCallId,
365     tt: &tt::Subtree,
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())
373             } else {
374                 ExpandError::Other("`compile_error!` argument must be a string".into())
375             }
376         }
377         _ => ExpandError::Other("`compile_error!` argument must be a string".into()),
378     };
379
380     ExpandResult { value: ExpandedEager::new(quote! {}), err: Some(err) }
381 }
382
383 fn concat_expand(
384     _db: &dyn AstDatabase,
385     _arg_id: MacroCallId,
386     tt: &tt::Subtree,
387 ) -> ExpandResult<ExpandedEager> {
388     let mut err = None;
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 {
397                     t = tt;
398                 }
399             }
400         }
401
402         match t {
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
406                 // as-is.
407                 let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
408                 text.push_str(&component);
409             }
410             // handle boolean literals
411             tt::TokenTree::Leaf(tt::Leaf::Ident(id))
412                 if i % 2 == 0 && (id.text == "true" || id.text == "false") =>
413             {
414                 text.push_str(id.text.as_str());
415             }
416             tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
417             _ => {
418                 err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
419             }
420         }
421     }
422     ExpandResult { value: ExpandedEager::new(quote!(#text)), err }
423 }
424
425 fn concat_idents_expand(
426     _db: &dyn AstDatabase,
427     _arg_id: MacroCallId,
428     tt: &tt::Subtree,
429 ) -> ExpandResult<ExpandedEager> {
430     let mut err = None;
431     let mut ident = String::new();
432     for (i, t) in tt.token_trees.iter().enumerate() {
433         match t {
434             tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => {
435                 ident.push_str(id.text.as_str());
436             }
437             tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
438             _ => {
439                 err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
440             }
441         }
442     }
443     let ident = tt::Ident { text: ident.into(), id: tt::TokenId::unspecified() };
444     ExpandResult { value: ExpandedEager::new(quote!(#ident)), err }
445 }
446
447 fn relative_file(
448     db: &dyn AstDatabase,
449     call_id: MacroCallId,
450     path_str: &str,
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 };
455     let res = db
456         .resolve_path(path)
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()))
461     } else {
462         Ok(res)
463     }
464 }
465
466 fn parse_string(tt: &tt::Subtree) -> Result<String, ExpandError> {
467     tt.token_trees
468         .get(0)
469         .and_then(|tt| match tt {
470             tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(it),
471             _ => None,
472         })
473         .ok_or(mbe::ExpandError::ConversionError.into())
474 }
475
476 fn include_expand(
477     db: &dyn AstDatabase,
478     arg_id: MacroCallId,
479     tt: &tt::Subtree,
480 ) -> ExpandResult<ExpandedEager> {
481     let res = (|| {
482         let path = parse_string(tt)?;
483         let file_id = relative_file(db, arg_id, &path, false)?;
484
485         let subtree =
486             parse_to_token_tree(&db.file_text(file_id)).ok_or(mbe::ExpandError::ConversionError)?.0;
487         Ok((subtree, file_id))
488     })();
489
490     match res {
491         Ok((subtree, file_id)) => {
492             ExpandResult::ok(ExpandedEager { subtree, included_file: Some(file_id) })
493         }
494         Err(e) => ExpandResult::only_err(e),
495     }
496 }
497
498 fn include_bytes_expand(
499     _db: &dyn AstDatabase,
500     _arg_id: MacroCallId,
501     tt: &tt::Subtree,
502 ) -> ExpandResult<ExpandedEager> {
503     if let Err(e) = parse_string(tt) {
504         return ExpandResult::only_err(e);
505     }
506
507     // FIXME: actually read the file here if the user asked for macro expansion
508     let res = tt::Subtree {
509         delimiter: None,
510         token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
511             text: r#"b"""#.into(),
512             id: tt::TokenId::unspecified(),
513         }))],
514     };
515     ExpandResult::ok(ExpandedEager::new(res))
516 }
517
518 fn include_str_expand(
519     db: &dyn AstDatabase,
520     arg_id: MacroCallId,
521     tt: &tt::Subtree,
522 ) -> ExpandResult<ExpandedEager> {
523     let path = match parse_string(tt) {
524         Ok(it) => it,
525         Err(e) => return ExpandResult::only_err(e),
526     };
527
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
531     // expansion.
532     let file_id = match relative_file(db, arg_id, &path, true) {
533         Ok(file_id) => file_id,
534         Err(_) => {
535             return ExpandResult::ok(ExpandedEager::new(quote!("")));
536         }
537     };
538
539     let text = db.file_text(file_id);
540     let text = &*text;
541
542     ExpandResult::ok(ExpandedEager::new(quote!(#text)))
543 }
544
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)
548 }
549
550 fn env_expand(
551     db: &dyn AstDatabase,
552     arg_id: MacroCallId,
553     tt: &tt::Subtree,
554 ) -> ExpandResult<ExpandedEager> {
555     let key = match parse_string(tt) {
556         Ok(it) => it,
557         Err(e) => return ExpandResult::only_err(e),
558     };
559
560     let mut err = None;
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(),
567             ));
568         }
569
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()
575     });
576     let expanded = quote! { #s };
577
578     ExpandResult { value: ExpandedEager::new(expanded), err }
579 }
580
581 fn option_env_expand(
582     db: &dyn AstDatabase,
583     arg_id: MacroCallId,
584     tt: &tt::Subtree,
585 ) -> ExpandResult<ExpandedEager> {
586     let key = match parse_string(tt) {
587         Ok(it) => it,
588         Err(e) => return ExpandResult::only_err(e),
589     };
590
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) },
594     };
595
596     ExpandResult::ok(ExpandedEager::new(expanded))
597 }