| @@ -0,0 +1,494 @@ |
| 1 | +//! Semantic tokens: every meaningful token of a file, classified from the |
| 2 | +//! real parse and from name resolution. Editors color code with them, so |
| 3 | +//! `io.println` shows `io` as a module and `println` as a function, and a |
| 4 | +//! parameter looks different from a local or a constructor. |
| 5 | +//! |
| 6 | +//! Lexical classes (keywords, literals, comments, operators) come from the |
| 7 | +//! syntax tree. An identifier gets the class of what it refers to: the |
| 8 | +//! innermost resolved name containing it. Within a qualified name, the |
| 9 | +//! segments before the name are modules. Identifiers that nothing |
| 10 | +//! resolves fall back on their syntactic position. |
| 11 | + |
| 12 | +use std::collections::{HashMap, HashSet}; |
| 13 | + |
| 14 | +use tilc_hir::body::{Body, Expr, LocalId, Pat, PatId, Stmt}; |
| 15 | +use tilc_hir::{DefId, DefKind, Hir, TypeRef}; |
| 16 | +use tilc_span::{FileId, TextRange}; |
| 17 | +use tilc_syntax::{SyntaxKind, SyntaxNode, SyntaxToken}; |
| 18 | + |
| 19 | +use super::nav::{signature_types, visit_type_refs}; |
| 20 | +use crate::{Analysis, Db}; |
| 21 | + |
| 22 | +/// What a token is. The names follow the LSP's standard token types. |
| 23 | +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] |
| 24 | +pub enum TokenClass { |
| 25 | + Namespace, |
| 26 | + Type, |
| 27 | + Interface, |
| 28 | + TypeParameter, |
| 29 | + Parameter, |
| 30 | + Variable, |
| 31 | + Property, |
| 32 | + EnumMember, |
| 33 | + Function, |
| 34 | + Method, |
| 35 | + Keyword, |
| 36 | + Comment, |
| 37 | + String, |
| 38 | + Number, |
| 39 | + Operator, |
| 40 | + Decorator, |
| 41 | +} |
| 42 | + |
| 43 | +impl TokenClass { |
| 44 | + /// Every class, in the order of the LSP legend. |
| 45 | + pub const ALL: [TokenClass; 16] = [ |
| 46 | + TokenClass::Namespace, |
| 47 | + TokenClass::Type, |
| 48 | + TokenClass::Interface, |
| 49 | + TokenClass::TypeParameter, |
| 50 | + TokenClass::Parameter, |
| 51 | + TokenClass::Variable, |
| 52 | + TokenClass::Property, |
| 53 | + TokenClass::EnumMember, |
| 54 | + TokenClass::Function, |
| 55 | + TokenClass::Method, |
| 56 | + TokenClass::Keyword, |
| 57 | + TokenClass::Comment, |
| 58 | + TokenClass::String, |
| 59 | + TokenClass::Number, |
| 60 | + TokenClass::Operator, |
| 61 | + TokenClass::Decorator, |
| 62 | + ]; |
| 63 | + |
| 64 | + /// The LSP token type name. |
| 65 | + pub fn lsp_name(self) -> &'static str { |
| 66 | + match self { |
| 67 | + TokenClass::Namespace => "namespace", |
| 68 | + TokenClass::Type => "type", |
| 69 | + TokenClass::Interface => "interface", |
| 70 | + TokenClass::TypeParameter => "typeParameter", |
| 71 | + TokenClass::Parameter => "parameter", |
| 72 | + TokenClass::Variable => "variable", |
| 73 | + TokenClass::Property => "property", |
| 74 | + TokenClass::EnumMember => "enumMember", |
| 75 | + TokenClass::Function => "function", |
| 76 | + TokenClass::Method => "method", |
| 77 | + TokenClass::Keyword => "keyword", |
| 78 | + TokenClass::Comment => "comment", |
| 79 | + TokenClass::String => "string", |
| 80 | + TokenClass::Number => "number", |
| 81 | + TokenClass::Operator => "operator", |
| 82 | + TokenClass::Decorator => "decorator", |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +/// Modifier bits, in the order of [`MODIFIERS`]. |
| 88 | +pub const DECLARATION: u32 = 1; |
| 89 | +pub const DOCUMENTATION: u32 = 1 << 1; |
| 90 | +pub const DEFAULT_LIBRARY: u32 = 1 << 2; |
| 91 | +/// The LSP modifier names, by bit. |
| 92 | +pub const MODIFIERS: [&str; 3] = ["declaration", "documentation", "defaultLibrary"]; |
| 93 | + |
| 94 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 95 | +pub struct SemanticToken { |
| 96 | + pub range: TextRange, |
| 97 | + pub class: TokenClass, |
| 98 | + pub modifiers: u32, |
| 99 | +} |
| 100 | + |
| 101 | +/// The semantic tokens of `file`, in order. |
| 102 | +pub fn semantic_tokens(db: &Db, analysis: &Analysis, file: FileId) -> Vec<SemanticToken> { |
| 103 | + let Some(parse) = db.parse(file) else { |
| 104 | + return Vec::new(); |
| 105 | + }; |
| 106 | + let names = resolved_names(analysis, db, file); |
| 107 | + let mut out = Vec::new(); |
| 108 | + for element in parse.syntax().descendants_with_tokens() { |
| 109 | + let Some(token) = element.into_token() else { |
| 110 | + continue; |
| 111 | + }; |
| 112 | + if let Some(t) = classify(&token, &names) { |
| 113 | + out.push(t); |
| 114 | + } |
| 115 | + } |
| 116 | + out |
| 117 | +} |
| 118 | + |
| 119 | +/// A resolved name: its range in the file, and what the name it contains |
| 120 | +/// is. |
| 121 | +struct Resolved { |
| 122 | + range: TextRange, |
| 123 | + /// The identifier text that is the name itself (the segments before it |
| 124 | + /// are modules); `None` when the range is exactly one identifier. |
| 125 | + name: Option<String>, |
| 126 | + class: TokenClass, |
| 127 | + modifiers: u32, |
| 128 | +} |
| 129 | + |
| 130 | +fn def_class(hir: &Hir, def: DefId) -> TokenClass { |
| 131 | + match &hir.def(def).kind { |
| 132 | + DefKind::Fn(f) => match f.owner.map(|o| &hir.def(o).kind) { |
| 133 | + Some(DefKind::Trait(_) | DefKind::Impl(_)) => TokenClass::Method, |
| 134 | + _ => TokenClass::Function, |
| 135 | + }, |
| 136 | + DefKind::Op(_) => TokenClass::Method, |
| 137 | + DefKind::Ctor(_) => TokenClass::EnumMember, |
| 138 | + DefKind::Trait(_) | DefKind::Effect(_) => TokenClass::Interface, |
| 139 | + DefKind::Type(_) => TokenClass::Type, |
| 140 | + _ => TokenClass::Variable, |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +fn resolved_names(analysis: &Analysis, db: &Db, file: FileId) -> Vec<Resolved> { |
| 145 | + let hir = &analysis.hir; |
| 146 | + let sources = db.sources(); |
| 147 | + let library = |def: DefId| { |
| 148 | + let f = hir.modules[hir.def(def).module].file; |
| 149 | + if sources.get(f).path().starts_with('<') { |
| 150 | + DEFAULT_LIBRARY |
| 151 | + } else { |
| 152 | + 0 |
| 153 | + } |
| 154 | + }; |
| 155 | + let mut out = Vec::new(); |
| 156 | + let reference = |range: TextRange, def: DefId, out: &mut Vec<Resolved>| { |
| 157 | + out.push(Resolved { |
| 158 | + range, |
| 159 | + name: Some(hir.def(def).name.clone()), |
| 160 | + class: def_class(hir, def), |
| 161 | + modifiers: library(def), |
| 162 | + }); |
| 163 | + }; |
| 164 | + for (id, def) in hir.defs.iter() { |
| 165 | + if hir.modules[def.module].file != file { |
| 166 | + continue; |
| 167 | + } |
| 168 | + if !def.name.is_empty() && !matches!(def.kind, DefKind::Impl(_)) { |
| 169 | + out.push(Resolved { |
| 170 | + range: def.span.range, |
| 171 | + name: None, |
| 172 | + class: def_class(hir, id), |
| 173 | + modifiers: DECLARATION, |
| 174 | + }); |
| 175 | + } |
| 176 | + for tref in signature_types(&def.kind) { |
| 177 | + visit_type_refs(tref, &mut |range, target| { |
| 178 | + reference(range, target, &mut out) |
| 179 | + }); |
| 180 | + visit_type_vars(tref, &mut |range| { |
| 181 | + out.push(Resolved { |
| 182 | + range, |
| 183 | + name: None, |
| 184 | + class: TokenClass::TypeParameter, |
| 185 | + modifiers: 0, |
| 186 | + }) |
| 187 | + }); |
| 188 | + } |
| 189 | + let DefKind::Fn(f) = &def.kind else { continue }; |
| 190 | + let Some(body) = &f.body else { continue }; |
| 191 | + let params = parameter_locals(body); |
| 192 | + let local_class = |l: LocalId| { |
| 193 | + if params.contains(&l) { |
| 194 | + TokenClass::Parameter |
| 195 | + } else { |
| 196 | + TokenClass::Variable |
| 197 | + } |
| 198 | + }; |
| 199 | + for (l, local) in body.locals.iter() { |
| 200 | + out.push(Resolved { |
| 201 | + range: local.span, |
| 202 | + name: None, |
| 203 | + class: local_class(l), |
| 204 | + modifiers: DECLARATION, |
| 205 | + }); |
| 206 | + } |
| 207 | + for (e, expr) in body.exprs.iter() { |
| 208 | + let range = body.expr_span(e); |
| 209 | + match expr { |
| 210 | + Expr::Def(d) => reference(range, *d, &mut out), |
| 211 | + Expr::Local(l) => out.push(Resolved { |
| 212 | + range, |
| 213 | + name: Some(body.locals[*l].name.clone()), |
| 214 | + class: local_class(*l), |
| 215 | + modifiers: 0, |
| 216 | + }), |
| 217 | + Expr::Lambda { params, ret, .. } => { |
| 218 | + for tref in params |
| 219 | + .iter() |
| 220 | + .filter_map(|(_, t)| t.as_ref()) |
| 221 | + .chain(ret.iter()) |
| 222 | + { |
| 223 | + visit_type_refs(tref, &mut |r, d| reference(r, d, &mut out)); |
| 224 | + } |
| 225 | + } |
| 226 | + Expr::Block { stmts, .. } => { |
| 227 | + for stmt in stmts { |
| 228 | + if let Stmt::Let { ty: Some(tref), .. } = stmt { |
| 229 | + visit_type_refs(tref, &mut |r, d| reference(r, d, &mut out)); |
| 230 | + } |
| 231 | + } |
| 232 | + } |
| 233 | + _ => {} |
| 234 | + } |
| 235 | + } |
| 236 | + for (p, pat) in body.pats.iter() { |
| 237 | + if let Pat::Ctor { def: c, .. } = pat { |
| 238 | + reference(body.pat_span(p), *c, &mut out); |
| 239 | + } |
| 240 | + } |
| 241 | + } |
| 242 | + out |
| 243 | +} |
| 244 | + |
| 245 | +/// Locals bound by the parameters of the function and of its lambdas. |
| 246 | +fn parameter_locals(body: &Body) -> HashSet<LocalId> { |
| 247 | + let mut out = HashSet::new(); |
| 248 | + let mut pats: Vec<PatId> = body.params.clone(); |
| 249 | + for (_, expr) in body.exprs.iter() { |
| 250 | + if let Expr::Lambda { params, .. } = expr { |
| 251 | + pats.extend(params.iter().map(|(p, _)| *p)); |
| 252 | + } |
| 253 | + } |
| 254 | + while let Some(p) = pats.pop() { |
| 255 | + match &body.pats[p] { |
| 256 | + Pat::Bind(l) => { |
| 257 | + out.insert(*l); |
| 258 | + } |
| 259 | + Pat::As { pat, local } => { |
| 260 | + out.insert(*local); |
| 261 | + pats.push(*pat); |
| 262 | + } |
| 263 | + Pat::Ctor { args, .. } => pats.extend(args.iter().map(|a| a.pat)), |
| 264 | + Pat::Tuple(elems) | Pat::Or(elems) => pats.extend(elems.iter().copied()), |
| 265 | + Pat::List { elems, rest } => { |
| 266 | + pats.extend(elems.iter().copied()); |
| 267 | + if let Some(Some(l)) = rest { |
| 268 | + out.insert(*l); |
| 269 | + } |
| 270 | + } |
| 271 | + Pat::Missing | Pat::Wild | Pat::Lit { .. } => {} |
| 272 | + } |
| 273 | + } |
| 274 | + out |
| 275 | +} |
| 276 | + |
| 277 | +fn visit_type_vars(tref: &TypeRef, f: &mut impl FnMut(TextRange)) { |
| 278 | + match tref { |
| 279 | + TypeRef::Var { span, .. } => f(*span), |
| 280 | + TypeRef::Def { args, .. } => args.iter().for_each(|a| visit_type_vars(a, f)), |
| 281 | + TypeRef::Fn { |
| 282 | + params, |
| 283 | + ret, |
| 284 | + effects, |
| 285 | + .. |
| 286 | + } => { |
| 287 | + params.iter().for_each(|p| visit_type_vars(p, f)); |
| 288 | + visit_type_vars(ret, f); |
| 289 | + if let Some(row) = effects { |
| 290 | + row.labels.iter().for_each(|l| visit_type_vars(l, f)); |
| 291 | + if let Some(t) = &row.tail { |
| 292 | + visit_type_vars(t, f); |
| 293 | + } |
| 294 | + } |
| 295 | + } |
| 296 | + TypeRef::Tuple { elems, .. } => elems.iter().for_each(|e| visit_type_vars(e, f)), |
| 297 | + TypeRef::Error { .. } => {} |
| 298 | + } |
| 299 | +} |
| 300 | + |
| 301 | +fn classify(token: &SyntaxToken, names: &[Resolved]) -> Option<SemanticToken> { |
| 302 | + use SyntaxKind::*; |
| 303 | + let kind = token.kind(); |
| 304 | + let range = token.text_range(); |
| 305 | + let plain = |class| { |
| 306 | + Some(SemanticToken { |
| 307 | + range, |
| 308 | + class, |
| 309 | + modifiers: 0, |
| 310 | + }) |
| 311 | + }; |
| 312 | + if kind.is_keyword() { |
| 313 | + return plain(TokenClass::Keyword); |
| 314 | + } |
| 315 | + match kind { |
| 316 | + COMMENT => plain(TokenClass::Comment), |
| 317 | + DOC_COMMENT => Some(SemanticToken { |
| 318 | + range, |
| 319 | + class: TokenClass::Comment, |
| 320 | + modifiers: DOCUMENTATION, |
| 321 | + }), |
| 322 | + STRING | HTML_STRING => plain(TokenClass::String), |
| 323 | + INT | FLOAT => plain(TokenClass::Number), |
| 324 | + ARROW | L_ARROW | EQ | NEQ | LT | GT | LTEQ | GTEQ | LT_GT | PLUS | MINUS | STAR |
| 325 | + | SLASH | PERCENT | BANG | PIPE | PIPE_GT => plain(TokenClass::Operator), |
| 326 | + AT => plain(TokenClass::Decorator), |
| 327 | + HTML_NAME => { |
| 328 | + let parent = token.parent()?; |
| 329 | + let class = match parent.kind() { |
| 330 | + HTML_ATTR => TokenClass::Property, |
| 331 | + _ if is_component(token.text()) => TokenClass::Function, |
| 332 | + _ => TokenClass::Type, |
| 333 | + }; |
| 334 | + plain(class) |
| 335 | + } |
| 336 | + IDENT => ident(token, names), |
| 337 | + _ => None, |
| 338 | + } |
| 339 | +} |
| 340 | + |
| 341 | +/// An Uppercase or dotted tag calls a function (ADR 0009). |
| 342 | +fn is_component(tag: &str) -> bool { |
| 343 | + tag.starts_with(|c: char| c.is_ascii_uppercase()) || tag.contains('.') |
| 344 | +} |
| 345 | + |
| 346 | +fn ident(token: &SyntaxToken, names: &[Resolved]) -> Option<SemanticToken> { |
| 347 | + let range = token.text_range(); |
| 348 | + // The innermost resolved name containing the identifier. |
| 349 | + let best = names |
| 350 | + .iter() |
| 351 | + .filter(|r| r.range.contains_range(range)) |
| 352 | + .min_by_key(|r| r.range.len()); |
| 353 | + if let Some(r) = best { |
| 354 | + let is_name = match &r.name { |
| 355 | + None => true, |
| 356 | + Some(name) => token.text() == name || r.range == range, |
| 357 | + }; |
| 358 | + if is_name { |
| 359 | + return Some(SemanticToken { |
| 360 | + range, |
| 361 | + class: r.class, |
| 362 | + modifiers: r.modifiers, |
| 363 | + }); |
| 364 | + } |
| 365 | + // A qualifier before the name: `io` in `io.println`. |
| 366 | + if name_follows(token, r) { |
| 367 | + return Some(SemanticToken { |
| 368 | + range, |
| 369 | + class: TokenClass::Namespace, |
| 370 | + modifiers: 0, |
| 371 | + }); |
| 372 | + } |
| 373 | + } |
| 374 | + syntactic(token) |
| 375 | +} |
| 376 | + |
| 377 | +/// Whether the resolved name's identifier comes after `token` in its |
| 378 | +/// range (so `token` qualifies it). |
| 379 | +fn name_follows(token: &SyntaxToken, r: &Resolved) -> bool { |
| 380 | + let Some(name) = &r.name else { return false }; |
| 381 | + let mut next = token.next_token(); |
| 382 | + while let Some(t) = next { |
| 383 | + if !r.range.contains_range(t.text_range()) { |
| 384 | + return false; |
| 385 | + } |
| 386 | + if t.kind() == SyntaxKind::IDENT && t.text() == name { |
| 387 | + return true; |
| 388 | + } |
| 389 | + next = t.next_token(); |
| 390 | + } |
| 391 | + false |
| 392 | +} |
| 393 | + |
| 394 | +/// A class from where the identifier sits, when nothing resolved it. |
| 395 | +fn syntactic(token: &SyntaxToken) -> Option<SemanticToken> { |
| 396 | + use SyntaxKind::*; |
| 397 | + let parent: SyntaxNode = token.parent()?; |
| 398 | + let upper = token.text().starts_with(|c: char| c.is_ascii_uppercase()); |
| 399 | + let class = match parent.kind() { |
| 400 | + IMPORT_PATH => TokenClass::Namespace, |
| 401 | + ATTR => TokenClass::Decorator, |
| 402 | + LABEL => TokenClass::Parameter, |
| 403 | + HANDLER_CLAUSE if token.text() == "return" => TokenClass::Keyword, |
| 404 | + HANDLER_CLAUSE => TokenClass::Method, |
| 405 | + _ => match parent.parent().map(|g| g.kind()) { |
| 406 | + Some(FIELD_EXPR) => TokenClass::Property, |
| 407 | + Some(FIELD) => TokenClass::Property, |
| 408 | + Some(LABEL) => TokenClass::Parameter, |
| 409 | + Some(IMPORT_ITEM) if upper => TokenClass::Type, |
| 410 | + Some(IMPORT_ITEM) => TokenClass::Function, |
| 411 | + Some(IMPORT_PATH) => TokenClass::Namespace, |
| 412 | + Some(ATTR) => TokenClass::Decorator, |
| 413 | + _ if upper => TokenClass::Type, |
| 414 | + _ => return None, |
| 415 | + }, |
| 416 | + }; |
| 417 | + Some(SemanticToken { |
| 418 | + range: token.text_range(), |
| 419 | + class, |
| 420 | + modifiers: 0, |
| 421 | + }) |
| 422 | +} |
| 423 | + |
| 424 | +/// Classes of the identifiers of a file, for tests: `(text, class)`. |
| 425 | +pub fn token_classes( |
| 426 | + db: &Db, |
| 427 | + analysis: &Analysis, |
| 428 | + file: FileId, |
| 429 | +) -> HashMap<String, Vec<TokenClass>> { |
| 430 | + let text = db.sources().get(file).text().clone(); |
| 431 | + let mut out: HashMap<String, Vec<TokenClass>> = HashMap::new(); |
| 432 | + for t in semantic_tokens(db, analysis, file) { |
| 433 | + let s = text[usize::from(t.range.start())..usize::from(t.range.end())].to_owned(); |
| 434 | + out.entry(s).or_default().push(t.class); |
| 435 | + } |
| 436 | + out |
| 437 | +} |
| 438 | + |
| 439 | +#[cfg(test)] |
| 440 | +mod tests { |
| 441 | + use super::TokenClass as C; |
| 442 | + use super::*; |
| 443 | + |
| 444 | + #[test] |
| 445 | + fn classifies_names_by_what_they_are() { |
| 446 | + let mut db = Db::new(); |
| 447 | + let src = r#"import std/io |
| 448 | + |
| 449 | +/// Shapes. |
| 450 | +pub type Shape { Circle(radius: Int) } |
| 451 | + |
| 452 | +effect log { |
| 453 | + fn log(message: String) -> () |
| 454 | +} |
| 455 | + |
| 456 | +fn area(s: Shape) -> Int / <log> { |
| 457 | + log("area") |
| 458 | + match s { Circle(r) -> r * r } |
| 459 | +} |
| 460 | + |
| 461 | +pub fn main() -> () / <io> { |
| 462 | + let total = handle { area(Circle(radius: 2)) } with { log(m) -> io.println(m) } |
| 463 | + io.println(show(total)) |
| 464 | +} |
| 465 | + |
| 466 | +fn page(xs: List<a>) -> Html { |
| 467 | + <ul class="list">{"items"}</ul> |
| 468 | +} |
| 469 | +"#; |
| 470 | + let file = db.add_module("main", "main.til", src.into()); |
| 471 | + let analysis = db.analyze(); |
| 472 | + let classes = token_classes(&db, &analysis, file); |
| 473 | + let has = |text: &str, class: C| classes.get(text).is_some_and(|cs| cs.contains(&class)); |
| 474 | + assert!(has("io", C::Namespace), "{classes:?}"); |
| 475 | + assert!(has("println", C::Function)); |
| 476 | + assert!(has("Shape", C::Type)); |
| 477 | + assert!(has("Circle", C::EnumMember)); |
| 478 | + assert!(has("log", C::Interface), "the effect"); |
| 479 | + assert!(has("log", C::Method), "the operation"); |
| 480 | + assert!(has("area", C::Function)); |
| 481 | + assert!(has("s", C::Parameter)); |
| 482 | + assert!(has("total", C::Variable)); |
| 483 | + assert!(has("r", C::Variable)); |
| 484 | + assert!(has("radius", C::Parameter), "a label"); |
| 485 | + assert!(has("a", C::TypeParameter)); |
| 486 | + assert!(has("fn", C::Keyword)); |
| 487 | + assert!(has("\"area\"", C::String)); |
| 488 | + assert!(has("2", C::Number)); |
| 489 | + assert!(has("ul", C::Type), "an HTML tag"); |
| 490 | + assert!(has("class", C::Property), "an HTML attribute"); |
| 491 | + assert!(has("/// Shapes.", C::Comment)); |
| 492 | + assert!(has("->", C::Operator)); |
| 493 | + } |
| 494 | +} |