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