use super::*;
#[derive(Debug)]
pub struct SemanticTokensUpdate {
pub path: PathBuf,
pub seq: u64,
pub generation: u64,
pub data: Vec<u32>,
pub legend: Arc<Vec<String>>,
pub is_full: bool,
}
impl LspManager {
pub fn request_semantic_tokens(&self, path: PathBuf, seq: u64) {
let generation = self.next_semantic_generation();
let _ = self.cmd_tx.send(Cmd::RequestSemanticTokens {
path,
seq,
generation,
});
}
pub(super) fn next_semantic_generation(&self) -> u64 {
self.semantic_generation
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
pub fn request_semantic_tokens_range(
&self,
path: PathBuf,
start_line: u32,
end: Position,
seq: u64,
) {
let generation = self.next_semantic_generation();
let _ = self.cmd_tx.send(Cmd::RequestSemanticTokensRange {
path,
start_line,
end,
seq,
generation,
});
}
pub fn drain_semantic_tokens(&self) -> Option<SemanticTokensUpdate> {
self.replies.semantic_tokens.try_recv().ok()
}
pub fn take_semantic_refresh(&self) -> bool {
self.semantic_refresh.swap(false, Ordering::Relaxed)
}
}
impl WorkerState {
pub(super) async fn request_semantic_tokens(
&mut self,
path: PathBuf,
seq: u64,
generation: u64,
tx: &std_mpsc::Sender<SemanticTokensUpdate>,
) {
let Some(doc) = self.docs.get(&path) else {
return;
};
let lang = doc.language;
let root = doc.project_root.clone();
self.ensure_clients(lang, &root).await;
let Some(clients) = self.clients.get(&(lang, root)) else {
return;
};
let pick = |c: &ManagedClient| {
c.semantic_legend
.clone()
.map(|leg| (c.name.clone(), c.client.clone(), leg))
};
let picked = clients
.iter()
.filter(|c| c.semantic_supports_range)
.find_map(&pick)
.or_else(|| clients.iter().find_map(&pick));
let Some((server_name, client_arc, legend)) = picked else {
return;
};
let Ok(uri) = Url::from_file_path(&path) else {
return;
};
let tx = tx.clone();
let path_clone = path.clone();
tokio::spawn(async move {
const BACKOFF_MS: [u64; 5] = [0, 80, 160, 320, 640];
let mut data: Vec<u32> = Vec::new();
for (attempt, delay) in BACKOFF_MS.iter().enumerate() {
if *delay > 0 {
tokio::time::sleep(std::time::Duration::from_millis(*delay)).await;
}
let mut client = client_arc.lock().await.requests();
let resp = client.semantic_tokens_full(uri.clone()).await;
drop(client);
data = match resp {
Ok(Some(SemanticTokensResult::Tokens(t))) => flatten_semantic_tokens(&t.data),
Ok(Some(SemanticTokensResult::Partial(p))) => flatten_semantic_tokens(&p.data),
Ok(None) => Vec::new(),
Err(e) => {
log_file::log(&format!("lsp[{server_name}] semantic_tokens error: {e}"));
Vec::new()
}
};
if !data.is_empty() {
if attempt > 0 {
log_file::log(&format!(
"semantic_tokens server={server_name} resolved on retry #{attempt} for {}",
path_clone.display()
));
}
break;
}
}
log_file::log(&format!(
"semantic_tokens response server={server_name} path={} tokens={}",
path_clone.display(),
data.len() / 5
));
let _ = tx.send(SemanticTokensUpdate {
path: path_clone,
seq,
generation,
data,
legend,
is_full: true,
});
});
}
pub(super) async fn request_semantic_tokens_range(
&mut self,
path: PathBuf,
start_line: u32,
end: Position,
seq: u64,
generation: u64,
tx: &std_mpsc::Sender<SemanticTokensUpdate>,
) {
let Some(doc) = self.docs.get(&path) else {
return;
};
let lang = doc.language;
let root = doc.project_root.clone();
self.ensure_clients(lang, &root).await;
let Some(clients) = self.clients.get(&(lang, root)) else {
return;
};
let picked = clients
.iter()
.filter(|c| c.semantic_supports_range)
.find_map(|c| {
c.semantic_legend
.clone()
.map(|leg| (c.name.clone(), c.client.clone(), leg))
});
let Some((server_name, client_arc, legend)) = picked else {
return;
};
let Ok(uri) = Url::from_file_path(&path) else {
return;
};
let tx = tx.clone();
let path_clone = path.clone();
tokio::spawn(async move {
let mut client = client_arc.lock().await.requests();
let resp = client.semantic_tokens_range(uri, start_line, end).await;
drop(client);
let data: Vec<u32> = match resp {
Ok(Some(SemanticTokensRangeResult::Tokens(t))) => flatten_semantic_tokens(&t.data),
Ok(Some(SemanticTokensRangeResult::Partial(p))) => flatten_semantic_tokens(&p.data),
Ok(None) => Vec::new(),
Err(e) => {
log_file::log(&format!(
"lsp[{server_name}] semantic_tokens_range error: {e}"
));
Vec::new()
}
};
log_file::log(&format!(
"semantic_tokens range response server={server_name} path={} lines={start_line}..{} tokens={}",
path_clone.display(),
end.line,
data.len() / 5
));
let _ = tx.send(SemanticTokensUpdate {
path: path_clone,
seq,
generation,
data,
legend,
is_full: false,
});
});
}
}
pub(super) fn semantic_legend_of(caps: &ServerCapabilities) -> Option<Vec<String>> {
let opts = match caps.semantic_tokens_provider.as_ref()? {
SemanticTokensServerCapabilities::SemanticTokensOptions(o) => o,
SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(o) => {
&o.semantic_tokens_options
}
};
let full_ok = matches!(
opts.full,
Some(SemanticTokensFullOptions::Bool(true)) | Some(SemanticTokensFullOptions::Delta { .. })
);
if !full_ok {
return None;
}
Some(
opts.legend
.token_types
.iter()
.map(|t| t.as_str().to_string())
.collect(),
)
}
pub(super) fn semantic_tokens_range_supported(caps: &ServerCapabilities) -> bool {
let opts = match caps.semantic_tokens_provider.as_ref() {
Some(SemanticTokensServerCapabilities::SemanticTokensOptions(o)) => o,
Some(SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(o)) => {
&o.semantic_tokens_options
}
None => return false,
};
matches!(opts.range, Some(true))
}
pub(super) fn flatten_semantic_tokens(tokens: &[lsp_types::SemanticToken]) -> Vec<u32> {
let mut out = Vec::with_capacity(tokens.len() * 5);
for t in tokens {
out.push(t.delta_line);
out.push(t.delta_start);
out.push(t.length);
out.push(t.token_type);
out.push(t.token_modifiers_bitset);
}
out
}