Skip to main content

wpl/parser/
error.rs

1use crate::winnow::error::{ContextError, ParseError, StrContext};
2use derive_more::From;
3use orion_error::{OrionError, StructError, UvsReason};
4use serde::Serialize;
5use winnow::error::{ErrMode, Needed};
6use wp_error::util::split_string;
7use wp_model_core::model::MetaErr;
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(Debug, Clone, PartialEq, Serialize, From, OrionError)]
88pub enum WplCodeReason {
89    #[orion_error(identity = "biz.plugin")]
90    #[from(skip)]
91    Plugin(String),
92    #[orion_error(identity = "biz.syntax")]
93    Syntax(String),
94    #[orion_error(identity = "biz.wpl_empty")]
95    #[from(skip)]
96    Empty(String),
97    #[orion_error(identity = "biz.unsupport")]
98    #[from(skip)]
99    UnSupport(String),
100    #[orion_error(transparent)]
101    Uvs(UvsReason),
102}
103
104pub type WplCodeError = StructError<WplCodeReason>;
105
106pub type WplCodeResult<T> = Result<T, WplCodeError>;
107
108/// Trait for converting various error types into WplCodeError.
109/// Uses a local trait to avoid orphan rule restrictions.
110pub(crate) trait IntoWplCodeError {
111    fn into_wpl_err(self) -> WplCodeError;
112}
113
114impl IntoWplCodeError for WplCodeError {
115    fn into_wpl_err(self) -> WplCodeError {
116        self
117    }
118}
119
120impl IntoWplCodeError for MetaErr {
121    fn into_wpl_err(self) -> WplCodeError {
122        WplCodeReason::UnSupport(self.to_string()).into()
123    }
124}
125
126impl IntoWplCodeError for wp_parse_api::WparseError {
127    fn into_wpl_err(self) -> WplCodeError {
128        WplCodeReason::Plugin(self.to_string()).into()
129    }
130}
131
132impl IntoWplCodeError for crate::idcard::Error {
133    fn into_wpl_err(self) -> WplCodeError {
134        WplCodeReason::Plugin(self.to_string()).into()
135    }
136}
137
138impl IntoWplCodeError for std::string::FromUtf8Error {
139    fn into_wpl_err(self) -> WplCodeError {
140        WplCodeReason::Plugin(self.to_string()).into()
141    }
142}
143
144impl IntoWplCodeError for std::net::AddrParseError {
145    fn into_wpl_err(self) -> WplCodeError {
146        WplCodeReason::Plugin(self.to_string()).into()
147    }
148}
149
150pub trait WPLCodeErrorTrait {
151    fn from_syntax(e: ErrMode<ContextError>, code: &str, path: &str) -> Self;
152    fn from_parse_err(e: ParseError<&str, ContextError>, code: &str, path: &str) -> Self;
153}
154impl WPLCodeErrorTrait for StructError<WplCodeReason> {
155    fn from_syntax(e: ErrMode<ContextError>, code: &str, path: &str) -> Self {
156        match e {
157            ErrMode::Incomplete(Needed::Size(u)) => {
158                StructError::from(WplCodeReason::Syntax(format!("parsing require {u}")))
159            }
160            ErrMode::Incomplete(Needed::Unknown) => StructError::from(WplCodeReason::Syntax(
161                "parsing require more data".to_string(),
162            )),
163            ErrMode::Backtrack(e) => {
164                let where_in = split_string(code);
165                StructError::from(WplCodeReason::Syntax(format!(
166                    ":wpl code parse fail!\n[path ]: '{}'\n[where]: '{}'\n[error]: {}",
167                    path, where_in, e
168                )))
169            }
170            ErrMode::Cut(e) => {
171                let where_in = split_string(code);
172                StructError::from(WplCodeReason::Syntax(format!(
173                    ":code parse fail\n[path ]: '{}'\n[where]: '{}'\n[error]: {}",
174                    path, where_in, e
175                )))
176            }
177        }
178    }
179
180    fn from_parse_err(e: ParseError<&str, ContextError>, code: &str, path: &str) -> Self {
181        let where_in = split_string(code);
182        StructError::from(WplCodeReason::Syntax(format!(
183            "parse error\n[path ]: '{}'\n[where]: '{}'\n[error]: {}",
184            path, where_in, e
185        )))
186    }
187}
188
189/*
190impl From<DataErrKind> for StructError<WplCodeReason> {
191    fn from(value: DataErrKind) -> Self {
192        WplCodeReason::from_data().to_err()
193    }
194}
195*/