Add fake main function to fix Python AST parsing (#6006)

The changes ensure the Python AST parser can handle code snippets where the main
function was previously removed, by appending a dummy main function.
This commit is contained in:
pyranota
2025-06-20 09:28:30 +02:00
committed by GitHub
parent 77c2d2fa84
commit f2a7b48433
@@ -160,10 +160,17 @@ fn parse_code_for_imports(code: &str, path: &str) -> error::Result<Vec<NImport>>
+ "\n";
}
let ast = Suite::parse(&code, "main.py").map_err(|e| {
// Add a fake main function to ensure the parser can process the code correctly
// This is needed because we've split off the real main function above
let code_with_fake_main = format!("{}\n\ndef main(): pass", code);
let ast = Suite::parse(&code_with_fake_main, "main.py").map_err(|e| {
error::Error::ExecutionErr(format!("Error parsing code for imports: {}", e.to_string()))
})?;
// Note: We're still using the original code for finding pins,
// as the TextRange values from the parsed AST would be based on code_with_fake_main
// but we want to match against the original code
let find_pin = |range: TextRange, key: String| {
let hs = code
.chars()