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
158 changes: 134 additions & 24 deletions shared/tree-sitter-extractor/src/extractor/desugaring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,146 @@
//! the same way.

use crate::trap;
use std::collections::BTreeMap;
use std::path::PathBuf;

use crate::diagnostics;
use crate::extractor::ParsedTree;
use crate::extractor::driver::{self, LanguageExtractor};
use crate::node_types::{self, NodeTypeMap};
use extractor_common::file_paths;

/// A parser turns source bytes into a [`ParsedTree`]. Tree-sitter grammars plug
/// in via [`crate::extractor::tree_sitter_parser`]; custom (non-tree-sitter)
/// parsers supply their own closure.
pub type Parser = Box<dyn Fn(&[u8]) -> Result<ParsedTree, String> + Send + Sync>;
pub type OutputLabels = BTreeMap<yeast::OutputId, Vec<trap::Label>>;
pub type PostExtract<C> =
Box<dyn Fn(&C, &OutputLabels, &mut trap::Writer) -> Result<(), String> + Send + Sync>;

trait LanguagePipeline: Send + Sync {
fn output_node_types_yaml(&self) -> &'static str;
fn parse(&self, source: &[u8]) -> Result<ParsedTree, String>;
fn desugar(&self, ast: yeast::Ast) -> Result<yeast::OutputAst, String>;
fn extract_file(
&self,
language_prefix: &str,
schema: &NodeTypeMap,
diagnostics_writer: &mut diagnostics::LogWriter,
trap_writer: &mut trap::Writer,
path: &std::path::Path,
source: &[u8],
) -> Result<(), String>;
}

struct DesugaringPipeline<C: Default + Clone + 'static> {
parser: Parser,
desugarer: yeast::ConcreteDesugarer<C>,
output_node_types_yaml: &'static str,
post_extract: Option<PostExtract<C>>,
}

pub struct LanguageSpec {
pub prefix: &'static str,
/// The parser: source -> `yeast::Ast` + `extra` tokens (see [`Parser`]).
pipeline: Box<dyn LanguagePipeline>,
pub file_globs: Vec<String>,
}

pub struct LanguageSpecBuilder<C> {
pub prefix: &'static str,
pub parser: Parser,
/// Fallback TRAP schema, used only when `desugarer` does not supply its own
/// output schema (via [`yeast::Desugarer::output_node_types_yaml`]). May be
/// empty for a custom parser whose desugarer always provides the schema.
pub node_types: &'static str,
/// The desugarer applied to the parsed AST before extraction. Its
/// `output_node_types_yaml()` (when set) provides the TRAP schema.
///
/// `Box<dyn yeast::Desugarer>` so the shared extractor is agnostic to the
/// user-defined context type the desugarer uses internally.
pub desugarer: Box<dyn yeast::Desugarer>,
pub desugaring: yeast::DesugaringConfig<C>,
pub file_globs: Vec<String>,
pub post_extract: Option<PostExtract<C>>,
}

impl<C> LanguageSpecBuilder<C>
where
C: Default + Clone + 'static,
{
pub fn build(self) -> Result<LanguageSpec, String> {
let output_node_types_yaml = self
.desugaring
.output_node_types_yaml
.ok_or("a language-free desugarer requires output_node_types_yaml to be set")?;
let pipeline = DesugaringPipeline {
parser: self.parser,
desugarer: yeast::ConcreteDesugarer::without_language(self.desugaring)?,
output_node_types_yaml,
post_extract: self.post_extract,
};
Ok(LanguageSpec {
prefix: self.prefix,
pipeline: Box::new(pipeline),
file_globs: self.file_globs,
})
}
}

impl<C> LanguagePipeline for DesugaringPipeline<C>
where
C: Default + Clone + 'static,
{
fn output_node_types_yaml(&self) -> &'static str {
self.output_node_types_yaml
}

fn parse(&self, source: &[u8]) -> Result<ParsedTree, String> {
(self.parser)(source)
}

fn desugar(&self, ast: yeast::Ast) -> Result<yeast::OutputAst, String> {
self.desugarer.run_from_ast_with_ctx(ast, &C::default())
}

fn extract_file(
&self,
language_prefix: &str,
schema: &NodeTypeMap,
diagnostics_writer: &mut diagnostics::LogWriter,
trap_writer: &mut trap::Writer,
path: &std::path::Path,
source: &[u8],
) -> Result<(), String> {
let path_str = file_paths::normalize_and_transform_path(path, None);
let span = tracing::span!(tracing::Level::TRACE, "extract", file = %path_str);
let _enter = span.enter();
tracing::debug!("extracting: {}", path_str);

let parsed = self
.parse(source)
.map_err(|error| format!("Parsing failed: {error}"))?;
let context = C::default();
let ast = self
.desugarer
.run_from_ast_with_ctx(parsed.ast, &context)
.map_err(|error| format!("Desugaring failed: {error}"))?;
let labels = crate::extractor::extract_output_ast(
language_prefix,
schema,
diagnostics_writer,
trap_writer,
None,
path,
source,
&ast,
&parsed.extras,
)?;
match &self.post_extract {
Some(post_extract) => post_extract(&context, &labels, trap_writer),
None => Ok(()),
}
}
}

impl LanguageSpec {
pub fn parse(&self, source: &[u8]) -> Result<ParsedTree, String> {
self.pipeline.parse(source)
}

pub fn desugar(&self, ast: yeast::Ast) -> Result<yeast::OutputAst, String> {
self.pipeline.desugar(ast)
}
}

impl LanguageExtractor for LanguageSpec {
Expand All @@ -44,15 +157,15 @@ impl LanguageExtractor for LanguageSpec {
}

fn build_schema(&self) -> std::io::Result<NodeTypeMap> {
let effective_node_types: String = match self.desugarer.output_node_types_yaml() {
Some(yaml) => yeast::node_types_yaml::convert(yaml).map_err(|e| {
std::io::Error::other(format!(
"Failed to convert YAML node-types to JSON for {}: {e}",
self.prefix
))
})?,
None => self.node_types.to_string(),
};
let effective_node_types = yeast::node_types_yaml::convert(
self.pipeline.output_node_types_yaml(),
)
.map_err(|e| {
std::io::Error::other(format!(
"Failed to convert YAML node-types to JSON for {}: {e}",
self.prefix
))
})?;
node_types::read_node_types_str(self.prefix, &effective_node_types)
}

Expand All @@ -64,16 +177,13 @@ impl LanguageExtractor for LanguageSpec {
path: &std::path::Path,
source: &[u8],
) -> Result<(), String> {
crate::extractor::extract_parsed(
self.parser.as_ref(),
self.pipeline.extract_file(
self.prefix,
schema,
diagnostics_writer,
trap_writer,
None,
path,
source,
self.desugarer.as_ref(),
)
}
}
Expand Down
32 changes: 28 additions & 4 deletions shared/tree-sitter-extractor/src/extractor/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ pub(crate) fn run_extractor<L: LanguageExtractor>(
languages_processed[i] = true;
let lang = &languages[i];

let trap_checkpoint = trap_writer.clone();
let result = lang.extract_file(
&schemas[i],
&mut diagnostics_writer,
Expand All @@ -185,6 +186,7 @@ pub(crate) fn run_extractor<L: LanguageExtractor>(
write_trap(trap_dir, &path, &trap_writer, trap_compression)?;
}
Err(error) => {
trap_writer = trap_checkpoint;
tracing::error!(
file = %path.display(),
error,
Expand Down Expand Up @@ -223,10 +225,11 @@ fn write_trap(
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::io::{Read, Write};

struct TestLanguage {
file_globs: Vec<String>,
fail_fallback: bool,
}

impl LanguageExtractor for TestLanguage {
Expand All @@ -248,6 +251,9 @@ mod tests {
) -> Result<(), String> {
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());
Err("failed after writing".to_string())
} else {
trap_writer.comment("success".to_string());
Ok(())
Expand All @@ -265,19 +271,29 @@ mod tests {

let good_path = source_dir.join("good.test");
let bad_path = source_dir.join("bad.test");
let fallback_path = source_dir.join("fallback.test");
std::fs::write(&good_path, b"good").unwrap();
std::fs::write(&bad_path, b"bad").unwrap();
std::fs::write(&fallback_path, b"fallback").unwrap();

let file_list = root.join("files.txt");
let mut file = std::fs::File::create(&file_list).unwrap();
writeln!(file, "{}", good_path.display()).unwrap();
writeln!(file, "{}", bad_path.display()).unwrap();
writeln!(file, "{}", fallback_path.display()).unwrap();

run_extractor(
"test",
&[TestLanguage {
file_globs: vec!["*.test".to_string()],
}],
&[
TestLanguage {
file_globs: vec!["*.test".to_string()],
fail_fallback: true,
},
TestLanguage {
file_globs: vec!["fallback.test".to_string()],
fail_fallback: false,
},
],
&trap_dir,
&source_archive_dir,
&[file_list],
Expand All @@ -287,13 +303,21 @@ mod tests {

let good_trap = file_paths::path_for(&trap_dir, &good_path, "trap.gz", None);
let bad_trap = file_paths::path_for(&trap_dir, &bad_path, "trap.gz", None);
let fallback_trap = file_paths::path_for(&trap_dir, &fallback_path, "trap.gz", None);
assert!(good_trap.is_file());
assert!(!bad_trap.exists());
let mut fallback_contents = String::new();
flate2::read::GzDecoder::new(std::fs::File::open(fallback_trap).unwrap())
.read_to_string(&mut fallback_contents)
.unwrap();
assert_eq!(fallback_contents, "// success\n");

let archived_good = file_paths::path_for(&source_archive_dir, &good_path, "", None);
let archived_bad = file_paths::path_for(&source_archive_dir, &bad_path, "", None);
let archived_fallback = file_paths::path_for(&source_archive_dir, &fallback_path, "", None);
assert!(archived_good.is_file());
assert!(archived_bad.is_file());
assert!(archived_fallback.is_file());

std::fs::remove_dir_all(root).unwrap();
}
Expand Down
Loading
Loading