需要帮助在 Tauri 中使用 Typescript 调用 Rust 库

问题描述 投票:0回答:1

在我的项目中,我想分析 PHP 文件的源代码并将其转换为 AST。 已经有一个用于此目的的 javascript 包,但它仅适用于节点。所以我尝试使用 Rust 库将 PHP 代码转换为 AST。然而,我对 Rust 没有任何经验,也没有取得任何进展:

文件 src-tauri/src/main.rs 内:

#[tauri::command] fn php_to_ast(code: &str) -> String { match parser::parse(code) { Ok(ast) => { format!("{:?}", ast) } } }

在打字稿中调用:

invoke('php_to_ast', { code: value }).then((result) => { this._ast = result; console.log({ast: this._ast}); }).catch((error) => { console.error({error}); });

控制台错误消息是:

error[E0004]: non-exhaustive patterns: `Err(_)` not covered --> src/main.rs:8:11 | 8 | match parser::parse(code) { | ^^^^^^^^^^^^^^^^^^^ pattern `Err(_)` not covered | note: `Result<Vec<php_parser_rs::parser::ast::Statement>, ParseErrorStack>` defined here = note: the matched value is of type `Result<Vec<php_parser_rs::parser::ast::Statement>, ParseErrorStack>` help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown | 11~ } 12+ Err(_) => todo!() |

我知道我没有完全处理 
parser::parse()

的返回值。作为比较,在

Rust 库示例
中,调用如下所示: fn main() -> Result<()> { match parser::parse(CODE) { Ok(ast) => { println!("{:#?}", ast); } Err(err) => { println!("{}", err.report(CODE, None, true, false)?); println!("parsed so far: {:#?}", err.partial); } } Ok(()) }

大概我还应该处理并返回错误(作为带有错误消息的字符串?)。

javascript typescript rust tauri php-parser
1个回答
0
投票

match parser::parse(code) { Ok(ast) => format!("{:?}", ast); Err(error) => /* Handle Error in Rust and return some indicator String */; }

然后在您的打字稿代码中,您可以检查返回的错误字符串:

invoke("php_to_ast", { code: value }) .then((ast_or_error) => { if (ast_or_error == "your_indicator") { /* Handle error in typescript */ } else { /* Use your ast */ } })

© www.soinside.com 2019 - 2024. All rights reserved.