
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 | //! Code actions. |
| 2 | |
| 3 | use louise_hir::{DefKind, Namespace}; |
| 4 | use louise_span::{FileId, TextRange}; |
| 5 | use louise_syntax::{SyntaxKind, SyntaxNode}; |
| 6 | use louise_types::{Printer, Ty}; |
| 7 | |
| 8 | use crate::{Analysis, Db}; |
| 9 | |
| 10 | /// "Insert inferred signature": complete the signature of a public |
| 11 | /// function from its inferred type (fixes E0107). |
| 12 | #[derive(Clone, PartialEq, Debug)] |
| 13 | pub struct SignatureFix { |
| 14 | pub title: String, |
| 15 | /// The parameter list through the end of the signature. |
| 16 | pub range: TextRange, |
| 17 | pub new_text: String, |
| 18 | } |
| 19 | |
| 20 | pub fn signature_fixes(db: &Db, analysis: &Analysis, file: FileId) -> Vec<SignatureFix> { |
| 21 | let hir = &analysis.hir; |
| 22 | let Some(parse) = db.parse(file) else { |
| 23 | return Vec::new(); |
| 24 | }; |
| 25 | let root = parse.syntax(); |
| 26 | let mut out = Vec::new(); |
| 27 | for (id, def) in hir.defs.iter() { |
| 28 | let DefKind::Fn(f) = &def.kind else { continue }; |
| 29 | let complete = f.sig.ret.is_some() && f.sig.params.iter().all(|p| p.ty.is_some()); |
| 30 | if hir.modules[def.module].file != file |
| 31 | || !def.is_pub |
| 32 | || complete |
| 33 | || def.namespace() != Namespace::Values |
| 34 | { |
| 35 | continue; |
| 36 | } |
| 37 | let Some(scheme) = analysis.typeck.schemes.get(&id) else { |
| 38 | continue; |
| 39 | }; |
| 40 | let Ty::Fn(params, ret, effects, _) = &scheme.ty else { |
| 41 | continue; |
| 42 | }; |
| 43 | let Some(fn_node) = fn_node_at(&root, def.span.range) else { |
| 44 | continue; |
| 45 | }; |
| 46 | let Some(range) = signature_range(&fn_node) else { |
| 47 | continue; |
| 48 | }; |
| 49 | let p = Printer { |
| 50 | hir, |
| 51 | ctx: None, |
| 52 | gen_names: &scheme.vars, |
| 53 | rigid_names: &[], |
| 54 | }; |
| 55 | let params: Vec<String> = f |
| 56 | .sig |
| 57 | .params |
| 58 | .iter() |
| 59 | .zip(params) |
| 60 | .map(|(param, ty)| { |
| 61 | let typed = format!("{}: {}", param.name, p.ty(&ty.ty)); |
| 62 | match ¶m.label { |
| 63 | // `~name: T` puns; `~label:(name: T)` renames. |
| 64 | Some(l) if *l == param.name => format!("~{l}: {}", p.ty(&ty.ty)), |
| 65 | Some(l) => format!("~{l}:({typed})"), |
| 66 | None => typed, |
| 67 | } |
| 68 | }) |
| 69 | .collect(); |
| 70 | let mut text = params.join(" "); |
| 71 | if !params.is_empty() { |
| 72 | text.push(' '); |
| 73 | } |
| 74 | text.push_str(&format!("-> {}", p.ty(ret))); |
| 75 | if !matches!(**effects, Ty::RowEmpty | Ty::RowEvidence) { |
| 76 | // The type printer shows a function's row after ` / `. |
| 77 | let fn_text = p.ty(&Ty::func_eff(Vec::new(), Ty::unit(), (**effects).clone())); |
| 78 | if let Some((_, row)) = fn_text.split_once(" / ") { |
| 79 | text.push_str(" / "); |
| 80 | text.push_str(row); |
| 81 | } |
| 82 | } |
| 83 | let cs: Vec<String> = scheme.all_constraints().map(|c| p.constraint(c)).collect(); |
| 84 | if !cs.is_empty() { |
| 85 | text.push_str(" where "); |
| 86 | text.push_str(&cs.join(", ")); |
| 87 | } |
| 88 | out.push(SignatureFix { |
| 89 | title: format!("Insert inferred signature of `{}`", def.name), |
| 90 | range, |
| 91 | new_text: text, |
| 92 | }); |
| 93 | } |
| 94 | out |
| 95 | } |
| 96 | |
| 97 | /// An inlay hint: text shown after `offset` without being part of it. |
| 98 | #[derive(Clone, PartialEq, Debug)] |
| 99 | pub struct InlayHint { |
| 100 | pub offset: louise_span::TextSize, |
| 101 | pub label: String, |
| 102 | } |
| 103 | |
| 104 | /// The inferred parts of functions without a complete signature: parameter |
| 105 | /// types, the result type and the effect row (ADR 0001: private functions |
| 106 | /// are inferred; seeing their effects is the point). |
| 107 | pub fn inlay_hints(db: &Db, analysis: &Analysis, file: FileId) -> Vec<InlayHint> { |
| 108 | let hir = &analysis.hir; |
| 109 | let Some(parse) = db.parse(file) else { |
| 110 | return Vec::new(); |
| 111 | }; |
| 112 | let root = parse.syntax(); |
| 113 | let mut out = Vec::new(); |
| 114 | for (id, def) in hir.defs.iter() { |
| 115 | let DefKind::Fn(f) = &def.kind else { continue }; |
| 116 | if hir.modules[def.module].file != file || f.body.is_none() { |
| 117 | continue; |
| 118 | } |
| 119 | let complete = f.sig.ret.is_some() && f.sig.params.iter().all(|p| p.ty.is_some()); |
| 120 | if complete { |
| 121 | continue; |
| 122 | } |
| 123 | let Some(scheme) = analysis.typeck.schemes.get(&id) else { |
| 124 | continue; |
| 125 | }; |
| 126 | let Ty::Fn(params, ret, effects, _) = &scheme.ty else { |
| 127 | continue; |
| 128 | }; |
| 129 | let p = Printer { |
| 130 | hir, |
| 131 | ctx: None, |
| 132 | gen_names: &scheme.vars, |
| 133 | rigid_names: &[], |
| 134 | }; |
| 135 | for (param, ty) in f.sig.params.iter().zip(params) { |
| 136 | if param.ty.is_none() { |
| 137 | out.push(InlayHint { |
| 138 | offset: param.span.end(), |
| 139 | label: format!(": {}", p.ty(&ty.ty)), |
| 140 | }); |
| 141 | } |
| 142 | } |
| 143 | let row = row_text(&p, effects); |
| 144 | let Some(fn_node) = fn_node_at(&root, def.span.range) else { |
| 145 | continue; |
| 146 | }; |
| 147 | let end_of = |kind: SyntaxKind| { |
| 148 | fn_node |
| 149 | .children() |
| 150 | .find(|n| n.kind() == kind) |
| 151 | .map(|n| n.text_range().end()) |
| 152 | }; |
| 153 | match (f.sig.ret.is_some(), f.sig.effects.is_some()) { |
| 154 | (false, _) => { |
| 155 | if let Some(offset) = end_of(SyntaxKind::PARAM_LIST) { |
| 156 | out.push(InlayHint { |
| 157 | offset, |
| 158 | label: format!(" -> {}{row}", p.ty(ret)), |
| 159 | }); |
| 160 | } |
| 161 | } |
| 162 | (true, false) if !row.is_empty() => { |
| 163 | if let Some(offset) = end_of(SyntaxKind::RET_TYPE) { |
| 164 | out.push(InlayHint { offset, label: row }); |
| 165 | } |
| 166 | } |
| 167 | _ => {} |
| 168 | } |
| 169 | } |
| 170 | out.sort_by_key(|h| h.offset); |
| 171 | out |
| 172 | } |
| 173 | |
| 174 | /// ` / <row>`, or nothing for a total function. |
| 175 | fn row_text(p: &Printer, effects: &Ty) -> String { |
| 176 | if matches!(effects, Ty::RowEmpty | Ty::RowEvidence) { |
| 177 | return String::new(); |
| 178 | } |
| 179 | let fn_text = p.ty(&Ty::func_eff(Vec::new(), Ty::unit(), effects.clone())); |
| 180 | fn_text |
| 181 | .split_once(" / ") |
| 182 | .map_or(String::new(), |(_, row)| format!(" / {row}")) |
| 183 | } |
| 184 | |
| 185 | fn fn_node_at(root: &SyntaxNode, name: TextRange) -> Option<SyntaxNode> { |
| 186 | root.covering_element(name) |
| 187 | .ancestors() |
| 188 | .find(|n| n.kind() == SyntaxKind::FN_DEF) |
| 189 | } |
| 190 | |
| 191 | /// From the parameter list to the end of the return type / where clause. |
| 192 | fn signature_range(fn_node: &SyntaxNode) -> Option<TextRange> { |
| 193 | let parts: Vec<_> = fn_node |
| 194 | .children() |
| 195 | .filter(|n| { |
| 196 | matches!( |
| 197 | n.kind(), |
| 198 | SyntaxKind::PARAM_LIST | SyntaxKind::RET_TYPE | SyntaxKind::WHERE_CLAUSE |
| 199 | ) |
| 200 | }) |
| 201 | .collect(); |
| 202 | let first = parts.first()?.text_range(); |
| 203 | let last = parts.last()?.text_range(); |
| 204 | Some(TextRange::new(first.start(), last.end())) |
| 205 | } |
| 206 | |
| 207 | #[cfg(test)] |
| 208 | mod tests { |
| 209 | use super::*; |
| 210 | |
| 211 | #[test] |
| 212 | fn hints_show_inferred_types_and_effects() { |
| 213 | let mut db = Db::new(); |
| 214 | 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"; |
| 215 | let file = db.add_module("main", "main.lse", src.into()); |
| 216 | let analysis = db.analyze(); |
| 217 | let hints = inlay_hints(&db, &analysis, file); |
| 218 | let labels: Vec<(usize, &str)> = hints |
| 219 | .iter() |
| 220 | .map(|h| (usize::from(h.offset), h.label.as_str())) |
| 221 | .collect(); |
| 222 | let after = |s: &str| src.find(s).unwrap() + s.len(); |
| 223 | assert_eq!( |
| 224 | labels, |
| 225 | vec![ |
| 226 | (after("fn greet :: name"), ": String"), |
| 227 | (after("fn greet :: name"), " -> () / <log>"), |
| 228 | ] |
| 229 | ); |
| 230 | } |
| 231 | |
| 232 | #[test] |
| 233 | fn completes_public_signatures_from_inference() { |
| 234 | let mut db = Db::new(); |
| 235 | let src = "effect log {\n fn log :: m: String -> ()\n}\npub fn describe :: x f {\n log (show x)\n f x\n}\n"; |
| 236 | let file = db.add_module("main", "main.lse", src.into()); |
| 237 | let analysis = db.analyze(); |
| 238 | let fixes = signature_fixes(&db, &analysis, file); |
| 239 | let [fix] = fixes.as_slice() else { |
| 240 | panic!("{fixes:?}") |
| 241 | }; |
| 242 | assert_eq!(&src[fix.range], "x f"); |
| 243 | assert_eq!( |
| 244 | fix.new_text, |
| 245 | "x: a f: fn(a) -> b / <log | e> -> b / <log | e> where Show<a>" |
| 246 | ); |
| 247 | // Applying it makes the module check cleanly. |
| 248 | let fixed = format!( |
| 249 | "{}{}{}", |
| 250 | &src[..usize::from(fix.range.start())], |
| 251 | fix.new_text, |
| 252 | &src[usize::from(fix.range.end())..] |
| 253 | ); |
| 254 | db.set_text(file, fixed); |
| 255 | assert!( |
| 256 | db.analyze().diagnostics.is_empty(), |
| 257 | "{:#?}", |
| 258 | db.analyze().diagnostics |
| 259 | ); |
| 260 | } |
| 261 | } |