Skip to content

Commit 75f4c54

Browse files
committed
Add stub for cargo environment variables auto completion
1 parent a415fb4 commit 75f4c54

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

crates/ide-completion/src/completions.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub(crate) mod snippet;
1919
pub(crate) mod r#type;
2020
pub(crate) mod use_;
2121
pub(crate) mod vis;
22+
pub(crate) mod env_vars;
2223

2324
use std::iter;
2425

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
}

crates/ide-completion/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ pub fn completions(
183183
CompletionAnalysis::String { original, expanded: Some(expanded) } => {
184184
completions::extern_abi::complete_extern_abi(acc, ctx, expanded);
185185
completions::format_string::format_string(acc, ctx, original, expanded);
186+
completions::env_vars::complete_cargo_env_vars(acc, ctx, original)
186187
}
187188
CompletionAnalysis::UnexpandedAttrTT {
188189
colon_prefix,

0 commit comments

Comments
 (0)