Skip to main content

r_dcf_syntax/
edit.rs

1//! Immutable and transactional text-preserving edits.
2
3use std::{error::Error, fmt, ops::Range};
4
5use crate::{
6    Field, FieldName, FormatStyle, LineEnding, LogicalValue, Parse, SourceSpan, make, parse,
7};
8
9/// Failure to apply a structured edit.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum EditError {
12    /// The selected record does not exist.
13    RecordOutOfBounds {
14        /// Requested zero-based record index.
15        index: usize,
16    },
17    /// No case-sensitive matching field exists.
18    FieldNotFound {
19        /// Requested case-sensitive field name.
20        name: String,
21    },
22}
23
24impl fmt::Display for EditError {
25    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::RecordOutOfBounds { index } => {
28                write!(formatter, "record index {index} is out of bounds")
29            }
30            Self::FieldNotFound { name } => write!(formatter, "field {name:?} was not found"),
31        }
32    }
33}
34
35impl Error for EditError {}
36
37impl Parse {
38    /// Starts a transactional editing session.
39    pub fn edit(&self) -> Editor {
40        Editor {
41            current: self.clone(),
42        }
43    }
44
45    /// Replaces the last matching field in one record.
46    ///
47    /// # Errors
48    ///
49    /// Returns an error if the record or field does not exist.
50    pub fn replace_last(
51        &self,
52        record: usize,
53        name: &str,
54        value: &LogicalValue,
55    ) -> Result<Self, EditError> {
56        replace(self, record, name, value, false)
57    }
58
59    /// Replaces all matching fields in one record.
60    ///
61    /// # Errors
62    ///
63    /// Returns an error if the record or field does not exist.
64    pub fn replace_all(
65        &self,
66        record: usize,
67        name: &str,
68        value: &LogicalValue,
69    ) -> Result<Self, EditError> {
70        replace(self, record, name, value, true)
71    }
72
73    /// Removes the last matching field in one record.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error if the record or field does not exist.
78    pub fn remove_last(&self, record: usize, name: &str) -> Result<Self, EditError> {
79        remove(self, record, name, false)
80    }
81
82    /// Removes all matching fields in one record.
83    ///
84    /// # Errors
85    ///
86    /// Returns an error if the record or field does not exist.
87    pub fn remove_all(&self, record: usize, name: &str) -> Result<Self, EditError> {
88        remove(self, record, name, true)
89    }
90
91    /// Inserts a new field after the last matching field in one record.
92    ///
93    /// # Errors
94    ///
95    /// Returns an error if the record or anchor field does not exist.
96    pub fn insert_after(
97        &self,
98        record: usize,
99        after: &str,
100        name: &FieldName,
101        value: &LogicalValue,
102    ) -> Result<Self, EditError> {
103        let selected = self
104            .records()
105            .nth(record)
106            .ok_or(EditError::RecordOutOfBounds { index: record })?;
107        let anchor = selected
108            .last_field(after)
109            .ok_or_else(|| EditError::FieldNotFound {
110                name: after.to_owned(),
111            })?;
112        let raw = anchor.raw_text();
113        let ending = final_ending(&raw);
114        let style = style_of(&anchor);
115        let new_field = make::field(name, value, &style);
116        let insertion = if ending.is_empty() {
117            format!("{}{new_field}", style.line_ending.as_str())
118        } else {
119            format!("{new_field}{ending}")
120        };
121        let offset = anchor.source_range().end;
122        Ok(parse(&replace_ranges(
123            &self.to_string(),
124            &[(SourceSpan::new(offset, offset), insertion)],
125        )))
126    }
127
128    /// Sets one canonical field, removing earlier matching declarations.
129    ///
130    /// If the field is absent, it is inserted after the final valid field in
131    /// the selected record. The supplied style applies only to the field being
132    /// set; all other source text is preserved.
133    ///
134    /// # Errors
135    ///
136    /// Returns an error if the record is absent or an absent field has no
137    /// valid insertion anchor.
138    pub fn set_unique(
139        &self,
140        record: usize,
141        name: &FieldName,
142        value: &LogicalValue,
143        style: &FormatStyle,
144    ) -> Result<Self, EditError> {
145        set_unique(self, record, name, value, style)
146    }
147}
148
149/// A chainable editing session. Each operation is atomic; `finish` returns the
150/// latest persistent parse.
151#[derive(Debug, Clone)]
152pub struct Editor {
153    current: Parse,
154}
155
156impl Editor {
157    /// Replaces the last matching field.
158    ///
159    /// # Errors
160    ///
161    /// Returns an error if the record or field does not exist.
162    pub fn replace_last(
163        mut self,
164        record: usize,
165        name: &str,
166        value: &LogicalValue,
167    ) -> Result<Self, EditError> {
168        self.current = self.current.replace_last(record, name, value)?;
169        Ok(self)
170    }
171
172    /// Replaces all matching fields.
173    ///
174    /// # Errors
175    ///
176    /// Returns an error if the record or field does not exist.
177    pub fn replace_all(
178        mut self,
179        record: usize,
180        name: &str,
181        value: &LogicalValue,
182    ) -> Result<Self, EditError> {
183        self.current = self.current.replace_all(record, name, value)?;
184        Ok(self)
185    }
186
187    /// Inserts a field after the last matching field.
188    ///
189    /// # Errors
190    ///
191    /// Returns an error if the record or anchor field does not exist.
192    pub fn insert_after(
193        mut self,
194        record: usize,
195        after: &str,
196        name: &FieldName,
197        value: &LogicalValue,
198    ) -> Result<Self, EditError> {
199        self.current = self.current.insert_after(record, after, name, value)?;
200        Ok(self)
201    }
202
203    /// Removes the last matching field.
204    ///
205    /// # Errors
206    ///
207    /// Returns an error if the record or field does not exist.
208    pub fn remove_last(mut self, record: usize, name: &str) -> Result<Self, EditError> {
209        self.current = self.current.remove_last(record, name)?;
210        Ok(self)
211    }
212
213    /// Removes all matching fields.
214    ///
215    /// # Errors
216    ///
217    /// Returns an error if the record or field does not exist.
218    pub fn remove_all(mut self, record: usize, name: &str) -> Result<Self, EditError> {
219        self.current = self.current.remove_all(record, name)?;
220        Ok(self)
221    }
222
223    /// Sets one canonical field and removes earlier matching declarations.
224    ///
225    /// # Errors
226    ///
227    /// Returns an error if the record is absent or an absent field has no
228    /// valid insertion anchor.
229    pub fn set_unique(
230        mut self,
231        record: usize,
232        name: &FieldName,
233        value: &LogicalValue,
234        style: &FormatStyle,
235    ) -> Result<Self, EditError> {
236        self.current = self.current.set_unique(record, name, value, style)?;
237        Ok(self)
238    }
239
240    /// Completes the transaction.
241    pub fn finish(self) -> Parse {
242        self.current
243    }
244}
245
246fn replace(
247    parse_result: &Parse,
248    record_index: usize,
249    name: &str,
250    value: &LogicalValue,
251    all: bool,
252) -> Result<Parse, EditError> {
253    let record = parse_result
254        .records()
255        .nth(record_index)
256        .ok_or(EditError::RecordOutOfBounds {
257            index: record_index,
258        })?;
259    let mut fields: Vec<_> = record.fields_named(name).collect();
260    if fields.is_empty() {
261        return Err(EditError::FieldNotFound {
262            name: name.to_owned(),
263        });
264    }
265    if !all {
266        fields.drain(..fields.len() - 1);
267    }
268    let replacements: Vec<_> = fields
269        .iter()
270        .map(|field| (field.source_range(), styled_replacement(field, value)))
271        .collect();
272    Ok(parse(&replace_ranges(
273        &parse_result.to_string(),
274        &replacements,
275    )))
276}
277
278fn remove(
279    parse_result: &Parse,
280    record_index: usize,
281    name: &str,
282    all: bool,
283) -> Result<Parse, EditError> {
284    let record = parse_result
285        .records()
286        .nth(record_index)
287        .ok_or(EditError::RecordOutOfBounds {
288            index: record_index,
289        })?;
290    let mut fields: Vec<_> = record.fields_named(name).collect();
291    if fields.is_empty() {
292        return Err(EditError::FieldNotFound {
293            name: name.to_owned(),
294        });
295    }
296    if !all {
297        fields.drain(..fields.len() - 1);
298    }
299    let replacements: Vec<_> = fields
300        .iter()
301        .map(|field| (field.source_range(), String::new()))
302        .collect();
303    Ok(parse(&replace_ranges(
304        &parse_result.to_string(),
305        &replacements,
306    )))
307}
308
309fn set_unique(
310    parse_result: &Parse,
311    record_index: usize,
312    name: &FieldName,
313    value: &LogicalValue,
314    style: &FormatStyle,
315) -> Result<Parse, EditError> {
316    let record = parse_result
317        .records()
318        .nth(record_index)
319        .ok_or(EditError::RecordOutOfBounds {
320            index: record_index,
321        })?;
322    let fields = record.fields_named(name.as_str()).collect::<Vec<_>>();
323    let source = parse_result.to_string();
324
325    if fields.is_empty() {
326        let anchor = record
327            .fields()
328            .last()
329            .ok_or_else(|| EditError::FieldNotFound {
330                name: "<insertion anchor>".to_owned(),
331            })?;
332        let raw = anchor.raw_text();
333        let ending = final_ending(&raw);
334        let field = make::field(name, value, style);
335        let insertion = if ending.is_empty() {
336            format!("{}{field}", style.line_ending.as_str())
337        } else {
338            format!("{field}{ending}")
339        };
340        let offset = anchor.source_range().end;
341        return Ok(parse(&replace_ranges(
342            &source,
343            &[(SourceSpan::new(offset, offset), insertion)],
344        )));
345    }
346
347    let Some((last, earlier)) = fields.split_last() else {
348        return Ok(parse_result.clone());
349    };
350    let ending = final_ending(&last.raw_text()).to_owned();
351    let replacement = format!("{}{ending}", make::field(name, value, style));
352    let mut replacements = earlier
353        .iter()
354        .map(|field| (field.source_range(), String::new()))
355        .collect::<Vec<_>>();
356    replacements.push((last.source_range(), replacement));
357    Ok(parse(&replace_ranges(&source, &replacements)))
358}
359
360fn styled_replacement(field: &Field, value: &LogicalValue) -> String {
361    let raw = field.raw_text();
362    let ending = final_ending(&raw);
363    let name = FieldName::new(field.name().expect("valid fields have names"))
364        .expect("parser validates field names");
365    let style = style_of(field);
366    let first_body = raw.split(['\r', '\n']).next().unwrap_or_default();
367    let after_colon = first_body.split_once(':').map_or("", |(_, text)| text);
368    let prefix_len = after_colon
369        .bytes()
370        .take_while(|byte| matches!(byte, b' ' | b'\t'))
371        .count();
372    let prefix = &after_colon[..prefix_len];
373    let mut lines = value.as_str().split('\n');
374    let first = lines.next().unwrap_or_default();
375    let mut replacement = format!("{name}:{prefix}{first}");
376    for line in lines {
377        replacement.push_str(style.line_ending.as_str());
378        replacement.push_str(&style.continuation_indent);
379        replacement.push_str(if line.is_empty() { "." } else { line });
380    }
381    replacement.push_str(ending);
382    replacement
383}
384
385fn style_of(field: &Field) -> FormatStyle {
386    let raw = field.raw_text();
387    let line_ending = if raw.contains("\r\n") {
388        LineEnding::CrLf
389    } else if raw.contains('\r') {
390        LineEnding::Cr
391    } else {
392        LineEnding::Lf
393    };
394    let first_body = raw.split(['\r', '\n']).next().unwrap_or_default();
395    let after_colon = first_body.split_once(':').map_or("", |(_, value)| value);
396    FormatStyle {
397        line_ending,
398        continuation_indent: continuation_indent(&raw).unwrap_or_else(|| " ".to_owned()),
399        space_after_colon: after_colon.starts_with([' ', '\t']),
400    }
401}
402
403fn continuation_indent(raw: &str) -> Option<String> {
404    raw.split(['\r', '\n']).skip(1).find_map(|line| {
405        let length = line
406            .bytes()
407            .take_while(|byte| matches!(byte, b' ' | b'\t'))
408            .count();
409        (length > 0).then(|| line[..length].to_owned())
410    })
411}
412
413fn final_ending(raw: &str) -> &str {
414    if raw.ends_with("\r\n") {
415        "\r\n"
416    } else if raw.ends_with('\r') {
417        "\r"
418    } else if raw.ends_with('\n') {
419        "\n"
420    } else {
421        ""
422    }
423}
424
425fn replace_ranges(source: &str, replacements: &[(SourceSpan, String)]) -> String {
426    let mut replacements = replacements.to_vec();
427    replacements.sort_unstable_by_key(|(span, _)| std::cmp::Reverse(span.start));
428    let mut output = source.to_owned();
429    for (span, replacement) in replacements {
430        output.replace_range(Range::<usize>::from(span), &replacement);
431    }
432    output
433}