Move unparse utility methods onto Generator (#4497)

This commit is contained in:
Charlie Marsh 2023-05-18 11:00:46 -04:00 committed by GitHub
parent d3b18345c5
commit e9c6f16c56
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
40 changed files with 137 additions and 157 deletions

View file

@ -17,27 +17,9 @@ use smallvec::SmallVec;
use crate::call_path::CallPath;
use crate::newlines::UniversalNewlineIterator;
use crate::source_code::{Generator, Indexer, Locator};
use crate::source_code::{Indexer, Locator};
use crate::statement_visitor::{walk_body, walk_stmt, StatementVisitor};
/// Generate source code from an [`Expr`].
pub fn unparse_expr(expr: &Expr, mut generator: Generator) -> String {
generator.unparse_expr(expr, 0);
generator.generate()
}
/// Generate source code from a [`Stmt`].
pub fn unparse_stmt(stmt: &Stmt, mut generator: Generator) -> String {
generator.unparse_stmt(stmt);
generator.generate()
}
/// Generate source code from an [`Constant`].
pub fn unparse_constant(constant: &Constant, mut generator: Generator) -> String {
generator.unparse_constant(constant);
generator.generate()
}
fn is_iterable_initializer<F>(id: &str, is_builtin: F) -> bool
where
F: Fn(&str) -> bool,

View file

@ -101,8 +101,22 @@ impl<'a> Generator<'a> {
}
}
pub fn generate(self) -> String {
self.buffer
/// Generate source code from a [`Stmt`].
pub fn stmt(mut self, stmt: &Stmt) -> String {
self.unparse_stmt(stmt);
self.generate()
}
/// Generate source code from an [`Expr`].
pub fn expr(mut self, expr: &Expr) -> String {
self.unparse_expr(expr, 0);
self.generate()
}
/// Generate source code from a [`Constant`].
pub fn constant(mut self, constant: &Constant) -> String {
self.unparse_constant(constant);
self.generate()
}
fn newline(&mut self) {
@ -165,13 +179,17 @@ impl<'a> Generator<'a> {
self.p_if(!std::mem::take(first), s);
}
pub fn unparse_suite<U>(&mut self, suite: &Suite<U>) {
pub(crate) fn generate(self) -> String {
self.buffer
}
pub(crate) fn unparse_suite<U>(&mut self, suite: &Suite<U>) {
for stmt in suite {
self.unparse_stmt(stmt);
}
}
pub fn unparse_stmt<U>(&mut self, ast: &Stmt<U>) {
pub(crate) fn unparse_stmt<U>(&mut self, ast: &Stmt<U>) {
macro_rules! statement {
($body:block) => {{
self.newline();
@ -824,7 +842,7 @@ impl<'a> Generator<'a> {
self.body(&ast.body);
}
pub fn unparse_expr<U>(&mut self, ast: &Expr<U>, level: u8) {
pub(crate) fn unparse_expr<U>(&mut self, ast: &Expr<U>, level: u8) {
macro_rules! opprec {
($opty:ident, $x:expr, $enu:path, $($var:ident($op:literal, $prec:ident)),*$(,)?) => {
match $x {
@ -1218,7 +1236,7 @@ impl<'a> Generator<'a> {
}
}
pub fn unparse_constant(&mut self, constant: &Constant) {
pub(crate) fn unparse_constant(&mut self, constant: &Constant) {
assert_eq!(f64::MAX_10_EXP, 308);
let inf_str = "1e309";
match constant {