]> git.lizzy.rs Git - rust.git/blob - crates/ide-completion/src/completions/env_vars.rs
Add stub for cargo environment variables auto completion
[rust.git] / crates / ide-completion / src / completions / env_vars.rs
1 //! Completes environment variables defined by Cargo (https://doc.rust-lang.org/cargo/reference/environment-variables.html)
2
3 use syntax::{ast, AstToken, AstNode, TextRange, TextSize};
4
5 use crate::{context::CompletionContext, CompletionItem, CompletionItemKind};
6
7 use super::Completions;
8
9 pub(crate) fn complete_cargo_env_vars(
10     acc: &mut Completions,
11     ctx: &CompletionContext<'_>,
12     original: &ast::String
13 ) {
14     if !is_env_macro(original) {
15         return;
16     }
17
18     let start = ctx.original_token.text_range().start() + TextSize::from(1);
19     let cursor = ctx.position.offset;
20
21     CompletionItem::new(CompletionItemKind::Binding, TextRange::new(start, cursor), "CARGO").add_to(acc);
22 }
23
24 fn is_env_macro(string: &ast::String) -> bool {
25     //todo: replace copypaste from format_string with separate function
26     (|| {
27         let macro_call = string.syntax().parent_ancestors().find_map(ast::MacroCall::cast)?;
28         let name = macro_call.path()?.segment()?.name_ref()?;
29
30         if !matches!(name.text().as_str(), 
31         "env" | "option_env") {
32             return None;
33         }
34
35
36         Some(())
37     })()
38     .is_some()
39 }
40
41 #[cfg(test)]
42 mod tests {
43     use expect_test::{expect, Expect};
44     use crate::tests::{check_edit};
45
46     #[test]
47     fn completes_env_variables() {
48         check_edit("CARGO", 
49         r#"
50             fn main() {
51                 let foo = env!("CA$0);
52             }
53         "#
54         ,r#"
55             fn main() {
56                 let foo = env!("CARGO);
57             }
58         "#)
59     }
60 }