scirs2-core 0.1.0-alpha.3

Core utilities and common functionality for SciRS2
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
//! Error types for the SciRS2 core module
//!
//! This module provides common error types used throughout the SciRS2 ecosystem.

use std::fmt;
use thiserror::Error;

/// Location information for error context
#[derive(Debug, Clone)]
pub struct ErrorLocation {
    /// File where the error occurred
    pub file: &'static str,
    /// Line number where the error occurred
    pub line: u32,
    /// Column number where the error occurred
    pub column: Option<u32>,
    /// Function where the error occurred
    pub function: Option<&'static str>,
}

impl ErrorLocation {
    /// Create a new error location
    #[inline]
    pub fn new(file: &'static str, line: u32) -> Self {
        Self {
            file,
            line,
            column: None,
            function: None,
        }
    }

    /// Create a new error location with function information
    #[inline]
    pub fn with_function(file: &'static str, line: u32, function: &'static str) -> Self {
        Self {
            file,
            line,
            column: None,
            function: Some(function),
        }
    }

    /// Create a new error location with column information
    #[inline]
    pub fn with_column(file: &'static str, line: u32, column: u32) -> Self {
        Self {
            file,
            line,
            column: Some(column),
            function: None,
        }
    }

    /// Create a new error location with function and column information
    #[inline]
    pub fn full(file: &'static str, line: u32, column: u32, function: &'static str) -> Self {
        Self {
            file,
            line,
            column: Some(column),
            function: Some(function),
        }
    }
}

impl fmt::Display for ErrorLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.file, self.line)?;
        if let Some(column) = self.column {
            write!(f, ":{}", column)?;
        }
        if let Some(function) = self.function {
            write!(f, " in {}", function)?;
        }
        Ok(())
    }
}

/// Error context containing additional information about an error
#[derive(Debug)]
pub struct ErrorContext {
    /// Error message
    pub message: String,
    /// Location where the error occurred
    pub location: Option<ErrorLocation>,
    /// Cause of the error
    pub cause: Option<Box<CoreError>>,
}

impl ErrorContext {
    /// Create a new error context
    pub fn new<S: Into<String>>(message: S) -> Self {
        Self {
            message: message.into(),
            location: None,
            cause: None,
        }
    }

    /// Add location information to the error context
    pub fn with_location(mut self, location: ErrorLocation) -> Self {
        self.location = Some(location);
        self
    }

    /// Add a cause to the error context
    pub fn with_cause(mut self, cause: CoreError) -> Self {
        self.cause = Some(Box::new(cause));
        self
    }
}

impl fmt::Display for ErrorContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)?;
        if let Some(location) = &self.location {
            write!(f, " at {}", location)?;
        }
        if let Some(cause) = &self.cause {
            write!(f, "\nCaused by: {}", cause)?;
        }
        Ok(())
    }
}

/// Core error type for SciRS2
#[derive(Error, Debug)]
pub enum CoreError {
    /// Computation error (generic error)
    #[error("{0}")]
    ComputationError(ErrorContext),

    /// Domain error (input outside valid domain)
    #[error("{0}")]
    DomainError(ErrorContext),

    /// Dispatch error (array protocol dispatch failed)
    #[error("{0}")]
    DispatchError(ErrorContext),

    /// Convergence error (algorithm did not converge)
    #[error("{0}")]
    ConvergenceError(ErrorContext),

    /// Dimension mismatch error
    #[error("{0}")]
    DimensionError(ErrorContext),

    /// Shape error (matrices/arrays have incompatible shapes)
    #[error("{0}")]
    ShapeError(ErrorContext),

    /// Out of bounds error
    #[error("{0}")]
    IndexError(ErrorContext),

    /// Value error (invalid value)
    #[error("{0}")]
    ValueError(ErrorContext),

    /// Type error (invalid type)
    #[error("{0}")]
    TypeError(ErrorContext),

    /// Not implemented error
    #[error("{0}")]
    NotImplementedError(ErrorContext),

    /// Implementation error (method exists but not fully implemented yet)
    #[error("{0}")]
    ImplementationError(ErrorContext),

    /// Memory error (could not allocate memory)
    #[error("{0}")]
    MemoryError(ErrorContext),

    /// Configuration error (invalid configuration)
    #[error("{0}")]
    ConfigError(ErrorContext),

    /// Invalid argument error
    #[error("{0}")]
    InvalidArgument(ErrorContext),

    /// Permission error (insufficient permissions)
    #[error("{0}")]
    PermissionError(ErrorContext),

    /// Validation error (input failed validation)
    #[error("{0}")]
    ValidationError(ErrorContext),

    /// JIT compilation error (error during JIT compilation)
    #[error("{0}")]
    JITError(ErrorContext),

    /// JSON error
    #[error("JSON error: {0}")]
    JSONError(ErrorContext),

    /// IO error
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

/// Result type alias for core operations
pub type CoreResult<T> = Result<T, CoreError>;

/// Convert from serde_json::Error to CoreError
#[cfg(feature = "serialization")]
impl From<serde_json::Error> for CoreError {
    fn from(err: serde_json::Error) -> Self {
        CoreError::JSONError(ErrorContext::new(format!("JSON error: {}", err)))
    }
}

/// Convert from OperationError to CoreError
impl From<crate::array_protocol::OperationError> for CoreError {
    fn from(err: crate::array_protocol::OperationError) -> Self {
        use crate::array_protocol::OperationError;
        match err {
            // Preserving NotImplemented for compatibility with older code,
            // but it will eventually be replaced with NotImplementedError
            OperationError::NotImplemented(msg) => {
                CoreError::NotImplementedError(ErrorContext::new(msg))
            }
            OperationError::ShapeMismatch(msg) => CoreError::ShapeError(ErrorContext::new(msg)),
            OperationError::TypeMismatch(msg) => CoreError::TypeError(ErrorContext::new(msg)),
            OperationError::Other(msg) => CoreError::ComputationError(ErrorContext::new(msg)),
        }
    }
}

/// Macro to create a new error context with location information
///
/// # Example
///
/// ```ignore
/// // This is a placeholder example
/// use scirs2_core::error_context;
///
/// fn example() -> scirs2_core::error::CoreResult<()> {
///     if false {
///         return Err(error_context!("An error occurred"));
///     }
///     Ok(())
/// }
/// ```
#[macro_export]
macro_rules! error_context {
    ($message:expr) => {
        $crate::error::ErrorContext::new($message)
            .with_location($crate::error::ErrorLocation::new(file!(), line!()))
    };
    ($message:expr, $function:expr) => {
        $crate::error::ErrorContext::new($message).with_location(
            $crate::error::ErrorLocation::with_function(file!(), line!(), $function),
        )
    };
}

/// Macro to create a domain error with location information
#[macro_export]
macro_rules! domain_error {
    ($message:expr) => {
        $crate::error::CoreError::DomainError(error_context!($message))
    };
    ($message:expr, $function:expr) => {
        $crate::error::CoreError::DomainError(error_context!($message, $function))
    };
}

/// Macro to create a dimension error with location information
#[macro_export]
macro_rules! dimension_error {
    ($message:expr) => {
        $crate::error::CoreError::DimensionError(error_context!($message))
    };
    ($message:expr, $function:expr) => {
        $crate::error::CoreError::DimensionError(error_context!($message, $function))
    };
}

/// Macro to create a value error with location information
#[macro_export]
macro_rules! value_error {
    ($message:expr) => {
        $crate::error::CoreError::ValueError(error_context!($message))
    };
    ($message:expr, $function:expr) => {
        $crate::error::CoreError::ValueError(error_context!($message, $function))
    };
}

/// Macro to create a computation error with location information
#[macro_export]
macro_rules! computation_error {
    ($message:expr) => {
        $crate::error::CoreError::ComputationError(error_context!($message))
    };
    ($message:expr, $function:expr) => {
        $crate::error::CoreError::ComputationError(error_context!($message, $function))
    };
}

/// Checks if a condition is true, otherwise returns a domain error
///
/// # Arguments
///
/// * `condition` - The condition to check
/// * `message` - The error message if the condition is false
///
/// # Returns
///
/// * `Ok(())` if the condition is true
/// * `Err(CoreError::DomainError)` if the condition is false
pub fn check_domain<S: Into<String>>(condition: bool, message: S) -> CoreResult<()> {
    if condition {
        Ok(())
    } else {
        Err(CoreError::DomainError(
            ErrorContext::new(message).with_location(ErrorLocation::new(file!(), line!())),
        ))
    }
}

/// Checks dimensions
///
/// # Arguments
///
/// * `condition` - The condition to check
/// * `message` - The error message if the condition is false
///
/// # Returns
///
/// * `Ok(())` if the condition is true
/// * `Err(CoreError::DimensionError)` if the condition is false
pub fn check_dimensions<S: Into<String>>(condition: bool, message: S) -> CoreResult<()> {
    if condition {
        Ok(())
    } else {
        Err(CoreError::DimensionError(
            ErrorContext::new(message).with_location(ErrorLocation::new(file!(), line!())),
        ))
    }
}

/// Checks if a value is valid
///
/// # Arguments
///
/// * `condition` - The condition to check
/// * `message` - The error message if the condition is false
///
/// # Returns
///
/// * `Ok(())` if the condition is true
/// * `Err(CoreError::ValueError)` if the condition is false
pub fn check_value<S: Into<String>>(condition: bool, message: S) -> CoreResult<()> {
    if condition {
        Ok(())
    } else {
        Err(CoreError::ValueError(
            ErrorContext::new(message).with_location(ErrorLocation::new(file!(), line!())),
        ))
    }
}

/// Checks if a value is valid according to a validator function
///
/// # Arguments
///
/// * `value` - The value to validate
/// * `validator` - A function that returns true if the value is valid
/// * `message` - The error message if the value is invalid
///
/// # Returns
///
/// * `Ok(value)` if the value is valid
/// * `Err(CoreError::ValidationError)` if the value is invalid
pub fn validate<T, F, S>(value: T, validator: F, message: S) -> CoreResult<T>
where
    F: FnOnce(&T) -> bool,
    S: Into<String>,
{
    if validator(&value) {
        Ok(value)
    } else {
        Err(CoreError::ValidationError(
            ErrorContext::new(message).with_location(ErrorLocation::new(file!(), line!())),
        ))
    }
}

/// Convert an error from one type to a CoreError
///
/// # Arguments
///
/// * `error` - The error to convert
/// * `message` - A message describing the context of the error
///
/// # Returns
///
/// * A CoreError with the original error as its cause
pub fn convert_error<E, S>(error: E, message: S) -> CoreError
where
    E: std::error::Error + 'static,
    S: Into<String>,
{
    // Create a computation error that contains the original error
    // We combine the provided message with the error's own message for extra context
    let message_str = message.into();
    let error_message = format!("{} | Original error: {}", message_str, error);

    // For I/O errors we have direct conversion via From trait implementation
    // but we can't use it directly due to the generic bounds.
    // In a real implementation, you would use a match or if statement with
    // type_id or another approach to distinguish error types.

    // For simplicity, we'll just use ComputationError as a general case
    CoreError::ComputationError(
        ErrorContext::new(error_message).with_location(ErrorLocation::new(file!(), line!())),
    )
}

/// Create an error chain by adding a new error context
///
/// # Arguments
///
/// * `error` - The error to chain
/// * `message` - A message describing the context of the error
///
/// # Returns
///
/// * A CoreError with the original error as its cause
pub fn chain_error<S>(error: CoreError, message: S) -> CoreError
where
    S: Into<String>,
{
    CoreError::ComputationError(
        ErrorContext::new(message)
            .with_location(ErrorLocation::new(file!(), line!()))
            .with_cause(error),
    )
}