]> git.lizzy.rs Git - rust.git/blob - crates/hir-expand/src/builtin_fn_macro.rs
Auto merge of #12652 - lnicola:openvsx, r=lnicola
[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::{
8     ast::{self, AstToken},
9     SmolStr,
10 };
11
12 use crate::{db::AstDatabase, name, quote, ExpandError, ExpandResult, MacroCallId, MacroCallLoc};
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 ) -> Option<Either<BuiltinFnLikeExpander, EagerExpander>> {
80     find_by_name(ident)
81 }
82
83 register_builtin! {
84     LAZY:
85     (column, Column) => column_expand,
86     (file, File) => file_expand,
87     (line, Line) => line_expand,
88     (module_path, ModulePath) => module_path_expand,
89     (assert, Assert) => assert_expand,
90     (stringify, Stringify) => stringify_expand,
91     (format_args, FormatArgs) => format_args_expand,
92     (const_format_args, ConstFormatArgs) => format_args_expand,
93     // format_args_nl only differs in that it adds a newline in the end,
94     // so we use the same stub expansion for now
95     (format_args_nl, FormatArgsNl) => format_args_expand,
96     (llvm_asm, LlvmAsm) => asm_expand,
97     (asm, Asm) => asm_expand,
98     (global_asm, GlobalAsm) => global_asm_expand,
99     (cfg, Cfg) => cfg_expand,
100     (core_panic, CorePanic) => panic_expand,
101     (std_panic, StdPanic) => panic_expand,
102     (unreachable, Unreachable) => unreachable_expand,
103     (log_syntax, LogSyntax) => log_syntax_expand,
104     (trace_macros, TraceMacros) => trace_macros_expand,
105
106     EAGER:
107     (compile_error, CompileError) => compile_error_expand,
108     (concat, Concat) => concat_expand,
109     (concat_idents, ConcatIdents) => concat_idents_expand,
110     (concat_bytes, ConcatBytes) => concat_bytes_expand,
111     (include, Include) => include_expand,
112     (include_bytes, IncludeBytes) => include_bytes_expand,
113     (include_str, IncludeStr) => include_str_expand,
114     (env, Env) => env_expand,
115     (option_env, OptionEnv) => option_env_expand
116 }
117
118 const DOLLAR_CRATE: tt::Ident =
119     tt::Ident { text: SmolStr::new_inline("$crate"), id: tt::TokenId::unspecified() };
120
121 fn module_path_expand(
122     _db: &dyn AstDatabase,
123     _id: MacroCallId,
124     _tt: &tt::Subtree,
125 ) -> ExpandResult<tt::Subtree> {
126     // Just return a dummy result.
127     ExpandResult::ok(quote! { "module::path" })
128 }
129
130 fn line_expand(
131     _db: &dyn AstDatabase,
132     _id: MacroCallId,
133     _tt: &tt::Subtree,
134 ) -> ExpandResult<tt::Subtree> {
135     // dummy implementation for type-checking purposes
136     let line_num = 0;
137     let expanded = quote! {
138         #line_num
139     };
140
141     ExpandResult::ok(expanded)
142 }
143
144 fn log_syntax_expand(
145     _db: &dyn AstDatabase,
146     _id: MacroCallId,
147     _tt: &tt::Subtree,
148 ) -> ExpandResult<tt::Subtree> {
149     ExpandResult::ok(quote! {})
150 }
151
152 fn trace_macros_expand(
153     _db: &dyn AstDatabase,
154     _id: MacroCallId,
155     _tt: &tt::Subtree,
156 ) -> ExpandResult<tt::Subtree> {
157     ExpandResult::ok(quote! {})
158 }
159
160 fn stringify_expand(
161     _db: &dyn AstDatabase,
162     _id: MacroCallId,
163     tt: &tt::Subtree,
164 ) -> ExpandResult<tt::Subtree> {
165     let pretty = tt::pretty(&tt.token_trees);
166
167     let expanded = quote! {
168         #pretty
169     };
170
171     ExpandResult::ok(expanded)
172 }
173
174 fn column_expand(
175     _db: &dyn AstDatabase,
176     _id: MacroCallId,
177     _tt: &tt::Subtree,
178 ) -> ExpandResult<tt::Subtree> {
179     // dummy implementation for type-checking purposes
180     let col_num = 0;
181     let expanded = quote! {
182         #col_num
183     };
184
185     ExpandResult::ok(expanded)
186 }
187
188 fn assert_expand(
189     _db: &dyn AstDatabase,
190     _id: MacroCallId,
191     tt: &tt::Subtree,
192 ) -> ExpandResult<tt::Subtree> {
193     let args = parse_exprs_with_sep(tt, ',');
194     let expanded = match &*args {
195         [cond, panic_args @ ..] => {
196             let comma = tt::Subtree {
197                 delimiter: None,
198                 token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct {
199                     char: ',',
200                     spacing: tt::Spacing::Alone,
201                     id: tt::TokenId::unspecified(),
202                 }))],
203             };
204             let cond = cond.clone();
205             let panic_args = itertools::Itertools::intersperse(panic_args.iter().cloned(), comma);
206             quote! {{
207                 if !#cond {
208                     #DOLLAR_CRATE::panic!(##panic_args);
209                 }
210             }}
211         }
212         [] => quote! {{}},
213     };
214
215     ExpandResult::ok(expanded)
216 }
217
218 fn file_expand(
219     _db: &dyn AstDatabase,
220     _id: MacroCallId,
221     _tt: &tt::Subtree,
222 ) -> ExpandResult<tt::Subtree> {
223     // FIXME: RA purposefully lacks knowledge of absolute file names
224     // so just return "".
225     let file_name = "";
226
227     let expanded = quote! {
228         #file_name
229     };
230
231     ExpandResult::ok(expanded)
232 }
233
234 fn format_args_expand(
235     _db: &dyn AstDatabase,
236     _id: MacroCallId,
237     tt: &tt::Subtree,
238 ) -> ExpandResult<tt::Subtree> {
239     // We expand `format_args!("", a1, a2)` to
240     // ```
241     // std::fmt::Arguments::new_v1(&[], &[
242     //   std::fmt::ArgumentV1::new(&arg1,std::fmt::Display::fmt),
243     //   std::fmt::ArgumentV1::new(&arg2,std::fmt::Display::fmt),
244     // ])
245     // ```,
246     // which is still not really correct, but close enough for now
247     let mut args = parse_exprs_with_sep(tt, ',');
248
249     if args.is_empty() {
250         return ExpandResult::only_err(mbe::ExpandError::NoMatchingRule.into());
251     }
252     for arg in &mut args {
253         // Remove `key =`.
254         if matches!(arg.token_trees.get(1), Some(tt::TokenTree::Leaf(tt::Leaf::Punct(p))) if p.char == '=' && p.spacing != tt::Spacing::Joint)
255         {
256             arg.token_trees.drain(..2);
257         }
258     }
259     let _format_string = args.remove(0);
260     let arg_tts = args.into_iter().flat_map(|arg| {
261         quote! { std::fmt::ArgumentV1::new(&(#arg), std::fmt::Display::fmt), }
262     }.token_trees);
263     let expanded = quote! {
264         // It's unsafe since https://github.com/rust-lang/rust/pull/83302
265         // Wrap an unsafe block to avoid false-positive `missing-unsafe` lint.
266         // FIXME: Currently we don't have `unused_unsafe` lint so an extra unsafe block won't cause issues on early
267         // stable rust-src.
268         unsafe {
269             std::fmt::Arguments::new_v1(&[], &[##arg_tts])
270         }
271     };
272     ExpandResult::ok(expanded)
273 }
274
275 fn asm_expand(
276     _db: &dyn AstDatabase,
277     _id: MacroCallId,
278     tt: &tt::Subtree,
279 ) -> ExpandResult<tt::Subtree> {
280     // We expand all assembly snippets to `format_args!` invocations to get format syntax
281     // highlighting for them.
282
283     let mut literals = Vec::new();
284     for tt in tt.token_trees.chunks(2) {
285         match tt {
286             [tt::TokenTree::Leaf(tt::Leaf::Literal(lit))]
287             | [tt::TokenTree::Leaf(tt::Leaf::Literal(lit)), tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: ',', id: _, spacing: _ }))] =>
288             {
289                 let krate = DOLLAR_CRATE.clone();
290                 literals.push(quote!(#krate::format_args!(#lit);));
291             }
292             _ => break,
293         }
294     }
295
296     let expanded = quote! {{
297         ##literals
298         loop {}
299     }};
300     ExpandResult::ok(expanded)
301 }
302
303 fn global_asm_expand(
304     _db: &dyn AstDatabase,
305     _id: MacroCallId,
306     _tt: &tt::Subtree,
307 ) -> ExpandResult<tt::Subtree> {
308     // Expand to nothing (at item-level)
309     ExpandResult::ok(quote! {})
310 }
311
312 fn cfg_expand(
313     db: &dyn AstDatabase,
314     id: MacroCallId,
315     tt: &tt::Subtree,
316 ) -> ExpandResult<tt::Subtree> {
317     let loc = db.lookup_intern_macro_call(id);
318     let expr = CfgExpr::parse(tt);
319     let enabled = db.crate_graph()[loc.krate].cfg_options.check(&expr) != Some(false);
320     let expanded = if enabled { quote!(true) } else { quote!(false) };
321     ExpandResult::ok(expanded)
322 }
323
324 fn panic_expand(
325     db: &dyn AstDatabase,
326     id: MacroCallId,
327     tt: &tt::Subtree,
328 ) -> ExpandResult<tt::Subtree> {
329     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
330     // Expand to a macro call `$crate::panic::panic_{edition}`
331     let mut call = if db.crate_graph()[loc.krate].edition >= Edition::Edition2021 {
332         quote!(#DOLLAR_CRATE::panic::panic_2021!)
333     } else {
334         quote!(#DOLLAR_CRATE::panic::panic_2015!)
335     };
336
337     // Pass the original arguments
338     call.token_trees.push(tt::TokenTree::Subtree(tt.clone()));
339     ExpandResult::ok(call)
340 }
341
342 fn unreachable_expand(
343     db: &dyn AstDatabase,
344     id: MacroCallId,
345     tt: &tt::Subtree,
346 ) -> ExpandResult<tt::Subtree> {
347     let loc: MacroCallLoc = db.lookup_intern_macro_call(id);
348     // Expand to a macro call `$crate::panic::unreachable_{edition}`
349     let mut call = if db.crate_graph()[loc.krate].edition >= Edition::Edition2021 {
350         quote!(#DOLLAR_CRATE::panic::unreachable_2021!)
351     } else {
352         quote!(#DOLLAR_CRATE::panic::unreachable_2015!)
353     };
354
355     // Pass the original arguments
356     call.token_trees.push(tt::TokenTree::Subtree(tt.clone()));
357     ExpandResult::ok(call)
358 }
359
360 fn unquote_str(lit: &tt::Literal) -> Option<String> {
361     let lit = ast::make::tokens::literal(&lit.to_string());
362     let token = ast::String::cast(lit)?;
363     token.value().map(|it| it.into_owned())
364 }
365
366 fn unquote_byte_string(lit: &tt::Literal) -> Option<Vec<u8>> {
367     let lit = ast::make::tokens::literal(&lit.to_string());
368     let token = ast::ByteString::cast(lit)?;
369     token.value().map(|it| it.into_owned())
370 }
371
372 fn compile_error_expand(
373     _db: &dyn AstDatabase,
374     _id: MacroCallId,
375     tt: &tt::Subtree,
376 ) -> ExpandResult<ExpandedEager> {
377     let err = match &*tt.token_trees {
378         [tt::TokenTree::Leaf(tt::Leaf::Literal(it))] => {
379             let text = it.text.as_str();
380             if text.starts_with('"') && text.ends_with('"') {
381                 // FIXME: does not handle raw strings
382                 ExpandError::Other(text[1..text.len() - 1].into())
383             } else {
384                 ExpandError::Other("`compile_error!` argument must be a string".into())
385             }
386         }
387         _ => ExpandError::Other("`compile_error!` argument must be a string".into()),
388     };
389
390     ExpandResult { value: ExpandedEager::new(quote! {}), err: Some(err) }
391 }
392
393 fn concat_expand(
394     _db: &dyn AstDatabase,
395     _arg_id: MacroCallId,
396     tt: &tt::Subtree,
397 ) -> ExpandResult<ExpandedEager> {
398     let mut err = None;
399     let mut text = String::new();
400     for (i, mut t) in tt.token_trees.iter().enumerate() {
401         // FIXME: hack on top of a hack: `$e:expr` captures get surrounded in parentheses
402         // to ensure the right parsing order, so skip the parentheses here. Ideally we'd
403         // implement rustc's model. cc https://github.com/rust-analyzer/rust-analyzer/pull/10623
404         if let tt::TokenTree::Subtree(tt::Subtree { delimiter: Some(delim), token_trees }) = t {
405             if let [tt] = &**token_trees {
406                 if delim.kind == tt::DelimiterKind::Parenthesis {
407                     t = tt;
408                 }
409             }
410         }
411
412         match t {
413             tt::TokenTree::Leaf(tt::Leaf::Literal(it)) if i % 2 == 0 => {
414                 // concat works with string and char literals, so remove any quotes.
415                 // It also works with integer, float and boolean literals, so just use the rest
416                 // as-is.
417                 let component = unquote_str(it).unwrap_or_else(|| it.text.to_string());
418                 text.push_str(&component);
419             }
420             // handle boolean literals
421             tt::TokenTree::Leaf(tt::Leaf::Ident(id))
422                 if i % 2 == 0 && (id.text == "true" || id.text == "false") =>
423             {
424                 text.push_str(id.text.as_str());
425             }
426             tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
427             _ => {
428                 err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
429             }
430         }
431     }
432     ExpandResult { value: ExpandedEager::new(quote!(#text)), err }
433 }
434
435 fn concat_bytes_expand(
436     _db: &dyn AstDatabase,
437     _arg_id: MacroCallId,
438     tt: &tt::Subtree,
439 ) -> ExpandResult<ExpandedEager> {
440     let mut bytes = Vec::new();
441     let mut err = None;
442     for (i, t) in tt.token_trees.iter().enumerate() {
443         match t {
444             tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => {
445                 let token = ast::make::tokens::literal(&lit.to_string());
446                 match token.kind() {
447                     syntax::SyntaxKind::BYTE => bytes.push(token.text().to_string()),
448                     syntax::SyntaxKind::BYTE_STRING => {
449                         let components = unquote_byte_string(lit).unwrap_or_else(Vec::new);
450                         components.into_iter().for_each(|x| bytes.push(x.to_string()));
451                     }
452                     _ => {
453                         err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
454                         break;
455                     }
456                 }
457             }
458             tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
459             tt::TokenTree::Subtree(tree)
460                 if tree.delimiter_kind() == Some(tt::DelimiterKind::Bracket) =>
461             {
462                 if let Err(e) = concat_bytes_expand_subtree(tree, &mut bytes) {
463                     err.get_or_insert(e);
464                     break;
465                 }
466             }
467             _ => {
468                 err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
469                 break;
470             }
471         }
472     }
473     let ident = tt::Ident { text: bytes.join(", ").into(), id: tt::TokenId::unspecified() };
474     ExpandResult { value: ExpandedEager::new(quote!([#ident])), err }
475 }
476
477 fn concat_bytes_expand_subtree(
478     tree: &tt::Subtree,
479     bytes: &mut Vec<String>,
480 ) -> Result<(), ExpandError> {
481     for (ti, tt) in tree.token_trees.iter().enumerate() {
482         match tt {
483             tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => {
484                 let lit = ast::make::tokens::literal(&lit.to_string());
485                 match lit.kind() {
486                     syntax::SyntaxKind::BYTE | syntax::SyntaxKind::INT_NUMBER => {
487                         bytes.push(lit.text().to_string())
488                     }
489                     _ => {
490                         return Err(mbe::ExpandError::UnexpectedToken.into());
491                     }
492                 }
493             }
494             tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if ti % 2 == 1 && punct.char == ',' => (),
495             _ => {
496                 return Err(mbe::ExpandError::UnexpectedToken.into());
497             }
498         }
499     }
500     Ok(())
501 }
502
503 fn concat_idents_expand(
504     _db: &dyn AstDatabase,
505     _arg_id: MacroCallId,
506     tt: &tt::Subtree,
507 ) -> ExpandResult<ExpandedEager> {
508     let mut err = None;
509     let mut ident = String::new();
510     for (i, t) in tt.token_trees.iter().enumerate() {
511         match t {
512             tt::TokenTree::Leaf(tt::Leaf::Ident(id)) => {
513                 ident.push_str(id.text.as_str());
514             }
515             tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if i % 2 == 1 && punct.char == ',' => (),
516             _ => {
517                 err.get_or_insert(mbe::ExpandError::UnexpectedToken.into());
518             }
519         }
520     }
521     let ident = tt::Ident { text: ident.into(), id: tt::TokenId::unspecified() };
522     ExpandResult { value: ExpandedEager::new(quote!(#ident)), err }
523 }
524
525 fn relative_file(
526     db: &dyn AstDatabase,
527     call_id: MacroCallId,
528     path_str: &str,
529     allow_recursion: bool,
530 ) -> Result<FileId, ExpandError> {
531     let call_site = call_id.as_file().original_file(db);
532     let path = AnchoredPath { anchor: call_site, path: path_str };
533     let res = db
534         .resolve_path(path)
535         .ok_or_else(|| ExpandError::Other(format!("failed to load file `{path_str}`").into()))?;
536     // Prevent include itself
537     if res == call_site && !allow_recursion {
538         Err(ExpandError::Other(format!("recursive inclusion of `{path_str}`").into()))
539     } else {
540         Ok(res)
541     }
542 }
543
544 fn parse_string(tt: &tt::Subtree) -> Result<String, ExpandError> {
545     tt.token_trees
546         .get(0)
547         .and_then(|tt| match tt {
548             tt::TokenTree::Leaf(tt::Leaf::Literal(it)) => unquote_str(it),
549             _ => None,
550         })
551         .ok_or(mbe::ExpandError::ConversionError.into())
552 }
553
554 fn include_expand(
555     db: &dyn AstDatabase,
556     arg_id: MacroCallId,
557     tt: &tt::Subtree,
558 ) -> ExpandResult<ExpandedEager> {
559     let res = (|| {
560         let path = parse_string(tt)?;
561         let file_id = relative_file(db, arg_id, &path, false)?;
562
563         let subtree =
564             parse_to_token_tree(&db.file_text(file_id)).ok_or(mbe::ExpandError::ConversionError)?.0;
565         Ok((subtree, file_id))
566     })();
567
568     match res {
569         Ok((subtree, file_id)) => {
570             ExpandResult::ok(ExpandedEager { subtree, included_file: Some(file_id) })
571         }
572         Err(e) => ExpandResult::only_err(e),
573     }
574 }
575
576 fn include_bytes_expand(
577     _db: &dyn AstDatabase,
578     _arg_id: MacroCallId,
579     tt: &tt::Subtree,
580 ) -> ExpandResult<ExpandedEager> {
581     if let Err(e) = parse_string(tt) {
582         return ExpandResult::only_err(e);
583     }
584
585     // FIXME: actually read the file here if the user asked for macro expansion
586     let res = tt::Subtree {
587         delimiter: None,
588         token_trees: vec![tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
589             text: r#"b"""#.into(),
590             id: tt::TokenId::unspecified(),
591         }))],
592     };
593     ExpandResult::ok(ExpandedEager::new(res))
594 }
595
596 fn include_str_expand(
597     db: &dyn AstDatabase,
598     arg_id: MacroCallId,
599     tt: &tt::Subtree,
600 ) -> ExpandResult<ExpandedEager> {
601     let path = match parse_string(tt) {
602         Ok(it) => it,
603         Err(e) => return ExpandResult::only_err(e),
604     };
605
606     // FIXME: we're not able to read excluded files (which is most of them because
607     // it's unusual to `include_str!` a Rust file), but we can return an empty string.
608     // Ideally, we'd be able to offer a precise expansion if the user asks for macro
609     // expansion.
610     let file_id = match relative_file(db, arg_id, &path, true) {
611         Ok(file_id) => file_id,
612         Err(_) => {
613             return ExpandResult::ok(ExpandedEager::new(quote!("")));
614         }
615     };
616
617     let text = db.file_text(file_id);
618     let text = &*text;
619
620     ExpandResult::ok(ExpandedEager::new(quote!(#text)))
621 }
622
623 fn get_env_inner(db: &dyn AstDatabase, arg_id: MacroCallId, key: &str) -> Option<String> {
624     let krate = db.lookup_intern_macro_call(arg_id).krate;
625     db.crate_graph()[krate].env.get(key)
626 }
627
628 fn env_expand(
629     db: &dyn AstDatabase,
630     arg_id: MacroCallId,
631     tt: &tt::Subtree,
632 ) -> ExpandResult<ExpandedEager> {
633     let key = match parse_string(tt) {
634         Ok(it) => it,
635         Err(e) => return ExpandResult::only_err(e),
636     };
637
638     let mut err = None;
639     let s = get_env_inner(db, arg_id, &key).unwrap_or_else(|| {
640         // The only variable rust-analyzer ever sets is `OUT_DIR`, so only diagnose that to avoid
641         // unnecessary diagnostics for eg. `CARGO_PKG_NAME`.
642         if key == "OUT_DIR" {
643             err = Some(ExpandError::Other(
644                 r#"`OUT_DIR` not set, enable "build scripts" to fix"#.into(),
645             ));
646         }
647
648         // If the variable is unset, still return a dummy string to help type inference along.
649         // We cannot use an empty string here, because for
650         // `include!(concat!(env!("OUT_DIR"), "/foo.rs"))` will become
651         // `include!("foo.rs"), which might go to infinite loop
652         "__RA_UNIMPLEMENTED__".to_string()
653     });
654     let expanded = quote! { #s };
655
656     ExpandResult { value: ExpandedEager::new(expanded), err }
657 }
658
659 fn option_env_expand(
660     db: &dyn AstDatabase,
661     arg_id: MacroCallId,
662     tt: &tt::Subtree,
663 ) -> ExpandResult<ExpandedEager> {
664     let key = match parse_string(tt) {
665         Ok(it) => it,
666         Err(e) => return ExpandResult::only_err(e),
667     };
668
669     let expanded = match get_env_inner(db, arg_id, &key) {
670         None => quote! { std::option::Option::None::<&str> },
671         Some(s) => quote! { std::option::Some(#s) },
672     };
673
674     ExpandResult::ok(ExpandedEager::new(expanded))
675 }