diff --git a/Cargo.lock b/Cargo.lock index a9bd2e079eaa..c15fc50a8c37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3772,6 +3772,19 @@ dependencies = [ "yeast-schema", ] +[[package]] +name = "yeast-python" +version = "0.1.0" +dependencies = [ + "anyhow", + "cc", + "clap", + "serde_json", + "tree-sitter", + "tree-sitter-language", + "yeast", +] + [[package]] name = "yeast-schema" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 55791ed6fb55..a726a12210f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ members = [ "shared/yeast", "shared/yeast-macros", "shared/yeast-schema", + "python/extractor/yeast-python", "ruby/extractor", "unified/extractor", "unified/swift-syntax-rs", diff --git a/misc/bazel/3rdparty/rust_workspace_deps/crates.bzl b/misc/bazel/3rdparty/rust_workspace_deps/crates.bzl index 052465c1affb..dab963f5cedd 100644 --- a/misc/bazel/3rdparty/rust_workspace_deps/crates.bzl +++ b/misc/bazel/3rdparty/rust_workspace_deps/crates.bzl @@ -315,6 +315,7 @@ def aliases( _CRATE_EDITIONS = { "cpp/extractor/bmn": "2024", + "python/extractor/yeast-python": "2024", "ql/buramu": "2021", "ql/buramu/tree-sitter-blame": "2021", "ql/extractor": "2021", @@ -353,6 +354,15 @@ _NORMAL_DEPENDENCIES = { "zip": Label("@vendor_rs//zip-9.0.5"), }, }, + "python/extractor/yeast-python": { + _COMMON_CONDITION: { + "anyhow": Label("@vendor_rs//anyhow-1.0.104"), + "clap": Label("@vendor_rs//clap-4.6.7"), + "serde_json": Label("@vendor_rs//serde_json-1.0.154"), + "tree-sitter": Label("@vendor_rs//tree-sitter-0.26.9"), + "tree-sitter-language": Label("@vendor_rs//tree-sitter-language-0.1.7"), + }, + }, "ql/buramu": { _COMMON_CONDITION: { "chrono": Label("@vendor_rs//chrono-0.4.45"), @@ -515,6 +525,10 @@ _NORMAL_ALIASES = { _COMMON_CONDITION: { }, }, + "python/extractor/yeast-python": { + _COMMON_CONDITION: { + }, + }, "ql/buramu": { _COMMON_CONDITION: { }, @@ -575,6 +589,8 @@ _NORMAL_ALIASES = { _NORMAL_DEV_DEPENDENCIES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -615,6 +631,8 @@ _NORMAL_DEV_DEPENDENCIES = { _NORMAL_DEV_ALIASES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -652,6 +670,8 @@ _NORMAL_DEV_ALIASES = { _PROC_MACRO_DEPENDENCIES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -687,6 +707,8 @@ _PROC_MACRO_DEPENDENCIES = { _PROC_MACRO_ALIASES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -722,6 +744,8 @@ _PROC_MACRO_ALIASES = { _PROC_MACRO_DEV_DEPENDENCIES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -757,6 +781,8 @@ _PROC_MACRO_DEV_DEPENDENCIES = { _PROC_MACRO_DEV_ALIASES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -794,6 +820,11 @@ _PROC_MACRO_DEV_ALIASES = { _BUILD_DEPENDENCIES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + _COMMON_CONDITION: { + "cc": Label("@vendor_rs//cc-1.4.6"), + }, + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -832,6 +863,10 @@ _BUILD_DEPENDENCIES = { _BUILD_ALIASES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + _COMMON_CONDITION: { + }, + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -869,6 +904,8 @@ _BUILD_ALIASES = { _BUILD_PROC_MACRO_DEPENDENCIES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { @@ -904,6 +941,8 @@ _BUILD_PROC_MACRO_DEPENDENCIES = { _BUILD_PROC_MACRO_ALIASES = { "cpp/extractor/bmn": { }, + "python/extractor/yeast-python": { + }, "ql/buramu": { }, "ql/buramu/tree-sitter-blame": { diff --git a/python/BUILD.bazel b/python/BUILD.bazel index d53770a726c9..06affcff9e25 100644 --- a/python/BUILD.bazel +++ b/python/BUILD.bazel @@ -43,6 +43,7 @@ codeql_pkg_files( name = "extractor-arch", exes = [ "//python/extractor/tsg-python", + "//python/extractor/yeast-python", ], prefix = "tools/{CODEQL_PLATFORM}", ) diff --git a/python/extractor/semmle/python/modules.py b/python/extractor/semmle/python/modules.py index 7192f97cfb11..e5e111e8350b 100644 --- a/python/extractor/semmle/python/modules.py +++ b/python/extractor/semmle/python/modules.py @@ -3,6 +3,7 @@ import semmle.python.parser.tokenizer import semmle.python.parser.tsg_parser +import semmle.python.parser.yeast_parser import re import os from blib2to3.pgen2 import tokenize @@ -121,6 +122,28 @@ def old_py_ast(self): @property def py_ast(self): + if self._py_ast is None and not os.environ.get( + "CODEQL_PYTHON_DISABLE_YEAST_PARSER" + ): + with timers["yeast_py_ast"]: + self.logger.debug("Trying yeast parser on %s", self.path) + try: + self._py_ast = semmle.python.parser.yeast_parser.parse( + self.path, self.source, self.logger + ) + except Exception as ex: + self.logger.debug( + "Yeast parser failed on %s: %s", self.path, ex + ) + self._py_ast = None + if self._py_ast is not None: + self.logger.debug("Yeast parser successful on %s", self.path) + self.diagnostics_writer.record_tree_sitter_parser() + return self._py_ast + elif self._py_ast is None: + self.logger.debug( + "Yeast parser disabled, skipping parse attempt for %s", self.path + ) try: # If the `CODEQL_PYTHON_DISABLE_OLD_PARSER` flag is present, we do not try to use the # old parser, and instead jump straight to the exception handler. diff --git a/python/extractor/semmle/python/parser/yeast_parser.py b/python/extractor/semmle/python/parser/yeast_parser.py new file mode 100644 index 000000000000..df8a42ba68cc --- /dev/null +++ b/python/extractor/semmle/python/parser/yeast_parser.py @@ -0,0 +1,83 @@ +# Functions used for parsing Python files with YEAST. + +import json +import os +import subprocess + + +_SUPPORTED_PLATFORMS = frozenset(("linux64", "linux-arm64", "osx64", "win64")) + + +def _is_within(path, root): + try: + return os.path.commonpath((root, path)) == root + except ValueError: + return False + + +def _packaged_command(extractor_root, platform): + if platform not in _SUPPORTED_PLATFORMS: + raise ValueError("Unsupported CodeQL platform {!r}".format(platform)) + + tools_root = os.path.realpath(os.path.join(extractor_root, "tools")) + tools = os.path.realpath(os.path.join(tools_root, platform)) + if not _is_within(tools, tools_root): + raise ValueError("Platform tools directory escapes extractor tools root") + + ext = ".exe" if platform == "win64" else "" + executable = os.path.realpath(os.path.join(tools, "yeast-python" + ext)) + if not _is_within(executable, tools): + raise ValueError("Parser executable escapes platform tools directory") + return [executable] + + +_SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)) +_SOURCE_TREE_ROOT = os.path.realpath( + os.path.join(_SCRIPT_PATH, "../../../yeast-python") +) +_SOURCE_TREE_COMMAND = [ + "cargo", + "run", + "--quiet", + "--release", + "--manifest-path=" + os.path.join(_SOURCE_TREE_ROOT, "Cargo.toml"), +] + + +def _parser_command(): + if "CODEQL_EXTRACTOR_PYTHON_ROOT" in os.environ: + return ( + _packaged_command( + os.environ["CODEQL_EXTRACTOR_PYTHON_ROOT"], + os.environ["CODEQL_PLATFORM"], + ), + [], + None, + ) + return ( + _SOURCE_TREE_COMMAND, + ["--"], + _SOURCE_TREE_ROOT, + ) + + +def parse(path, source, _logger): + command, command_separator, cwd = _parser_command() + command_args = command + command_separator + [os.path.abspath(path)] + process = subprocess.Popen( + command_args, + cwd=cwd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + stdout, stderr = process.communicate(source.encode("utf-8")) + if process.returncode: + raise subprocess.CalledProcessError( + process.returncode, command_args, stdout, stderr + ) + + result = json.loads(stdout) + if result == {"status": "not_parsed"}: + return None + raise ValueError("Unsupported yeast parser response {!r}".format(result)) diff --git a/python/extractor/tests/test_diagnostics.py b/python/extractor/tests/test_diagnostics.py index ddfd22436de9..bd2512f4da61 100644 --- a/python/extractor/tests/test_diagnostics.py +++ b/python/extractor/tests/test_diagnostics.py @@ -124,6 +124,7 @@ def test_records_old_parser_usage_once(mocker, monkeypatch): monkeypatch.delenv("CODEQL_PYTHON_DISABLE_OLD_PARSER", raising=False) monkeypatch.delenv("CODEQL_PYTHON_DISABLE_TSG_PARSER", raising=False) old_ast = object() + mocker.patch("semmle.python.parser.yeast_parser.parse", return_value=None) mocker.patch("semmle.python.parser.parse", return_value=old_ast) diagnostics_writer = worker.DiagnosticsWriter(1) module = PythonSourceModule( @@ -142,10 +143,110 @@ def test_records_old_parser_usage_once(mocker, monkeypatch): assert diagnostics_writer.parser_statistics() == (1, 0) +def test_tries_yeast_parser_before_old_parser(mocker, monkeypatch): + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_YEAST_PARSER", raising=False) + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_OLD_PARSER", raising=False) + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_TSG_PARSER", raising=False) + calls = [] + old_ast = object() + mocker.patch( + "semmle.python.parser.yeast_parser.parse", + side_effect=lambda *_args: calls.append("yeast"), + ) + mocker.patch( + "semmle.python.parser.parse", + side_effect=lambda *_args: calls.append("old") or old_ast, + ) + diagnostics_writer = worker.DiagnosticsWriter(1) + module = PythonSourceModule( + None, + "test.py", + mocker.Mock(), + diagnostics_writer, + bytes_source=b"x = 1\n", + ) + + assert module.py_ast is old_ast + assert calls == ["yeast", "old"] + assert diagnostics_writer.parser_statistics() == (1, 0) + + +def test_can_disable_yeast_parser(mocker, monkeypatch): + monkeypatch.setenv("CODEQL_PYTHON_DISABLE_YEAST_PARSER", "1") + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_OLD_PARSER", raising=False) + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_TSG_PARSER", raising=False) + old_ast = object() + yeast_parse = mocker.patch("semmle.python.parser.yeast_parser.parse") + mocker.patch("semmle.python.parser.parse", return_value=old_ast) + diagnostics_writer = worker.DiagnosticsWriter(1) + module = PythonSourceModule( + None, + "test.py", + mocker.Mock(), + diagnostics_writer, + bytes_source=b"x = 1\n", + ) + + assert module.py_ast is old_ast + yeast_parse.assert_not_called() + assert diagnostics_writer.parser_statistics() == (1, 0) + + +def test_passes_decoded_non_utf8_source_to_yeast_parser(mocker, monkeypatch): + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_YEAST_PARSER", raising=False) + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_OLD_PARSER", raising=False) + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_TSG_PARSER", raising=False) + old_ast = object() + yeast_parse = mocker.patch( + "semmle.python.parser.yeast_parser.parse", return_value=None + ) + mocker.patch("semmle.python.parser.parse", return_value=old_ast) + diagnostics_writer = worker.DiagnosticsWriter(1) + logger = mocker.Mock() + module = PythonSourceModule( + None, + "test.py", + logger, + diagnostics_writer, + bytes_source=b"# coding: latin-1\nvalue = '\xe9'\n", + ) + + assert module.py_ast is old_ast + yeast_parse.assert_called_once_with( + "test.py", "# coding: latin-1\nvalue = '\xe9'\n", logger + ) + assert diagnostics_writer.parser_statistics() == (1, 0) + + +def test_falls_back_when_yeast_parser_fails(mocker, monkeypatch): + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_YEAST_PARSER", raising=False) + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_OLD_PARSER", raising=False) + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_TSG_PARSER", raising=False) + old_ast = object() + mocker.patch( + "semmle.python.parser.yeast_parser.parse", + side_effect=ValueError("unsupported input"), + ) + mocker.patch("semmle.python.parser.parse", return_value=old_ast) + diagnostics_writer = worker.DiagnosticsWriter(1) + module = PythonSourceModule( + None, + "test.py", + mocker.Mock(), + diagnostics_writer, + bytes_source=b"x = 1\n", + ) + + assert module.py_ast is old_ast + assert diagnostics_writer.parser_statistics() == (1, 0) + + def test_records_tree_sitter_parser_usage_once(mocker, monkeypatch): + monkeypatch.delenv("CODEQL_PYTHON_DISABLE_YEAST_PARSER", raising=False) monkeypatch.delenv("CODEQL_PYTHON_DISABLE_OLD_PARSER", raising=False) monkeypatch.delenv("CODEQL_PYTHON_DISABLE_TSG_PARSER", raising=False) tree_sitter_ast = object() + mocker.patch("semmle.python.parser.yeast_parser.parse", return_value=None) mocker.patch("semmle.python.parser.parse", side_effect=SyntaxError("old parser failed")) mocker.patch( "semmle.python.parser.tsg_parser.parse", return_value=tree_sitter_ast diff --git a/python/extractor/tests/test_yeast_parser.py b/python/extractor/tests/test_yeast_parser.py new file mode 100644 index 000000000000..3a2a3fb5a67f --- /dev/null +++ b/python/extractor/tests/test_yeast_parser.py @@ -0,0 +1,78 @@ +from pathlib import Path + +import pytest + +from semmle.python.parser import yeast_parser +from semmle.python.parser.tokenizer import encoding_from_source + + +class Logger: + def debug(self, *_args, **_kwargs): + pass + + +def test_non_utf8_source_is_passed_as_utf8(mocker, monkeypatch): + monkeypatch.delenv("CODEQL_EXTRACTOR_PYTHON_ROOT", raising=False) + path = (Path(__file__).parent / "tokenizer" / "latin.py").resolve() + encoding, source = encoding_from_source(path.read_bytes()) + source = source.decode(encoding) + process = mocker.Mock(returncode=0) + process.communicate.return_value = (b'{"status":"not_parsed"}', b"") + popen = mocker.patch( + "semmle.python.parser.yeast_parser.subprocess.Popen", + return_value=process, + ) + + assert yeast_parser.parse(str(path), source, Logger()) is None + command, command_separator, cwd = yeast_parser._parser_command() + popen.assert_called_once_with( + command + command_separator + [str(path)], + cwd=cwd, + stdin=yeast_parser.subprocess.PIPE, + stdout=yeast_parser.subprocess.PIPE, + stderr=yeast_parser.subprocess.PIPE, + ) + process.communicate.assert_called_once_with(source.encode("utf-8")) + + +def test_packaged_command_accepts_supported_platform(tmp_path): + expected = tmp_path / "tools" / "linux64" / "yeast-python" + + assert yeast_parser._packaged_command(str(tmp_path), "linux64") == [ + str(expected) + ] + + +def test_packaged_command_rejects_unsupported_platform(tmp_path): + with pytest.raises(ValueError, match="Unsupported CodeQL platform"): + yeast_parser._packaged_command(str(tmp_path), "../linux64") + + +def test_packaged_command_rejects_tools_symlink_escape(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + tools = tmp_path / "tools" + tools.mkdir() + (tools / "linux64").symlink_to(outside, target_is_directory=True) + + with pytest.raises(ValueError, match="escapes extractor tools root"): + yeast_parser._packaged_command(str(tmp_path), "linux64") + + +def test_packaged_command_rejects_executable_symlink_escape(tmp_path): + outside = tmp_path / "outside" + outside.touch() + tools = tmp_path / "tools" / "linux64" + tools.mkdir(parents=True) + (tools / "yeast-python").symlink_to(outside) + + with pytest.raises(ValueError, match="escapes platform tools directory"): + yeast_parser._packaged_command(str(tmp_path), "linux64") + + +def test_packaged_command_validation_is_deferred(monkeypatch, tmp_path): + monkeypatch.setenv("CODEQL_EXTRACTOR_PYTHON_ROOT", str(tmp_path)) + monkeypatch.setenv("CODEQL_PLATFORM", "../linux64") + + with pytest.raises(ValueError, match="Unsupported CodeQL platform"): + yeast_parser._parser_command() diff --git a/python/extractor/tsg-python/tsp/BUILD.bazel b/python/extractor/tsg-python/tsp/BUILD.bazel index f45d8f7f41f4..6cd3e889e652 100644 --- a/python/extractor/tsg-python/tsp/BUILD.bazel +++ b/python/extractor/tsg-python/tsp/BUILD.bazel @@ -4,6 +4,11 @@ load("//misc/bazel/3rdparty/py_deps:defs.bzl", "aliases", "all_crate_deps") package(default_visibility = ["//visibility:public"]) +filegroup( + name = "parser-sources", + srcs = glob(["src/**"]), +) + # This will run the build script from the root of the workspace, and # collect the outputs. cargo_build_script( diff --git a/python/extractor/yeast-python/BUILD.bazel b/python/extractor/yeast-python/BUILD.bazel new file mode 100644 index 000000000000..959ac234cb3e --- /dev/null +++ b/python/extractor/yeast-python/BUILD.bazel @@ -0,0 +1,34 @@ +load("@rules_rust//cargo:defs.bzl", "cargo_build_script") +load("//misc/bazel:rust.bzl", "codeql_rust_binary") +load("//misc/bazel/3rdparty/rust_workspace_deps:defs.bzl", "aliases", "all_crate_deps") + +cargo_build_script( + name = "yeast-python-build", + srcs = ["build.rs"], + data = ["//python/extractor/tsg-python/tsp:parser-sources"], + deps = all_crate_deps( + build = True, + ), +) + +codeql_rust_binary( + name = "yeast-python", + srcs = [ + "src/main.rs", + "src/parser.rs", + ], + aliases = aliases(), + compile_data = ["//python/extractor/tsg-python/tsp:src/node-types.json"], + proc_macro_deps = all_crate_deps( + proc_macro = True, + ), + visibility = ["//visibility:public"], + deps = all_crate_deps( + normal = True, + ) + [ + ":yeast-python-build", + "//shared/yeast", + ], +) + +exports_files(["Cargo.toml"]) diff --git a/python/extractor/yeast-python/Cargo.toml b/python/extractor/yeast-python/Cargo.toml new file mode 100644 index 000000000000..58eebfc52ea7 --- /dev/null +++ b/python/extractor/yeast-python/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "yeast-python" +version = "0.1.0" +authors = ["Taus "] +edition = "2024" + +[dependencies] +anyhow = "1.0" +clap = "4.5" +serde_json = "1.0" +tree-sitter = "=0.26.9" +tree-sitter-language = "=0.1.7" +yeast = { path = "../../../shared/yeast" } + +[build-dependencies] +cc = "1.4" + +[lints] +workspace = true diff --git a/python/extractor/yeast-python/README.md b/python/extractor/yeast-python/README.md new file mode 100644 index 000000000000..01c8483f23ea --- /dev/null +++ b/python/extractor/yeast-python/README.md @@ -0,0 +1,9 @@ +# `yeast-python` + +Parse Python source with tree-sitter and translate its syntax tree with YEAST. + +The parser currently contains no translation rules and reports +`{"status":"not_parsed"}` for every file. This allows the Python extractor to +exercise the parser infrastructure before falling back to its existing parsers. +The source path is supplied as the argument and decoded UTF-8 source is read from +standard input. diff --git a/python/extractor/yeast-python/build.rs b/python/extractor/yeast-python/build.rs new file mode 100644 index 000000000000..a9e5c0b5aa46 --- /dev/null +++ b/python/extractor/yeast-python/build.rs @@ -0,0 +1,28 @@ +use std::path::Path; + +fn main() { + let src_dir = Path::new("../tsg-python/tsp/src"); + + let header_path = src_dir.join("tree_sitter/parser.h"); + println!("cargo:rerun-if-changed={}", header_path.display()); + + let parser_path = src_dir.join("parser.c"); + cc::Build::new() + .include(src_dir) + .flag_if_supported("-Wno-unused-parameter") + .flag_if_supported("-Wno-unused-but-set-variable") + .flag_if_supported("-Wno-trigraphs") + .file(&parser_path) + .compile("parser"); + println!("cargo:rerun-if-changed={}", parser_path.display()); + + let scanner_path = src_dir.join("scanner.cc"); + cc::Build::new() + .cpp(true) + .include(src_dir) + .flag_if_supported("-Wno-unused-parameter") + .flag_if_supported("-Wno-unused-but-set-variable") + .file(&scanner_path) + .compile("scanner"); + println!("cargo:rerun-if-changed={}", scanner_path.display()); +} diff --git a/python/extractor/yeast-python/src/main.rs b/python/extractor/yeast-python/src/main.rs new file mode 100644 index 000000000000..2a9ed4439292 --- /dev/null +++ b/python/extractor/yeast-python/src/main.rs @@ -0,0 +1,25 @@ +use std::io::Read; +use std::path::Path; + +use anyhow::Result; +use clap::{Arg, Command}; + +mod parser; + +const BUILD_VERSION: &str = env!("CARGO_PKG_VERSION"); + +fn main() -> Result<()> { + let matches = Command::new("yeast-python") + .version(BUILD_VERSION) + .about("Extracts a Python AST with YEAST") + .arg(Arg::new("source").index(1).required(true)) + .get_matches(); + + let source_path = Path::new(matches.get_one::("source").unwrap()); + let mut source = String::new(); + std::io::stdin().read_to_string(&mut source)?; + + let result = parser::parse(source_path, &source)?; + serde_json::to_writer(std::io::stdout().lock(), &result)?; + Ok(()) +} diff --git a/python/extractor/yeast-python/src/parser.rs b/python/extractor/yeast-python/src/parser.rs new file mode 100644 index 000000000000..87b048c3a1df --- /dev/null +++ b/python/extractor/yeast-python/src/parser.rs @@ -0,0 +1,44 @@ +use std::path::Path; + +use anyhow::{Result, anyhow}; +use serde_json::{Value, json}; +use tree_sitter::Parser; +use tree_sitter_language::LanguageFn; + +unsafe extern "C" { + fn tree_sitter_python() -> *const (); +} + +pub(crate) fn parse(source_path: &Path, source: &str) -> Result { + // SAFETY: `tree_sitter_python` was generated by tree-sitter for this grammar. + let language_fn = unsafe { LanguageFn::from_raw(tree_sitter_python) }; + let language = tree_sitter::Language::new(language_fn); + let mut parser = Parser::new(); + parser.set_language(&language)?; + let tree = parser + .parse(source, None) + .ok_or_else(|| anyhow!("Could not parse {}", source_path.display()))?; + + let _ast = yeast::Ast::from_tree_with_schema_and_source( + yeast::schema::from_language(&language), + &tree, + &language, + source.as_bytes().to_vec(), + ); + Ok(json!({ "status": "not_parsed" })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reports_that_the_file_was_not_parsed() { + let source = "# Günter\npass\n"; + + assert_eq!( + parse(Path::new("test.py"), source).unwrap(), + json!({ "status": "not_parsed" }) + ); + } +} diff --git a/python/scripts/create-extractor-pack.sh b/python/scripts/create-extractor-pack.sh index ae9248f6ccfc..a97abc2ff07c 100755 --- a/python/scripts/create-extractor-pack.sh +++ b/python/scripts/create-extractor-pack.sh @@ -24,6 +24,10 @@ cd "$(dirname "$0")/.." (cd extractor/tsg-python && cargo build --release) tsg_bin="extractor/tsg-python/target/release/tsg-python" +# Build the yeast-python Rust binary in the repository Cargo workspace. +cargo build --release --package yeast-python +yeast_bin="../target/release/yeast-python" + # Generate python3src.zip from the Python extractor source. # make_zips.py creates the zip in the source directory and then copies it to the # given output directory. We use a temporary directory to avoid a same-file copy @@ -65,3 +69,4 @@ cp -r downgrades extractor-pack/ # Platform-specific Rust binary cp "${tsg_bin}" extractor-pack/tools/${platform}/tsg-python +cp "${yeast_bin}" extractor-pack/tools/${platform}/yeast-python