Skip to main content

aft/
edit.rs

1//! Shared edit engine: byte-offset conversion, content replacement,
2//! syntax validation, and auto-backup orchestration.
3//!
4//! Used by `write`, `edit_symbol`, `edit_match`, and `batch` commands.
5
6#![cfg_attr(test, allow(clippy::items_after_test_module))]
7
8use std::path::Path;
9
10use crate::config::Config;
11use crate::context::AppContext;
12use crate::error::AftError;
13use crate::format;
14use crate::parser::{detect_language, grammar_for, FileParser};
15
16/// Convert 0-indexed line/col to a byte offset within `source`.
17///
18/// Tree-sitter columns are byte-indexed within the line, so `col` is a byte
19/// offset from the start of the line (not a character offset).
20///
21/// Scans raw bytes so both LF and CRLF line endings are counted correctly.
22/// Returns `source.len()` if line is beyond the end of the file.
23pub fn line_col_to_byte(source: &str, line: u32, col: u32) -> usize {
24    let bytes = source.as_bytes();
25    let target_line = line as usize;
26    let mut current_line = 0usize;
27    let mut line_start = 0usize;
28
29    loop {
30        let mut line_end = line_start;
31        while line_end < bytes.len() && bytes[line_end] != b'\n' && bytes[line_end] != b'\r' {
32            line_end += 1;
33        }
34
35        if current_line == target_line {
36            return line_start + (col as usize).min(line_end.saturating_sub(line_start));
37        }
38
39        if line_end >= bytes.len() {
40            return source.len();
41        }
42
43        line_start = if bytes[line_end] == b'\r'
44            && line_end + 1 < bytes.len()
45            && bytes[line_end + 1] == b'\n'
46        {
47            line_end + 2
48        } else {
49            line_end + 1
50        };
51        current_line += 1;
52    }
53}
54
55/// Replace bytes in `[start..end)` with `replacement`.
56///
57/// Returns an error if the range is invalid or does not align to UTF-8 char boundaries.
58pub fn replace_byte_range(
59    source: &str,
60    start: usize,
61    end: usize,
62    replacement: &str,
63) -> Result<String, AftError> {
64    if start > end {
65        return Err(AftError::InvalidRequest {
66            message: format!(
67                "invalid byte range [{}..{}): start must be <= end",
68                start, end
69            ),
70        });
71    }
72    if end > source.len() {
73        return Err(AftError::InvalidRequest {
74            message: format!(
75                "invalid byte range [{}..{}): end exceeds source length {}",
76                start,
77                end,
78                source.len()
79            ),
80        });
81    }
82    if !source.is_char_boundary(start) {
83        return Err(AftError::InvalidRequest {
84            message: format!(
85                "invalid byte range [{}..{}): start is not a char boundary",
86                start, end
87            ),
88        });
89    }
90    if !source.is_char_boundary(end) {
91        return Err(AftError::InvalidRequest {
92            message: format!(
93                "invalid byte range [{}..{}): end is not a char boundary",
94                start, end
95            ),
96        });
97    }
98
99    let mut result = String::with_capacity(
100        source.len().saturating_sub(end.saturating_sub(start)) + replacement.len(),
101    );
102    result.push_str(&source[..start]);
103    result.push_str(replacement);
104    result.push_str(&source[end..]);
105    Ok(result)
106}
107
108/// Validate syntax of a file using a fresh FileParser (D023).
109///
110/// Returns `Ok(Some(true))` if syntax is valid, `Ok(Some(false))` if there are
111/// parse errors, and `Ok(None)` if the language is unsupported.
112pub fn validate_syntax(path: &Path) -> Result<Option<bool>, AftError> {
113    let mut parser = FileParser::new();
114    match parser.parse(path) {
115        Ok((tree, _lang)) => Ok(Some(!tree.root_node().has_error())),
116        Err(AftError::InvalidRequest { .. }) => {
117            // Unsupported language — not an error, just can't validate
118            Ok(None)
119        }
120        Err(e) => Err(e),
121    }
122}
123
124/// Validate syntax of an in-memory string without touching disk.
125///
126/// Uses `detect_language(path)` + `grammar_for(lang)` + `parser.parse()`
127/// to validate syntax of a proposed content string. Returns `None` for
128/// unsupported languages, `Some(true)` for valid, `Some(false)` for invalid.
129pub fn validate_syntax_str(content: &str, path: &Path) -> Option<bool> {
130    let lang = detect_language(path)?;
131    let grammar = grammar_for(lang);
132    let mut parser = tree_sitter::Parser::new();
133    if parser.set_language(&grammar).is_err() {
134        return None;
135    }
136    let tree = parser.parse(content.as_bytes(), None)?;
137    Some(!tree.root_node().has_error())
138}
139
140/// Result of a dry-run diff computation.
141pub struct DryRunResult {
142    /// Unified diff between original and proposed content.
143    pub diff: String,
144    /// Whether the proposed content has valid syntax. `None` for unsupported languages.
145    pub syntax_valid: Option<bool>,
146}
147
148/// Compute a unified diff between original and proposed content, plus syntax validation.
149///
150/// Returns a standard unified diff with `a/` and `b/` path prefixes and 3 lines of context.
151/// Also validates syntax of the proposed content via tree-sitter.
152pub fn dry_run_diff(original: &str, proposed: &str, path: &Path) -> DryRunResult {
153    let display_path = path.display().to_string();
154    let text_diff = similar::TextDiff::from_lines(original, proposed);
155    let diff = text_diff
156        .unified_diff()
157        .context_radius(3)
158        .header(
159            &format!("a/{}", display_path),
160            &format!("b/{}", display_path),
161        )
162        .to_string();
163    let syntax_valid = validate_syntax_str(proposed, path);
164    DryRunResult { diff, syntax_valid }
165}
166
167/// Extract the `dry_run` boolean from request params.
168///
169/// Returns `true` if `params["dry_run"]` is `true`, `false` otherwise.
170pub fn is_dry_run(params: &serde_json::Value) -> bool {
171    params
172        .get("dry_run")
173        .and_then(|v| v.as_bool())
174        .unwrap_or(false)
175}
176
177/// Check if the caller requested diff info in the response.
178pub fn wants_diff(params: &serde_json::Value) -> bool {
179    params
180        .get("include_diff")
181        .and_then(|v| v.as_bool())
182        .unwrap_or(false)
183}
184
185/// Compute diff info between before/after content for UI metadata.
186/// Returns a JSON value with before, after, additions, deletions.
187/// For files >512KB, omits full content and returns only counts.
188pub fn compute_diff_info(before: &str, after: &str) -> serde_json::Value {
189    use similar::ChangeTag;
190
191    let diff = similar::TextDiff::from_lines(before, after);
192    let mut additions = 0usize;
193    let mut deletions = 0usize;
194    for change in diff.iter_all_changes() {
195        match change.tag() {
196            ChangeTag::Insert => additions += 1,
197            ChangeTag::Delete => deletions += 1,
198            ChangeTag::Equal => {}
199        }
200    }
201
202    // For large files, skip sending full content to avoid bloating JSON
203    let size_limit = 512 * 1024; // 512KB
204    if before.len() > size_limit || after.len() > size_limit {
205        serde_json::json!({
206            "additions": additions,
207            "deletions": deletions,
208            "truncated": true,
209        })
210    } else {
211        serde_json::json!({
212            "before": before,
213            "after": after,
214            "additions": additions,
215            "deletions": deletions,
216        })
217    }
218}
219/// Snapshot the file into the backup store before mutation, scoped to a session.
220///
221/// Returns `Ok(Some(backup_id))` if the file existed and was backed up,
222/// `Ok(None)` if the file doesn't exist (new file creation).
223///
224/// The `session` argument is the request-level session namespace (see
225/// [`crate::protocol::RawRequest::session`]). Snapshots created by one session
226/// are not visible from another, which is what keeps undo state isolated in
227/// a shared-bridge setup (issue #14).
228///
229/// Drops the RefCell borrow before returning (D029).
230pub fn auto_backup(
231    ctx: &AppContext,
232    session: &str,
233    path: &Path,
234    description: &str,
235) -> Result<Option<String>, AftError> {
236    if !path.exists() {
237        return Ok(None);
238    }
239    let backup_id = {
240        let mut store = ctx.backup().borrow_mut();
241        store.snapshot(session, path, description)?
242    }; // borrow dropped here
243    Ok(Some(backup_id))
244}
245
246/// Result of the write → format → validate pipeline.
247///
248/// Returned by `write_format_validate` to give callers a single struct
249/// with all post-write signals for the response JSON.
250pub struct WriteResult {
251    /// Whether tree-sitter syntax validation passed. `None` if unsupported language.
252    pub syntax_valid: Option<bool>,
253    /// Whether the file was auto-formatted.
254    pub formatted: bool,
255    /// Why formatting was skipped, if it was. Values: "unsupported_language",
256    /// "no_formatter_configured", "formatter_not_installed", "formatter_excluded_path",
257    /// "timeout", "error".
258    pub format_skipped_reason: Option<String>,
259    /// Whether full validation was requested (controls whether validation_errors is included in response).
260    pub validate_requested: bool,
261    /// Structured type-checker errors (only populated when validate:"full" is requested).
262    pub validation_errors: Vec<format::ValidationError>,
263    /// Why validation was skipped, if it was. Values: "unsupported_language",
264    /// "no_checker_configured", "checker_not_installed", "timeout", "error".
265    pub validate_skipped_reason: Option<String>,
266    /// Per-edit LSP diagnostics outcome (v0.17.3). Carries the verified-fresh
267    /// diagnostics PLUS per-server status (pending/exited) so the response
268    /// can report `complete: bool` honestly.
269    ///
270    /// `None` means the caller didn't request diagnostics OR the request
271    /// was a fire-and-forget notify (no wait). `Some(outcome)` always
272    /// reports diagnostics from servers that proved freshness against the
273    /// post-edit document version.
274    pub lsp_outcome: Option<crate::lsp::manager::PostEditWaitOutcome>,
275}
276
277impl WriteResult {
278    /// Append LSP diagnostics + per-server status to a response JSON
279    /// object.
280    ///
281    /// v0.17.3 honest-reporting contract: when diagnostics were requested
282    /// (`lsp_outcome.is_some()`), this ALWAYS emits `lsp_diagnostics: [...]`
283    /// (even if empty) plus `lsp_complete: bool`, `lsp_pending_servers`,
284    /// and `lsp_exited_servers`. Empty `lsp_diagnostics` no longer means
285    /// "the field disappeared" — it means "we waited and got an explicit
286    /// fresh-but-clean result, OR every expected server is in the pending/
287    /// exited list (check `lsp_complete`)."
288    ///
289    /// When diagnostics were NOT requested (`lsp_outcome.is_none()`),
290    /// nothing is added — keeps the no-LSP edit path's response shape
291    /// unchanged.
292    pub fn append_lsp_diagnostics_to(&self, result: &mut serde_json::Value) {
293        let Some(outcome) = self.lsp_outcome.as_ref() else {
294            return;
295        };
296
297        result["lsp_diagnostics"] = serde_json::json!(outcome
298            .diagnostics
299            .iter()
300            .map(|d| {
301                serde_json::json!({
302                    "file": d.file.display().to_string(),
303                    "line": d.line,
304                    "column": d.column,
305                    "end_line": d.end_line,
306                    "end_column": d.end_column,
307                    "severity": d.severity.as_str(),
308                    "message": d.message,
309                    "code": d.code,
310                    "source": d.source,
311                })
312            })
313            .collect::<Vec<_>>());
314
315        result["lsp_complete"] = serde_json::Value::Bool(outcome.complete());
316
317        if !outcome.pending_servers.is_empty() {
318            result["lsp_pending_servers"] = serde_json::json!(outcome
319                .pending_servers
320                .iter()
321                .map(|key| key.kind.id_str().to_string())
322                .collect::<Vec<_>>());
323        }
324        if !outcome.exited_servers.is_empty() {
325            result["lsp_exited_servers"] = serde_json::json!(outcome
326                .exited_servers
327                .iter()
328                .map(|key| key.kind.id_str().to_string())
329                .collect::<Vec<_>>());
330        }
331    }
332}
333
334/// Write content to disk, auto-format, then validate syntax.
335///
336/// This is the shared tail for all mutation commands. The pipeline order is:
337/// 1. `fs::write` — persist content
338/// 2. `auto_format` — run the project formatter (reads the written file, writes back)
339/// 3. `validate_syntax` — parse the (potentially formatted) file
340/// 4. `validate_full` — run type checker if requested by params or config
341///
342/// The `params` argument carries the original request parameters. When it
343/// contains `"validate": "full"`, or config sets `validate_on_edit: "full"`,
344/// the project's type checker is invoked after syntax validation and the
345/// results are included in `WriteResult`.
346pub fn write_format_validate(
347    path: &Path,
348    content: &str,
349    config: &Config,
350    params: &serde_json::Value,
351) -> Result<WriteResult, AftError> {
352    // Step 1: Write
353    std::fs::write(path, content).map_err(|e| AftError::InvalidRequest {
354        message: format!("failed to write file: {}", e),
355    })?;
356
357    // Step 2: Format (before validate so we validate the formatted content)
358    let (formatted, format_skipped_reason) = format::auto_format(path, config);
359
360    // Step 3: Validate syntax
361    let syntax_valid = match validate_syntax(path) {
362        Ok(sv) => sv,
363        Err(_) => None,
364    };
365
366    // Step 4: Full validation (type checker) — only when requested
367    let param_validate = params.get("validate").and_then(|v| v.as_str());
368    let config_validate = config.validate_on_edit.as_deref();
369    // Explicit param overrides config. Valid values: "syntax" | "full" | "off".
370    let validate_mode = param_validate.or(config_validate).unwrap_or("off");
371    let validate_requested = validate_mode == "full";
372    let (validation_errors, validate_skipped_reason) = if validate_requested {
373        format::validate_full(path, config)
374    } else {
375        (Vec::new(), None)
376    };
377
378    Ok(WriteResult {
379        syntax_valid,
380        formatted,
381        format_skipped_reason,
382        validate_requested,
383        validation_errors,
384        validate_skipped_reason,
385        lsp_outcome: None,
386    })
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    // --- line_col_to_byte ---
394
395    #[test]
396    fn line_col_to_byte_empty_string() {
397        assert_eq!(line_col_to_byte("", 0, 0), 0);
398    }
399
400    #[test]
401    fn line_col_to_byte_single_line() {
402        let source = "hello";
403        assert_eq!(line_col_to_byte(source, 0, 0), 0);
404        assert_eq!(line_col_to_byte(source, 0, 3), 3);
405        assert_eq!(line_col_to_byte(source, 0, 5), 5); // end of line
406    }
407
408    #[test]
409    fn line_col_to_byte_multi_line() {
410        let source = "abc\ndef\nghi\n";
411        // line 0: "abc" at bytes 0..3, newline at 3
412        assert_eq!(line_col_to_byte(source, 0, 0), 0);
413        assert_eq!(line_col_to_byte(source, 0, 2), 2);
414        // line 1: "def" at bytes 4..7, newline at 7
415        assert_eq!(line_col_to_byte(source, 1, 0), 4);
416        assert_eq!(line_col_to_byte(source, 1, 3), 7);
417        // line 2: "ghi" at bytes 8..11, newline at 11
418        assert_eq!(line_col_to_byte(source, 2, 0), 8);
419        assert_eq!(line_col_to_byte(source, 2, 2), 10);
420    }
421
422    #[test]
423    fn line_col_to_byte_last_line_no_trailing_newline() {
424        let source = "abc\ndef";
425        // line 1: "def" at bytes 4..7, no trailing newline
426        assert_eq!(line_col_to_byte(source, 1, 0), 4);
427        assert_eq!(line_col_to_byte(source, 1, 3), 7); // end
428    }
429
430    #[test]
431    fn line_col_to_byte_multi_byte_utf8() {
432        // "é" is 2 bytes in UTF-8
433        let source = "café\nbar";
434        // line 0: "café" is 5 bytes (c=1, a=1, f=1, é=2)
435        assert_eq!(line_col_to_byte(source, 0, 0), 0);
436        assert_eq!(line_col_to_byte(source, 0, 5), 5); // end of "café"
437                                                       // line 1: "bar" starts at byte 6
438        assert_eq!(line_col_to_byte(source, 1, 0), 6);
439        assert_eq!(line_col_to_byte(source, 1, 2), 8);
440    }
441
442    #[test]
443    fn line_col_to_byte_beyond_end() {
444        let source = "abc";
445        // Line beyond file returns source.len()
446        assert_eq!(line_col_to_byte(source, 5, 0), source.len());
447    }
448
449    #[test]
450    fn line_col_to_byte_col_clamped_to_line_length() {
451        let source = "ab\ncd";
452        // col=10 on a 2-char line should clamp to 2
453        assert_eq!(line_col_to_byte(source, 0, 10), 2);
454    }
455
456    #[test]
457    fn line_col_to_byte_crlf() {
458        let source = "abc\r\ndef\r\nghi\r\n";
459        assert_eq!(line_col_to_byte(source, 0, 0), 0);
460        assert_eq!(line_col_to_byte(source, 0, 10), 3);
461        assert_eq!(line_col_to_byte(source, 1, 0), 5);
462        assert_eq!(line_col_to_byte(source, 1, 3), 8);
463        assert_eq!(line_col_to_byte(source, 2, 0), 10);
464    }
465
466    // --- replace_byte_range ---
467
468    #[test]
469    fn replace_byte_range_basic() {
470        let source = "hello world";
471        let result = replace_byte_range(source, 6, 11, "rust").unwrap();
472        assert_eq!(result, "hello rust");
473    }
474
475    #[test]
476    fn replace_byte_range_delete() {
477        let source = "hello world";
478        let result = replace_byte_range(source, 5, 11, "").unwrap();
479        assert_eq!(result, "hello");
480    }
481
482    #[test]
483    fn replace_byte_range_insert_at_same_position() {
484        let source = "helloworld";
485        let result = replace_byte_range(source, 5, 5, " ").unwrap();
486        assert_eq!(result, "hello world");
487    }
488
489    #[test]
490    fn replace_byte_range_replace_entire_string() {
491        let source = "old content";
492        let result = replace_byte_range(source, 0, source.len(), "new content").unwrap();
493        assert_eq!(result, "new content");
494    }
495}