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
use core::fmt;
use pest::Span;

mod interpreter;
use interpreter::expr::eval_visitor::EvalVisitor;
use interpreter::{ast::create_ast, parser::parse_dala};

/// The result of a successful evaluation of a `DalaExpression`.
/// It can be either a `String`, a `f64` or a `bool`.
#[derive(Debug, Clone)]
pub enum DalaValue {
    Str(String),
    Num(f64),
    Boolean(bool),
}

impl fmt::Display for DalaValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DalaValue::Str(value) => write!(f, "{}", value),
            DalaValue::Num(value) => write!(f, "{}", value),
            DalaValue::Boolean(value) => write!(f, "{}", value),
        }
    }
}

/// Contains the position of a `DalaExpression` in the source code.
#[derive(Debug, Clone)]
pub struct Position {
    pub start: usize,
    pub end: usize,
}

impl Position {
    pub fn new(pair: Span) -> Self {
        Self {
            start: pair.start(),
            end: pair.end(),
        }
    }
}

impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}, {}", self.start, self.end)
    }
}

/// The result of an unsuccessful evaluation of a `DalaExpression`.
#[derive(Debug, Clone)]
pub enum DalaError {
    BuildError(BuildError),
    RuntimeError(RuntimeError),
    ParseError(ParseError),
}

impl fmt::Display for DalaError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DalaError::BuildError(err) => write!(f, "{}", err),
            DalaError::RuntimeError(err) => write!(f, "{}", err),
            DalaError::ParseError(err) => write!(f, "{}", err),
        }
    }
}

/// An error that occurs during the evaluation of a `DalaExpression`.
#[derive(Debug, Clone)]
pub struct RuntimeError {
    pub pos: Position,
    pub message: String,
}

impl RuntimeError {
    pub fn new(pos: Position, message: String) -> Self {
        Self { pos, message }
    }
}

impl fmt::Display for RuntimeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Runtime error: {}, at: {}", self.message, self.pos)
    }
}

/// An error that occurs when processing the a `DalaExpression`, before its evaluation.
#[derive(Debug, Clone)]
pub struct BuildError {
    pub pos: Position,
    pub message: String,
}

impl BuildError {
    pub fn new(pos: Position, message: String) -> Self {
        Self { pos, message }
    }
}

impl fmt::Display for BuildError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Build error: {}, at: {}", self.message, self.pos)
    }
}

/// An error that occurs when parsing a `DalaExpression`.
#[derive(Debug, Clone)]
pub struct ParseError {
    pub message: String,
}

impl ParseError {
    pub fn new(message: String) -> Self {
        Self { message }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Parse error: {}", self.message)
    }
}

/// Evaluates a `DalaExpression` and returns a `DalaValue` if the evaluation is successful or a `DalaError` if it is not.
///
/// # Examples
///
/// ```
/// use dala::{eval, DalaValue};
///
/// let result = eval("CONCAT(\"Hello\", \" \", \"World\")");
/// let DalaValue::Str(value) = result[0].as_ref().unwrap() else { panic!("Not a string") };
/// assert_eq!(value, "Hello World");
/// ```
pub fn eval(str: &str) -> Vec<Result<DalaValue, DalaError>> {
    let parsed = parse_dala(str);
    if parsed.is_err() {
        return vec![Err(parsed.unwrap_err())];
    }

    create_ast(parsed.unwrap())
        .into_iter()
        .map(|expr| expr.and_then(|expr| expr.eval()))
        .collect()
}