python_ast/ast/dump/
mod.rs

1use pyo3::prelude::*;
2use std::ffi::CString;
3
4/// A wrapper for the Python ast.dump function. This is a convenience function for dumping the AST
5/// to the terminal.
6pub fn dump(o: &Bound<'_, PyAny>, indent: Option<u8>) -> PyResult<String> {
7    let pymodule_code = include_str!("__init__.py");
8
9    Python::with_gil(|py| -> PyResult<String> {
10        // We want to call tokenize.tokenize from Python.
11        let code_cstr = CString::new(pymodule_code)?;
12        let pymodule = PyModule::from_code(py, &code_cstr, c"dump.py", c"parser")?;
13        let t = pymodule.getattr("dump")?;
14        assert!(t.is_callable());
15        let args = (o, indent);
16
17        t.call1(args)?.extract()
18    })
19}