1818
1919use std:: path:: Path ;
2020
21+ use pico_args:: Arguments ;
22+
2123use oxc_allocator:: Allocator ;
2224use oxc_ast:: ast:: Program ;
23- use oxc_codegen:: { Codegen , CodegenOptions } ;
25+ use oxc_codegen:: { Codegen , CodegenOptions , CodegenReturn } ;
2426use oxc_parser:: { ParseOptions , Parser } ;
27+ use oxc_sourcemap:: SourcemapVisualizer ;
2528use oxc_span:: SourceType ;
26- use pico_args:: Arguments ;
2729
2830// Instruction:
2931// create a `test.js`,
@@ -36,17 +38,20 @@ fn main() -> std::io::Result<()> {
3638
3739 let twice = args. contains ( "--twice" ) ;
3840 let minify = args. contains ( "--minify" ) ;
39- let name = args. free_from_str ( ) . unwrap_or_else ( |_| "test.js" . to_string ( ) ) ;
41+ let sourcemap = args. contains ( "--sourcemap" ) ;
4042
43+ let name = args. free_from_str ( ) . unwrap_or_else ( |_| "test.js" . to_string ( ) ) ;
4144 let path = Path :: new ( & name) ;
45+ let sourcemap = sourcemap. then_some ( path) ;
46+
4247 let source_text = std:: fs:: read_to_string ( path) ?;
4348 let source_type = SourceType :: from_path ( path) . unwrap ( ) ;
4449 let mut allocator = Allocator :: default ( ) ;
4550
4651 // First round: parse and generate
4752 let printed = {
4853 let program = parse ( & allocator, & source_text, source_type) ;
49- codegen ( & program, minify)
54+ codegen ( & program, minify, sourcemap )
5055 } ;
5156 println ! ( "First time:" ) ;
5257 println ! ( "{printed}" ) ;
@@ -58,7 +63,7 @@ fn main() -> std::io::Result<()> {
5863
5964 let program = parse ( & allocator, & printed, source_type) ;
6065 println ! ( "Second time:" ) ;
61- let printed2 = codegen ( & program, minify) ;
66+ let printed2 = codegen ( & program, minify, None ) ;
6267 println ! ( "{printed2}" ) ;
6368 // Check syntax error
6469 parse ( & allocator, & printed2, source_type) ;
@@ -87,9 +92,17 @@ fn parse<'a>(
8792}
8893
8994/// Generate JavaScript code from an AST
90- fn codegen ( program : & Program < ' _ > , minify : bool ) -> String {
91- Codegen :: new ( )
92- . with_options ( if minify { CodegenOptions :: minify ( ) } else { CodegenOptions :: default ( ) } )
93- . build ( program)
94- . code
95+ fn codegen ( program : & Program < ' _ > , minify : bool , source_map_path : Option < & Path > ) -> String {
96+ let mut options = if minify { CodegenOptions :: minify ( ) } else { CodegenOptions :: default ( ) } ;
97+ options. source_map_path = source_map_path. map ( Path :: to_path_buf) ;
98+
99+ let CodegenReturn { code, map, .. } = Codegen :: new ( ) . with_options ( options) . build ( program) ;
100+
101+ if let Some ( map) = map {
102+ let visualizer = SourcemapVisualizer :: new ( & code, & map) ;
103+ println ! ( "{}" , visualizer. get_url( ) ) ;
104+ println ! ( "{}" , visualizer. get_text( ) ) ;
105+ }
106+
107+ code
95108}
0 commit comments