
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1209 · main · 10 min 03 s
1Étoiles
0Forks
0Issues
| 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::HashSet; |
| 13 | |
| 14 | use louise_hir::body::{Body, Expr, LocalId, Pat, PatId, Stmt}; |
| 15 | use louise_hir::{DefId, DefKind, Hir, TypeRef}; |
| 16 | use louise_span::{FileId, TextRange}; |
| 17 | use louise_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(_) | DefKind::EffectAlias(_) => TokenClass::Interface, |
| 139 | DefKind::Type(_) | DefKind::AssocType(_) => 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().filter(|(_, local)| !local.synthetic) { |
| 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) if !body.locals[*l].synthetic => 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(|p| p.ty.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.pat)); |
| 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 { name, args, span } => { |
| 280 | // `f<a>`: the variable is the name, before its arguments. |
| 281 | let len = louise_span::TextSize::of(name.as_str()).min(span.len()); |
| 282 | f(TextRange::at(span.start(), len)); |
| 283 | args.iter().for_each(|a| visit_type_vars(a, f)); |
| 284 | } |
| 285 | TypeRef::Def { args, .. } => args.iter().for_each(|a| visit_type_vars(a, f)), |
| 286 | TypeRef::Fn { |
| 287 | params, |
| 288 | ret, |
| 289 | effects, |
| 290 | .. |
| 291 | } => { |
| 292 | params.iter().for_each(|p| visit_type_vars(&p.ty, f)); |
| 293 | visit_type_vars(ret, f); |
| 294 | if let Some(row) = effects { |
| 295 | row.labels.iter().for_each(|l| visit_type_vars(l, f)); |
| 296 | if let Some(t) = &row.tail { |
| 297 | visit_type_vars(t, f); |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | TypeRef::Tuple { elems, .. } => elems.iter().for_each(|e| visit_type_vars(e, f)), |
| 302 | TypeRef::Row { row, .. } => { |
| 303 | row.labels.iter().for_each(|l| visit_type_vars(l, f)); |
| 304 | if let Some(t) = &row.tail { |
| 305 | visit_type_vars(t, f); |
| 306 | } |
| 307 | } |
| 308 | TypeRef::Error { .. } => {} |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | fn classify(token: &SyntaxToken, names: &[Resolved]) -> Option<SemanticToken> { |
| 313 | use SyntaxKind::*; |
| 314 | let kind = token.kind(); |
| 315 | let range = token.text_range(); |
| 316 | let plain = |class| { |
| 317 | Some(SemanticToken { |
| 318 | range, |
| 319 | class, |
| 320 | modifiers: 0, |
| 321 | }) |
| 322 | }; |
| 323 | if kind.is_keyword() { |
| 324 | return plain(TokenClass::Keyword); |
| 325 | } |
| 326 | match kind { |
| 327 | COMMENT => plain(TokenClass::Comment), |
| 328 | DOC_COMMENT => Some(SemanticToken { |
| 329 | range, |
| 330 | class: TokenClass::Comment, |
| 331 | modifiers: DOCUMENTATION, |
| 332 | }), |
| 333 | STRING | HTML_STRING | STRING_START | STRING_TEXT | STRING_END => plain(TokenClass::String), |
| 334 | TEMPLATE | TEMPLATE_START | TEMPLATE_TEXT | TEMPLATE_END => plain(TokenClass::String), |
| 335 | INT | FLOAT => plain(TokenClass::Number), |
| 336 | ARROW | L_ARROW | EQ | NEQ | LT | GT | LTEQ | GTEQ | LT_GT | PLUS | MINUS | STAR |
| 337 | | SLASH | PERCENT | BANG | PIPE | PIPE_GT => plain(TokenClass::Operator), |
| 338 | AT => plain(TokenClass::Decorator), |
| 339 | HTML_NAME => { |
| 340 | let parent = token.parent()?; |
| 341 | let class = match parent.kind() { |
| 342 | HTML_ATTR => TokenClass::Property, |
| 343 | _ if is_component(token.text()) => TokenClass::Function, |
| 344 | _ => TokenClass::Type, |
| 345 | }; |
| 346 | plain(class) |
| 347 | } |
| 348 | IDENT => ident(token, names), |
| 349 | _ => None, |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | /// An Uppercase or dotted tag calls a function (ADR 0009). |
| 354 | fn is_component(tag: &str) -> bool { |
| 355 | tag.starts_with(|c: char| c.is_ascii_uppercase()) || tag.contains('.') |
| 356 | } |
| 357 | |
| 358 | fn ident(token: &SyntaxToken, names: &[Resolved]) -> Option<SemanticToken> { |
| 359 | let range = token.text_range(); |
| 360 | // The innermost resolved name containing the identifier. |
| 361 | let best = names |
| 362 | .iter() |
| 363 | .filter(|r| r.range.contains_range(range)) |
| 364 | .min_by_key(|r| r.range.len()); |
| 365 | if let Some(r) = best { |
| 366 | let is_name = match &r.name { |
| 367 | None => true, |
| 368 | Some(name) => token.text() == name || r.range == range, |
| 369 | }; |
| 370 | if is_name { |
| 371 | return Some(SemanticToken { |
| 372 | range, |
| 373 | class: r.class, |
| 374 | modifiers: r.modifiers, |
| 375 | }); |
| 376 | } |
| 377 | // A qualifier before the name: `io` in `io.println`. |
| 378 | if name_follows(token, r) { |
| 379 | return Some(SemanticToken { |
| 380 | range, |
| 381 | class: TokenClass::Namespace, |
| 382 | modifiers: 0, |
| 383 | }); |
| 384 | } |
| 385 | } |
| 386 | syntactic(token) |
| 387 | } |
| 388 | |
| 389 | /// Whether the resolved name's identifier comes after `token` in its |
| 390 | /// range (so `token` qualifies it). |
| 391 | fn name_follows(token: &SyntaxToken, r: &Resolved) -> bool { |
| 392 | let Some(name) = &r.name else { return false }; |
| 393 | let mut next = token.next_token(); |
| 394 | while let Some(t) = next { |
| 395 | if !r.range.contains_range(t.text_range()) { |
| 396 | return false; |
| 397 | } |
| 398 | if t.kind() == SyntaxKind::IDENT && t.text() == name { |
| 399 | return true; |
| 400 | } |
| 401 | next = t.next_token(); |
| 402 | } |
| 403 | false |
| 404 | } |
| 405 | |
| 406 | /// A class from where the identifier sits, when nothing resolved it. |
| 407 | fn syntactic(token: &SyntaxToken) -> Option<SemanticToken> { |
| 408 | use SyntaxKind::*; |
| 409 | let parent: SyntaxNode = token.parent()?; |
| 410 | let upper = token.text().starts_with(|c: char| c.is_ascii_uppercase()); |
| 411 | let class = match parent.kind() { |
| 412 | IMPORT_PATH => TokenClass::Namespace, |
| 413 | ATTR => TokenClass::Decorator, |
| 414 | LABEL => TokenClass::Parameter, |
| 415 | HANDLER_CLAUSE => TokenClass::Method, |
| 416 | _ => match parent.parent().map(|g| g.kind()) { |
| 417 | Some(FIELD_EXPR) => TokenClass::Property, |
| 418 | Some(FIELD) => TokenClass::Property, |
| 419 | Some(LABEL) => TokenClass::Parameter, |
| 420 | Some(IMPORT_ITEM) if upper => TokenClass::Type, |
| 421 | Some(IMPORT_ITEM) => TokenClass::Function, |
| 422 | Some(IMPORT_PATH) => TokenClass::Namespace, |
| 423 | Some(ATTR) => TokenClass::Decorator, |
| 424 | _ if upper => TokenClass::Type, |
| 425 | _ => return None, |
| 426 | }, |
| 427 | }; |
| 428 | Some(SemanticToken { |
| 429 | range: token.text_range(), |
| 430 | class, |
| 431 | modifiers: 0, |
| 432 | }) |
| 433 | } |
| 434 | |
| 435 | /// Classes of the tokens of a file, by text (for tests). |
| 436 | #[cfg(test)] |
| 437 | pub fn token_classes( |
| 438 | db: &Db, |
| 439 | analysis: &Analysis, |
| 440 | file: FileId, |
| 441 | ) -> std::collections::HashMap<String, Vec<TokenClass>> { |
| 442 | let text = db.sources().get(file).text().clone(); |
| 443 | let mut out: std::collections::HashMap<String, Vec<TokenClass>> = Default::default(); |
| 444 | for t in semantic_tokens(db, analysis, file) { |
| 445 | let s = text[usize::from(t.range.start())..usize::from(t.range.end())].to_owned(); |
| 446 | out.entry(s).or_default().push(t.class); |
| 447 | } |
| 448 | out |
| 449 | } |
| 450 | |
| 451 | #[cfg(test)] |
| 452 | mod tests { |
| 453 | use super::TokenClass as C; |
| 454 | use super::*; |
| 455 | |
| 456 | #[test] |
| 457 | fn classifies_names_by_what_they_are() { |
| 458 | let mut db = Db::new(); |
| 459 | let src = r#"import std/io |
| 460 | |
| 461 | /// Shapes. |
| 462 | pub type Shape { Circle(radius: Int) } |
| 463 | |
| 464 | effect log { |
| 465 | fn log :: message: String -> () |
| 466 | } |
| 467 | |
| 468 | fn area :: s: Shape -> Int / <log> { |
| 469 | log "area" |
| 470 | match s { |
| 471 | Circle(r) -> r * r |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | pub fn main :: -> () / <io> { |
| 476 | let total = handle { area Circle(radius: 2) } with { |
| 477 | log m -> io.println m |
| 478 | } |
| 479 | io.println (show total) |
| 480 | } |
| 481 | |
| 482 | fn page :: xs: List<a> -> Html { |
| 483 | <ul class="list">{"items"}</ul> |
| 484 | } |
| 485 | "#; |
| 486 | let file = db.add_module("main", "main.lse", src.into()); |
| 487 | let analysis = db.analyze(); |
| 488 | let classes = token_classes(&db, &analysis, file); |
| 489 | let has = |text: &str, class: C| classes.get(text).is_some_and(|cs| cs.contains(&class)); |
| 490 | assert!(has("io", C::Namespace), "{classes:?}"); |
| 491 | assert!(has("println", C::Function)); |
| 492 | assert!(has("Shape", C::Type)); |
| 493 | assert!(has("Circle", C::EnumMember)); |
| 494 | assert!(has("log", C::Interface), "the effect"); |
| 495 | assert!(has("log", C::Method), "the operation"); |
| 496 | assert!(has("area", C::Function)); |
| 497 | assert!(has("s", C::Parameter)); |
| 498 | assert!(has("total", C::Variable)); |
| 499 | assert!(has("r", C::Variable)); |
| 500 | assert!(has("radius", C::Parameter), "a label"); |
| 501 | assert!(has("a", C::TypeParameter)); |
| 502 | assert!(has("fn", C::Keyword)); |
| 503 | assert!(has("\"area\"", C::String)); |
| 504 | assert!(has("2", C::Number)); |
| 505 | assert!(has("ul", C::Type), "an HTML tag"); |
| 506 | assert!(has("class", C::Property), "an HTML attribute"); |
| 507 | assert!(has("/// Shapes.", C::Comment)); |
| 508 | assert!(has("->", C::Operator)); |
| 509 | } |
| 510 | } |