Skip to main content

wpl/parser/
error.rs

1use crate::winnow::error::{ContextError, ParseError, StrContext};
2use derive_more::From;
3use orion_error::StructError;
4use orion_error::{ErrorCode, UvsReason};
5use thiserror::Error;
6use winnow::error::{ErrMode, Needed};
7use wp_error::util::split_string;
8// use wp_error::DataErrKind; // kept for potential future conversions
9
10fn translate_position(input: &[u8], index: usize) -> (usize, usize) {
11    if input.is_empty() {
12        return (0, index);
13    }
14
15    let safe_index = index.min(input.len() - 1);
16    let column_offset = index - safe_index;
17    let index = safe_index;
18
19    let nl = input[0..index]
20        .iter()
21        .rev()
22        .enumerate()
23        .find(|(_, b)| **b == b'\n')
24        .map(|(nl, _)| index - nl - 1);
25    let line_start = match nl {
26        Some(nl) => nl + 1,
27        None => 0,
28    };
29    let line = input[0..line_start].iter().filter(|b| **b == b'\n').count();
30
31    let column = std::str::from_utf8(&input[line_start..=index])
32        .map(|s| s.chars().count() - 1)
33        .unwrap_or_else(|_| index - line_start);
34    let column = column + column_offset;
35
36    (line, column)
37}
38
39pub fn error_detail(error: ParseError<&str, ContextError<StrContext>>) -> String {
40    let offset = error.offset();
41    let original = *error.input();
42    let span = if offset == original.len() {
43        offset..offset
44    } else {
45        offset..(offset + 1)
46    };
47
48    let mut msg = String::new();
49    let (line, column) = translate_position(original.as_bytes(), span.start);
50    let line_num = line + 1;
51    let col_num = column + 1;
52    let gutter = line_num.to_string().len();
53    let content = original.split('\n').nth(line).expect("valid line number");
54
55    msg.push_str(&format!(
56        "parse error at line {}, column {}\n",
57        line_num, col_num
58    ));
59    //   |
60    for _ in 0..=gutter {
61        msg.push(' ');
62    }
63    msg.push_str("|\n");
64
65    // 1 | 00:32:00.a999999
66    msg.push_str(&format!("{} | ", line_num));
67    msg.push_str(&format!("{}\n", content));
68    for _ in 0..=gutter {
69        msg.push(' ');
70    }
71    msg.push('|');
72    for _ in 0..=column {
73        msg.push(' ');
74    }
75    // The span will be empty at eof, so we need to make sure we always print at least
76    // one `^`
77    msg.push('^');
78    for _ in (span.start + 1)..(span.end.min(span.start + content.len())) {
79        msg.push('^');
80    }
81    msg.push('\n');
82    msg.push('\n');
83    msg.push_str(&error.inner().to_string());
84    msg
85}
86
87#[derive(Error, Debug, PartialEq, Serialize, From)]
88pub enum WplCodeReason {
89    #[from(skip)]
90    #[error("plugin error >{0}")]
91    Plugin(String),
92    #[error("syntax error >{0}")]
93    Syntax(String),
94    #[from(skip)]
95    #[error("wpl is empty >{0}")]
96    Empty(String),
97    #[from(skip)]
98    #[error("unsupport > {0}")]
99    UnSupport(String),
100    #[error("{0}")]
101    Uvs(UvsReason),
102}
103impl ErrorCode for WplCodeReason {
104    fn error_code(&self) -> i32 {
105        500
106    }
107}
108
109pub type WplCodeError = StructError<WplCodeReason>;
110
111pub type WplCodeResult<T> = Result<T, WplCodeError>;
112
113pub trait WPLCodeErrorTrait {
114    fn from_syntax(e: ErrMode<ContextError>, code: &str, path: &str) -> Self;
115}
116impl WPLCodeErrorTrait for StructError<WplCodeReason> {
117    fn from_syntax(e: ErrMode<ContextError>, code: &str, path: &str) -> Self {
118        match e {
119            ErrMode::Incomplete(Needed::Size(u)) => {
120                StructError::from(WplCodeReason::Syntax(format!("parsing require {u}")))
121            }
122            ErrMode::Incomplete(Needed::Unknown) => StructError::from(WplCodeReason::Syntax(
123                "parsing require more data".to_string(),
124            )),
125            ErrMode::Backtrack(e) => {
126                let where_in = split_string(code);
127                StructError::from(WplCodeReason::Syntax(format!(
128                    ":wpl code parse fail!\n[path ]: '{}'\n[where]: '{}'\n[error]: {}",
129                    path, where_in, e
130                )))
131            }
132            ErrMode::Cut(e) => {
133                let where_in = split_string(code);
134                StructError::from(WplCodeReason::Syntax(format!(
135                    ":code parse fail\n[path ]: '{}'\n[where]: '{}'\n[error]: {}",
136                    path, where_in, e
137                )))
138            }
139        }
140    }
141}
142
143/*
144impl From<DataErrKind> for StructError<WplCodeReason> {
145    fn from(value: DataErrKind) -> Self {
146        WplCodeReason::from_data().to_err()
147    }
148}
149*/