Skip to main content

typescript_types/
lib.rs

1use std::rc::Rc;
2
3/// TypeScript 值类型枚举
4pub enum TsValue {
5    /// 未定义
6    Undefined,
7    /// 空值
8    Null,
9    /// 布尔值
10    Boolean(bool),
11    /// 数字
12    Number(f64),
13    /// 字符串
14    String(String),
15    /// 对象
16    Object(Vec<(String, TsValue)>),
17    /// 数组
18    Array(Vec<TsValue>),
19    /// 函数
20    Function(Rc<dyn Fn(&[TsValue]) -> TsValue>),
21    /// 错误
22    Error(String),
23    /// 联合类型
24    Union(Vec<TsValue>),
25    /// 泛型类型
26    Generic(String, Vec<TsValue>),
27    /// 符号
28    Symbol(String),
29    /// 大整数
30    BigInt(i128),
31    /// 日期
32    Date(i64),
33    /// 正则表达式
34    RegExp(String),
35    /// Map
36    Map(Vec<(TsValue, TsValue)>),
37    /// Set
38    Set(Vec<TsValue>),
39    /// Promise
40    Promise(Box<TsValue>),
41    /// 可迭代对象
42    Iterable(Box<dyn Iterator<Item = TsValue>>),
43}
44
45impl Clone for TsValue {
46    fn clone(&self) -> Self {
47        match self {
48            TsValue::Undefined => TsValue::Undefined,
49            TsValue::Null => TsValue::Null,
50            TsValue::Boolean(b) => TsValue::Boolean(*b),
51            TsValue::Number(n) => TsValue::Number(*n),
52            TsValue::String(s) => TsValue::String(s.clone()),
53            TsValue::Object(props) => TsValue::Object(props.clone()),
54            TsValue::Array(arr) => TsValue::Array(arr.clone()),
55            TsValue::Function(f) => TsValue::Function(Rc::clone(f)), // 函数可以克隆
56            TsValue::Error(s) => TsValue::Error(s.clone()),
57            TsValue::Union(values) => TsValue::Union(values.clone()),
58            TsValue::Generic(name, args) => TsValue::Generic(name.clone(), args.clone()),
59            TsValue::Symbol(s) => TsValue::Symbol(s.clone()),
60            TsValue::BigInt(bi) => TsValue::BigInt(*bi),
61            TsValue::Date(d) => TsValue::Date(*d),
62            TsValue::RegExp(pattern) => TsValue::RegExp(pattern.clone()),
63            TsValue::Map(entries) => TsValue::Map(entries.clone()),
64            TsValue::Set(values) => TsValue::Set(values.clone()),
65            TsValue::Promise(value) => TsValue::Promise(value.clone()),
66            TsValue::Iterable(_) => TsValue::Undefined, // 可迭代对象无法克隆,返回 Undefined
67        }
68    }
69}
70
71impl std::fmt::Debug for TsValue {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match self {
74            TsValue::Undefined => write!(f, "Undefined"),
75            TsValue::Null => write!(f, "Null"),
76            TsValue::Boolean(_) => write!(f, "Boolean"),
77            TsValue::Number(_) => write!(f, "Number"),
78            TsValue::String(_) => write!(f, "String"),
79            TsValue::Object(_) => write!(f, "Object"),
80            TsValue::Array(_) => write!(f, "Array"),
81            TsValue::Function(_) => write!(f, "Function"),
82            TsValue::Error(_) => write!(f, "Error"),
83            TsValue::Union(_) => write!(f, "Union"),
84            TsValue::Generic(name, _) => write!(f, "Generic({})", name),
85            TsValue::Symbol(_) => write!(f, "Symbol"),
86            TsValue::BigInt(_) => write!(f, "BigInt"),
87            TsValue::Date(_) => write!(f, "Date"),
88            TsValue::RegExp(_) => write!(f, "RegExp"),
89            TsValue::Map(_) => write!(f, "Map"),
90            TsValue::Set(_) => write!(f, "Set"),
91            TsValue::Promise(_) => write!(f, "Promise"),
92            TsValue::Iterable(_) => write!(f, "Iterable"),
93        }
94    }
95}
96
97impl TsValue {
98    /// 检查是否为未定义
99    pub fn is_undefined(&self) -> bool {
100        matches!(self, TsValue::Undefined)
101    }
102
103    /// 检查是否为空值
104    pub fn is_null(&self) -> bool {
105        matches!(self, TsValue::Null)
106    }
107
108    /// 检查是否为布尔值
109    pub fn is_boolean(&self) -> bool {
110        matches!(self, TsValue::Boolean(_))
111    }
112
113    /// 检查是否为数字
114    pub fn is_number(&self) -> bool {
115        matches!(self, TsValue::Number(_))
116    }
117
118    /// 检查是否为字符串
119    pub fn is_string(&self) -> bool {
120        matches!(self, TsValue::String(_))
121    }
122
123    /// 检查是否为对象
124    pub fn is_object(&self) -> bool {
125        matches!(self, TsValue::Object(_))
126    }
127
128    /// 检查是否为数组
129    pub fn is_array(&self) -> bool {
130        matches!(self, TsValue::Array(_))
131    }
132
133    /// 检查是否为函数
134    pub fn is_function(&self) -> bool {
135        matches!(self, TsValue::Function(_))
136    }
137
138    /// 检查是否为错误
139    pub fn is_error(&self) -> bool {
140        matches!(self, TsValue::Error(_))
141    }
142
143    /// 检查是否为联合类型
144    pub fn is_union(&self) -> bool {
145        matches!(self, TsValue::Union(_))
146    }
147
148    /// 检查是否为泛型类型
149    pub fn is_generic(&self) -> bool {
150        matches!(self, TsValue::Generic(_, _))
151    }
152
153    /// 检查是否为符号
154    pub fn is_symbol(&self) -> bool {
155        matches!(self, TsValue::Symbol(_))
156    }
157
158    /// 检查是否为大整数
159    pub fn is_bigint(&self) -> bool {
160        matches!(self, TsValue::BigInt(_))
161    }
162
163    /// 检查是否为日期
164    pub fn is_date(&self) -> bool {
165        matches!(self, TsValue::Date(_))
166    }
167
168    /// 检查是否为正则表达式
169    pub fn is_regexp(&self) -> bool {
170        matches!(self, TsValue::RegExp(_))
171    }
172
173    /// 检查是否为 Map
174    pub fn is_map(&self) -> bool {
175        matches!(self, TsValue::Map(_))
176    }
177
178    /// 检查是否为 Set
179    pub fn is_set(&self) -> bool {
180        matches!(self, TsValue::Set(_))
181    }
182
183    /// 检查是否为 Promise
184    pub fn is_promise(&self) -> bool {
185        matches!(self, TsValue::Promise(_))
186    }
187
188    /// 检查是否为可迭代对象
189    pub fn is_iterable(&self) -> bool {
190        matches!(self, TsValue::Iterable(_))
191    }
192
193    /// 转换为布尔值
194    pub fn to_boolean(&self) -> bool {
195        match self {
196            TsValue::Undefined => false,
197            TsValue::Null => false,
198            TsValue::Boolean(b) => *b,
199            TsValue::Number(n) => *n != 0.0 && !n.is_nan(),
200            TsValue::String(s) => !s.is_empty(),
201            TsValue::Object(_) => true,
202            TsValue::Array(_) => true,
203            TsValue::Function(_) => true,
204            TsValue::Error(_) => true,
205            TsValue::Union(values) => !values.is_empty(),
206            TsValue::Generic(_, _) => true,
207            TsValue::Symbol(_) => true,
208            TsValue::BigInt(bi) => *bi != 0,
209            TsValue::Date(_) => true,
210            TsValue::RegExp(_) => true,
211            TsValue::Map(entries) => !entries.is_empty(),
212            TsValue::Set(values) => !values.is_empty(),
213            TsValue::Promise(_) => true,
214            TsValue::Iterable(_) => true,
215        }
216    }
217
218    /// 转换为数字
219    pub fn to_number(&self) -> f64 {
220        match self {
221            TsValue::Undefined => f64::NAN,
222            TsValue::Null => 0.0,
223            TsValue::Boolean(b) => if *b { 1.0 } else { 0.0 },
224            TsValue::Number(n) => *n,
225            TsValue::String(s) => s.parse().unwrap_or(f64::NAN),
226            TsValue::Object(_) => f64::NAN,
227            TsValue::Array(_) => if let TsValue::Array(arr) = self {
228                if arr.is_empty() {
229                    0.0
230                } else {
231                    f64::NAN
232                }
233            } else {
234                f64::NAN
235            },
236            TsValue::Function(_) => f64::NAN,
237            TsValue::Error(_) => f64::NAN,
238            TsValue::Union(values) => if values.is_empty() {
239                0.0
240            } else {
241                values[0].to_number()
242            },
243            TsValue::Generic(_, _) => f64::NAN,
244            TsValue::Symbol(_) => f64::NAN,
245            TsValue::BigInt(bi) => *bi as f64,
246            TsValue::Date(d) => *d as f64,
247            TsValue::RegExp(_) => f64::NAN,
248            TsValue::Map(_) => f64::NAN,
249            TsValue::Set(_) => f64::NAN,
250            TsValue::Promise(_) => f64::NAN,
251            TsValue::Iterable(_) => f64::NAN,
252        }
253    }
254
255    /// 转换为字符串
256    pub fn to_string(&self) -> String {
257        match self {
258            TsValue::Undefined => "undefined".to_string(),
259            TsValue::Null => "null".to_string(),
260            TsValue::Boolean(b) => b.to_string(),
261            TsValue::Number(n) => n.to_string(),
262            TsValue::String(s) => s.clone(),
263            TsValue::Object(_) => "[object Object]".to_string(),
264            TsValue::Array(_) => {
265                if let TsValue::Array(arr) = self {
266                    let elements: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
267                    format!("[{}]", elements.join(", "))
268                } else {
269                    "[object Array]".to_string()
270                }
271            }
272            TsValue::Function(_) => "[Function]".to_string(),
273            TsValue::Error(s) => format!("Error: {}", s),
274            TsValue::Union(values) => {
275                let elements: Vec<String> = values.iter().map(|v| v.to_string()).collect();
276                format!("Union({})", elements.join(", "))
277            }
278            TsValue::Generic(name, args) => {
279                let args_str: Vec<String> = args.iter().map(|v| v.to_string()).collect();
280                format!("{}{{ {} }}", name, args_str.join(", "))
281            }
282            TsValue::Symbol(s) => format!("Symbol({})", s),
283            TsValue::BigInt(bi) => bi.to_string(),
284            TsValue::Date(d) => format!("Date({})", d),
285            TsValue::RegExp(pattern) => format!("/{}/", pattern),
286            TsValue::Map(entries) => {
287                let entries_str: Vec<String> = entries.iter().map(|(k, v)| format!("{}: {}", k.to_string(), v.to_string())).collect();
288                format!("Map({})", entries_str.join(", "))
289            },
290            TsValue::Set(values) => {
291                let values_str: Vec<String> = values.iter().map(|v| v.to_string()).collect();
292                format!("Set({})", values_str.join(", "))
293            },
294            TsValue::Promise(value) => format!("Promise<{}>", value.to_string()),
295            TsValue::Iterable(_) => "[object Iterable]".to_string(),
296        }
297    }
298}
299
300/// TypeScript 错误类型枚举
301#[derive(Debug, Clone)]
302pub enum TsError {
303    /// 类型错误
304    TypeError(String),
305    /// 引用错误
306    ReferenceError(String),
307    /// 语法错误
308    SyntaxError(String),
309    /// 范围错误
310    RangeError(String),
311    /// 其他错误
312    Other(String),
313}
314
315/// 从 Rust 类型转换为 TypeScript 值的 trait
316pub trait ToTsValue {
317    /// 转换为 TypeScript 值
318    fn to_ts_value(&self) -> TsValue;
319}
320
321impl ToTsValue for bool {
322    fn to_ts_value(&self) -> TsValue {
323        TsValue::Boolean(*self)
324    }
325}
326
327impl ToTsValue for f64 {
328    fn to_ts_value(&self) -> TsValue {
329        TsValue::Number(*self)
330    }
331}
332
333impl ToTsValue for i32 {
334    fn to_ts_value(&self) -> TsValue {
335        TsValue::Number(*self as f64)
336    }
337}
338
339impl ToTsValue for &str {
340    fn to_ts_value(&self) -> TsValue {
341        TsValue::String(self.to_string())
342    }
343}
344
345impl ToTsValue for String {
346    fn to_ts_value(&self) -> TsValue {
347        TsValue::String(self.clone())
348    }
349}
350
351impl<T: ToTsValue> ToTsValue for Vec<T> {
352    fn to_ts_value(&self) -> TsValue {
353        let values: Vec<TsValue> = self.iter().map(|v| v.to_ts_value()).collect();
354        TsValue::Array(values)
355    }
356}
357
358impl<K: ToString, V: ToTsValue> ToTsValue for Vec<(K, V)> {
359    fn to_ts_value(&self) -> TsValue {
360        let entries: Vec<(String, TsValue)> = self
361            .iter()
362            .map(|(k, v)| (k.to_string(), v.to_ts_value()))
363            .collect();
364        TsValue::Object(entries)
365    }
366}
367
368impl ToTsValue for i128 {
369    fn to_ts_value(&self) -> TsValue {
370        TsValue::BigInt(*self)
371    }
372}
373
374impl ToTsValue for i64 {
375    fn to_ts_value(&self) -> TsValue {
376        TsValue::Date(*self)
377    }
378}
379
380impl<T: ToTsValue> ToTsValue for Option<T> {
381    fn to_ts_value(&self) -> TsValue {
382        match self {
383            Some(value) => value.to_ts_value(),
384            None => TsValue::Null,
385        }
386    }
387}
388
389impl<T: ToTsValue, E: ToString> ToTsValue for Result<T, E> {
390    fn to_ts_value(&self) -> TsValue {
391        match self {
392            Ok(value) => value.to_ts_value(),
393            Err(error) => TsValue::Error(error.to_string()),
394        }
395    }
396}
397
398impl ToTsValue for std::collections::HashMap<String, TsValue> {
399    fn to_ts_value(&self) -> TsValue {
400        let entries: Vec<(String, TsValue)> = self
401            .iter()
402            .map(|(k, v)| (k.clone(), v.clone()))
403            .collect();
404        TsValue::Object(entries)
405    }
406}
407
408impl ToTsValue for std::collections::HashSet<TsValue> {
409    fn to_ts_value(&self) -> TsValue {
410        let values: Vec<TsValue> = self.iter().cloned().collect();
411        TsValue::Set(values)
412    }
413}
414
415impl ToTsValue for std::collections::HashMap<TsValue, TsValue> {
416    fn to_ts_value(&self) -> TsValue {
417        let entries: Vec<(TsValue, TsValue)> = self
418            .iter()
419            .map(|(k, v)| (k.clone(), v.clone()))
420            .collect();
421        TsValue::Map(entries)
422    }
423}