Files
RustPython/examples/parse_folder.rs
Jeong, YunWon a1ba6a662c Align compiler and AST behavior with CPython (#8138)
* Align compiler and AST behavior with CPython

Update the compiler pipeline, AST module support, and related VM compile/eval paths toward CPython 3.14 behavior.

Use upstream Ruff parser crates directly and keep RustPython-specific syntax preflight handling in the compile path.

Refresh opcode metadata, snapshots, and targeted tests for the aligned bytecode and AST behavior.

* fix

* Fix PR 8138 CI failures

* Fix match mapping wildcard scan complexity

* fixes

* Use Ruff runtime AST fields

* Minimize residual patch diff

* refactor error handling

* Remove _ast conversion context wrappers

* Clean up _ast conversion glue and compiler warning escalation

Rename the Node conversion parameter `ctx` to `vm` throughout the _ast
module.

Remove the unused compile_program, compile_program_single,
compile_block_expression, and compile_expression forwarders; compile_top
stays as the entry point.

Stash an escalated compiler SyntaxWarning so a non-SyntaxWarning category
propagates unchanged instead of being rewritten to SyntaxError, matching
PyErr_ExceptionMatches(SyntaxWarning) in compiler_warn. Drop the now-unused
CompileWarningError::into_codegen_error.

Replace the PositionalArguments two-variant enum with a struct holding a
shared range and a PositionalArgumentsKind enum.

Assisted-by: Claude

* Represent compiler flags as a CompilerFlags bitflags

Replace the loose PY_CF_*/CO_* i32 constants in compile_mode with a
CompilerFlags bitflags covering the PyCF_* flags and __future__
CO_FUTURE_* bits. The Python-visible ast.PyCF_* attribute values are
derived from it via bits(); parser input modes stay plain consts.

builtins::compile and the compile_string flag handling test flags
through CompilerFlags::contains instead of raw bit math.

Assisted-by: Claude

* Fix PR 8138 test regressions

* Fix PR 8138 CI failures

* Avoid shell interpolation in Linux deps action

* Fix review findings in compiler/AST changes

- frame.rs: compute the MATCH_CLASS class name lazily so a successful
  match no longer takes the type name lock or allocates; the
  __match_args__-not-a-tuple branch reuses it instead of recomputing.
- _ast/constant.rs: add the missing leading space to the with_recursion
  label ("maximum recursion depth exceeded during compilation").
- sys.set_int_max_str_digits: restore the "maxdigits must be 0 or larger
  than {n}" error text.
- codegen: set CO_MAXBLOCKS to 20 in both ir.rs and compile.rs.
- _ast/exception.rs: extract the duplicated excepthandler node guard
  into ensure_excepthandler_node.
- codegen: correct the validate_keywords doc comment.
- Drop redundant "CPython" qualifiers from comments added in this branch.

Assisted-by: Claude
2026-06-26 18:22:08 +09:00

135 lines
3.7 KiB
Rust

/// This an example usage of the rustpython_parser crate.
/// This program crawls over a directory of python files and
/// tries to parse them into an abstract syntax tree (AST)
///
/// example usage:
/// $ RUST_LOG=info cargo run --release parse_folder /usr/lib/python3.7
extern crate env_logger;
#[macro_use]
extern crate log;
use ruff_python_parser::parse_module;
use rustpython_compiler::ast;
use std::{
path::{Path, PathBuf},
time::{Duration, Instant},
};
fn main() {
env_logger::init();
let folder: PathBuf = std::env::args_os()
.nth(1)
.expect("please pass a path argument")
.into();
if folder.exists() && folder.is_dir() {
println!("Parsing folder of python code: {folder:?}");
let t1 = Instant::now();
let parsed_files = parse_folder(&folder).unwrap();
let t2 = Instant::now();
let results = ScanResult {
t1,
t2,
parsed_files,
};
statistics(results);
} else {
println!("{folder:?} is not a folder.");
}
}
fn parse_folder(path: &Path) -> std::io::Result<Vec<ParsedFile>> {
let mut res = vec![];
info!("Parsing folder of python code: {path:?}");
for entry in path.read_dir()? {
debug!("Entry: {entry:?}");
let entry = entry?;
let metadata = entry.metadata()?;
let path = entry.path();
if metadata.is_dir() {
res.extend(parse_folder(&path)?);
}
if metadata.is_file() && path.extension().and_then(|s| s.to_str()) == Some("py") {
let parsed_file = parse_python_file(&path);
match &parsed_file.result {
Ok(_) => {}
Err(y) => error!("Error in file {path:?} {y:?}"),
}
res.push(parsed_file);
}
}
Ok(res)
}
fn parse_python_file(filename: &Path) -> ParsedFile {
info!("Parsing file {filename:?}");
match std::fs::read_to_string(filename) {
Err(e) => ParsedFile {
num_lines: 0,
result: Err(e.to_string()),
},
Ok(source) => {
let num_lines = source.lines().count();
let result = parse_module(&source)
.map(|x| x.into_suite())
.map_err(|e| e.to_string());
ParsedFile { num_lines, result }
}
}
}
fn statistics(results: ScanResult) {
// println!("Processed {:?} files", res.len());
println!("Scanned a total of {} files", results.parsed_files.len());
let total: usize = results.parsed_files.len();
let total_lines: usize = results.parsed_files.iter().map(|p| p.num_lines).sum();
let failed = results
.parsed_files
.iter()
.filter(|p| p.result.is_err())
.count();
let passed = results
.parsed_files
.iter()
.filter(|p| p.result.is_ok())
.count();
println!("Passed: {passed} Failed: {failed} Total: {total}");
println!(
"That is {} % success rate.",
(passed as f64 * 100.0) / total as f64
);
let duration = results.t2 - results.t1;
println!("Total time spend: {duration:?}");
println!(
"Processed {} files. That's {} files/second",
total,
rate(total, duration)
);
println!(
"Processed {} lines of python code. That's {} lines/second",
total_lines,
rate(total_lines, duration)
);
}
fn rate(counter: usize, duration: Duration) -> f64 {
(counter * 1_000_000) as f64 / duration.as_micros() as f64
}
struct ScanResult {
t1: Instant,
t2: Instant,
parsed_files: Vec<ParsedFile>,
}
struct ParsedFile {
num_lines: usize,
result: ParseResult,
}
type ParseResult = Result<ast::Suite, String>;