bevy_mortar_bond 0.4.0

Bevy integration plug-in for mortar language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Function binding system for Mortar.
//!
//! Mortar 函数绑定系统。
//!
//! # Type System
//!
//! Mortar uses strongly-typed wrappers for function arguments:
//! - [`MortarString`] - for string values
//! - [`MortarNumber`] - for numeric values (f64)
//! - [`MortarBoolean`] - for boolean values
//! - [`MortarVoid`] - for void/unit values
//!
//! # Example
//!
//! ```no_run
//! use bevy_mortar_bond::{MortarString, MortarNumber, MortarBoolean};
//!
//! // Clear, type-safe function signature
//!
//! // 清晰且类型安全的函数签名
//! fn create_message(verb: MortarString, obj: MortarString, level: MortarNumber) -> String {
//!     format!("{}{}{}", verb.as_str(), obj.as_str(), "!".repeat(level.as_usize()))
//! }
//! ```
//!
//! # 类型系统
//!
//! Mortar 为函数参数提供强类型封装:
//! - [`MortarString`] —— 表示字符串值
//! - [`MortarNumber`] —— 表示数值(f64)
//! - [`MortarBoolean`] —— 表示布尔值
//! - [`MortarVoid`] —— 表示空返回值
//!
//! # 示例
//!
//! 上述代码展示了如何编写一个类型安全且语义清晰的 Mortar 函数。

use std::collections::HashMap;

/// String type for Mortar functions.
///
/// Mortar 函数的字符串类型。
#[derive(Debug, Clone, PartialEq)]
pub struct MortarString(pub String);

impl std::fmt::Display for MortarString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Number type for Mortar functions.
///
/// Mortar 函数的数字类型。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MortarNumber(pub f64);

impl std::fmt::Display for MortarNumber {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Boolean type for Mortar functions.
///
/// Mortar 函数的布尔类型。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MortarBoolean(pub bool);

impl std::fmt::Display for MortarBoolean {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Void type for Mortar functions.
///
/// Mortar 函数的空类型。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MortarVoid;

impl std::fmt::Display for MortarVoid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "")
    }
}

/// Arguments and return values for Mortar functions.
///
/// Mortar 函数的参数和返回值。
#[derive(Debug, Clone)]
pub enum MortarValue {
    String(MortarString),
    Number(MortarNumber),
    Boolean(MortarBoolean),
    Void,
}

impl MortarString {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl MortarNumber {
    pub fn as_f64(&self) -> f64 {
        self.0
    }

    pub fn as_i32(&self) -> i32 {
        self.0 as i32
    }

    pub fn as_usize(&self) -> usize {
        self.0 as usize
    }
}

impl MortarBoolean {
    pub fn as_bool(&self) -> bool {
        self.0
    }
}

impl MortarValue {
    pub fn as_string(&self) -> Option<&MortarString> {
        match self {
            MortarValue::String(s) => Some(s),
            _ => None,
        }
    }

    pub fn as_number(&self) -> Option<MortarNumber> {
        match self {
            MortarValue::Number(n) => Some(*n),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<MortarBoolean> {
        match self {
            MortarValue::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    pub fn to_display_string(&self) -> String {
        match self {
            MortarValue::String(s) => s.0.clone(),
            MortarValue::Number(n) => n.0.to_string(),
            MortarValue::Boolean(b) => b.0.to_string(),
            MortarValue::Void => String::new(),
        }
    }

    /// Evaluate MortarValue truthiness.
    ///
    /// 判断 MortarValue 的布尔语义。
    pub fn is_truthy(&self) -> bool {
        match self {
            MortarValue::Boolean(b) => b.0,
            MortarValue::Number(n) => n.0 != 0.0,
            MortarValue::String(s) => !s.0.is_empty(),
            MortarValue::Void => false,
        }
    }

    /// Parse a string argument into a MortarValue.
    ///
    /// 将字符串参数解析为 MortarValue。
    pub fn parse(s: &str) -> Self {
        // Try to parse as number first.
        //
        // 优先尝试解析为数字。
        if let Ok(n) = s.parse::<f64>() {
            return MortarValue::Number(MortarNumber(n));
        }
        // Try to parse as boolean.
        //
        // 尝试解析为布尔值。
        match s {
            "true" => return MortarValue::Boolean(MortarBoolean(true)),
            "false" => return MortarValue::Boolean(MortarBoolean(false)),
            _ => {}
        }
        // Default to string (remove quotes if present).
        //
        // 否则视为字符串(如有引号则移除)。
        let trimmed = s.trim();
        if trimmed.len() >= 2
            && ((trimmed.starts_with('"') && trimmed.ends_with('"'))
                || (trimmed.starts_with('\'') && trimmed.ends_with('\'')))
        {
            MortarValue::String(MortarString(trimmed[1..trimmed.len() - 1].to_string()))
        } else {
            MortarValue::String(MortarString(s.to_string()))
        }
    }
}

// From implementations for specific types.
//
// 针对特定类型的 From 实现。
impl From<String> for MortarString {
    fn from(s: String) -> Self {
        MortarString(s)
    }
}

impl From<&str> for MortarString {
    fn from(s: &str) -> Self {
        MortarString(s.to_string())
    }
}

impl From<f64> for MortarNumber {
    fn from(n: f64) -> Self {
        MortarNumber(n)
    }
}

impl From<i32> for MortarNumber {
    fn from(n: i32) -> Self {
        MortarNumber(n as f64)
    }
}

impl From<usize> for MortarNumber {
    fn from(n: usize) -> Self {
        MortarNumber(n as f64)
    }
}

impl From<bool> for MortarBoolean {
    fn from(b: bool) -> Self {
        MortarBoolean(b)
    }
}

// From implementations for MortarValue.
//
// MortarValue 的 From 实现。
impl From<MortarString> for MortarValue {
    fn from(s: MortarString) -> Self {
        MortarValue::String(s)
    }
}

impl From<String> for MortarValue {
    fn from(s: String) -> Self {
        MortarValue::String(MortarString(s))
    }
}

impl From<&str> for MortarValue {
    fn from(s: &str) -> Self {
        MortarValue::String(MortarString(s.to_string()))
    }
}

impl From<MortarNumber> for MortarValue {
    fn from(n: MortarNumber) -> Self {
        MortarValue::Number(n)
    }
}

impl From<f64> for MortarValue {
    fn from(n: f64) -> Self {
        MortarValue::Number(MortarNumber(n))
    }
}

impl From<i32> for MortarValue {
    fn from(n: i32) -> Self {
        MortarValue::Number(MortarNumber(n as f64))
    }
}

impl From<usize> for MortarValue {
    fn from(n: usize) -> Self {
        MortarValue::Number(MortarNumber(n as f64))
    }
}

impl From<MortarBoolean> for MortarValue {
    fn from(b: MortarBoolean) -> Self {
        MortarValue::Boolean(b)
    }
}

impl From<bool> for MortarValue {
    fn from(b: bool) -> Self {
        MortarValue::Boolean(MortarBoolean(b))
    }
}

impl From<MortarVoid> for MortarValue {
    fn from(_: MortarVoid) -> Self {
        MortarValue::Void
    }
}

impl From<()> for MortarValue {
    fn from(_: ()) -> Self {
        MortarValue::Void
    }
}

/// A function that can be called from Mortar.
///
/// 可以从 Mortar 调用的函数。
pub type MortarFunction = Box<dyn Fn(&[MortarValue]) -> MortarValue + Send + Sync>;

/// A registry for Mortar functions.
///
/// Mortar 函数注册表。
#[derive(Default)]
pub struct MortarFunctionRegistry {
    functions: HashMap<String, MortarFunction>,
}

impl MortarFunctionRegistry {
    /// Creates a new function registry.
    ///
    /// 创建一个新的函数注册表。
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a function (internal use by macros).
    pub fn register<F>(&mut self, name: impl Into<String>, func: F)
    where
        F: Fn(&[MortarValue]) -> MortarValue + Send + Sync + 'static,
    {
        self.functions.insert(name.into(), Box::new(func));
    }

    /// Calls a function by name with the given arguments.
    ///
    /// 按名称调用函数,并传递参数。
    pub fn call(&self, name: &str, args: &[MortarValue]) -> Option<MortarValue> {
        self.functions.get(name).map(|f| f(args))
    }
}

// TryFrom implementations for specific types.
//
// 针对特定类型的 TryFrom 实现。
impl TryFrom<MortarValue> for MortarString {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::String(s) => Ok(s),
            MortarValue::Number(n) => Ok(MortarString(n.0.to_string())),
            MortarValue::Boolean(b) => Ok(MortarString(b.0.to_string())),
            MortarValue::Void => Ok(MortarString(String::new())),
        }
    }
}

impl TryFrom<MortarValue> for MortarNumber {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::Number(n) => Ok(n),
            MortarValue::String(s) => s.0.parse().map(MortarNumber).map_err(|_| ()),
            _ => Err(()),
        }
    }
}

impl TryFrom<MortarValue> for MortarBoolean {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::Boolean(b) => Ok(b),
            _ => Err(()),
        }
    }
}

// TryFrom implementations for common types.
//
// 常见类型的 TryFrom 实现。
impl TryFrom<MortarValue> for String {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::String(s) => Ok(s.0),
            MortarValue::Number(n) => Ok(n.0.to_string()),
            MortarValue::Boolean(b) => Ok(b.0.to_string()),
            MortarValue::Void => Ok(String::new()),
        }
    }
}

impl TryFrom<MortarValue> for f64 {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::Number(n) => Ok(n.0),
            MortarValue::String(s) => s.0.parse().map_err(|_| ()),
            _ => Err(()),
        }
    }
}

impl TryFrom<MortarValue> for i32 {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::Number(n) => Ok(n.0 as i32),
            MortarValue::String(s) => s.0.parse().map_err(|_| ()),
            _ => Err(()),
        }
    }
}

impl TryFrom<MortarValue> for usize {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::Number(n) => Ok(n.0 as usize),
            MortarValue::String(s) => s.0.parse().map_err(|_| ()),
            _ => Err(()),
        }
    }
}

impl TryFrom<MortarValue> for bool {
    type Error = ();

    fn try_from(value: MortarValue) -> Result<Self, Self::Error> {
        match value {
            MortarValue::Boolean(b) => Ok(b.0),
            _ => Err(()),
        }
    }
}