parse_output.rs

  1use crate::{
  2    PredictionProvider,
  3    example::{ActualCursor, Example},
  4    format_prompt::TeacherPrompt,
  5    repair,
  6};
  7use anyhow::{Context as _, Result};
  8use zeta_prompt::{CURSOR_MARKER, ZetaFormat};
  9
 10pub fn run_parse_output(example: &mut Example) -> Result<()> {
 11    example
 12        .prompt_inputs
 13        .as_ref()
 14        .context("prompt_inputs required")?;
 15
 16    let to_parse: Vec<_> = example
 17        .predictions
 18        .iter()
 19        .enumerate()
 20        .filter(|(_, p)| !p.actual_output.is_empty())
 21        .map(|(ix, p)| (ix, p.actual_output.clone(), p.provider))
 22        .collect();
 23
 24    for (ix, actual_output, provider) in to_parse {
 25        let (actual_patch, actual_cursor) =
 26            parse_prediction_output(example, &actual_output, provider)?;
 27        example.predictions[ix].actual_patch = Some(actual_patch);
 28        example.predictions[ix].actual_cursor = actual_cursor;
 29    }
 30
 31    Ok(())
 32}
 33
 34pub fn parse_prediction_output(
 35    example: &Example,
 36    actual_output: &str,
 37    provider: PredictionProvider,
 38) -> Result<(String, Option<ActualCursor>)> {
 39    match provider {
 40        PredictionProvider::Teacher(_) | PredictionProvider::TeacherNonBatching(_) => {
 41            TeacherPrompt::parse(example, actual_output)
 42        }
 43        PredictionProvider::Zeta2(version) => parse_zeta2_output(example, actual_output, version),
 44        PredictionProvider::Repair => repair::parse(example, actual_output),
 45        _ => anyhow::bail!(
 46            "parse-output only supports Teacher and Zeta2 providers, got {:?}",
 47            provider
 48        ),
 49    }
 50}
 51
 52fn extract_zeta2_current_region(prompt: &str, format: ZetaFormat) -> Result<String> {
 53    let (current_marker, end_marker) = match format {
 54        ZetaFormat::V0112MiddleAtEnd => ("<|fim_middle|>current\n", "<|fim_middle|>updated"),
 55        ZetaFormat::V0113Ordered | ZetaFormat::V0114180EditableRegion => {
 56            ("<|fim_middle|>current\n", "<|fim_suffix|>")
 57        }
 58        ZetaFormat::V0120GitMergeMarkers
 59        | ZetaFormat::V0131GitMergeMarkersPrefix
 60        | ZetaFormat::V0211Prefill => (
 61            zeta_prompt::v0120_git_merge_markers::START_MARKER,
 62            zeta_prompt::v0120_git_merge_markers::SEPARATOR,
 63        ),
 64    };
 65
 66    let start = prompt.find(current_marker).with_context(|| {
 67        format!(
 68            "missing current marker '{}' in prompt",
 69            current_marker.trim()
 70        )
 71    })? + current_marker.len();
 72
 73    let end = prompt[start..]
 74        .find(end_marker)
 75        .with_context(|| format!("missing end marker '{}' in prompt", end_marker.trim()))?
 76        + start;
 77
 78    let region = &prompt[start..end];
 79    let region = region.replace(CURSOR_MARKER, "");
 80
 81    Ok(region)
 82}
 83
 84fn parse_zeta2_output(
 85    example: &Example,
 86    actual_output: &str,
 87    format: ZetaFormat,
 88) -> Result<(String, Option<ActualCursor>)> {
 89    let prompt = &example.prompt.as_ref().context("prompt required")?.input;
 90    let prompt_inputs = example
 91        .prompt_inputs
 92        .as_ref()
 93        .context("prompt_inputs required")?;
 94
 95    let old_text = extract_zeta2_current_region(prompt, format)?;
 96
 97    let mut new_text = actual_output.to_string();
 98    let cursor_offset = if let Some(offset) = new_text.find(CURSOR_MARKER) {
 99        new_text.replace_range(offset..offset + CURSOR_MARKER.len(), "");
100        Some(offset)
101    } else {
102        None
103    };
104
105    let suffix = match format {
106        ZetaFormat::V0131GitMergeMarkersPrefix | ZetaFormat::V0211Prefill => {
107            zeta_prompt::v0131_git_merge_markers_prefix::END_MARKER
108        }
109        ZetaFormat::V0120GitMergeMarkers => zeta_prompt::v0120_git_merge_markers::END_MARKER,
110        ZetaFormat::V0112MiddleAtEnd
111        | ZetaFormat::V0113Ordered
112        | ZetaFormat::V0114180EditableRegion => "",
113    };
114    if !suffix.is_empty() {
115        new_text = new_text
116            .strip_suffix(suffix)
117            .unwrap_or(&new_text)
118            .to_string();
119    }
120
121    let mut old_text_normalized = old_text.clone();
122    if !new_text.is_empty() && !new_text.ends_with('\n') {
123        new_text.push('\n');
124    }
125    if !old_text_normalized.is_empty() && !old_text_normalized.ends_with('\n') {
126        old_text_normalized.push('\n');
127    }
128
129    let old_text_trimmed = old_text.trim_end_matches('\n');
130    let (editable_region_offset, _) = prompt_inputs
131        .content
132        .match_indices(old_text_trimmed)
133        .min_by_key(|(index, _)| index.abs_diff(prompt_inputs.cursor_offset))
134        .with_context(|| {
135            format!(
136                "could not find editable region in content.\nLooking for:\n{}\n\nIn content:\n{}",
137                old_text_trimmed, &prompt_inputs.content
138            )
139        })?;
140
141    let editable_region_start_line = prompt_inputs.content[..editable_region_offset]
142        .matches('\n')
143        .count();
144
145    // Use full context so cursor offset (relative to editable region start) aligns with diff content
146    let editable_region_lines = old_text_normalized.lines().count() as u32;
147    let diff = language::unified_diff_with_context(
148        &old_text_normalized,
149        &new_text,
150        editable_region_start_line as u32,
151        editable_region_start_line as u32,
152        editable_region_lines,
153    );
154
155    let formatted_diff = format!(
156        "--- a/{path}\n+++ b/{path}\n{diff}",
157        path = example.spec.cursor_path.to_string_lossy(),
158    );
159
160    let actual_cursor = cursor_offset.map(|editable_region_cursor_offset| {
161        ActualCursor::from_editable_region(
162            &example.spec.cursor_path,
163            editable_region_cursor_offset,
164            &new_text,
165            &prompt_inputs.content,
166            editable_region_offset,
167            editable_region_start_line,
168        )
169    });
170
171    Ok((formatted_diff, actual_cursor))
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn test_extract_zeta2_current_region_v0113() {
180        let prompt = indoc::indoc! {"
181            <|file_sep|>src/main.rs
182            <|fim_prefix|>
183            fn main() {
184            <|fim_middle|>current
185            println!(\"hello\");
186            <|fim_suffix|>
187            }
188            <|fim_middle|>updated
189        "};
190
191        let region = extract_zeta2_current_region(prompt, ZetaFormat::V0113Ordered).unwrap();
192        assert_eq!(region, "println!(\"hello\");\n");
193    }
194
195    #[test]
196    fn test_extract_zeta2_current_region_v0112() {
197        let prompt = indoc::indoc! {"
198            <|file_sep|>src/main.rs
199            <|fim_prefix|>
200            fn main() {
201            <|fim_suffix|>
202            }
203            <|fim_middle|>current
204            println!(\"hello\");
205            <|fim_middle|>updated
206        "};
207
208        let region = extract_zeta2_current_region(prompt, ZetaFormat::V0112MiddleAtEnd).unwrap();
209        assert_eq!(region, "println!(\"hello\");\n");
210    }
211
212    #[test]
213    fn test_extract_zeta2_current_region_with_cursor_marker() {
214        let prompt = indoc::indoc! {"
215            <|file_sep|>src/main.rs
216            <|fim_prefix|>
217            fn main() {
218            <|fim_middle|>current
219            print<|user_cursor|>ln!(\"hello\");
220            <|fim_suffix|>
221            }
222            <|fim_middle|>updated
223        "};
224
225        let region = extract_zeta2_current_region(prompt, ZetaFormat::V0113Ordered).unwrap();
226        assert_eq!(region, "println!(\"hello\");\n");
227    }
228
229    #[test]
230    fn test_extract_zeta2_current_region_v0120_git_merge_markers() {
231        let prompt = indoc::indoc! {"
232            <|file_sep|>src/main.rs
233            <|fim_prefix|>
234            fn main() {
235            <|fim_suffix|>
236            }
237            <|fim_middle|><<<<<<< CURRENT
238            println!(\"hello\");
239            =======
240        "};
241
242        let region =
243            extract_zeta2_current_region(prompt, ZetaFormat::V0120GitMergeMarkers).unwrap();
244        assert_eq!(region, "println!(\"hello\");\n");
245    }
246
247    #[test]
248    fn test_extract_zeta2_current_region_v0120_with_cursor_marker() {
249        let prompt = indoc::indoc! {"
250            <|file_sep|>src/main.rs
251            <|fim_prefix|>
252            fn main() {
253            <|fim_suffix|>
254            }
255            <|fim_middle|><<<<<<< CURRENT
256            print<|user_cursor|>ln!(\"hello\");
257            =======
258        "};
259
260        let region =
261            extract_zeta2_current_region(prompt, ZetaFormat::V0120GitMergeMarkers).unwrap();
262        assert_eq!(region, "println!(\"hello\");\n");
263    }
264}