Building a Writer
Thankfully because of the existence of resw
completing the console.log
debugging tool is going to be trivial. The primary entry point for resw
is the Writer
struct, which has a method write_part
that will take a &mut self
and &ProgramPart
, so we can use that in our for loop to write out the parts as they are parsed. That might look like this.
use resast::prelude::*; fn main() { let js = get_js().expect("Unable to get JavaScript"); let parser = Parser::new(&js).expect("Unable to construct parser"); let mut writer = Writer::new(::std::io::stdout()); for part in parser.filter_map(|p| p.ok()).map(map_part) { writer.write_part(&part).expect("Failed to write part"); }
With that complete we can see how well it works for us. Let's use the following example JavaScript.
function Thing(stuff) {
this.stuff = stuff;
}
let x = new Thing('argument');
Just as a simple test we could enter the following into our terminal
$ echo "function Thing(stuff) {
this.stuff = stuff;
}
let x = new Thing('argument');
" | console_logify
function Thing(stuff) {
console.log('Thing', stuff);
this.stuff = stuff;
}
let x = new Thing('argument!');
That looks exactly like the output we were looking for. Let's double check that it will behave as expected by piping the output to node
$ echo "function Thing(stuff) {
this.stuff = stuff;
}
let x = new Thing('argument');
" | console_logify | node -
Thing argument
It worked!