//! Editor queries over an [`Analysis`]: what the language server answers. use louise_hir::body::{Expr, Pat}; use louise_hir::{DefId, DefKind, TypeRef}; use louise_span::{FileId, TextRange, TextSize}; use louise_types::Printer; use crate::Analysis; /// Hover content: Markdown, and the range it describes. #[derive(Debug, PartialEq)] pub struct Hover { pub range: TextRange, pub markdown: String, } /// The type (with effects) of whatever is at `offset`: an item's name, a /// reference to an item, a local binding, or the innermost expression. pub fn hover(analysis: &Analysis, file: FileId, offset: TextSize) -> Option { let hir = &analysis.hir; for (id, def) in hir.defs.iter() { if def.span.file == file && !def.name.is_empty() && def.span.range.contains_inclusive(offset) { return Some(Hover { range: def.span.range, markdown: item_markdown(analysis, id), }); } } let mut best: Option<(TextRange, String)> = None; let mut consider = |range: TextRange, text: &dyn Fn() -> String| { if range.contains_inclusive(offset) && best.as_ref().is_none_or(|(r, _)| range.len() < r.len()) { best = Some((range, text())); } }; for (id, f) in hir.fn_defs() { if hir.modules[hir.def(id).module].file != file { continue; } let (Some(body), Some(results)) = (&f.body, analysis.typeck.bodies.get(&id)) else { continue; }; for (e, expr) in body.exprs.iter() { let range = body.expr_span(e); let ty = &results.types.exprs[e.index()]; match expr { Expr::Def(def) => consider(range, &|| item_markdown(analysis, *def)), Expr::Local(l) if !body.locals[*l].synthetic => consider(range, &|| { code(&format!( "{}: {}", body.locals[*l].name, results.show(hir, ty) )) }), _ => consider(range, &|| code(&results.show(hir, ty))), } } for (p, pat) in body.pats.iter() { if let Pat::Bind(l) = pat && !body.locals[*l].synthetic { let ty = &results.types.locals[l.index()]; let text = || { code(&format!( "{}: {}", body.locals[*l].name, results.show(hir, ty) )) }; consider(body.pat_span(p), &text); } } } best.map(|(range, markdown)| Hover { range, markdown }) } fn code(text: &str) -> String { format!("```louise\n{text}\n```") } pub(super) fn item_markdown(analysis: &Analysis, id: DefId) -> String { let hir = &analysis.hir; let def = hir.def(id); let scheme = analysis.typeck.schemes.get(&id).map(|s| { Printer { hir, ctx: None, gen_names: &[], rigid_names: &[], } .scheme(s) }); let signature = match (&def.kind, scheme) { (DefKind::Fn(_) | DefKind::Ctor(_) | DefKind::Op(_), Some(s)) => { format!("{}: {s}", def.name) } (DefKind::Type(t), _) => format!( "{}type {}{}", if t.opaque { "opaque " } else { "" }, def.name, params(&t.params) ), (DefKind::Trait(t), _) => format!("trait {}{}", def.name, params(&t.params)), // `type Elem` of `trait Container`: written `Elem`. (DefKind::AssocType(a), _) => { let owner = hir.def(a.owner); let trait_params = match &owner.kind { DefKind::Trait(t) => t.params.clone(), _ => Vec::new(), }; let all: Vec = trait_params .into_iter() .chain(a.params.iter().cloned()) .collect(); format!( "type {}{} (of trait {})", def.name, params(&all), owner.name ) } (DefKind::Effect(e), _) => format!("effect {}{}", def.name, params(&e.params)), // The alias, then its expansion (ADR 0044). (DefKind::EffectAlias(a), _) => { let members = a .members .iter() .map(|m| match m { TypeRef::Def { def: d, args, .. } => { let args = if args.is_empty() { String::new() } else { format!( "<{}>", args.iter() .map(|a| match a { TypeRef::Def { def: d, .. } => hir.def(*d).name.clone(), TypeRef::Var { name, .. } => name.clone(), _ => "_".into(), }) .collect::>() .join(", ") ) }; format!("{}{}", hir.def(*d).name, args) } _ => "_".into(), }) .collect::>(); format!("effect alias {} = {}", def.name, members.join(", ")) } _ => def.name.clone(), }; let module = &hir.modules[def.module].path; let mut out = code(&signature); out.push_str(&format!("\n\n*{module}*")); if let Some(doc) = &def.doc { out.push_str("\n\n"); out.push_str(doc); } out } fn params(names: &[String]) -> String { if names.is_empty() { String::new() } else { format!("<{}>", names.join(", ")) } } #[cfg(test)] mod tests { use crate::Db; fn hover_at(src: &str, marker: &str) -> String { let mut db = Db::new(); let file = db.add_module("main", "main.lse", src.replace(marker, "")); let offset = src.find(marker).expect("marker in source") as u32; let analysis = db.analyze(); assert!( analysis.diagnostics.is_empty(), "{:#?}", analysis.diagnostics ); super::hover(&analysis, file, offset.into()) .expect("something to hover") .markdown } #[test] fn hovers_show_types_and_effects() { let src = "effect log { fn log :: m: String -> () }\n\ /// Logs twice.\n\ fn tw$0ice :: m { log m\n log m }\n\ pub fn run :: f: fn(a) -> b / x: a -> b / { f (x$1) }\n\ fn use_it :: { tw$2ice \"x\" }"; // Keep one marker, drop the others. let only = |keep: &str| { ["$0", "$1", "$2"] .iter() .filter(|m| **m != keep) .fold(src.to_owned(), |s, m| s.replace(m, "")) }; let item = hover_at(&only("$0"), "$0"); assert!(item.contains("twice: fn(String) -> () / "), "{item}"); assert!(item.contains("Logs twice."), "{item}"); let local = hover_at(&only("$1"), "$1"); assert!(local.contains("x: a"), "{local}"); let reference = hover_at(&only("$2"), "$2"); assert!( reference.contains("twice: fn(String) -> () / "), "{reference}" ); } }