use tower_lsp::lsp_types::{CompletionItem, CompletionItemKind};
use super::ast_utils::{calculate_offset, find_node_at_position};
use crate::ast::AstNode;
#[derive(Debug, Clone)]
pub struct ToonCompletion {
pub label: String,
pub kind: CompletionItemKind,
pub detail: Option<String>,
}
impl ToonCompletion {
pub fn key(name: &str) -> Self {
Self {
label: name.to_string(),
kind: CompletionItemKind::PROPERTY,
detail: Some("key".to_string()),
}
}
pub fn literal(value: &str) -> Self {
Self {
label: value.to_string(),
kind: CompletionItemKind::KEYWORD,
detail: Some("literal".to_string()),
}
}
}
impl From<ToonCompletion> for CompletionItem {
fn from(tc: ToonCompletion) -> Self {
CompletionItem {
label: tc.label,
kind: Some(tc.kind),
detail: tc.detail,
..Default::default()
}
}
}
pub fn get_completions_at_position(
ast: &AstNode,
source: &str,
line: u32,
column: u32,
) -> Vec<ToonCompletion> {
let mut completions = Vec::new();
let offset = match calculate_offset(source, line, column) {
Some(o) => o,
None => return completions,
};
let context = determine_completion_context(source, line, column);
match context {
CompletionContext::AfterColon => {
completions.push(ToonCompletion::literal("true"));
completions.push(ToonCompletion::literal("false"));
completions.push(ToonCompletion::literal("null"));
}
CompletionContext::ReferencePosition => {
let key_paths = collect_all_key_paths(ast);
for path in key_paths {
completions.push(ToonCompletion {
label: path,
kind: CompletionItemKind::VARIABLE,
detail: Some("variable".to_string()),
});
}
}
CompletionContext::EnvVarPosition => {
for (key, _) in std::env::vars() {
completions.push(ToonCompletion {
label: key,
kind: CompletionItemKind::VARIABLE,
detail: Some("environment variable".to_string()),
});
}
}
CompletionContext::KeyPosition => {
if let Some(node_at_pos) = find_node_at_position(ast, line, column, offset) {
for entry in &node_at_pos.path {
if let Some(key) = &entry.key {
completions.push(ToonCompletion::key(key));
}
}
}
let root_keys = collect_root_keys(ast);
for key in root_keys {
if !completions.iter().any(|c| c.label == key) {
completions.push(ToonCompletion::key(&key));
}
}
}
CompletionContext::Unknown => {
completions.push(ToonCompletion::literal("true"));
completions.push(ToonCompletion::literal("false"));
completions.push(ToonCompletion::literal("null"));
let root_keys = collect_root_keys(ast);
for key in root_keys {
completions.push(ToonCompletion::key(&key));
}
}
}
completions
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CompletionContext {
AfterColon,
KeyPosition,
ReferencePosition,
EnvVarPosition,
Unknown,
}
fn determine_completion_context(source: &str, line: u32, column: u32) -> CompletionContext {
let lines: Vec<&str> = source.lines().collect();
let line_idx = line as usize;
if line_idx >= lines.len() {
return CompletionContext::KeyPosition;
}
let line_text = lines[line_idx];
let col = column as usize;
let prefix = if col <= line_text.len() { &line_text[..col] } else { line_text };
if let Some(ref_start_idx) = prefix.rfind("${") {
let suffix = &prefix[ref_start_idx + 2..];
if !suffix.contains('}') {
if suffix.starts_with("env:") {
return CompletionContext::EnvVarPosition;
}
return CompletionContext::ReferencePosition;
}
}
if prefix.contains(':') {
let after_colon = prefix.rsplit(':').next().unwrap_or("");
if after_colon.trim().is_empty() {
return CompletionContext::AfterColon;
}
}
let trimmed = prefix.trim();
if trimmed.is_empty() || !prefix.contains(':') {
return CompletionContext::KeyPosition;
}
CompletionContext::Unknown
}
fn collect_root_keys(ast: &AstNode) -> Vec<String> {
let mut keys = Vec::new();
match ast {
AstNode::Document { children, .. } => {
for child in children {
if let AstNode::Object { entries, .. } = child {
for entry in entries {
keys.push(entry.key.clone());
}
}
}
}
AstNode::Object { entries, .. } => {
for entry in entries {
keys.push(entry.key.clone());
}
}
_ => {}
}
keys
}
fn collect_all_key_paths(ast: &AstNode) -> Vec<String> {
let mut paths = Vec::new();
let mut current_path = Vec::new();
collect_key_paths_recursive(ast, &mut current_path, &mut paths);
paths
}
fn collect_key_paths_recursive(
node: &AstNode,
current_path: &mut Vec<String>,
paths: &mut Vec<String>,
) {
match node {
AstNode::Document { children, .. } => {
for child in children {
collect_key_paths_recursive(child, current_path, paths);
}
}
AstNode::Object { entries, .. } => {
for entry in entries {
current_path.push(entry.key.clone());
paths.push(current_path.join("."));
collect_key_paths_recursive(&entry.value, current_path, paths);
current_path.pop();
}
}
AstNode::Array { items, .. } => {
for item in items {
collect_key_paths_recursive(item, current_path, paths);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::parse_with_errors;
#[test]
fn test_completion_after_colon() {
let source = "enabled: ";
let (ast, _) = parse_with_errors(source);
if let Some(ast) = ast {
let completions = get_completions_at_position(&ast, source, 0, 9);
let labels: Vec<&str> = completions.iter().map(|c| c.label.as_str()).collect();
assert!(labels.contains(&"true"));
assert!(labels.contains(&"false"));
}
}
#[test]
fn test_completion_at_key_position() {
let source = "name: Alice\n";
let (ast, _) = parse_with_errors(source);
let ast = ast.expect("should parse");
let completions = get_completions_at_position(&ast, source, 1, 0);
let has_name = completions.iter().any(|c| c.label == "name");
assert!(has_name || completions.is_empty());
}
#[test]
fn test_completion_inside_reference() {
let source = "db:\n port: 5432\nconnection: ${d";
let (ast, _) = parse_with_errors(source);
let ast = ast.expect("should parse");
let completions = get_completions_at_position(&ast, source, 2, 15);
let labels: Vec<&str> = completions.iter().map(|c| c.label.as_str()).collect();
assert!(labels.contains(&"db"));
assert!(labels.contains(&"db.port"));
}
#[test]
fn test_completion_inside_env_reference() {
let source = "connection: ${env:P";
let (ast, _) = parse_with_errors(source);
let ast = ast.expect("should parse");
let completions = get_completions_at_position(&ast, source, 0, 19);
let labels: Vec<&str> = completions.iter().map(|c| c.label.as_str()).collect();
assert!(labels.contains(&"PATH") || !labels.is_empty());
}
}