Skip to main content

typescript_webidl/
lib.rs

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