Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
refactor(ast_codegen): move formatting regex definitions (#4775)
Pure refactor. Move the regex definitions used in formatting to next to the `Replacer`s for those regexes.
  • Loading branch information
overlookmotel committed Aug 9, 2024
commit c15c931a3f2e509cb8037efcb17ab1d7b8c73d20
59 changes: 41 additions & 18 deletions tasks/ast_codegen/src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ use syn::parse_file;

static INSERT_MACRO_IDENT: &str = "insert";
static ENDL_MACRO_IDENT: &str = "endl";
static WHITE_SPACES: &str = " ";
static WHITE_SPACES: &str = " \t";

/// Replace `insert!` macro calls with the contents of the `insert!`.
///
/// e.g. `insert!("#![allow(dead_code)]")` is replaced by `#![allow(dead_code)]`.
///
/// We use this when inserting outer attributes (`#![allow(unused)]`) or plain comments (`//` not `///`).
/// `quote!` macro ignores plain comments, so it's not possible to produce them otherwise.
struct InsertReplacer;

impl Replacer for InsertReplacer {
Expand All @@ -21,36 +27,53 @@ impl Replacer for InsertReplacer {
}
}

lazy_static! {
static ref INSERT_REGEX: Regex = Regex::new(
format!(
r#"(?m)^[{WHITE_SPACES}]*{INSERT_MACRO_IDENT}!\([\n\s\S]*?\"([\n\s\S]*?)\"[\n\s\S]*?\);$"#
)
.as_str()
)
.unwrap();
}

/// Remove `endl!();`, so it produces a line break.
///
/// e.g.:
/// ```
/// use oxc_allocator::Allocator;
/// endl!();
/// use oxc_ast::*;
/// ```
/// becomes:
/// ```
/// use oxc_allocator::Allocator;
///
/// use oxc_ast::*;
/// ```
///
/// We use `endl!();` because `quote!` macro ignores whitespace,
/// so we have to use another means to generate line breaks.
struct EndlReplacer;

impl Replacer for EndlReplacer {
fn replace_append(&mut self, _: &Captures, _: &mut String) {}
}

/// Pretty Print
pub fn pprint(input: &TokenStream) -> String {
lazy_static! {
static ref INSERT_REGEX: Regex = Regex::new(
format!(
r#"(?m)^[{WHITE_SPACES}]*{INSERT_MACRO_IDENT}!\([\n\s\S]*?\"([\n\s\S]*?)\"[\n\s\S]*?\);$"#
)
.as_str()
)
.unwrap();
};

lazy_static! {
static ref ENDL_REGEX: Regex =
Regex::new(format!(r"[{WHITE_SPACES}]*{ENDL_MACRO_IDENT}!\(\);").as_str()).unwrap();
};
lazy_static! {
static ref ENDL_REGEX: Regex =
Regex::new(format!(r"[{WHITE_SPACES}]*{ENDL_MACRO_IDENT}!\(\);").as_str()).unwrap();
}

/// Pretty print
pub fn pprint(input: &TokenStream) -> String {
let result = prettyplease::unparse(&parse_file(input.to_string().as_str()).unwrap());
let result = ENDL_REGEX.replace_all(&result, EndlReplacer);
let result = INSERT_REGEX.replace_all(&result, InsertReplacer).to_string();
result
}

/// Runs cargo fmt.
/// Run `cargo fmt`
pub fn cargo_fmt() {
Command::new("cargo").arg("fmt").status().unwrap();
}