griz_core/model.rs
1//! Values that cross the engine boundary.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5use std::{collections::BTreeMap, path::PathBuf};
6
7use crate::syntax::{FileSyntax, PlanSyntax};
8
9use crate::pattern_locator::PatternLocator;
10pub use crate::problem::{Problem, ProblemKind, Window};
11
12/// A half-open byte range `[start, end)` in a file's text.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
14#[serde(deny_unknown_fields)]
15pub struct ByteRange {
16 /// First byte of the range.
17 pub start: usize,
18 /// One past the last byte of the range.
19 pub end: usize,
20}
21
22/// Which matches of an anchor an operation targets.
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
24#[serde(rename_all = "snake_case")]
25pub enum Occurrence {
26 /// Exactly one match; two or more is an error listing every candidate.
27 #[default]
28 Unique,
29 /// Every match.
30 All,
31 /// The Nth match, counting from 1.
32 Nth(usize),
33}
34
35/// Text that locates an edit inside a file. A plain string is accepted as
36/// shorthand for `{ text }`.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
38#[serde(from = "crate::anchor_input::AnchorInput")]
39pub struct Anchor {
40 /// Text to find.
41 pub text: String,
42 /// Only consider matches after the first occurrence of this text.
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub after: Option<String>,
45 /// Match whole lines only. Patch hunks set this.
46 #[serde(default)]
47 pub whole_lines: bool,
48}
49
50/// One requested change.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
52#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
53pub enum Op {
54 /// Replace anchored text, an exact byte range, or a structural pattern
55 /// match.
56 Replace {
57 /// File to change.
58 path: PathBuf,
59 /// Text to locate, or exact old text when `range` is given.
60 /// Required unless `range` or `pattern` is given.
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 find: Option<Anchor>,
63 /// Exact byte range in the file as it was when found.
64 /// Requires `expect_hash` or expected old `find` text.
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 range: Option<ByteRange>,
67 /// Structural pattern match, as an alternative to `find`/`range`.
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pattern: Option<PatternLocator>,
70 /// Replacement text.
71 replace: String,
72 /// Which matches to replace.
73 #[serde(default)]
74 occurrence: Occurrence,
75 /// With `pattern`, edit only this metavariable's range, e.g. `$NAME`.
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 target: Option<String>,
78 /// Fingerprint the file must still have.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 expect_hash: Option<String>,
81 },
82 /// Insert text before or after a unique anchor.
83 Insert {
84 /// File to change.
85 path: PathBuf,
86 /// Text to locate.
87 anchor: Anchor,
88 /// Insert after the anchor instead of before it.
89 #[serde(default)]
90 after: bool,
91 /// Text to insert.
92 text: String,
93 /// Fingerprint the file must still have.
94 #[serde(default, skip_serializing_if = "Option::is_none")]
95 expect_hash: Option<String>,
96 },
97 /// Create a file, which must not exist unless `overwrite` is set.
98 Create {
99 /// File to create.
100 path: PathBuf,
101 /// Full contents.
102 text: String,
103 /// Replace the file when it already exists, instead of refusing.
104 /// Replacing a whole file needs no range and no byte count.
105 #[serde(default)]
106 overwrite: bool,
107 /// Fingerprint the original file must still have; absence is stale.
108 #[serde(default, skip_serializing_if = "Option::is_none")]
109 expect_hash: Option<String>,
110 },
111 /// Delete a file that must exist.
112 Delete {
113 /// File to delete.
114 path: PathBuf,
115 /// Fingerprint the file must still have.
116 #[serde(default, skip_serializing_if = "Option::is_none")]
117 expect_hash: Option<String>,
118 },
119 /// Move a file to a path that must not exist yet.
120 Move {
121 /// File to move.
122 path: PathBuf,
123 /// Destination.
124 to: PathBuf,
125 /// Fingerprint the file must still have.
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 expect_hash: Option<String>,
128 },
129}
130
131impl Op {
132 /// The file this operation starts from.
133 #[must_use]
134 pub fn path(&self) -> &PathBuf {
135 match self {
136 Self::Replace { path, .. }
137 | Self::Insert { path, .. }
138 | Self::Create { path, .. }
139 | Self::Delete { path, .. }
140 | Self::Move { path, .. } => path,
141 }
142 }
143}
144
145/// How sure the engine is that an edit landed where the caller meant.
146///
147/// Ordered: `Maybe` is below `Machine`.
148#[derive(
149 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
150)]
151#[serde(rename_all = "snake_case")]
152pub enum Confidence {
153 /// Located by tolerant matching; a person or program should look first.
154 Maybe,
155 /// Located exactly; safe to apply without review.
156 Machine,
157}
158
159/// The matching rung that located an edit.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
161#[serde(rename_all = "snake_case")]
162pub enum Rung {
163 /// Byte range supplied by the caller.
164 Range,
165 /// Exact text.
166 Exact,
167 /// Lines equal after trimming trailing whitespace.
168 TrailingWhitespace,
169 /// Lines equal after trimming both ends.
170 Trimmed,
171 /// Lines equal after removing their shared indentation.
172 Indentation,
173 /// Whole-file operation such as create, delete, or move.
174 File,
175 /// A structural pattern match: exact identity on the parse tree, never tolerant.
176 Pattern,
177}
178
179impl Rung {
180 /// Only exact rungs are safe to apply unattended.
181 #[must_use]
182 pub fn confidence(self) -> Confidence {
183 match self {
184 Self::Range | Self::Exact | Self::File | Self::Pattern => Confidence::Machine,
185 Self::TrailingWhitespace | Self::Trimmed | Self::Indentation => Confidence::Maybe,
186 }
187 }
188}
189
190/// One change the plan makes.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
192pub struct Edit {
193 /// Stable identifier: `e<op>` or `e<op>.<n>` for repeated matches.
194 pub id: String,
195 /// Index of the operation that produced this edit.
196 pub op: usize,
197 /// File the edit lands in.
198 pub path: PathBuf,
199 /// 1-based line where the edit starts, 0 for whole-file edits.
200 pub line: usize,
201 /// Rung that located it.
202 pub rung: Rung,
203 /// Confidence derived from the rung.
204 pub confidence: Confidence,
205}
206
207/// What a file change does.
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
209#[serde(rename_all = "snake_case")]
210pub enum ChangeKind {
211 /// Existing file rewritten.
212 Modify,
213 /// New file.
214 Create,
215 /// File removed.
216 Delete,
217}
218
219/// The planned before and after state of one file.
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
221pub struct FileChange {
222 /// File path.
223 pub path: PathBuf,
224 /// What happens to it.
225 pub kind: ChangeKind,
226 /// Text the plan was computed against; absent for a new file.
227 pub before: Option<String>,
228 /// Fingerprint of `before`.
229 pub before_hash: Option<String>,
230 /// Text after the plan; absent for a deleted file.
231 pub after: Option<String>,
232 /// Fingerprint of `after`.
233 pub after_hash: Option<String>,
234}
235
236/// The complete, unwritten result of a set of operations.
237#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
238pub struct Plan {
239 /// Every changed file, sorted by path.
240 pub files: Vec<FileChange>,
241 /// Original text of read files whose final state is unchanged; `None` records absence.
242 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
243 pub unchanged_inputs: BTreeMap<PathBuf, Option<String>>,
244 /// Every edit, in operation order.
245 pub edits: Vec<Edit>,
246 /// Every operation that could not be planned. A plan with problems must
247 /// never be applied.
248 pub problems: Vec<Problem>,
249 /// Overall syntax verdict, over every changed file's [`FileSyntax`].
250 /// Fact only: never `problems`, never refuses.
251 #[serde(default)]
252 pub syntax: PlanSyntax,
253 /// Parse facts for each changed file in an enabled language.
254 #[serde(default)]
255 pub file_syntax: BTreeMap<PathBuf, FileSyntax>,
256}
257
258impl Plan {
259 /// Lowest confidence of any edit, or `Machine` for an empty plan.
260 #[must_use]
261 pub fn confidence(&self) -> Confidence {
262 self.edits
263 .iter()
264 .map(|edit| edit.confidence)
265 .min()
266 .unwrap_or(Confidence::Machine)
267 }
268}