From d4a55d1d80e9e3658e9045e4e7894d2d169c4ed3 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 13:54:37 +0000 Subject: [PATCH] Shared: stream TRAP output in the tree-sitter extractor writer Format TRAP entries straight into a byte buffer instead of buffering owned `Entry` values and formatting them at write time. Output is unchanged. Drop the now unused `Entry`, `Program` and `Display for Arg`, and take `comment` text by reference. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ab88cf13c49431ab5be915077ce518e --- .../src/extractor/driver.rs | 4 +- .../src/extractor/mod.rs | 4 +- shared/tree-sitter-extractor/src/trap.rs | 152 ++++++++++-------- 3 files changed, 90 insertions(+), 70 deletions(-) diff --git a/shared/tree-sitter-extractor/src/extractor/driver.rs b/shared/tree-sitter-extractor/src/extractor/driver.rs index 93aac9e379db..05afb0aafc8b 100644 --- a/shared/tree-sitter-extractor/src/extractor/driver.rs +++ b/shared/tree-sitter-extractor/src/extractor/driver.rs @@ -252,10 +252,10 @@ mod tests { if source == b"bad" { Err("invalid parser output".to_string()) } else if source == b"fallback" && self.fail_fallback { - trap_writer.comment("discard-me".to_string()); + trap_writer.comment("discard-me"); Err("failed after writing".to_string()) } else { - trap_writer.comment("success".to_string()); + trap_writer.comment("success"); Ok(()) } } diff --git a/shared/tree-sitter-extractor/src/extractor/mod.rs b/shared/tree-sitter-extractor/src/extractor/mod.rs index 07663e4481a6..39231fcdb214 100644 --- a/shared/tree-sitter-extractor/src/extractor/mod.rs +++ b/shared/tree-sitter-extractor/src/extractor/mod.rs @@ -326,7 +326,7 @@ pub fn extract( parser.set_language(language).unwrap(); parser.set_included_ranges(ranges).unwrap(); let tree = parser.parse(source, None).expect("Failed to parse file"); - trap_writer.comment(format!("Auto-generated TRAP file for {path_str}")); + trap_writer.comment(&format!("Auto-generated TRAP file for {path_str}")); let file_label = populate_file(trap_writer, path, transformer); let mut visitor = Visitor::new( source, @@ -435,7 +435,7 @@ pub fn extract_output_ast( .and_then(|d| d.canonicalize().ok()); let diagnostics_path = file_paths::relativize_for_diagnostic(path, source_root.as_deref()); - trap_writer.comment(format!("Auto-generated TRAP file for {path_str}")); + trap_writer.comment(&format!("Auto-generated TRAP file for {path_str}")); let file_label = populate_file(trap_writer, path, transformer); let mut visitor = Visitor::new( source, diff --git a/shared/tree-sitter-extractor/src/trap.rs b/shared/tree-sitter-extractor/src/trap.rs index c11ad973e035..7c105e251512 100644 --- a/shared/tree-sitter-extractor/src/trap.rs +++ b/shared/tree-sitter-extractor/src/trap.rs @@ -16,8 +16,8 @@ pub struct Location { #[derive(Clone)] pub struct Writer { - /// The accumulated trap entries - trap_output: Vec, + /// The accumulated TRAP output, already formatted + trap_output: Vec, /// A counter for generating fresh labels counter: u32, /// cache of global keys @@ -45,7 +45,8 @@ impl Writer { pub fn fresh_id(&mut self) -> Label { let label = Label(self.counter); self.counter += 1; - self.trap_output.push(Entry::FreshId(label)); + write_label(&mut self.trap_output, label); + self.trap_output.extend_from_slice(b"=*\n"); label } @@ -64,8 +65,10 @@ impl Writer { let label = Label(self.counter); self.counter += 1; self.global_keys.insert(key.to_owned(), label); - self.trap_output - .push(Entry::MapLabelToKey(label, key.to_owned())); + write_label(&mut self.trap_output, label); + self.trap_output.extend_from_slice(b"=@"); + write_quoted(&mut self.trap_output, key); + self.trap_output.push(b'\n'); (label, true) } @@ -81,12 +84,26 @@ impl Writer { } pub fn add_tuple(&mut self, table_name: &str, args: Vec) { - self.trap_output - .push(Entry::GenericTuple(table_name.to_owned(), args)); + let out = &mut self.trap_output; + out.extend_from_slice(table_name.as_bytes()); + out.push(b'('); + for (index, arg) in args.into_iter().enumerate() { + if index > 0 { + out.push(b','); + } + match arg { + Arg::Label(label) => write_label(out, label), + Arg::Int(i) => write!(out, "{i}").unwrap(), + Arg::String(x) => write_quoted(out, limit_string(&x, MAX_STRLEN)), + } + } + out.extend_from_slice(b")\n"); } - pub fn comment(&mut self, text: String) { - self.trap_output.push(Entry::Comment(text)); + pub fn comment(&mut self, text: &str) { + self.trap_output.extend_from_slice(b"// "); + self.trap_output.extend_from_slice(text.as_bytes()); + self.trap_output.push(b'\n'); } pub fn write_to_file(&self, path: &Path, compression: Compression) -> std::io::Result<()> { @@ -112,44 +129,27 @@ impl Writer { } fn write_trap_entries(&self, file: &mut W) -> std::io::Result<()> { - for trap_entry in &self.trap_output { - writeln!(file, "{trap_entry}")?; - } - Ok(()) + file.write_all(&self.trap_output) } } -#[derive(Clone)] -pub enum Entry { - /// Maps the label to a fresh id, e.g. `#123=*`. - FreshId(Label), - /// Maps the label to a key, e.g. `#7=@"foo"`. - MapLabelToKey(Label, String), - /// `foo_bar(arg*)` - GenericTuple(String, Vec), - Comment(String), +fn write_label(out: &mut Vec, label: Label) { + // writing to a `Vec` cannot fail + write!(out, "{label}").unwrap(); } -impl fmt::Display for Entry { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Entry::FreshId(label) => write!(f, "{label}=*"), - Entry::MapLabelToKey(label, key) => { - write!(f, "{}=@\"{}\"", label, key.replace('"', "\"\"")) - } - Entry::GenericTuple(name, args) => { - write!(f, "{name}(")?; - for (index, arg) in args.iter().enumerate() { - if index > 0 { - write!(f, ",")?; - } - write!(f, "{arg}")?; - } - write!(f, ")") - } - Entry::Comment(line) => write!(f, "// {line}"), - } +/// Writes `"s"`, doubling any `"` in `s`. +fn write_quoted(out: &mut Vec, s: &str) { + out.push(b'"'); + let mut parts = s.split('"'); + if let Some(first) = parts.next() { + out.extend_from_slice(first.as_bytes()); + } + for part in parts { + out.extend_from_slice(b"\"\""); + out.extend_from_slice(part.as_bytes()); } + out.push(b'"'); } #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] @@ -178,20 +178,6 @@ pub enum Arg { const MAX_STRLEN: usize = 1_048_576; -impl fmt::Display for Arg { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Arg::Label(x) => write!(f, "{x}"), - Arg::Int(x) => write!(f, "{x}"), - Arg::String(x) => write!( - f, - "\"{}\"", - limit_string(x, MAX_STRLEN).replace('"', "\"\"") - ), - } - } -} - impl From for Arg { fn from(value: String) -> Self { Arg::String(value) @@ -216,17 +202,6 @@ impl From for Arg { } } -pub struct Program(Vec); - -impl fmt::Display for Program { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - for trap_entry in &self.0 { - writeln!(f, "{trap_entry}")?; - } - Ok(()) - } -} - pub fn full_id_for_file(normalized_path: &str) -> String { format!("{};sourcefile", escape_key(normalized_path)) } @@ -343,3 +318,48 @@ fn escape_key_test() { escape_key("/path/to/foo&{}\"@#.rb") ); } + +#[test] +fn trap_output_test() { + let mut w = Writer::new(); + let a = w.fresh_id(); + let (b, _) = w.global_id("k\"e\"y;x"); + w.add_tuple( + "t", + vec![ + Arg::Label(a), + Arg::Int(1234), + Arg::String("a\"b\"\"".into()), + Arg::Label(b), + ], + ); + w.add_tuple("empty", vec![]); + w.comment("c \"x\""); + for _ in 0..9 { + w.fresh_id(); + } + let mut out = Vec::new(); + w.write_trap_entries(&mut out).unwrap(); + assert_eq!( + String::from_utf8(out).unwrap(), + concat!( + "#0=*\n", + "#1=@\"k\"\"e\"\"y;x\"\n", + "t(#0,1234,\"a\"\"b\"\"\"\"\",#1)\n", + "empty()\n", + "// c \"x\"\n", + "#2=*\n#3=*\n#4=*\n#5=*\n#6=*\n#7=*\n#8=*\n#9=*\n#a=*\n", + ) + ); +} + +#[test] +fn trap_output_truncates_long_strings() { + let mut w = Writer::new(); + w.add_tuple("t", vec![Arg::String("é".repeat(MAX_STRLEN))]); + let expected = format!("t(\"{}\")\n", "é".repeat(MAX_STRLEN / 2)); + assert!( + w.trap_output == expected.as_bytes(), + "unexpected TRAP output" + ); +}