1use std::path::Path;
8
9use bynk_check::index::{ProjectIndex, SymbolKind};
10use bynk_syntax::span::Span;
11
12pub fn semantic_tokens_legend() -> tower_lsp::lsp_types::SemanticTokensLegend {
21 use bynk_syntax::semantic_tokens::{TOKEN_MODIFIERS, TOKEN_TYPES};
22 use tower_lsp::lsp_types::{SemanticTokenModifier, SemanticTokenType, SemanticTokensLegend};
23 SemanticTokensLegend {
24 token_types: TOKEN_TYPES
25 .iter()
26 .map(|n| SemanticTokenType::new(n))
27 .collect(),
28 token_modifiers: TOKEN_MODIFIERS
29 .iter()
30 .map(|n| SemanticTokenModifier::new(n))
31 .collect(),
32 }
33}
34
35fn token_type_index(kind: SymbolKind) -> u32 {
37 match kind {
38 SymbolKind::Type => 0,
39 SymbolKind::Fn => 1,
40 SymbolKind::Capability => 2,
41 SymbolKind::Service => 3,
42 SymbolKind::Agent => 4,
43 SymbolKind::Provider => 5,
44 SymbolKind::Method => 7,
46 SymbolKind::CapabilityOp => 7,
48 SymbolKind::Field => 8,
49 SymbolKind::Actor => 9,
51 SymbolKind::Handler => 7,
53 SymbolKind::Messages => 11,
55 SymbolKind::Asset => 13,
57 SymbolKind::Embed => 14,
59 SymbolKind::Const => 16,
61 }
62}
63
64const TOK_LOCAL: u32 = 6;
66
67pub const TOK_DECORATOR: u32 = 10;
70
71pub const TOK_INTERFACE: u32 = 15;
73
74pub const TOK_METHOD: u32 = 7;
76
77pub const TOK_PROPERTY: u32 = 8;
79
80pub const TOK_KEYWORD: u32 = 17;
83
84pub const TOK_ESCAPE: u32 = 18;
87
88pub const TOK_STRING: u32 = 19;
90
91const MOD_DECLARATION: u32 = 1 << 0;
92const MOD_REFINED: u32 = 1 << 1;
93const MOD_OPAQUE: u32 = 1 << 2;
94const MOD_PLATFORM_NATIVE: u32 = 1 << 3;
95
96fn modifier_bits(m: bynk_check::index::SymbolModifiers) -> u32 {
97 (if m.refined { MOD_REFINED } else { 0 })
98 | (if m.opaque { MOD_OPAQUE } else { 0 })
99 | (if m.platform_native {
100 MOD_PLATFORM_NATIVE
101 } else {
102 0
103 })
104}
105
106pub fn semantic_tokens(
113 index: &ProjectIndex,
114 local_tokens: &[(Span, bool)],
115 syntax_tokens: &[(Span, u32)],
116 path: &Path,
117 text: &str,
118 range: Option<Span>,
119) -> Vec<tower_lsp::lsp_types::SemanticToken> {
120 let in_scope = |span: Span| {
121 span.end <= text.len() && range.is_none_or(|r| span.end > r.start && span.start < r.end)
122 };
123 let mut raw: Vec<(Span, u32, u32)> = Vec::new();
124 for (key, entry) in &index.symbols {
125 if entry.call_only {
128 continue;
129 }
130 let ty = token_type_index(key.kind);
131 let mods = modifier_bits(entry.modifiers);
132 if let Some(def) = &entry.def
133 && def.path == path
134 && in_scope(def.span)
135 {
136 raw.push((def.span, ty, mods | MOD_DECLARATION));
137 }
138 for site in &entry.refs {
139 if site.path == path && in_scope(site.span) {
140 raw.push((site.span, ty, mods));
141 }
142 }
143 }
144 for fr in &index.foreign_refs {
145 if fr.site.path == path && in_scope(fr.site.span) {
146 raw.push((
147 fr.site.span,
148 token_type_index(fr.kind),
149 modifier_bits(fr.modifiers),
150 ));
151 }
152 }
153 for &(span, is_decl) in local_tokens {
158 if in_scope(span) {
159 raw.push((span, TOK_LOCAL, if is_decl { MOD_DECLARATION } else { 0 }));
160 }
161 }
162 for &(span, ty) in syntax_tokens {
170 if in_scope(span) {
171 raw.push((span, ty, 0));
172 }
173 }
174 raw.sort_by_key(|(span, _, _)| (span.start, span.end));
177 raw.dedup_by_key(|(span, _, _)| (span.start, span.end));
181 let mut data = Vec::with_capacity(raw.len());
182 let positions = crate::position::PositionMap::new(text);
186 let (mut prev_line, mut prev_start) = (0u32, 0u32);
187 for (span, token_type, token_modifiers_bitset) in raw {
188 let pos = positions.position(span.start);
189 let delta_line = pos.line - prev_line;
190 let delta_start = if delta_line == 0 {
191 pos.character - prev_start
192 } else {
193 pos.character
194 };
195 data.push(tower_lsp::lsp_types::SemanticToken {
196 delta_line,
197 delta_start,
198 length: text[span.range()].encode_utf16().count() as u32,
201 token_type,
202 token_modifiers_bitset,
203 });
204 prev_line = pos.line;
205 prev_start = pos.character;
206 }
207 data
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use bynk_check::index::{SiteRef, SymbolEntry, SymbolKey};
214 use std::path::PathBuf;
215
216 fn site(path: &str, start: usize, end: usize) -> SiteRef {
217 SiteRef {
218 path: PathBuf::from(path),
219 span: Span::new(start, end),
220 }
221 }
222
223 fn key(unit: &str, kind: SymbolKind, name: &str) -> SymbolKey {
224 SymbolKey {
225 unit: unit.into(),
226 kind,
227 name: name.into(),
228 }
229 }
230
231 fn index_with(entries: Vec<(SymbolKey, SiteRef, Vec<SiteRef>)>) -> ProjectIndex {
232 let mut index = ProjectIndex::default();
233 for (k, def, refs) in entries {
234 index.symbols.insert(
235 k,
236 SymbolEntry {
237 def: Some(def),
238 refs,
239 ..Default::default()
240 },
241 );
242 }
243 index
244 }
245
246 #[test]
252 fn legend_is_frozen() {
253 let legend = semantic_tokens_legend();
254 let types: Vec<&str> = legend.token_types.iter().map(|t| t.as_str()).collect();
255 assert_eq!(
256 types,
257 [
258 "type",
259 "function",
260 "capability",
261 "service",
262 "agent",
263 "provider",
264 "variable", "method", "property", "actor", "decorator", "messages", "comment", "asset", "embed", "interface", "constant", "keyword", "escape", "string", ]
279 );
280 let modifiers: Vec<&str> = legend.token_modifiers.iter().map(|m| m.as_str()).collect();
281 assert_eq!(
282 modifiers,
283 [
284 "declaration",
285 "refined",
286 "opaque",
287 "platformNative",
288 "documentation"
289 ]
290 );
291 }
292
293 #[test]
297 fn doc_lines_get_no_semantic_token() {
298 let text = "commons m\n\n --- A doc.\n// a comment\ntype T = Int\n";
299 let tokens = semantic_tokens(
300 &ProjectIndex::default(),
301 &[],
302 &[],
303 Path::new("a.bynk"),
304 text,
305 None,
306 );
307 assert!(tokens.is_empty(), "{tokens:?}");
308 let legend = semantic_tokens_legend();
309 assert_eq!(legend.token_types[12].as_str(), "comment");
310 assert_eq!(legend.token_modifiers[4].as_str(), "documentation");
311 }
312
313 #[test]
317 fn derives_and_bound_constraint_names_are_interface_tokens() {
318 let text = "commons m\n\ntype P = Int derives Ord\nfn f[T: Eq + Ord](a: T) -> T { a }\n";
319 let syntax: Vec<(Span, u32)> = crate::symbols::constraint_token_spans(text)
320 .into_iter()
321 .map(|s| (s, TOK_INTERFACE))
322 .collect();
323 let tokens = semantic_tokens(
324 &ProjectIndex::default(),
325 &[],
326 &syntax,
327 Path::new("a.bynk"),
328 text,
329 None,
330 );
331 assert_eq!(tokens.len(), 3, "{tokens:?}");
332 assert!(tokens.iter().all(|t| t.token_type == TOK_INTERFACE));
333 assert_eq!(
335 (
336 tokens[0].delta_line,
337 tokens[0].delta_start,
338 tokens[0].length
339 ),
340 (2, 21, 3)
341 );
342 }
343
344 #[test]
345 fn tokens_are_delta_encoded_with_modifier_bitsets() {
346 let text = "type Age = Int\nfn f(a: Age) -> Age {}\n";
349 let mut index = index_with(vec![(
350 key("shop", SymbolKind::Type, "Age"),
351 site("a.bynk", 5, 8),
352 vec![site("a.bynk", 23, 26), site("a.bynk", 31, 34)],
353 )]);
354 index
355 .symbols
356 .get_mut(&key("shop", SymbolKind::Type, "Age"))
357 .unwrap()
358 .modifiers = bynk_check::index::SymbolModifiers {
359 refined: true,
360 ..Default::default()
361 };
362 let tokens = semantic_tokens(&index, &[], &[], Path::new("a.bynk"), text, None);
363 assert_eq!(tokens.len(), 3);
364 assert_eq!(
366 (
367 tokens[0].delta_line,
368 tokens[0].delta_start,
369 tokens[0].length
370 ),
371 (0, 5, 3)
372 );
373 assert_eq!(tokens[0].token_type, 0);
374 assert_eq!(tokens[0].token_modifiers_bitset, 0b0011);
375 assert_eq!(
377 (
378 tokens[1].delta_line,
379 tokens[1].delta_start,
380 tokens[1].length
381 ),
382 (1, 8, 3)
383 );
384 assert_eq!(tokens[1].token_modifiers_bitset, 0b0010);
385 assert_eq!(
387 (
388 tokens[2].delta_line,
389 tokens[2].delta_start,
390 tokens[2].length
391 ),
392 (0, 8, 3)
393 );
394 }
395
396 #[test]
399 fn call_only_service_handler_adds_no_tokens() {
400 let mut index = ProjectIndex::default();
401 index.symbols.insert(
402 SymbolKey {
403 unit: "u".into(),
404 kind: SymbolKind::Service,
405 name: "charge".into(),
406 },
407 SymbolEntry {
408 def: Some(site("a.bynk", 0, 6)),
409 refs: vec![site("a.bynk", 20, 26)],
410 ..Default::default()
411 },
412 );
413 index.symbols.insert(
414 SymbolKey {
415 unit: "u".into(),
416 kind: SymbolKind::Handler,
417 name: "charge.call".into(),
418 },
419 SymbolEntry {
420 def: Some(site("a.bynk", 10, 12)),
421 refs: vec![site("a.bynk", 20, 26)],
422 call_only: true,
423 ..Default::default()
424 },
425 );
426 let toks = semantic_tokens(&index, &[], &[], Path::new("a.bynk"), &" ".repeat(40), None);
427 assert_eq!(toks.len(), 2, "service def + service call site only");
428 assert!(toks.iter().all(|t| t.token_type == 3));
429 }
430
431 #[test]
432 fn foreign_refs_emit_tokens_and_range_filters() {
433 let text = "given Kv {\n Kv.get(k)\n}\n";
434 let mut index = ProjectIndex::default();
435 index.foreign_refs.push(bynk_check::index::ForeignRef {
436 site: site("a.bynk", 6, 8),
437 kind: SymbolKind::Capability,
438 modifiers: bynk_check::index::SymbolModifiers {
439 platform_native: true,
440 ..Default::default()
441 },
442 });
443 index.foreign_refs.push(bynk_check::index::ForeignRef {
444 site: site("a.bynk", 13, 15),
445 kind: SymbolKind::Capability,
446 modifiers: bynk_check::index::SymbolModifiers {
447 platform_native: true,
448 ..Default::default()
449 },
450 });
451 let all = semantic_tokens(&index, &[], &[], Path::new("a.bynk"), text, None);
452 assert_eq!(all.len(), 2);
453 assert_eq!(all[0].token_type, 2); assert_eq!(all[0].token_modifiers_bitset, 0b1000); let ranged = semantic_tokens(
457 &index,
458 &[],
459 &[],
460 Path::new("a.bynk"),
461 text,
462 Some(Span::new(0, 10)),
463 );
464 assert_eq!(ranged.len(), 1);
465 assert!(semantic_tokens(&index, &[], &[], Path::new("b.bynk"), text, None).is_empty());
467 assert!(
468 semantic_tokens(
469 &ProjectIndex::default(),
470 &[],
471 &[],
472 Path::new("a.bynk"),
473 text,
474 None
475 )
476 .is_empty()
477 );
478 }
479}