1use crate::lsp::backend::{EditResult, RangeEdit, TextRange0Based};
10
11pub fn offset_of(content: &str, line: u32, character: u32) -> Result<usize, String> {
15 let mut offset = 0usize;
16 let mut cur_line = 0u32;
17 for l in content.split_inclusive('\n') {
18 if cur_line == line {
19 let line_len = l.trim_end_matches('\n').len();
20 if character as usize > line_len {
21 return Err(format!(
22 "POSITION_OUT_OF_RANGE: character {character} past end of line {line}"
23 ));
24 }
25 return Ok(offset + character as usize);
26 }
27 offset += l.len();
28 cur_line += 1;
29 }
30 if line == cur_line && character == 0 {
32 return Ok(offset);
33 }
34 Err(format!(
35 "POSITION_OUT_OF_RANGE: line {line} past end of file"
36 ))
37}
38
39pub fn local_range_write(edit: &RangeEdit) -> Result<EditResult, String> {
44 let content = std::fs::read_to_string(&edit.abs_path)
45 .map_err(|e| format!("FILE_NOT_FOUND: {}: {e}", edit.abs_path))?;
46
47 let start = offset_of(&content, edit.range.start_line, edit.range.start_char)?;
48 let end = offset_of(&content, edit.range.end_line, edit.range.end_char)?;
49 if end < start {
50 return Err("POSITION_OUT_OF_RANGE: end before start".to_string());
51 }
52 let old = &content[start..end];
53
54 if let Some(expected) = edit.expected_hash.as_deref() {
55 let actual = crate::core::hasher::hash_hex(old.as_bytes());
56 if expected != actual {
57 return Err(format!(
58 "CONFLICT: range hash mismatch (expected={expected}, actual={actual})"
59 ));
60 }
61 }
62
63 let mut new_content = String::with_capacity(content.len() - old.len() + edit.text.len());
64 new_content.push_str(&content[..start]);
65 new_content.push_str(&edit.text);
66 new_content.push_str(&content[end..]);
67
68 write_file_atomic(&edit.abs_path, &new_content)?;
69
70 let new_range = range_after_write(&content[..start], &edit.text);
71 Ok(EditResult {
72 applied: true,
73 new_range,
74 edited_text: edit.text.clone(),
75 diff: build_range_diff(&edit.rel_path, old, &edit.text),
76 })
77}
78
79fn nearest_git_root(abs_path: &str) -> Option<String> {
83 let mut dir = std::path::Path::new(abs_path).parent();
84 while let Some(d) = dir {
85 if d.join(".git").exists() {
86 return Some(d.to_string_lossy().to_string());
87 }
88 dir = d.parent();
89 }
90 None
91}
92
93pub fn overview_from_index(abs_path: &str) -> Vec<crate::lsp::backend::SymbolOverviewItem> {
97 use crate::core::graph_provider;
98 let Some(project_root) = nearest_git_root(abs_path) else {
99 return Vec::new();
100 };
101 let Some(open) = graph_provider::open_or_build(&project_root) else {
102 return Vec::new();
103 };
104 let rel = abs_path
105 .strip_prefix(&project_root)
106 .map_or(abs_path, |s| s.trim_start_matches('/'));
107 let mut items: Vec<_> = open
108 .provider
109 .find_symbols("", Some(rel), None)
110 .into_iter()
111 .map(|s| crate::lsp::backend::SymbolOverviewItem {
112 name: s.name,
113 kind: s.kind,
114 line: s.start_line as u32,
115 })
116 .collect();
117 items.sort_by_key(|i| i.line);
118 items
119}
120
121fn range_after_write(prefix: &str, text: &str) -> TextRange0Based {
124 let (sl, sc) = line_col_at_end(prefix);
125 let (dl, dc) = line_col_at_end(text);
126 let end_line = sl + dl;
127 let end_char = if dl == 0 { sc + dc } else { dc };
128 TextRange0Based {
129 start_line: sl,
130 start_char: sc,
131 end_line,
132 end_char,
133 }
134}
135
136fn line_col_at_end(s: &str) -> (u32, u32) {
138 let line = s.matches('\n').count() as u32;
139 let col = match s.rfind('\n') {
140 Some(i) => (s.len() - i - 1) as u32,
141 None => s.len() as u32,
142 };
143 (line, col)
144}
145
146fn build_range_diff(path: &str, old: &str, new: &str) -> String {
147 let mut out = format!("--- {path}\n");
148 for l in old.lines() {
149 out.push_str(&format!("- {l}\n"));
150 }
151 for l in new.lines() {
152 out.push_str(&format!("+ {l}\n"));
153 }
154 out
155}
156
157fn write_file_atomic(path: &str, content: &str) -> Result<(), String> {
158 let p = std::path::Path::new(path);
159 crate::core::pathjail::enforce_writable(p)?;
162 crate::core::atomic_fs::try_atomic_write(p, content.as_bytes(), None)
166 .map_err(|e| format!("atomic write failed: {e}"))
167}
168
169pub struct HeadlessBackend;
173
174impl crate::lsp::backend::LspBackend for HeadlessBackend {
175 fn open_file(&mut self, _u: &lsp_types::Uri, _l: &str, _t: &str) -> Result<(), String> {
176 Ok(())
177 }
178 fn references(
179 &mut self,
180 _u: &lsp_types::Uri,
181 _p: lsp_types::Position,
182 _s: &str,
183 ) -> Result<Vec<lsp_types::Location>, String> {
184 Err("references requires a backend".into())
185 }
186 fn definition(
187 &mut self,
188 _u: &lsp_types::Uri,
189 _p: lsp_types::Position,
190 ) -> Result<lsp_types::GotoDefinitionResponse, String> {
191 Err("definition requires a backend".into())
192 }
193 fn implementations(
194 &mut self,
195 _u: &lsp_types::Uri,
196 _p: lsp_types::Position,
197 _s: &str,
198 ) -> Result<Vec<lsp_types::Location>, String> {
199 Err("implementations requires a backend".into())
200 }
201 fn rename(
202 &mut self,
203 _u: &lsp_types::Uri,
204 _p: lsp_types::Position,
205 _n: &str,
206 ) -> Result<Option<lsp_types::WorkspaceEdit>, String> {
207 Err("rename requires a backend".into())
208 }
209 }
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 #[test]
218 fn offset_of_maps_lines_and_columns() {
219 let s = "ab\ncde\nf";
220 assert_eq!(offset_of(s, 0, 0).unwrap(), 0);
221 assert_eq!(offset_of(s, 0, 2).unwrap(), 2); assert_eq!(offset_of(s, 1, 0).unwrap(), 3); assert_eq!(offset_of(s, 1, 3).unwrap(), 6); assert_eq!(offset_of(s, 2, 1).unwrap(), 8); }
226
227 #[test]
228 fn offset_of_one_past_last_line_is_eof() {
229 let s = "ab\ncde\n";
230 assert_eq!(offset_of(s, 2, 0).unwrap(), s.len());
231 }
232
233 #[test]
234 fn offset_of_rejects_overrun() {
235 let s = "ab\ncde";
236 assert!(offset_of(s, 0, 5).is_err());
237 assert!(offset_of(s, 9, 0).is_err());
238 }
239
240 fn tmp_file(content: &str) -> (tempfile::TempDir, String) {
241 let dir = tempfile::tempdir().unwrap();
242 let path = dir.path().join("Foo.txt");
243 std::fs::write(&path, content).unwrap();
244 (dir, path.to_string_lossy().to_string())
245 }
246
247 fn edit(abs: &str, r: TextRange0Based, text: &str, hash: Option<String>) -> RangeEdit {
248 RangeEdit {
249 abs_path: abs.to_string(),
250 rel_path: "Foo.txt".to_string(),
251 range: r,
252 text: text.to_string(),
253 expected_hash: hash,
254 }
255 }
256
257 #[test]
258 fn local_range_write_replaces_range() {
259 let (_d, p) = tmp_file("aaa\nBODY\nccc\n");
260 let r = TextRange0Based {
261 start_line: 1,
262 start_char: 0,
263 end_line: 1,
264 end_char: 4,
265 };
266 let res = local_range_write(&edit(&p, r, "NEW", None)).unwrap();
267 assert!(res.applied);
268 assert_eq!(std::fs::read_to_string(&p).unwrap(), "aaa\nNEW\nccc\n");
269 assert_eq!(res.edited_text, "NEW");
270 }
271
272 #[cfg(unix)]
273 #[test]
274 fn local_range_write_ignores_a_planted_temp_symlink() {
275 let (d, p) = tmp_file("aaa\nBODY\nccc\n");
276 let outside = tempfile::tempdir().unwrap();
277 let target = outside.path().join("out.txt");
278 let planted = d
279 .path()
280 .join(format!(".Foo.txt.lean-ctx.v2a.tmp.{}", std::process::id()));
281 std::os::unix::fs::symlink(&target, &planted).unwrap();
282 let r = TextRange0Based {
283 start_line: 1,
284 start_char: 0,
285 end_line: 1,
286 end_char: 4,
287 };
288
289 local_range_write(&edit(&p, r, "NEW", None)).unwrap();
290
291 assert!(!target.exists());
292 let meta = std::fs::symlink_metadata(&p).unwrap();
293 assert!(!meta.file_type().is_symlink());
294 assert_eq!(std::fs::read_to_string(&p).unwrap(), "aaa\nNEW\nccc\n");
295 }
296
297 #[cfg(not(feature = "no-jail"))]
300 #[test]
301 fn local_range_write_denied_in_read_only_root() {
302 let _iso = crate::core::data_dir::isolated_data_dir();
303 let dir = tempfile::tempdir().unwrap();
304 let ro = dir.path().join("refrepo");
305 std::fs::create_dir_all(&ro).unwrap();
306 let path = ro.join("Foo.txt");
307 std::fs::write(&path, "aaa\nBODY\nccc\n").unwrap();
308
309 let ro_canon = crate::core::pathjail::canonicalize_or_self(&ro);
310 crate::test_env::set_var(
311 "LEAN_CTX_READ_ONLY_ROOTS",
312 ro_canon.to_string_lossy().as_ref(),
313 );
314 let r = TextRange0Based {
315 start_line: 1,
316 start_char: 0,
317 end_line: 1,
318 end_char: 4,
319 };
320 let res = local_range_write(&edit(&path.to_string_lossy(), r, "NEW", None));
321 crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
322
323 let err = res.expect_err("write into a read-only root must be denied");
324 assert!(
325 err.contains("read-only"),
326 "error must name the read-only tier: {err}"
327 );
328 assert_eq!(
329 std::fs::read_to_string(&path).unwrap(),
330 "aaa\nBODY\nccc\n",
331 "the file must be left untouched"
332 );
333 }
334
335 #[test]
336 fn overview_from_index_is_empty_without_graph() {
337 let items = overview_from_index("/nonexistent/Nope.rs");
339 assert!(items.is_empty(), "{items:?}");
340 }
341
342 #[test]
343 fn local_range_write_zero_width_insert() {
344 let (_d, p) = tmp_file("aaa\nccc\n");
345 let r = TextRange0Based {
346 start_line: 1,
347 start_char: 0,
348 end_line: 1,
349 end_char: 0,
350 };
351 local_range_write(&edit(&p, r, "bbb\n", None)).unwrap();
352 assert_eq!(std::fs::read_to_string(&p).unwrap(), "aaa\nbbb\nccc\n");
353 }
354
355 #[test]
356 fn local_range_write_hash_match_and_mismatch() {
357 let (_d, p) = tmp_file("aaa\nBODY\nccc\n");
358 let r = TextRange0Based {
359 start_line: 1,
360 start_char: 0,
361 end_line: 1,
362 end_char: 4,
363 };
364 let good = crate::core::hasher::hash_hex(b"BODY");
365 local_range_write(&edit(&p, r, "XXXX", Some(good))).unwrap();
367 assert_eq!(std::fs::read_to_string(&p).unwrap(), "aaa\nXXXX\nccc\n");
368 let err = local_range_write(&edit(&p, r, "YYYY", Some("deadbeef".into()))).unwrap_err();
370 assert!(err.starts_with("CONFLICT"), "got: {err}");
371 assert_eq!(std::fs::read_to_string(&p).unwrap(), "aaa\nXXXX\nccc\n");
372 }
373}