diff --git a/shared/tree-sitter-extractor/src/extractor/desugaring.rs b/shared/tree-sitter-extractor/src/extractor/desugaring.rs index 3aa7ad36e897..7f2d7666f6c5 100644 --- a/shared/tree-sitter-extractor/src/extractor/desugaring.rs +++ b/shared/tree-sitter-extractor/src/extractor/desugaring.rs @@ -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 Result + Send + Sync>; +pub type OutputLabels = BTreeMap>; +pub type PostExtract = + Box Result<(), String> + Send + Sync>; + +trait LanguagePipeline: Send + Sync { + fn output_node_types_yaml(&self) -> &'static str; + fn parse(&self, source: &[u8]) -> Result; + fn desugar(&self, ast: yeast::Ast) -> Result; + 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 { + parser: Parser, + desugarer: yeast::ConcreteDesugarer, + output_node_types_yaml: &'static str, + post_extract: Option>, +} pub struct LanguageSpec { pub prefix: &'static str, - /// The parser: source -> `yeast::Ast` + `extra` tokens (see [`Parser`]). + pipeline: Box, + pub file_globs: Vec, +} + +pub struct LanguageSpecBuilder { + 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` so the shared extractor is agnostic to the - /// user-defined context type the desugarer uses internally. - pub desugarer: Box, + pub desugaring: yeast::DesugaringConfig, pub file_globs: Vec, + pub post_extract: Option>, +} + +impl LanguageSpecBuilder +where + C: Default + Clone + 'static, +{ + pub fn build(self) -> Result { + 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 LanguagePipeline for DesugaringPipeline +where + C: Default + Clone + 'static, +{ + fn output_node_types_yaml(&self) -> &'static str { + self.output_node_types_yaml + } + + fn parse(&self, source: &[u8]) -> Result { + (self.parser)(source) + } + + fn desugar(&self, ast: yeast::Ast) -> Result { + 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 { + self.pipeline.parse(source) + } + + pub fn desugar(&self, ast: yeast::Ast) -> Result { + self.pipeline.desugar(ast) + } } impl LanguageExtractor for LanguageSpec { @@ -44,15 +157,15 @@ impl LanguageExtractor for LanguageSpec { } fn build_schema(&self) -> std::io::Result { - 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) } @@ -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(), ) } } diff --git a/shared/tree-sitter-extractor/src/extractor/driver.rs b/shared/tree-sitter-extractor/src/extractor/driver.rs index 14993da9f915..93aac9e379db 100644 --- a/shared/tree-sitter-extractor/src/extractor/driver.rs +++ b/shared/tree-sitter-extractor/src/extractor/driver.rs @@ -171,6 +171,7 @@ pub(crate) fn run_extractor( languages_processed[i] = true; let lang = &languages[i]; + let trap_checkpoint = trap_writer.clone(); let result = lang.extract_file( &schemas[i], &mut diagnostics_writer, @@ -185,6 +186,7 @@ pub(crate) fn run_extractor( write_trap(trap_dir, &path, &trap_writer, trap_compression)?; } Err(error) => { + trap_writer = trap_checkpoint; tracing::error!( file = %path.display(), error, @@ -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, + fail_fallback: bool, } impl LanguageExtractor for TestLanguage { @@ -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(()) @@ -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], @@ -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(); } diff --git a/shared/tree-sitter-extractor/src/extractor/mod.rs b/shared/tree-sitter-extractor/src/extractor/mod.rs index 29a290a96bf3..ed3925a23848 100644 --- a/shared/tree-sitter-extractor/src/extractor/mod.rs +++ b/shared/tree-sitter-extractor/src/extractor/mod.rs @@ -289,18 +289,13 @@ pub fn location_label(writer: &mut trap::Writer, location: trap::Location) -> tr loc_label } -/// Extracts the source file at `path`, which is assumed to be canonicalized. -/// -/// When `desugarer` is `Some`, the parsed tree is first transformed -/// through the supplied yeast desugarer before TRAP extraction. Building -/// the desugarer (which parses YAML and constructs the schema) is the -/// caller's responsibility, allowing it to be done once and shared across -/// files. -#[allow(clippy::too_many_arguments)] /// Extract a file with a tree-sitter grammar, walking the parse tree directly. +/// +/// `path` is assumed to be canonicalized. /// Comments and other `extra` nodes are emitted inline as tokens. This is the /// path for languages that don't desugar their syntax tree (and hence have no -/// `extra` side channel); desugaring languages use [`extract_parsed`] instead. +/// `extra` side channel); desugaring languages use [`desugaring::LanguageSpec`]. +#[allow(clippy::too_many_arguments)] pub fn extract( language: &Language, language_prefix: &str, @@ -417,19 +412,13 @@ fn collect_extras(node: Node<'_>, source: &[u8], out: &mut Vec) { } } -/// Extract a file from a [`ParsedTree`]-producing parser that desugars. +/// Extract a desugared YEAST AST and its side-channel `extra` tokens. /// -/// The parser yields a `yeast::Ast` plus side-channel `extra` tokens; the AST is -/// rewritten through `desugarer` ([`yeast::Desugarer::run_from_ast`]) before -/// TRAP extraction, and the `extra` tokens (comments and similar, which the -/// desugared AST does not carry) are emitted from the side channel. Both -/// tree-sitter grammars (via [`tree_sitter_parser`]) and custom parsers plug in -/// here; languages that don't desugar use [`extract`] instead. Parse and -/// desugaring errors are returned to the multi-file driver so it can skip only -/// this file and continue extracting the rest. +/// Returns every TRAP label allocated for each reachable [`yeast::OutputId`]. +/// A single output id may have multiple labels when it occurs in multiple +/// structural positions. #[allow(clippy::too_many_arguments)] -pub fn extract_parsed( - parse: &(dyn Fn(&[u8]) -> Result + Send + Sync), +pub fn extract_output_ast( language_prefix: &str, schema: &NodeTypeMap, diagnostics_writer: &mut diagnostics::LogWriter, @@ -437,21 +426,14 @@ pub fn extract_parsed( transformer: Option<&file_paths::PathTransformer>, path: &Path, source: &[u8], - desugarer: &dyn yeast::Desugarer, -) -> Result<(), String> { + ast: &yeast::OutputAst, + extras: &[ExtraToken], +) -> Result>, String> { let path_str = file_paths::normalize_and_transform_path(path, transformer); let source_root = std::env::current_dir() .ok() .and_then(|d| d.canonicalize().ok()); let diagnostics_path = file_paths::relativize_for_diagnostic(path, source_root.as_deref()); - let span = tracing::span!(tracing::Level::TRACE, "extract", file = %path_str); - let _enter = span.enter(); - tracing::debug!("extracting: {}", path_str); - - let parsed = parse(source).map_err(|e| format!("Parsing failed: {e}"))?; - let ast = desugarer - .run_from_ast(parsed.ast) - .map_err(|e| format!("Desugaring failed: {e}"))?; trap_writer.comment(format!("Auto-generated TRAP file for {path_str}")); let file_label = populate_file(trap_writer, path, transformer); @@ -465,13 +447,13 @@ pub fn extract_parsed( schema, ); - traverse_yeast(&ast, &mut visitor); + traverse_yeast(ast, &mut visitor); // Comments and other `extra` tokens are not part of the desugared AST; emit // them directly from the parser's side channel. - for extra in &parsed.extras { + for extra in extras { visitor.emit_extra(extra); } - Ok(()) + Ok(visitor.output_labels) } /// A lightweight [`AstNode`] over a piece of side-channel `extra` content @@ -554,6 +536,7 @@ struct Visitor<'a> { /// matched against the dbscheme for the node. If the expectations are met /// the corresponding row definitions are added to the trap output. stack: Vec<(trap::Label, usize, Vec)>, + output_labels: Map>, } impl<'a> Visitor<'a> { @@ -578,7 +561,17 @@ impl<'a> Visitor<'a> { trivia_tokeninfo_table_name: format!("{language_prefix}_trivia_tokeninfo"), schema, stack: Vec::new(), + output_labels: Map::new(), + } + } + + fn enter_output_node(&mut self, id: yeast::OutputId, node: &N) -> bool { + let recurse = self.enter_node(node); + if recurse { + let label = self.stack.last().expect("entered node must be on stack").0; + self.output_labels.entry(id).or_default().push(label); } + recurse } /// Emit an `extra` token (a location row plus a `trivia_tokeninfo` row) for @@ -1051,16 +1044,16 @@ fn traverse(tree: &Tree, visitor: &mut Visitor) { fn traverse_yeast(tree: &yeast::OutputAst, visitor: &mut Visitor) { let mut cursor = tree.walk(); - visitor.enter_node(cursor.node()); + visitor.enter_output_node(cursor.node_id(), cursor.node()); let mut recurse = true; loop { if recurse && cursor.goto_first_child() { - recurse = visitor.enter_node(cursor.node()); + recurse = visitor.enter_output_node(cursor.node_id(), cursor.node()); } else { visitor.leave_node(cursor.field_name(), cursor.node()); if cursor.goto_next_sibling() { - recurse = visitor.enter_node(cursor.node()); + recurse = visitor.enter_output_node(cursor.node_id(), cursor.node()); } else if cursor.goto_parent() { recurse = false; } else { diff --git a/shared/tree-sitter-extractor/src/trap.rs b/shared/tree-sitter-extractor/src/trap.rs index 80ace03fbc7c..c11ad973e035 100644 --- a/shared/tree-sitter-extractor/src/trap.rs +++ b/shared/tree-sitter-extractor/src/trap.rs @@ -14,6 +14,7 @@ pub struct Location { pub end_column: usize, } +#[derive(Clone)] pub struct Writer { /// The accumulated trap entries trap_output: Vec, @@ -118,6 +119,7 @@ impl Writer { } } +#[derive(Clone)] pub enum Entry { /// Maps the label to a fresh id, e.g. `#123=*`. FreshId(Label), diff --git a/shared/yeast/src/lib.rs b/shared/yeast/src/lib.rs index 04c878f097a1..7a77b58717a7 100644 --- a/shared/yeast/src/lib.rs +++ b/shared/yeast/src/lib.rs @@ -1684,6 +1684,10 @@ impl Runner<'_, C> { output.set_source(ast.into_source()); output } + + pub fn run_from_ast_with_ctx(&self, ast: Ast, user_ctx: &C) -> Result { + self.run_once(ast, user_ctx) + } } impl Runner<'_, C> { @@ -1746,7 +1750,7 @@ pub trait Desugarer: Send + Sync { /// Stores the language and a pre-built schema so that per-call cost is bounded /// to constructing a transient /// [`Runner`] and cloning the schema (no YAML re-parsing). -pub struct ConcreteDesugarer { +pub struct ConcreteDesugarer { /// The input tree-sitter language, or `None` for a custom (non-tree-sitter) /// front-end that only ever desugars an externally-built AST /// (`run_from_ast`). @@ -1756,7 +1760,12 @@ pub struct ConcreteDesugarer { config: DesugaringConfig, } -impl ConcreteDesugarer { +impl ConcreteDesugarer { + pub fn run_from_ast_with_ctx(&self, ast: Ast, user_ctx: &C) -> Result { + let runner = Runner::with_schema_no_language(&self.schema, &self.config.phases); + runner.run_from_ast_with_ctx(ast, user_ctx) + } + /// Build a desugarer for `language` from `config`. Parses the output /// schema YAML once and stores it for reuse across files. pub fn new( @@ -1797,7 +1806,7 @@ impl ConcreteDesugarer { } } -impl Desugarer for ConcreteDesugarer { +impl Desugarer for ConcreteDesugarer { fn output_node_types_yaml(&self) -> Option<&'static str> { self.config.output_node_types_yaml } diff --git a/unified/extractor/BUILD.bazel b/unified/extractor/BUILD.bazel index 2f880d877cdb..73ce3ca0e810 100644 --- a/unified/extractor/BUILD.bazel +++ b/unified/extractor/BUILD.bazel @@ -11,6 +11,7 @@ codeql_rust_binary( aliases = aliases(), compile_data = [ "ast_types.yml", + "string_values.dbscheme", "swift_node_types.yml", ], data = ["//unified/swift-syntax-rs:swift_runtime"], diff --git a/unified/extractor/src/generator.rs b/unified/extractor/src/generator.rs index f1f8a34ca84d..2fd5df4896d1 100644 --- a/unified/extractor/src/generator.rs +++ b/unified/extractor/src/generator.rs @@ -1,4 +1,5 @@ use clap::Args; +use std::io::Write; use std::path::PathBuf; use codeql_extractor::generator::{generate, language::Language}; @@ -31,11 +32,14 @@ pub fn run(options: Options) -> std::io::Result<()> { desugar: Some(desugar), }]; + let dbscheme = options.dbscheme.clone(); generate( languages, options.dbscheme, options.library, true, // use facade AST "run unified/scripts/create-extractor-pack.sh", - ) + )?; + let mut dbscheme = std::fs::OpenOptions::new().append(true).open(dbscheme)?; + writeln!(dbscheme, "\n{}", include_str!("../string_values.dbscheme")) } diff --git a/unified/extractor/src/languages/swift/swift.rs b/unified/extractor/src/languages/swift/swift.rs index eb667fe2a11d..b89340e825aa 100644 --- a/unified/extractor/src/languages/swift/swift.rs +++ b/unified/extractor/src/languages/swift/swift.rs @@ -1,5 +1,7 @@ use codeql_extractor::extractor::desugaring; -use yeast::{ConcreteDesugarer, DesugaringConfig, Rule}; +use std::cell::RefCell; +use std::rc::Rc; +use yeast::{DesugaringConfig, Rule}; yeast::tree_schema! { swift_tree, @@ -15,6 +17,8 @@ yeast::query_match_schema! { use swift_output_query::query_match as output_query_match; +const STRING_VALUE_TABLE: &str = "unified_string_literal_interpreted"; + /// User context propagated from outer rules down to the inner rules that /// emit the corresponding output declarations, so that each emitted node /// is born with the outer information (name, type, modifiers, etc.) @@ -65,6 +69,8 @@ struct SwiftContext { /// name has no argument label. It is cleared when translating accessor /// bodies. subscript: Option, + /// Interpreted values keyed by their output string literal. + interpreted_strings: Rc>>, } /// The parts of a `subscriptDecl` shared by its getter and setter. These are @@ -93,10 +99,29 @@ impl SwiftContext { /// interpolations additionally restore the context after evaluation, /// preventing mutations from leaking into sibling fields. fn reset(&mut self) { + let interpreted_strings = Rc::clone(&self.interpreted_strings); *self = SwiftContext::default(); + self.interpreted_strings = interpreted_strings; } } +fn make_string_literal( + ctx: &mut yeast::build::BuildCtx<'_, SwiftContext>, + source: yeast::Id, +) -> yeast::OutputId { + let raw = ctx.source_text(source); + let interpreted = raw + .strip_prefix('"') + .and_then(|value| value.strip_suffix('"')) + .unwrap_or(&raw) + .to_string(); + let literal = tree!((string_literal #{source})); + ctx.interpreted_strings + .borrow_mut() + .push((literal, interpreted)); + literal +} + fn implicit_parameterless_initializer( ctx: &mut yeast::build::BuildCtx<'_, SwiftContext>, members: &[yeast::OutputId], @@ -305,20 +330,26 @@ fn translation_rules() -> Vec> { rule!((nilLiteralExpr) @@node => expr { tree!((builtin_expr #{node})) }), - rule!((simpleStringLiteralExpr) @@node => (string_literal #{node})), + rule!((simpleStringLiteralExpr) @@node => expr { + make_string_literal(&mut ctx, node) + }), // String literal with a single constant segment (for some reason not typed as simpleStringLiteralExpr) rule!( (stringLiteralExpr segments: (stringSegment) segments: _* @@rest) @@node where rest.is_empty() => - (string_literal #{node}) + expr { + make_string_literal(&mut ctx, node) + } ), rule!( (stringLiteralExpr segments: _* @segments) => (string_interpolation_expr element: {segments}) ), - rule!((stringSegment content: @@content) => (string_literal #{content})), + rule!((stringSegment content: @@content) => expr { + make_string_literal(&mut ctx, content) + }), rule!( (expressionSegment expressions: _* @expressions) => @@ -1898,13 +1929,33 @@ pub fn language_spec(desugared_ast_schema: &'static str) -> desugaring::Language .with_ignored_location_fields(["trailingComma"]) .add_phase("translate", translation_rules()) .with_output_node_types_yaml(desugared_ast_schema); - let desugarer = - ConcreteDesugarer::without_language(config).expect("failed to build Swift desugarer"); - desugaring::LanguageSpec { + desugaring::LanguageSpecBuilder { prefix: "swift", parser: Box::new(super::swift_parse::parse), - node_types: "", + desugaring: config, file_globs: vec!["*.swift".into(), "*.swiftinterface".into()], - desugarer: Box::new(desugarer), + post_extract: Some(Box::new( + |context: &SwiftContext, + labels: &desugaring::OutputLabels, + trap_writer: &mut codeql_extractor::trap::Writer| { + for (node, value) in context.interpreted_strings.borrow().iter() { + let node_labels = labels.get(node).ok_or_else(|| { + format!( + "interpreted string references unreachable output node {}", + node.0 + ) + })?; + for label in node_labels { + trap_writer.add_tuple( + STRING_VALUE_TABLE, + vec![(*label).into(), value.clone().into()], + ); + } + } + Ok(()) + }, + )), } + .build() + .expect("failed to build Swift desugarer") } diff --git a/unified/extractor/string_values.dbscheme b/unified/extractor/string_values.dbscheme new file mode 100644 index 000000000000..d26fb3ee133e --- /dev/null +++ b/unified/extractor/string_values.dbscheme @@ -0,0 +1,4 @@ +unified_string_literal_interpreted( + unique int node: @unified_token_string_literal ref, + string value: string ref +); diff --git a/unified/extractor/tests/corpus_tests.rs b/unified/extractor/tests/corpus_tests.rs index e5ce3c5e3249..93fab33213ef 100644 --- a/unified/extractor/tests/corpus_tests.rs +++ b/unified/extractor/tests/corpus_tests.rs @@ -62,9 +62,8 @@ fn render_corpus(case: &CorpusCase) -> String { /// Parse `input` through the language's parser and desugar it, returning the /// mapped AST. fn run_desugaring(lang: &desugaring::LanguageSpec, input: &str) -> Result { - let parsed = (lang.parser)(input.as_bytes())?; - lang.desugarer - .run_from_ast(parsed.ast) + let parsed = lang.parse(input.as_bytes())?; + lang.desugar(parsed.ast) .map_err(|e| format!("Desugaring failed: {e}")) } @@ -72,7 +71,7 @@ fn run_desugaring(lang: &desugaring::LanguageSpec, input: &str) -> Result Result { - let parsed = (lang.parser)(input.as_bytes())?; + let parsed = lang.parse(input.as_bytes())?; Ok(dump_ast(&parsed.ast, parsed.ast.get_root(), input)) } diff --git a/unified/extractor/tests/location_tests.rs b/unified/extractor/tests/location_tests.rs index 66e24473993c..58d783af9085 100644 --- a/unified/extractor/tests/location_tests.rs +++ b/unified/extractor/tests/location_tests.rs @@ -13,10 +13,8 @@ fn desugar(source: &str) -> Ast { .any(|glob| glob.contains("swift")) }) .expect("Swift language spec"); - let parsed = (lang.parser)(source.as_bytes()).expect("Swift should parse"); - lang.desugarer - .run_from_ast(parsed.ast) - .expect("Swift should desugar") + let parsed = lang.parse(source.as_bytes()).expect("Swift should parse"); + lang.desugar(parsed.ast).expect("Swift should desugar") } fn spans(ast: &Ast, source: &str, kind: &str, content: Option<&str>) -> Vec { diff --git a/unified/extractor/tests/swift_syntax_pipeline.rs b/unified/extractor/tests/swift_syntax_pipeline.rs index fde060f98203..aa1cf05fa175 100644 --- a/unified/extractor/tests/swift_syntax_pipeline.rs +++ b/unified/extractor/tests/swift_syntax_pipeline.rs @@ -22,7 +22,6 @@ fn swift_syntax_json_runs_through_the_desugarer() { .into_iter() .find(|l| l.file_globs.iter().any(|g| g.contains("swift"))) .expect("swift language spec"); - let desugarer = lang.desugarer.as_ref(); // Adapt the swift-syntax JSON into a yeast AST (pure Rust, no Swift FFI). let adapted = @@ -39,8 +38,8 @@ fn swift_syntax_json_runs_through_the_desugarer() { // Run the real Swift desugaring rules over the externally-built AST. The // top-level swift-syntax rules map `sourceFile` to `top_level`/`block`; // kinds without swift-syntax rules yet fall back to `unsupported_node`. - let desugared = desugarer - .run_from_ast(adapted.ast) + let desugared = lang + .desugar(adapted.ast) .expect("desugaring an externally-built AST should not error"); let dump = dump_ast(&desugared, desugared.get_root(), ""); diff --git a/unified/ql/lib/codeql/unified/internal/FacadeAst.qll b/unified/ql/lib/codeql/unified/internal/FacadeAst.qll index 8848a58e2a1b..01aa78812b82 100644 --- a/unified/ql/lib/codeql/unified/internal/FacadeAst.qll +++ b/unified/ql/lib/codeql/unified/internal/FacadeAst.qll @@ -115,17 +115,7 @@ module Unified { /** An expression */ class Expr extends G::Expr { /** Gets the string value of this expression, if it is a known string constant. */ - string getStringValue() { - // TODO: we'll want to cook the string literals extractor-side, but for now - // just strip the quotes here and ignore escape sequences. - exists(string text | text = this.(StringLiteral).getValue() | - result = text.regexpCapture("\"(.*)\"", 1) - or - // Constant-segments of string interpolations are represented as string literals, but their raw text does not have quotes - not exists(text.regexpCapture("\"(.*)\"", 1)) and - result = text - ) - } + string getStringValue() { result = this.(StringLiteral).getInterpretedValue() } /** Gets the immediately-enclosing expression, skipping over intermediate sub-nodes like `Argument`, and without crossing a function boundary. */ Expr getEnclosingExpr() { @@ -142,6 +132,11 @@ module Unified { BasicBlock getBasicBlock() { result = this.getControlFlowNode().getBasicBlock() } } + class StringLiteral extends G::StringLiteral { + /** Gets the interpreted value of this string literal or constant segment. */ + string getInterpretedValue() { unified_string_literal_interpreted(this, result) } + } + class AccessorDeclaration extends G::AccessorDeclaration { /** Gets the name of this accessor. */ string getName() { result = this.getNameNode().getValue() } diff --git a/unified/ql/lib/unified.dbscheme b/unified/ql/lib/unified.dbscheme index 248bbdb74d16..ac4d9bde59f9 100644 --- a/unified/ql/lib/unified.dbscheme +++ b/unified/ql/lib/unified.dbscheme @@ -1059,3 +1059,9 @@ unified_ast_node_parent( int parent_index: int ref ); + +unified_string_literal_interpreted( + unique int node: @unified_token_string_literal ref, + string value: string ref +); +