Skip to main content

typescript_webidl/
lib.rs

1#![doc = include_str!("readme.md")]
2#![warn(missing_docs)]
3#![feature(new_range_api)]
4
5pub use oak_idl::ast;
6
7use std::fs;
8
9/// WebIDL 到 TypeScript 转换模块
10pub mod converter;
11
12/// WebIDL 类型定义模块
13pub mod types;
14
15/// WebIDL 类型检查模块
16pub mod type_checker;
17
18/// 调试模块
19pub mod debug;
20
21/// 解析 WebIDL 字符串
22///
23/// # 参数
24/// - `idl`: 要解析的 WebIDL 字符串
25///
26/// # 返回值
27/// - `Ok(oak_idl::ast::IdlRoot)`: 解析成功,返回 WebIDL AST
28/// - `Err(String)`: 解析失败,返回错误信息
29pub fn parse(idl: &str) -> Result<oak_idl::ast::IdlRoot, String> {
30    use oak_idl::{builder::IdlBuilder, language::IdlLanguage};
31    use oak_core::{builder::Builder, parser::session::ParseSession, source::SourceText};
32    
33    let language = IdlLanguage::default();
34    let builder = IdlBuilder::new(&language);
35    let source = SourceText::new(idl.to_string());
36    let mut cache = ParseSession::default();
37    let result = builder.build(&source, &[], &mut cache);
38    result.result.map_err(|e| format!("{:?}", e))
39}
40
41/// 从文件读取并解析 WebIDL
42///
43/// # 参数
44/// - `file_path`: WebIDL 文件路径
45///
46/// # 返回值
47/// - `Ok(oak_idl::ast::IdlRoot)`: 读取和解析成功,返回 WebIDL AST
48/// - `Err(String)`: 读取或解析失败,返回错误信息
49pub fn parse_file(file_path: &str) -> Result<oak_idl::ast::IdlRoot, String> {
50    if file_path.is_empty() {
51        return Err("Empty file path".to_string());
52    }
53
54    match fs::read_to_string(file_path) {
55        Ok(content) => {
56            if content.trim().is_empty() {
57                return Err("Empty WebIDL file".to_string());
58            }
59            parse(&content)
60        }
61        Err(error) => {
62            let error_msg = format!("Failed to read file '{}': {}", file_path, error);
63            Err(error_msg)
64        }
65    }
66}
67
68/// 将 WebIDL AST 转换为 TypeScript 类型定义
69///
70/// # 参数
71/// - `root`: WebIDL AST 根节点
72///
73/// # 返回值
74/// - 生成的 TypeScript 类型定义字符串
75pub fn convert_to_typescript(root: &oak_idl::ast::IdlRoot) -> String {
76    converter::convert(root)
77}