简体   繁体   English

是否可以使用 rust 生成 jsx AST?

[英]is it possible using rust to generate jsx AST?

I'm not familiar with rust and trynna using swc to replace the babel我不熟悉 rust 和 trynna 使用 swc 替换 babel

but I found @swc/core doesn't offer the api to generate code AST, so I want to write one using rust, is it possible to generate jsx ast?但是我发现@swc/core没有提供生成代码AST的api,所以我想用rust写一个,是否可以生成jsx ast?

Here is a good place to start: https://github.com/swc-project/swc/blob/main/crates/swc_ecma_parser/examples/typescript.rs but link can get invalid so I also pasted the code:这是一个很好的起点: https ://github.com/swc-project/swc/blob/main/crates/swc_ecma_parser/examples/typescript.rs 但链接可能会失效,所以我也粘贴了代码:

use swc_common::{
    self,
    errors::{ColorConfig, Handler},
    sync::Lrc,
    FileName, SourceMap,
};
use swc_ecma_parser::{lexer::Lexer, Capturing, Parser, StringInput, Syntax};

fn main() {
    let cm: Lrc<SourceMap> = Default::default();
    let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(cm.clone()));

    // Real usage
    // let fm = cm
    //     .load_file(Path::new("test.js"))
    //     .expect("failed to load test.js");

    let fm = cm.new_source_file(
        FileName::Custom("test.js".into()),
        "interface Foo {}".into(),
    );

    let lexer = Lexer::new(
        Syntax::Typescript(Default::default()),
        Default::default(),
        StringInput::from(&*fm),
        None,
    );

    let capturing = Capturing::new(lexer);

    let mut parser = Parser::new_from(capturing);

    for e in parser.take_errors() {
        e.into_diagnostic(&handler).emit();
    }

    let _module = parser
        .parse_typescript_module()
        .map_err(|e| e.into_diagnostic(&handler).emit())
        .expect("Failed to parse module.");

    println!("Tokens: {:?}", parser.input().take());
}

I never really worked or cared about this.我从来没有真正工作过或关心过这个。 All it took was 5min of browsing the repository, all the resources are there but if you are new to rust, I recommend the rust book first.浏览存储库只需要 5 分钟,所有资源都在那里,但如果您是 rust 新手,我建议先阅读 rust 书

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM