| @@ -0,0 +1,311 @@ |
| 1 | +//! Navigation: go to definition, document symbols. |
| 2 | + |
| 3 | +use tilc_hir::body::{Body, Expr, Pat, Stmt}; |
| 4 | +use tilc_hir::{DefId, DefKind, FnSig, Hir, TypeBody, TypeRef}; |
| 5 | +use tilc_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: &tilc_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 | + for (_, def) in hir.defs.iter() { |
| 27 | + if hir.modules[def.module].file != file { |
| 28 | + continue; |
| 29 | + } |
| 30 | + if !def.name.is_empty() { |
| 31 | + consider(def.span.range, def.span); |
| 32 | + } |
| 33 | + for tref in signature_types(&def.kind) { |
| 34 | + visit_type_refs(tref, &mut |range, target| { |
| 35 | + consider(range, hir.def(target).span) |
| 36 | + }); |
| 37 | + } |
| 38 | + if let DefKind::Fn(f) = &def.kind |
| 39 | + && let Some(body) = &f.body |
| 40 | + { |
| 41 | + body_targets(hir, body, file, &mut consider); |
| 42 | + } |
| 43 | + } |
| 44 | + let (_, target) = best?; |
| 45 | + (!sources.get(target.file).path().starts_with('<')).then_some(target) |
| 46 | +} |
| 47 | + |
| 48 | +/// Type syntax written in an item's signature. |
| 49 | +fn signature_types(kind: &DefKind) -> Vec<&TypeRef> { |
| 50 | + fn sig_types<'a>(s: &'a FnSig, out: &mut Vec<&'a TypeRef>) { |
| 51 | + out.extend(s.params.iter().filter_map(|p| p.ty.as_ref())); |
| 52 | + out.extend(s.ret.iter()); |
| 53 | + out.extend(s.constraints.iter()); |
| 54 | + if let Some(row) = &s.effects { |
| 55 | + out.extend(row.labels.iter()); |
| 56 | + } |
| 57 | + } |
| 58 | + let mut out = Vec::new(); |
| 59 | + match kind { |
| 60 | + DefKind::Fn(f) => sig_types(&f.sig, &mut out), |
| 61 | + DefKind::Op(o) => sig_types(&o.sig, &mut out), |
| 62 | + DefKind::Ctor(c) => out.extend(c.fields.iter().map(|f| &f.ty)), |
| 63 | + DefKind::Type(t) => { |
| 64 | + if let TypeBody::Alias(a) = &t.body { |
| 65 | + out.push(a); |
| 66 | + } |
| 67 | + } |
| 68 | + DefKind::Impl(i) => { |
| 69 | + out.push(&i.target); |
| 70 | + out.extend(i.constraints.iter()); |
| 71 | + } |
| 72 | + _ => {} |
| 73 | + } |
| 74 | + out |
| 75 | +} |
| 76 | + |
| 77 | +fn visit_type_refs(tref: &TypeRef, f: &mut impl FnMut(TextRange, DefId)) { |
| 78 | + match tref { |
| 79 | + TypeRef::Def { def, args, span } => { |
| 80 | + f(*span, *def); |
| 81 | + args.iter().for_each(|a| visit_type_refs(a, f)); |
| 82 | + } |
| 83 | + TypeRef::Fn { |
| 84 | + params, |
| 85 | + ret, |
| 86 | + effects, |
| 87 | + .. |
| 88 | + } => { |
| 89 | + params.iter().for_each(|p| visit_type_refs(p, f)); |
| 90 | + visit_type_refs(ret, f); |
| 91 | + if let Some(row) = effects { |
| 92 | + row.labels.iter().for_each(|l| visit_type_refs(l, f)); |
| 93 | + } |
| 94 | + } |
| 95 | + TypeRef::Tuple { elems, .. } => elems.iter().for_each(|e| visit_type_refs(e, f)), |
| 96 | + TypeRef::Var { .. } | TypeRef::Error { .. } => {} |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +fn body_targets(hir: &Hir, body: &Body, file: FileId, consider: &mut impl FnMut(TextRange, Span)) { |
| 101 | + for (e, expr) in body.exprs.iter() { |
| 102 | + let range = body.expr_span(e); |
| 103 | + match expr { |
| 104 | + Expr::Def(d) => consider(range, hir.def(*d).span), |
| 105 | + Expr::Local(l) => consider( |
| 106 | + range, |
| 107 | + Span { |
| 108 | + file, |
| 109 | + range: body.locals[*l].span, |
| 110 | + }, |
| 111 | + ), |
| 112 | + Expr::Lambda { params, ret, .. } => { |
| 113 | + for tref in params |
| 114 | + .iter() |
| 115 | + .filter_map(|(_, t)| t.as_ref()) |
| 116 | + .chain(ret.iter()) |
| 117 | + { |
| 118 | + visit_type_refs(tref, &mut |r, d| consider(r, hir.def(d).span)); |
| 119 | + } |
| 120 | + } |
| 121 | + Expr::Block { stmts, .. } => { |
| 122 | + for stmt in stmts { |
| 123 | + if let Stmt::Let { ty: Some(tref), .. } = stmt { |
| 124 | + visit_type_refs(tref, &mut |r, d| consider(r, hir.def(d).span)); |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + _ => {} |
| 129 | + } |
| 130 | + } |
| 131 | + for (p, pat) in body.pats.iter() { |
| 132 | + if let Pat::Ctor { def, .. } = pat { |
| 133 | + // Only the constructor name, not its arguments. |
| 134 | + let range = body.pat_span(p); |
| 135 | + let name_len = TextSize::new(hir.def(*def).name.len() as u32); |
| 136 | + consider( |
| 137 | + TextRange::at(range.start(), name_len.min(range.len())), |
| 138 | + hir.def(*def).span, |
| 139 | + ); |
| 140 | + } |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 145 | +pub enum SymbolKind { |
| 146 | + Function, |
| 147 | + Type, |
| 148 | + Constructor, |
| 149 | + Trait, |
| 150 | + Impl, |
| 151 | + Effect, |
| 152 | + Operation, |
| 153 | + Method, |
| 154 | +} |
| 155 | + |
| 156 | +/// An item of the document outline. |
| 157 | +#[derive(Clone, PartialEq, Debug)] |
| 158 | +pub struct Symbol { |
| 159 | + pub name: String, |
| 160 | + pub kind: SymbolKind, |
| 161 | + /// The item's name. |
| 162 | + pub range: TextRange, |
| 163 | + pub children: Vec<Symbol>, |
| 164 | +} |
| 165 | + |
| 166 | +/// The outline of `file`: items, with constructors, operations and |
| 167 | +/// methods nested under their type, effect, trait or impl. |
| 168 | +pub fn document_symbols(analysis: &Analysis, file: FileId) -> Vec<Symbol> { |
| 169 | + let hir = &analysis.hir; |
| 170 | + let Some((_, module)) = hir.modules.iter().find(|(_, m)| m.file == file) else { |
| 171 | + return Vec::new(); |
| 172 | + }; |
| 173 | + let leaf = |id: DefId, kind| Symbol { |
| 174 | + name: hir.def(id).name.clone(), |
| 175 | + kind, |
| 176 | + range: hir.def(id).span.range, |
| 177 | + children: Vec::new(), |
| 178 | + }; |
| 179 | + let mut out = Vec::new(); |
| 180 | + for &id in &module.items { |
| 181 | + let def = hir.def(id); |
| 182 | + let symbol = match &def.kind { |
| 183 | + DefKind::Fn(f) if f.owner.is_none() => leaf(id, SymbolKind::Function), |
| 184 | + DefKind::Type(t) => { |
| 185 | + let mut s = leaf(id, SymbolKind::Type); |
| 186 | + if let TypeBody::Adt(ctors) = &t.body { |
| 187 | + s.children = ctors |
| 188 | + .iter() |
| 189 | + .map(|c| leaf(*c, SymbolKind::Constructor)) |
| 190 | + .collect(); |
| 191 | + } |
| 192 | + s |
| 193 | + } |
| 194 | + DefKind::Effect(e) => { |
| 195 | + let mut s = leaf(id, SymbolKind::Effect); |
| 196 | + s.children = e |
| 197 | + .ops |
| 198 | + .iter() |
| 199 | + .map(|o| leaf(*o, SymbolKind::Operation)) |
| 200 | + .collect(); |
| 201 | + s |
| 202 | + } |
| 203 | + DefKind::Trait(t) => { |
| 204 | + let mut s = leaf(id, SymbolKind::Trait); |
| 205 | + s.children = t |
| 206 | + .methods |
| 207 | + .iter() |
| 208 | + .map(|m| leaf(*m, SymbolKind::Method)) |
| 209 | + .collect(); |
| 210 | + s |
| 211 | + } |
| 212 | + DefKind::Impl(i) => { |
| 213 | + let name = analysis |
| 214 | + .typeck |
| 215 | + .impls |
| 216 | + .iter() |
| 217 | + .find(|info| info.def == Some(id)) |
| 218 | + .map(|info| { |
| 219 | + format!( |
| 220 | + "impl {}<{}>", |
| 221 | + hir.def(info.trait_).name, |
| 222 | + hir.def(info.head).name |
| 223 | + ) |
| 224 | + }) |
| 225 | + .unwrap_or_else(|| "impl".into()); |
| 226 | + Symbol { |
| 227 | + name, |
| 228 | + kind: SymbolKind::Impl, |
| 229 | + range: def.span.range, |
| 230 | + children: i |
| 231 | + .methods |
| 232 | + .iter() |
| 233 | + .map(|m| leaf(*m, SymbolKind::Method)) |
| 234 | + .collect(), |
| 235 | + } |
| 236 | + } |
| 237 | + _ => continue, |
| 238 | + }; |
| 239 | + out.push(symbol); |
| 240 | + } |
| 241 | + out |
| 242 | +} |
| 243 | + |
| 244 | +#[cfg(test)] |
| 245 | +mod tests { |
| 246 | + use super::*; |
| 247 | + use crate::Db; |
| 248 | + |
| 249 | + fn at(src: &str, marker: &str) -> (Db, FileId, TextSize) { |
| 250 | + let mut db = Db::new(); |
| 251 | + let offset = src.find(marker).expect("marker") as u32; |
| 252 | + let file = db.add_module("main", "main.til", src.replace(marker, "")); |
| 253 | + (db, file, offset.into()) |
| 254 | + } |
| 255 | + |
| 256 | + #[test] |
| 257 | + fn definitions_of_items_locals_constructors_and_types() { |
| 258 | + // Markers `^n` are inserted between characters and removed. |
| 259 | + 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)) }"; |
| 260 | + let cases = [ |
| 261 | + ("^1", "Shape"), |
| 262 | + ("^2", "Circle"), |
| 263 | + ("^3", "r"), |
| 264 | + ("^4", "area"), |
| 265 | + ]; |
| 266 | + for (marker, expected) in cases { |
| 267 | + let others: String = cases |
| 268 | + .iter() |
| 269 | + .filter(|(m, _)| *m != marker) |
| 270 | + .fold(src.to_owned(), |s, (m, _)| s.replace(m, "")); |
| 271 | + let (db, file, offset) = at(&others, marker); |
| 272 | + let analysis = db.analyze(); |
| 273 | + assert!( |
| 274 | + analysis.diagnostics.is_empty(), |
| 275 | + "{:#?}", |
| 276 | + analysis.diagnostics |
| 277 | + ); |
| 278 | + let target = definition(&analysis, db.sources(), file, offset) |
| 279 | + .unwrap_or_else(|| panic!("{marker}")); |
| 280 | + let text = &db.sources().get(target.file).text()[target.range]; |
| 281 | + assert!(text.starts_with(expected), "{marker}: {text:?}"); |
| 282 | + } |
| 283 | + } |
| 284 | + |
| 285 | + #[test] |
| 286 | + fn std_definitions_are_not_navigable() { |
| 287 | + let (db, file, offset) = at("import std/list\nfn f() { list.len^gth([]) }", "^"); |
| 288 | + let analysis = db.analyze(); |
| 289 | + assert_eq!(definition(&analysis, db.sources(), file, offset), None); |
| 290 | + } |
| 291 | + |
| 292 | + #[test] |
| 293 | + fn outline_nests_members() { |
| 294 | + let mut db = Db::new(); |
| 295 | + let file = db.add_module( |
| 296 | + "main", |
| 297 | + "main.til", |
| 298 | + "type T { A B }\neffect e { fn op() -> () }\ntrait Tr<a> { fn m(x: a) -> Int }\nimpl Tr<T> { fn m(x) { 1 } }\nfn f() { 1 }".into(), |
| 299 | + ); |
| 300 | + let analysis = db.analyze(); |
| 301 | + let symbols = document_symbols(&analysis, file); |
| 302 | + let names: Vec<_> = symbols |
| 303 | + .iter() |
| 304 | + .map(|s| (s.name.as_str(), s.children.len())) |
| 305 | + .collect(); |
| 306 | + assert_eq!( |
| 307 | + names, |
| 308 | + [("T", 2), ("e", 1), ("Tr", 1), ("impl Tr<T>", 1), ("f", 0)] |
| 309 | + ); |
| 310 | + } |
| 311 | +} |