lumesh 0.18.2

a lighting shell ⚡ bash alternative
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use crate::{Diagnostic, Expression, tokens::Tokens};

use common_macros::b_tree_map;
use core::fmt;
use detached_str::{Str, StrSlice};
use nom::error::{ErrorKind, ParseError};
use std::{collections::BTreeMap, error::Error as StdError};

// ============== 语法错误部分 ==============

#[derive(Debug)]
pub struct SyntaxError {
    pub source: Str,
    pub kind: SyntaxErrorKind,
}

#[derive(Debug)]
pub enum SyntaxErrorKind {
    Expected {
        input: StrSlice,
        expected: &'static str,
        found: Option<String>,
        hint: Option<&'static str>,
    },
    TokenizationErrors(Box<[Diagnostic]>),
    ExpectedChar {
        expected: char,
        at: Option<StrSlice>,
    },
    NomError {
        kind: ErrorKind,
        at: Option<StrSlice>,
        cause: Option<Box<SyntaxError>>,
    },
    InternalError(String),
    InvalidCmdSymbol(String),
    CustomError(String, StrSlice),
    UnknownOperator(String, StrSlice),
    UnExpectedToken(String, StrSlice),
    InvalidEscapeSequence(String, StrSlice),
    PrecedenceTooLow(StrSlice),
    NoExpression,
    ArgumentMismatch {
        name: String,
        expected: u8,
        received: u8,
    },
    RecursionDepth {
        input: StrSlice,
        depth: usize,
    },
}

// impl StdError for SyntaxError {
//     fn source(&self) -> Option<&(dyn StdError + 'static)> {
//         match &self.kind {
//             SyntaxErrorKind::NomError { cause, .. } => cause.as_deref(),
//             _ => None,
//         }
//     }
// }

impl StdError for SyntaxError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match &self.kind {
            SyntaxErrorKind::NomError { cause, .. } => {
                // Box the cause to convert it to a trait object
                cause
                    .as_ref()
                    .map(|c| c.as_ref() as &(dyn StdError + 'static))
            }
            _ => None,
        }
    }
}

impl SyntaxError {
    pub const ERROR_CODE_EXPECTED: u8 = 1;
    pub const ERROR_CODE_TOKENIZATION_ERRORS: u8 = 2;
    pub const ERROR_CODE_EXPECTED_CHAR: u8 = 3;
    pub const ERROR_CODE_NOM_ERROR: u8 = 4;
    pub const ERROR_CODE_INTERNAL_ERROR: u8 = 5;
    pub const ERROR_CODE_INVALID_CMD_SYMBOL: u8 = 6;
    pub const ERROR_CODE_CUSTOM_ERROR: u8 = 7;
    pub const ERROR_CODE_UNKNOWN_OPERATOR: u8 = 8;
    pub const ERROR_CODE_UNEXPECTED_TOKEN: u8 = 9;
    pub const ERROR_CODE_INVALID_ESCAPE_SEQUENCE: u8 = 10;
    pub const ERROR_CODE_PRECEDENCE_TOO_LOW: u8 = 11;
    pub const ERROR_CODE_NO_EXPRESSION: u8 = 12;
    pub const ERROR_CODE_ARGUMENT_MISMATCH: u8 = 13;
    pub const ERROR_CODE_RECURSION_DEPTH: u8 = 14;

    pub fn codes() -> BTreeMap<String, Expression> {
        b_tree_map! {
            String::from("expected") => Expression::from(Self::ERROR_CODE_EXPECTED),
            String::from("tokenization_errors") => Expression::from(Self::ERROR_CODE_TOKENIZATION_ERRORS),
            String::from("expected_char") => Expression::from(Self::ERROR_CODE_EXPECTED_CHAR),
            String::from("nom_error") => Expression::from(Self::ERROR_CODE_NOM_ERROR),
            String::from("internal_error") => Expression::from(Self::ERROR_CODE_INTERNAL_ERROR),
            String::from("invalid_cmd_symbol") => Expression::from(Self::ERROR_CODE_INVALID_CMD_SYMBOL),
            String::from("custom_error") => Expression::from(Self::ERROR_CODE_CUSTOM_ERROR),
            String::from("unknown_operator") => Expression::from(Self::ERROR_CODE_UNKNOWN_OPERATOR),
            String::from("unexpected_token") => Expression::from(Self::ERROR_CODE_UNEXPECTED_TOKEN),
            String::from("invalid_escape_sequence") => Expression::from(Self::ERROR_CODE_INVALID_ESCAPE_SEQUENCE),
            String::from("precedence_too_low") => Expression::from(Self::ERROR_CODE_PRECEDENCE_TOO_LOW),
            String::from("no_expression") => Expression::from(Self::ERROR_CODE_NO_EXPRESSION),
            String::from("argument_mismatch") => Expression::from(Self::ERROR_CODE_ARGUMENT_MISMATCH),
            String::from("recursion_depth") => Expression::from(Self::ERROR_CODE_RECURSION_DEPTH),
        }
    }

    pub fn code(&self) -> u8 {
        match self.kind {
            SyntaxErrorKind::Expected { .. } => Self::ERROR_CODE_EXPECTED,
            SyntaxErrorKind::TokenizationErrors(..) => Self::ERROR_CODE_TOKENIZATION_ERRORS,
            SyntaxErrorKind::ExpectedChar { .. } => Self::ERROR_CODE_EXPECTED_CHAR,
            SyntaxErrorKind::NomError { .. } => Self::ERROR_CODE_NOM_ERROR,
            SyntaxErrorKind::InternalError(..) => Self::ERROR_CODE_INTERNAL_ERROR,
            SyntaxErrorKind::InvalidCmdSymbol(..) => Self::ERROR_CODE_INVALID_CMD_SYMBOL,
            SyntaxErrorKind::CustomError(..) => Self::ERROR_CODE_CUSTOM_ERROR,
            SyntaxErrorKind::UnknownOperator(..) => Self::ERROR_CODE_UNKNOWN_OPERATOR,
            SyntaxErrorKind::UnExpectedToken(..) => Self::ERROR_CODE_UNEXPECTED_TOKEN,
            SyntaxErrorKind::InvalidEscapeSequence(..) => Self::ERROR_CODE_INVALID_ESCAPE_SEQUENCE,
            SyntaxErrorKind::PrecedenceTooLow(..) => Self::ERROR_CODE_PRECEDENCE_TOO_LOW,
            SyntaxErrorKind::NoExpression => Self::ERROR_CODE_NO_EXPRESSION,
            SyntaxErrorKind::ArgumentMismatch { .. } => Self::ERROR_CODE_ARGUMENT_MISMATCH,
            SyntaxErrorKind::RecursionDepth { .. } => Self::ERROR_CODE_RECURSION_DEPTH,
        }
    }

    pub fn new(source: Str, kind: SyntaxErrorKind) -> Self {
        Self { source, kind }
    }

    // pub fn expected(
    //     source: Str,
    //     input: StrSlice,
    //     expected: &'static str,
    //     found: Option<String>,
    //     hint: Option<&'static str>,
    // ) -> nom::Err<Self> {
    //     nom::Err::Error(Self::new(
    //         source,
    //         SyntaxErrorKind::Expected {
    //             input,
    //             expected,
    //             found,
    //             hint,
    //         },
    //     ))
    // }

    // pub fn unclosed_delimiter(source: Str, start: StrSlice, delim: &'static str) -> Self {
    //     Self::new(
    //         source,
    //         SyntaxErrorKind::Expected {
    //             input: start,
    //             expected: delim,
    //             found: None,
    //             hint: Some("检查括号/引号是否匹配"),
    //         },
    //     )
    // }
}
impl SyntaxErrorKind {
    #[inline]
    pub fn failure(
        input: StrSlice,
        expected: &'static str,
        found: Option<String>,
        hint: Option<&'static str>,
    ) -> nom::Err<Self> {
        nom::Err::Failure(SyntaxErrorKind::Expected {
            input,
            expected,
            found,
            hint,
        })
    }
    /// return Fail to stop all parse. use this **carefully**!
    pub fn empty_fail(input: Tokens<'_>) -> Result<(), nom::Err<Self>> {
        if input.is_empty() {
            Err(nom::Err::Failure(SyntaxErrorKind::Expected {
                input: input.get_str_slice(),
                expected: "Some Expression",
                found: Some("Nothing".into()),
                hint: None,
            }))
        } else {
            Ok(())
        }
    }
    /// return an Error to stop process.
    pub fn empty_back(input: Tokens<'_>) -> Result<(), nom::Err<Self>> {
        if input.is_empty() {
            Err(nom::Err::Error(SyntaxErrorKind::Expected {
                input: input.get_str_slice(),
                expected: "Some Expression to parse",
                found: Some("Nothing".into()),
                hint: None,
            }))
        } else {
            Ok(())
        }
    }

    #[inline]
    pub fn expected(
        input: StrSlice,
        expected: &'static str,
        found: Option<String>,
        hint: Option<&'static str>,
    ) -> nom::Err<Self> {
        nom::Err::Error(SyntaxErrorKind::Expected {
            input,
            expected,
            found,
            hint,
        })
    }

    pub fn unclosed_delimiter(start: StrSlice, delim: &'static str) -> nom::Err<Self> {
        nom::Err::Error(SyntaxErrorKind::Expected {
            input: start,
            expected: delim,
            found: None,
            hint: Some("Check if parentheses/quotes are matched"),
        })
    }
}

impl ParseError<Tokens<'_>> for SyntaxErrorKind {
    fn from_error_kind(input: Tokens<'_>, kind: ErrorKind) -> Self {
        SyntaxErrorKind::NomError {
            kind,
            at: input.first().map(|t| t.range),
            cause: None,
        }
    }

    fn append(input: Tokens<'_>, kind: ErrorKind, _: Self) -> Self {
        SyntaxErrorKind::NomError {
            kind,
            at: input.first().map(|t| t.range),
            cause: None,
        }
    }

    fn from_char(input: Tokens<'_>, expected: char) -> Self {
        SyntaxErrorKind::ExpectedChar {
            expected,
            at: input.first().map(|t| t.range),
        }
    }

    fn or(self, other: Self) -> Self {
        use SyntaxErrorKind::*;

        match (&self, &other) {
            // TokenizationErrors 是致命错误,优先级最高
            (TokenizationErrors(_), _) => self,
            (_, TokenizationErrors(_)) => other,

            // RecursionDepth 是严重错误,优先级很高
            (RecursionDepth { .. }, _) => self,
            (_, RecursionDepth { .. }) => other,

            // Expected 错误优先级较高,包含具体的期望信息
            (Expected { .. }, NomError { .. }) => self,
            (NomError { .. }, Expected { .. }) => other,

            // ArgumentMismatch 比一般错误更具体
            (ArgumentMismatch { .. }, NomError { .. }) => self,
            (NomError { .. }, ArgumentMismatch { .. }) => other,

            // UnknownOperator 比 NoExpression 更具体
            (UnknownOperator(..), NoExpression) => self,
            (NoExpression, UnknownOperator(..)) => other,

            // InternalError 优先级最低,总是被其他错误替换
            (InternalError(_), _) => other,
            (_, InternalError(_)) => self,

            // 对于相同类型的错误,选择包含更多上下文信息的
            (
                Expected {
                    input: input1,
                    hint: hint1,
                    ..
                },
                Expected {
                    input: input2,
                    hint: hint2,
                    ..
                },
            ) => {
                // 优先选择有 hint 的错误
                if hint1.is_some() && hint2.is_none() {
                    self
                } else if hint1.is_none() && hint2.is_some() {
                    other
                } else {
                    // 选择输入位置更靠前的错误(通常更相关)
                    if input1.start() <= input2.start() {
                        self
                    } else {
                        other
                    }
                }
            }

            // 默认情况:保留第一个错误
            _ => self,
        }
    }
}
impl ParseError<Tokens<'_>> for SyntaxError {
    fn from_error_kind(input: Tokens<'_>, kind: ErrorKind) -> Self {
        Self::new(
            input.str.clone(),
            SyntaxErrorKind::NomError {
                kind,
                at: input.first().map(|t| t.range),
                cause: None,
            },
        )
    }

    fn append(input: Tokens<'_>, kind: ErrorKind, other: Self) -> Self {
        Self::new(
            input.str.clone(),
            SyntaxErrorKind::NomError {
                kind,
                at: input.first().map(|t| t.range),
                cause: Some(Box::new(other)),
            },
        )
    }

    fn from_char(input: Tokens<'_>, expected: char) -> Self {
        Self::new(
            input.str.clone(),
            SyntaxErrorKind::ExpectedChar {
                expected,
                at: input.first().map(|t| t.range),
            },
        )
    }

    fn or(self, other: Self) -> Self {
        match self.kind {
            SyntaxErrorKind::InternalError(_) => other,
            SyntaxErrorKind::TokenizationErrors(..) => self,
            //    ExpectedChar { /* … */ }=>
            // Expected { /* … */ },
            //    NomError { /* … */ },
            _ => self,
        }
    }
}

impl fmt::Display for SyntaxError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.kind {
            SyntaxErrorKind::Expected {
                input,
                expected,
                found,
                hint,
            } => {
                write!(f, "{RED_START}{BOLD}syntax error{RESET}: ")?;
                write!(f, "expect {YELLOW_START}{expected}{RESET}")?;
                if let Some(found) = found {
                    write!(f, ", found {RED2_START}{found}{RESET}")?;
                }
                writeln!(f)?;
                // 使用增强的错误显示
                print_error_lines(&self.source, *input, f, 72)?;

                // print_error_lines(&self.source, *input, f, 72)?;
                if let Some(hint) = hint {
                    writeln!(f, "    hint: {hint}")?;
                }
                Ok(())
            }
            SyntaxErrorKind::TokenizationErrors(errors) => {
                for err in errors.iter() {
                    fmt_token_error(&self.source, err, f)?;
                }
                Ok(())
            }
            SyntaxErrorKind::ExpectedChar { expected, at } => {
                write!(f, "{RED_START}{BOLD}syntax error{RESET}: ")?;
                write!(f, "expect character {YELLOW_START}{expected:?}{RESET}")?;
                writeln!(f)?;
                if let Some(at) = at {
                    print_error_lines(&self.source, *at, f, 72)?;
                    // writeln!(f, "    hint: check if quotes or brackets are properly closed")?;
                }
                Ok(())
            }
            SyntaxErrorKind::NomError { kind, at, cause } => {
                write!(f, "{RED_START}{BOLD}nom syntax error{RESET}: ")?;
                writeln!(f, "`{kind:?}`")?;
                if let Some(at) = at {
                    print_error_lines(&self.source, *at, f, 72)?;
                }
                if let Some(cause) = cause {
                    writeln!(f, "Caused by: {cause}")?;
                }
                Ok(())
            }
            SyntaxErrorKind::InternalError(s) => {
                writeln!(f, "{RED_START}{BOLD}internal syntax error: {s}{RESET}")
            }
            SyntaxErrorKind::InvalidCmdSymbol(s) => {
                writeln!(f, "{RED_START}{BOLD}invalid cmd symbo: {s}{RESET}")
            }
            SyntaxErrorKind::CustomError(s, at) => {
                writeln!(f, "{RED_START}{BOLD}syntax error: {s}{RESET}")?;
                print_error_lines(&self.source, *at, f, 72)?;
                Ok(())
            }
            SyntaxErrorKind::NoExpression => {
                writeln!(f, "{RED_START}{BOLD}no expression recognized{RESET}")
            }
            SyntaxErrorKind::UnknownOperator(op, at) => {
                writeln!(f, "{RED_START}{BOLD}unknown operator {op:?}{RESET}")?;
                print_error_lines(&self.source, *at, f, 72)?;
                Ok(())
            }
            SyntaxErrorKind::UnExpectedToken(op, at) => {
                writeln!(f, "{RED_START}{BOLD}unexpected token {op:?}{RESET}")?;
                print_error_lines(&self.source, *at, f, 72)?;
                Ok(())
            }
            SyntaxErrorKind::InvalidEscapeSequence(op, at) => {
                writeln!(f, "{RED_START}{BOLD}invalid escape sequence {op:?}{RESET}")?;
                print_error_lines(&self.source, *at, f, 72)?;
                Ok(())
            }
            SyntaxErrorKind::PrecedenceTooLow(at) => {
                writeln!(f, "{RED_START}{BOLD}precedence too low {RESET}")?;
                print_error_lines(&self.source, *at, f, 72)?;
                Ok(())
            }
            SyntaxErrorKind::ArgumentMismatch {
                name,
                expected,
                received,
            } => {
                writeln!(
                    f,
                    "{RED_START}{BOLD}arguments mismatch for function `{name}`: expected {expected}, found {received} {RESET}"
                )
            }
            SyntaxErrorKind::RecursionDepth { input, depth } => {
                write!(f, "{RED_START}{BOLD}max recursion reached{RESET}: ")?;
                write!(f, "depth: {YELLOW_START}{depth}{RESET}")?;

                writeln!(f)?;
                print_error_lines(&self.source, *input, f, 72)?;
                writeln!(
                    f,
                    "    hint: simplify your script, or config LUME_MAX_SYNTAX_RECURSION larger."
                )?;
                Ok(())
            }
        }
    }
}

// ============== 彩色显示辅助函数 ==============

fn fmt_token_error(string: &Str, err: &Diagnostic, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{RED_START}{BOLD}token error{RESET}: ")?;
    match err {
        Diagnostic::Valid => Ok(()),
        &Diagnostic::InvalidNumber(at) => {
            let num = at.to_str(string).trim();
            writeln!(f, "invalid number `{num}`")?;
            print_error_lines(string, at, f, 72)
        }
        &Diagnostic::IllegalChar(at) => {
            writeln!(f, "invalid char {:?}", at.to_str(string))?;
            print_error_lines(string, at, f, 72)
        }
        &Diagnostic::NotTokenized(at) => {
            writeln!(
                f,
                "there are leftover tokens after tokenization:\n{}",
                at.to_str(string)
            )?;
            print_error_lines(string, at, f, 72)
        }
        &Diagnostic::UnterminatedString(at) => {
            writeln!(f, "unterminated string:\n{}", at.to_str(string))?;
            print_error_lines(string, at, f, 72)
        }
    }
}

// 添加新的颜色常量
const DIM_START: &str = "\x1b[2m";
// const GREEN_START: &str = "\x1b[32m";
const BLUE_START: &str = "\x1b[34m";
const YELLOW_START: &str = "\x1b[38;5;230m";
const RED2_START: &str = "\x1b[38;5;210m";
const RED_START: &str = "\x1b[38;5;9m";
const BOLD: &str = "\x1b[1m";
const RESET: &str = "\x1b[m\x1b[0m";

fn print_error_lines(
    string: &Str,
    at: StrSlice,
    f: &mut fmt::Formatter,
    _max_width: usize,
) -> fmt::Result {
    let error_start = at.start();
    let error_end = at.end();

    // 计算错误所在的行号和列号
    let before_text = &string[..error_start];
    let lines_before: Vec<&str> = before_text.lines().collect();
    let error_line_num = lines_before.len();
    let error_col = lines_before.last().map(|line| line.len()).unwrap_or(0);

    // 获取错误周围的上下文行(前后各3行)
    let all_lines: Vec<&str> = string.lines().collect();
    let context_start = error_line_num.saturating_sub(3);
    let context_end = (error_line_num + 3).min(all_lines.len());

    writeln!(f, "     {BLUE_START}{RESET}")?;

    // 显示上下文行
    for (i, line) in all_lines[context_start..context_end].iter().enumerate() {
        let line_num = context_start + i + 1;
        let is_error_line = line_num == error_line_num;

        // dbg!(is_error_line, line_num, error_line_num, i, line);
        if is_error_line {
            // 安全地计算行内位置
            let line_start = before_text.rfind('\n').map(|pos| pos + 1).unwrap_or(0);
            let error_start_in_line = error_start.saturating_sub(line_start);
            let error_end_in_line = (error_end.saturating_sub(line_start)).min(line.len());

            // 确保索引不超出行的范围
            let safe_start = error_start_in_line.min(line.len());
            let safe_end = error_end_in_line.min(line.len()).max(safe_start);
            // dbg!(error_start_in_line, error_end_in_line, safe_start, safe_end);

            write!(f, "{RED_START}{line_num:>5}{RESET} {BLUE_START}{RESET} ")?;
            if safe_start > 0 {
                write!(f, "{}", &line[..safe_start])?;
            }
            if safe_end > safe_start {
                write!(f, "{}{}{}", RED_START, &line[safe_start..safe_end], RESET)?;
            }
            if safe_end < line.len() {
                writeln!(f, "{}", &line[safe_end..])?;
            } else {
                writeln!(f)?;
            }

            // 添加指示箭头(只有在有错误内容时才显示)
            if safe_end >= safe_start {
                write!(f, "      {BLUE_START}{RESET} ")?;
                for _ in 0..safe_start {
                    write!(f, " ")?;
                }
                write!(f, "{RED_START}{BOLD}\x1b[5m^")?;
                for _ in 1..(safe_end - safe_start) {
                    write!(f, "~")?;
                }
                writeln!(f, "{RESET}")?;
            }
        } else {
            // 普通上下文行
            writeln!(
                f,
                "{BLUE_START}{line_num:>5}{RESET} {DIM_START}{line}{RESET}"
            )?;
        }
    }

    writeln!(f, "     {BLUE_START}{RESET}")?;

    // 显示错误位置信息
    writeln!(
        f,
        "      ↳ at line {}, column {}",
        error_line_num,
        error_col + 1
    )?;

    Ok(())
}