//! Code actions. use louise_hir::{DefKind, Namespace}; use louise_span::{FileId, TextRange}; use louise_syntax::{SyntaxKind, SyntaxNode}; use louise_types::{Printer, Ty}; use crate::{Analysis, Db}; /// "Insert inferred signature": complete the signature of a public /// function from its inferred type (fixes E0107). #[derive(Clone, PartialEq, Debug)] pub struct SignatureFix { pub title: String, /// The parameter list through the end of the signature. pub range: TextRange, pub new_text: String, } pub fn signature_fixes(db: &Db, analysis: &Analysis, file: FileId) -> Vec { let hir = &analysis.hir; let Some(parse) = db.parse(file) else { return Vec::new(); }; let root = parse.syntax(); let mut out = Vec::new(); for (id, def) in hir.defs.iter() { let DefKind::Fn(f) = &def.kind else { continue }; let complete = f.sig.ret.is_some() && f.sig.params.iter().all(|p| p.ty.is_some()); if hir.modules[def.module].file != file || !def.is_pub || complete || def.namespace() != Namespace::Values { continue; } let Some(scheme) = analysis.typeck.schemes.get(&id) else { continue; }; let Ty::Fn(params, ret, effects, _) = &scheme.ty else { continue; }; let Some(fn_node) = fn_node_at(&root, def.span.range) else { continue; }; let Some(range) = signature_range(&fn_node) else { continue; }; let p = Printer { hir, ctx: None, gen_names: &scheme.vars, rigid_names: &[], }; let params: Vec = f .sig .params .iter() .zip(params) .map(|(param, ty)| { let typed = format!("{}: {}", param.name, p.ty(&ty.ty)); match ¶m.label { // `~name: T` puns; `~label:(name: T)` renames. Some(l) if *l == param.name => format!("~{l}: {}", p.ty(&ty.ty)), Some(l) => format!("~{l}:({typed})"), None => typed, } }) .collect(); let mut text = params.join(" "); if !params.is_empty() { text.push(' '); } text.push_str(&format!("-> {}", p.ty(ret))); if !matches!(**effects, Ty::RowEmpty | Ty::RowEvidence) { // The type printer shows a function's row after ` / `. let fn_text = p.ty(&Ty::func_eff(Vec::new(), Ty::unit(), (**effects).clone())); if let Some((_, row)) = fn_text.split_once(" / ") { text.push_str(" / "); text.push_str(row); } } let cs: Vec = scheme.all_constraints().map(|c| p.constraint(c)).collect(); if !cs.is_empty() { text.push_str(" where "); text.push_str(&cs.join(", ")); } out.push(SignatureFix { title: format!("Insert inferred signature of `{}`", def.name), range, new_text: text, }); } out } /// An inlay hint: text shown after `offset` without being part of it. #[derive(Clone, PartialEq, Debug)] pub struct InlayHint { pub offset: louise_span::TextSize, pub label: String, } /// The inferred parts of functions without a complete signature: parameter /// types, the result type and the effect row (ADR 0001: private functions /// are inferred; seeing their effects is the point). pub fn inlay_hints(db: &Db, analysis: &Analysis, file: FileId) -> Vec { let hir = &analysis.hir; let Some(parse) = db.parse(file) else { return Vec::new(); }; let root = parse.syntax(); let mut out = Vec::new(); for (id, def) in hir.defs.iter() { let DefKind::Fn(f) = &def.kind else { continue }; if hir.modules[def.module].file != file || f.body.is_none() { continue; } let complete = f.sig.ret.is_some() && f.sig.params.iter().all(|p| p.ty.is_some()); if complete { continue; } let Some(scheme) = analysis.typeck.schemes.get(&id) else { continue; }; let Ty::Fn(params, ret, effects, _) = &scheme.ty else { continue; }; let p = Printer { hir, ctx: None, gen_names: &scheme.vars, rigid_names: &[], }; for (param, ty) in f.sig.params.iter().zip(params) { if param.ty.is_none() { out.push(InlayHint { offset: param.span.end(), label: format!(": {}", p.ty(&ty.ty)), }); } } let row = row_text(&p, effects); let Some(fn_node) = fn_node_at(&root, def.span.range) else { continue; }; let end_of = |kind: SyntaxKind| { fn_node .children() .find(|n| n.kind() == kind) .map(|n| n.text_range().end()) }; match (f.sig.ret.is_some(), f.sig.effects.is_some()) { (false, _) => { if let Some(offset) = end_of(SyntaxKind::PARAM_LIST) { out.push(InlayHint { offset, label: format!(" -> {}{row}", p.ty(ret)), }); } } (true, false) if !row.is_empty() => { if let Some(offset) = end_of(SyntaxKind::RET_TYPE) { out.push(InlayHint { offset, label: row }); } } _ => {} } } out.sort_by_key(|h| h.offset); out } /// ` / `, or nothing for a total function. fn row_text(p: &Printer, effects: &Ty) -> String { if matches!(effects, Ty::RowEmpty | Ty::RowEvidence) { return String::new(); } let fn_text = p.ty(&Ty::func_eff(Vec::new(), Ty::unit(), effects.clone())); fn_text .split_once(" / ") .map_or(String::new(), |(_, row)| format!(" / {row}")) } fn fn_node_at(root: &SyntaxNode, name: TextRange) -> Option { root.covering_element(name) .ancestors() .find(|n| n.kind() == SyntaxKind::FN_DEF) } /// From the parameter list to the end of the return type / where clause. fn signature_range(fn_node: &SyntaxNode) -> Option { let parts: Vec<_> = fn_node .children() .filter(|n| { matches!( n.kind(), SyntaxKind::PARAM_LIST | SyntaxKind::RET_TYPE | SyntaxKind::WHERE_CLAUSE ) }) .collect(); let first = parts.first()?.text_range(); let last = parts.last()?.text_range(); Some(TextRange::new(first.start(), last.end())) } #[cfg(test)] mod tests { use super::*; #[test] fn hints_show_inferred_types_and_effects() { let mut db = Db::new(); let src = "effect log {\n fn log :: m: String -> ()\n}\nfn greet :: name {\n log (\"hi \" <> name)\n}\nfn twice :: x: Int -> Int {\n x * 2\n}\n"; let file = db.add_module("main", "main.lse", src.into()); let analysis = db.analyze(); let hints = inlay_hints(&db, &analysis, file); let labels: Vec<(usize, &str)> = hints .iter() .map(|h| (usize::from(h.offset), h.label.as_str())) .collect(); let after = |s: &str| src.find(s).unwrap() + s.len(); assert_eq!( labels, vec![ (after("fn greet :: name"), ": String"), (after("fn greet :: name"), " -> () / "), ] ); } #[test] fn completes_public_signatures_from_inference() { let mut db = Db::new(); let src = "effect log {\n fn log :: m: String -> ()\n}\npub fn describe :: x f {\n log (show x)\n f x\n}\n"; let file = db.add_module("main", "main.lse", src.into()); let analysis = db.analyze(); let fixes = signature_fixes(&db, &analysis, file); let [fix] = fixes.as_slice() else { panic!("{fixes:?}") }; assert_eq!(&src[fix.range], "x f"); assert_eq!( fix.new_text, "x: a f: fn(a) -> b / -> b / where Show" ); // Applying it makes the module check cleanly. let fixed = format!( "{}{}{}", &src[..usize::from(fix.range.start())], fix.new_text, &src[usize::from(fix.range.end())..] ); db.set_text(file, fixed); assert!( db.analyze().diagnostics.is_empty(), "{:#?}", db.analyze().diagnostics ); } }