Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 86 additions & 66 deletions shared/extractor-common/src/trap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ pub struct Location {

#[derive(Clone)]
pub struct Writer {
/// The accumulated trap entries
trap_output: Vec<Entry>,
/// The accumulated TRAP output, already formatted
trap_output: Vec<u8>,
/// A counter for generating fresh labels
counter: u32,
/// cache of global keys
Expand Down Expand Up @@ -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
}

Expand All @@ -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)
}

Expand All @@ -81,12 +84,26 @@ impl Writer {
}

pub fn add_tuple(&mut self, table_name: &str, args: Vec<Arg>) {
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<()> {
Expand All @@ -112,44 +129,27 @@ impl Writer {
}

fn write_trap_entries<W: Write>(&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<Arg>),
Comment(String),
fn write_label(out: &mut Vec<u8>, label: Label) {
// writing to a `Vec<u8>` 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<u8>, 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)]
Expand Down Expand Up @@ -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<String> for Arg {
fn from(value: String) -> Self {
Arg::String(value)
Expand All @@ -216,17 +202,6 @@ impl From<usize> for Arg {
}
}

pub struct Program(Vec<Entry>);

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))
}
Expand Down Expand Up @@ -342,3 +317,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"
);
}
4 changes: 2 additions & 2 deletions shared/tree-sitter-extractor/src/extractor/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,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(())
}
}
Expand Down
4 changes: 2 additions & 2 deletions shared/tree-sitter-extractor/src/extractor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,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,
Expand Down Expand Up @@ -242,7 +242,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,
Expand Down
Loading