
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 | //! Navigation: go to definition, document symbols. |
| 2 | |
| 3 | use louise_hir::body::{Body, Expr, Pat, Stmt}; |
| 4 | use louise_hir::{DefId, DefKind, FnSig, Hir, TypeBody, TypeRef}; |
| 5 | use louise_span::{FileId, Span, TextRange, TextSize}; |
| 6 | |
| 7 | use crate::Analysis; |
| 8 | |
| 9 | /// Where the name at `offset` is defined. `None` for names defined in the |
| 10 | /// embedded standard library (it has no file to open). |
| 11 | pub fn definition( |
| 12 | analysis: &Analysis, |
| 13 | sources: &louise_span::SourceDb, |
| 14 | file: FileId, |
| 15 | offset: TextSize, |
| 16 | ) -> Option<Span> { |
| 17 | let hir = &analysis.hir; |
| 18 | let mut best: Option<(TextRange, Span)> = None; |
| 19 | let mut consider = |range: TextRange, target: Span| { |
| 20 | if range.contains_inclusive(offset) |
| 21 | && best.as_ref().is_none_or(|(r, _)| range.len() < r.len()) |
| 22 | { |
| 23 | best = Some((range, target)); |
| 24 | } |
| 25 | }; |
| 26 | // Alias uses first: their members are spliced at the same range, and |
| 27 | // the alias is the better target (ADR 0044). |
| 28 | for (m, range, alias) in &hir.alias_uses { |
| 29 | if hir.modules[*m].file == file { |
| 30 | consider(*range, hir.def(*alias).span); |
| 31 | } |
| 32 | } |
| 33 | for (_, def) in hir.defs.iter() { |
| 34 | if hir.modules[def.module].file != file { |
| 35 | continue; |
| 36 | } |
| 37 | if !def.name.is_empty() { |
| 38 | consider(def.span.range, def.span); |
| 39 | } |
| 40 | for tref in signature_types(&def.kind) { |
| 41 | visit_type_refs(tref, &mut |range, target| { |
| 42 | consider(range, hir.def(target).span) |
| 43 | }); |
| 44 | } |
| 45 | if let DefKind::Fn(f) = &def.kind |
| 46 | && let Some(body) = &f.body |
| 47 | { |
| 48 | body_targets(hir, body, file, &mut consider); |
| 49 | } |
| 50 | } |
| 51 | let (_, target) = best?; |
| 52 | (!sources.get(target.file).path().starts_with('<')).then_some(target) |
| 53 | } |
| 54 | |
| 55 | /// What a name refers to: an item, or a local of a function's body. |
| 56 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 57 | enum Target { |
| 58 | Def(DefId), |
| 59 | Local(DefId, louise_hir::body::LocalId), |
| 60 | } |
| 61 | |
| 62 | /// Every place (outside the embedded standard library) that names what |
| 63 | /// the name at `offset` names, declaration included, in source order. |
| 64 | pub fn references( |
| 65 | analysis: &Analysis, |
| 66 | sources: &louise_span::SourceDb, |
| 67 | file: FileId, |
| 68 | offset: TextSize, |
| 69 | ) -> Vec<Span> { |
| 70 | let hir = &analysis.hir; |
| 71 | // What is at `offset` (the innermost name). |
| 72 | let mut best: Option<(TextRange, Target)> = None; |
| 73 | let mut consider = |range: TextRange, target: Target| { |
| 74 | if range.contains_inclusive(offset) |
| 75 | && best.as_ref().is_none_or(|(r, _)| range.len() < r.len()) |
| 76 | { |
| 77 | best = Some((range, target)); |
| 78 | } |
| 79 | }; |
| 80 | // Alias uses first: their members are spliced at the same range, and |
| 81 | // the alias is the better target (ADR 0044). |
| 82 | for (m, range, alias) in &hir.alias_uses { |
| 83 | if hir.modules[*m].file == file { |
| 84 | consider(*range, Target::Def(*alias)); |
| 85 | } |
| 86 | } |
| 87 | for (id, def) in hir.defs.iter() { |
| 88 | if hir.modules[def.module].file != file { |
| 89 | continue; |
| 90 | } |
| 91 | if !def.name.is_empty() { |
| 92 | consider(def.span.range, Target::Def(id)); |
| 93 | } |
| 94 | names_in(hir, id, &mut |_, range, target| consider(range, target)); |
| 95 | } |
| 96 | let Some((_, target)) = best else { |
| 97 | return Vec::new(); |
| 98 | }; |
| 99 | // Everywhere it is named. |
| 100 | let mut out: Vec<Span> = Vec::new(); |
| 101 | if let Target::Def(d) = target { |
| 102 | for (m, range, alias) in &hir.alias_uses { |
| 103 | if *alias == d { |
| 104 | out.push(Span { |
| 105 | file: hir.modules[*m].file, |
| 106 | range: *range, |
| 107 | }); |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | for (id, def) in hir.defs.iter() { |
| 112 | if sources |
| 113 | .get(hir.modules[def.module].file) |
| 114 | .path() |
| 115 | .starts_with('<') |
| 116 | { |
| 117 | continue; |
| 118 | } |
| 119 | if target == Target::Def(id) { |
| 120 | out.push(def.span); |
| 121 | } |
| 122 | names_in(hir, id, &mut |f, range, t| { |
| 123 | if t == target { |
| 124 | out.push(Span { file: f, range }); |
| 125 | } |
| 126 | }); |
| 127 | } |
| 128 | out.sort_by_key(|s| (s.file, s.range.start())); |
| 129 | out.dedup(); |
| 130 | out |
| 131 | } |
| 132 | |
| 133 | /// The names written in item `id` (its signature and body) and what each |
| 134 | /// refers to. |
| 135 | fn names_in(hir: &Hir, id: DefId, f: &mut impl FnMut(FileId, TextRange, Target)) { |
| 136 | let def = hir.def(id); |
| 137 | let file = hir.modules[def.module].file; |
| 138 | for tref in signature_types(&def.kind) { |
| 139 | visit_type_refs(tref, &mut |range, target| { |
| 140 | f(file, range, Target::Def(target)) |
| 141 | }); |
| 142 | } |
| 143 | let DefKind::Fn(func) = &def.kind else { return }; |
| 144 | let Some(body) = &func.body else { return }; |
| 145 | for (local_id, local) in body.locals.iter().filter(|(_, local)| !local.synthetic) { |
| 146 | f(file, local.span, Target::Local(id, local_id)); |
| 147 | } |
| 148 | for (e, expr) in body.exprs.iter() { |
| 149 | let range = body.expr_span(e); |
| 150 | match expr { |
| 151 | Expr::Def(d) => f(file, range, Target::Def(*d)), |
| 152 | Expr::Local(l) if !body.locals[*l].synthetic => f(file, range, Target::Local(id, *l)), |
| 153 | Expr::Lambda { params, ret, .. } => { |
| 154 | for tref in params |
| 155 | .iter() |
| 156 | .filter_map(|p| p.ty.as_ref()) |
| 157 | .chain(ret.iter()) |
| 158 | { |
| 159 | visit_type_refs(tref, &mut |r, d| f(file, r, Target::Def(d))); |
| 160 | } |
| 161 | } |
| 162 | Expr::Block { stmts, .. } => { |
| 163 | for stmt in stmts { |
| 164 | if let Stmt::Let { ty: Some(tref), .. } = stmt { |
| 165 | visit_type_refs(tref, &mut |r, d| f(file, r, Target::Def(d))); |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | _ => {} |
| 170 | } |
| 171 | } |
| 172 | for (p, pat) in body.pats.iter() { |
| 173 | if let Pat::Ctor { def: c, .. } = pat { |
| 174 | let range = body.pat_span(p); |
| 175 | let name_len = TextSize::new(hir.def(*c).name.len() as u32); |
| 176 | f( |
| 177 | file, |
| 178 | TextRange::at(range.start(), name_len.min(range.len())), |
| 179 | Target::Def(*c), |
| 180 | ); |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | /// Type syntax written in an item's signature. |
| 186 | pub(super) fn signature_types(kind: &DefKind) -> Vec<&TypeRef> { |
| 187 | fn sig_types<'a>(s: &'a FnSig, out: &mut Vec<&'a TypeRef>) { |
| 188 | out.extend(s.params.iter().filter_map(|p| p.ty.as_ref())); |
| 189 | out.extend(s.ret.iter()); |
| 190 | out.extend(s.constraints.iter()); |
| 191 | if let Some(row) = &s.effects { |
| 192 | out.extend(row.labels.iter()); |
| 193 | } |
| 194 | } |
| 195 | let mut out = Vec::new(); |
| 196 | match kind { |
| 197 | DefKind::Fn(f) => sig_types(&f.sig, &mut out), |
| 198 | DefKind::Op(o) => sig_types(&o.sig, &mut out), |
| 199 | DefKind::Ctor(c) => out.extend(c.fields.iter().map(|f| &f.ty)), |
| 200 | DefKind::Type(t) => { |
| 201 | if let TypeBody::Alias(a) = &t.body { |
| 202 | out.push(a); |
| 203 | } |
| 204 | } |
| 205 | DefKind::Impl(i) => { |
| 206 | out.push(&i.target); |
| 207 | out.extend(i.constraints.iter()); |
| 208 | } |
| 209 | DefKind::AssocType(a) => out.extend(a.body.iter()), |
| 210 | DefKind::EffectAlias(a) => out.extend(a.members.iter()), |
| 211 | _ => {} |
| 212 | } |
| 213 | out |
| 214 | } |
| 215 | |
| 216 | pub(super) fn visit_type_refs(tref: &TypeRef, f: &mut impl FnMut(TextRange, DefId)) { |
| 217 | match tref { |
| 218 | TypeRef::Def { |
| 219 | def, |
| 220 | args, |
| 221 | bindings, |
| 222 | span, |
| 223 | } => { |
| 224 | f(*span, *def); |
| 225 | args.iter().for_each(|a| visit_type_refs(a, f)); |
| 226 | bindings.iter().for_each(|b| visit_type_refs(&b.ty, f)); |
| 227 | } |
| 228 | TypeRef::Fn { |
| 229 | params, |
| 230 | ret, |
| 231 | effects, |
| 232 | .. |
| 233 | } => { |
| 234 | params.iter().for_each(|p| visit_type_refs(&p.ty, f)); |
| 235 | visit_type_refs(ret, f); |
| 236 | if let Some(row) = effects { |
| 237 | row.labels.iter().for_each(|l| visit_type_refs(l, f)); |
| 238 | } |
| 239 | } |
| 240 | TypeRef::Tuple { elems, .. } => elems.iter().for_each(|e| visit_type_refs(e, f)), |
| 241 | TypeRef::Row { row, .. } => row.labels.iter().for_each(|l| visit_type_refs(l, f)), |
| 242 | TypeRef::Var { args, .. } => args.iter().for_each(|a| visit_type_refs(a, f)), |
| 243 | TypeRef::Error { .. } => {} |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | fn body_targets(hir: &Hir, body: &Body, file: FileId, consider: &mut impl FnMut(TextRange, Span)) { |
| 248 | for (e, expr) in body.exprs.iter() { |
| 249 | let range = body.expr_span(e); |
| 250 | match expr { |
| 251 | Expr::Def(d) => consider(range, hir.def(*d).span), |
| 252 | Expr::Local(l) if !body.locals[*l].synthetic => consider( |
| 253 | range, |
| 254 | Span { |
| 255 | file, |
| 256 | range: body.locals[*l].span, |
| 257 | }, |
| 258 | ), |
| 259 | Expr::Lambda { params, ret, .. } => { |
| 260 | for tref in params |
| 261 | .iter() |
| 262 | .filter_map(|p| p.ty.as_ref()) |
| 263 | .chain(ret.iter()) |
| 264 | { |
| 265 | visit_type_refs(tref, &mut |r, d| consider(r, hir.def(d).span)); |
| 266 | } |
| 267 | } |
| 268 | Expr::Block { stmts, .. } => { |
| 269 | for stmt in stmts { |
| 270 | if let Stmt::Let { ty: Some(tref), .. } = stmt { |
| 271 | visit_type_refs(tref, &mut |r, d| consider(r, hir.def(d).span)); |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | _ => {} |
| 276 | } |
| 277 | } |
| 278 | for (p, pat) in body.pats.iter() { |
| 279 | if let Pat::Ctor { def, .. } = pat { |
| 280 | // Only the constructor name, not its arguments. |
| 281 | let range = body.pat_span(p); |
| 282 | let name_len = TextSize::new(hir.def(*def).name.len() as u32); |
| 283 | consider( |
| 284 | TextRange::at(range.start(), name_len.min(range.len())), |
| 285 | hir.def(*def).span, |
| 286 | ); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 292 | pub enum SymbolKind { |
| 293 | Function, |
| 294 | Type, |
| 295 | Constructor, |
| 296 | Trait, |
| 297 | Impl, |
| 298 | Effect, |
| 299 | Operation, |
| 300 | Method, |
| 301 | } |
| 302 | |
| 303 | /// An item of the document outline. |
| 304 | #[derive(Clone, PartialEq, Debug)] |
| 305 | pub struct Symbol { |
| 306 | pub name: String, |
| 307 | pub kind: SymbolKind, |
| 308 | /// The item's name. |
| 309 | pub range: TextRange, |
| 310 | pub children: Vec<Symbol>, |
| 311 | } |
| 312 | |
| 313 | /// The outline of `file`: items, with constructors, operations and |
| 314 | /// methods nested under their type, effect, trait or impl. |
| 315 | pub fn document_symbols(analysis: &Analysis, file: FileId) -> Vec<Symbol> { |
| 316 | let hir = &analysis.hir; |
| 317 | let Some((_, module)) = hir.modules.iter().find(|(_, m)| m.file == file) else { |
| 318 | return Vec::new(); |
| 319 | }; |
| 320 | let leaf = |id: DefId, kind| Symbol { |
| 321 | name: hir.def(id).name.clone(), |
| 322 | kind, |
| 323 | range: hir.def(id).span.range, |
| 324 | children: Vec::new(), |
| 325 | }; |
| 326 | let mut out = Vec::new(); |
| 327 | for &id in &module.items { |
| 328 | let def = hir.def(id); |
| 329 | let symbol = match &def.kind { |
| 330 | DefKind::Fn(f) if f.owner.is_none() => leaf(id, SymbolKind::Function), |
| 331 | DefKind::Type(t) => { |
| 332 | let mut s = leaf(id, SymbolKind::Type); |
| 333 | if let TypeBody::Adt(ctors) = &t.body { |
| 334 | s.children = ctors |
| 335 | .iter() |
| 336 | .map(|c| leaf(*c, SymbolKind::Constructor)) |
| 337 | .collect(); |
| 338 | } |
| 339 | s |
| 340 | } |
| 341 | DefKind::Effect(e) => { |
| 342 | let mut s = leaf(id, SymbolKind::Effect); |
| 343 | s.children = e |
| 344 | .ops |
| 345 | .iter() |
| 346 | .map(|o| leaf(*o, SymbolKind::Operation)) |
| 347 | .collect(); |
| 348 | s |
| 349 | } |
| 350 | DefKind::EffectAlias(_) => leaf(id, SymbolKind::Effect), |
| 351 | DefKind::Trait(t) => { |
| 352 | let mut s = leaf(id, SymbolKind::Trait); |
| 353 | s.children = t |
| 354 | .assoc_types |
| 355 | .iter() |
| 356 | .map(|a| leaf(*a, SymbolKind::Type)) |
| 357 | .chain(t.methods.iter().map(|m| leaf(*m, SymbolKind::Method))) |
| 358 | .collect(); |
| 359 | s |
| 360 | } |
| 361 | DefKind::Impl(i) => { |
| 362 | let name = analysis |
| 363 | .typeck |
| 364 | .impls |
| 365 | .iter() |
| 366 | .find(|info| info.def == Some(id)) |
| 367 | .map(|info| { |
| 368 | let heads: Vec<String> = info.heads.iter().map(|h| h.show(hir)).collect(); |
| 369 | format!("impl {}<{}>", hir.def(info.trait_).name, heads.join(", ")) |
| 370 | }) |
| 371 | .unwrap_or_else(|| "impl".into()); |
| 372 | Symbol { |
| 373 | name, |
| 374 | kind: SymbolKind::Impl, |
| 375 | range: def.span.range, |
| 376 | children: i |
| 377 | .assoc_types |
| 378 | .iter() |
| 379 | .map(|a| leaf(*a, SymbolKind::Type)) |
| 380 | .chain(i.methods.iter().map(|m| leaf(*m, SymbolKind::Method))) |
| 381 | .collect(), |
| 382 | } |
| 383 | } |
| 384 | _ => continue, |
| 385 | }; |
| 386 | out.push(symbol); |
| 387 | } |
| 388 | out |
| 389 | } |
| 390 | |
| 391 | #[cfg(test)] |
| 392 | mod tests { |
| 393 | use super::*; |
| 394 | use crate::Db; |
| 395 | |
| 396 | fn at(src: &str, marker: &str) -> (Db, FileId, TextSize) { |
| 397 | let mut db = Db::new(); |
| 398 | let offset = src.find(marker).expect("marker") as u32; |
| 399 | let file = db.add_module("main", "main.lse", src.replace(marker, "")); |
| 400 | (db, file, offset.into()) |
| 401 | } |
| 402 | |
| 403 | #[test] |
| 404 | fn definitions_of_items_locals_constructors_and_types() { |
| 405 | // Markers `^n` are inserted between characters and removed. |
| 406 | let src = "type Shape { Circle(Int) }\nfn area :: s: Sh^1ape -> Int {\n let r = 2\n match s { Cir^2cle(x) -> x * ^3r }\n}\nfn use_it :: { ar^4ea (Circle(1)) }"; |
| 407 | let cases = [ |
| 408 | ("^1", "Shape"), |
| 409 | ("^2", "Circle"), |
| 410 | ("^3", "r"), |
| 411 | ("^4", "area"), |
| 412 | ]; |
| 413 | for (marker, expected) in cases { |
| 414 | let others: String = cases |
| 415 | .iter() |
| 416 | .filter(|(m, _)| *m != marker) |
| 417 | .fold(src.to_owned(), |s, (m, _)| s.replace(m, "")); |
| 418 | let (db, file, offset) = at(&others, marker); |
| 419 | let analysis = db.analyze(); |
| 420 | assert!( |
| 421 | analysis.diagnostics.is_empty(), |
| 422 | "{:#?}", |
| 423 | analysis.diagnostics |
| 424 | ); |
| 425 | let target = definition(&analysis, db.sources(), file, offset) |
| 426 | .unwrap_or_else(|| panic!("{marker}")); |
| 427 | let text = &db.sources().get(target.file).text()[target.range]; |
| 428 | assert!(text.starts_with(expected), "{marker}: {text:?}"); |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | #[test] |
| 433 | fn std_definitions_are_not_navigable() { |
| 434 | let (db, file, offset) = at("import std/list\nfn f :: { list.len^gth [] }", "^"); |
| 435 | let analysis = db.analyze(); |
| 436 | assert_eq!(definition(&analysis, db.sources(), file, offset), None); |
| 437 | } |
| 438 | |
| 439 | #[test] |
| 440 | fn a_row_alias_use_leads_to_the_alias() { |
| 441 | // Not to a member: the members are spliced at the use's range |
| 442 | // (ADR 0044). |
| 443 | let (db, file, offset) = at( |
| 444 | "effect io { fn print :: s: String -> () }\neffect alias app = io\nfn f :: -> () / <ap^p> { print \"x\" }", |
| 445 | "^", |
| 446 | ); |
| 447 | let analysis = db.analyze(); |
| 448 | assert!( |
| 449 | analysis.diagnostics.is_empty(), |
| 450 | "{:#?}", |
| 451 | analysis.diagnostics |
| 452 | ); |
| 453 | let target = definition(&analysis, db.sources(), file, offset).expect("a definition"); |
| 454 | let text = &db.sources().get(target.file).text()[target.range]; |
| 455 | assert_eq!(text, "app"); |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn definitions_inside_template_holes() { |
| 460 | // `na^me` is inside the template literal's hole (ADR 0048). |
| 461 | let (db, file, offset) = at( |
| 462 | "import std/template.{pug}\nfn f :: {\n let name = \"x\"\n pug`p {na^me}`\n}", |
| 463 | "^", |
| 464 | ); |
| 465 | let analysis = db.analyze(); |
| 466 | assert!( |
| 467 | analysis.diagnostics.is_empty(), |
| 468 | "{:#?}", |
| 469 | analysis.diagnostics |
| 470 | ); |
| 471 | let target = definition(&analysis, db.sources(), file, offset).expect("definition"); |
| 472 | assert_eq!(&db.sources().get(target.file).text()[target.range], "name"); |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn outline_nests_members() { |
| 477 | let mut db = Db::new(); |
| 478 | let file = db.add_module( |
| 479 | "main", |
| 480 | "main.lse", |
| 481 | "type T\n { A\n , B\n }\neffect e {\n fn op :: -> ()\n}\ntrait Tr<a> {\n fn m :: x: a -> Int\n}\nimpl Tr<T> {\n fn m :: x {\n 1\n }\n}\nfn f :: {\n 1\n}\n".into(), |
| 482 | ); |
| 483 | let analysis = db.analyze(); |
| 484 | let symbols = document_symbols(&analysis, file); |
| 485 | let names: Vec<_> = symbols |
| 486 | .iter() |
| 487 | .map(|s| (s.name.as_str(), s.children.len())) |
| 488 | .collect(); |
| 489 | assert_eq!( |
| 490 | names, |
| 491 | [("T", 2), ("e", 1), ("Tr", 1), ("impl Tr<T>", 1), ("f", 0)] |
| 492 | ); |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | #[cfg(test)] |
| 497 | mod reference_tests { |
| 498 | use super::*; |
| 499 | use crate::Db; |
| 500 | |
| 501 | #[test] |
| 502 | fn finds_items_and_locals() { |
| 503 | let mut db = Db::new(); |
| 504 | let src = "type Shape { Circle(r: Int) }\nfn area :: s: Shape {\n match s {\n Circle(r) -> r * r\n }\n}\nfn two :: {\n area Circle(1) + area Circle(2)\n}\n"; |
| 505 | let file = db.add_module("main", "main.lse", src.into()); |
| 506 | let analysis = db.analyze(); |
| 507 | let at = |needle: &str| TextSize::new(src.find(needle).unwrap() as u32); |
| 508 | let texts = |offset| -> Vec<&str> { |
| 509 | references(&analysis, db.sources(), file, offset) |
| 510 | .iter() |
| 511 | .map(|s| &src[usize::from(s.range.start())..usize::from(s.range.end())]) |
| 512 | .collect() |
| 513 | }; |
| 514 | // `area`: its declaration and both calls. |
| 515 | assert_eq!(texts(at("area ::")), vec!["area", "area", "area"]); |
| 516 | // The type `Shape`: declaration and the parameter's annotation. |
| 517 | assert_eq!(texts(at("Shape {")), vec!["Shape", "Shape"]); |
| 518 | // The local `s`: the parameter and its use. |
| 519 | assert_eq!(texts(at("s {")), vec!["s", "s"]); |
| 520 | // The constructor: declaration, pattern, and two calls. |
| 521 | assert_eq!(texts(at("Circle(1)")).len(), 4); |
| 522 | } |
| 523 | } |