Skip to content

Commit

Permalink
feat(codegen): implement the basics of non-minifying codegen (#987)
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen committed Oct 13, 2023
1 parent efad0fc commit e0ca09b
Show file tree
Hide file tree
Showing 23 changed files with 574 additions and 402 deletions.
4 changes: 1 addition & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 15 additions & 1 deletion crates/oxc_ast/src/ast/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1465,7 +1465,9 @@ pub struct Function<'a> {

impl<'a> Function<'a> {
pub fn is_typescript_syntax(&self) -> bool {
self.modifiers.contains(ModifierKind::Declare) || self.body.is_none()
self.r#type == FunctionType::TSDeclareFunction
|| self.body.is_none()
|| self.modifiers.contains(ModifierKind::Declare)
}

pub fn is_expression(&self) -> bool {
Expand Down Expand Up @@ -1939,6 +1941,12 @@ pub struct ExportDefaultDeclaration<'a> {
pub exported: ModuleExportName, // `default`
}

impl<'a> ExportDefaultDeclaration<'a> {
pub fn is_typescript_syntax(&self) -> bool {
self.declaration.is_typescript_syntax()
}
}

#[derive(Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize), serde(tag = "type"))]
pub struct ExportAllDeclaration<'a> {
Expand All @@ -1950,6 +1958,12 @@ pub struct ExportAllDeclaration<'a> {
pub export_kind: ImportOrExportKind, // `export type *`
}

impl<'a> ExportAllDeclaration<'a> {
pub fn is_typescript_syntax(&self) -> bool {
self.export_kind.is_type()
}
}

#[derive(Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize), serde(tag = "type"))]
pub struct ExportSpecifier {
Expand Down
9 changes: 4 additions & 5 deletions crates/oxc_codegen/examples/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use oxc_span::SourceType;
// 2. run `cargo run -p oxc_codegen --example codegen` or `just example codegen`

fn main() {
let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
let name = env::args().nth(1).unwrap_or_else(|| "test.ts".to_string());
let path = Path::new(&name);
let source_text = std::fs::read_to_string(path).unwrap_or_else(|_| panic!("{name} not found"));
let source_type = SourceType::from_path(path).unwrap();
Expand All @@ -26,11 +26,10 @@ fn main() {
}

let codegen_options = CodegenOptions;
let minified = Codegen::<true>::new(source_text.len(), codegen_options).build(&ret.program);
println!("Minified:");
println!("{minified}");
let printed = Codegen::<false>::new(source_text.len(), codegen_options).build(&ret.program);
println!("{printed}");

let ret = Parser::new(&allocator, &printed, source_type).parse();
let printed = Codegen::<false>::new(source_text.len(), codegen_options).build(&ret.program);
println!("Printed:");
println!("{printed}");
}
Loading

0 comments on commit e0ca09b

Please sign in to comment.