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
use std::convert::TryFrom;
use std::fmt;
use std::str::FromStr;

use yolol_number::YololNumber;

use crate::error::YolkError;
use crate::optimizer::optimize;
use crate::parser::parse;
use crate::transpiler::transpile;

#[cfg(test)]
mod tests;

/// Represents a Yolk program.
#[derive(Debug, Clone, PartialEq)]
pub struct YolkProgram {
    stmts: Vec<YolkStmt>,
}

impl From<Vec<YolkStmt>> for YolkProgram {
    /// Converts Yolk statements to a program.
    fn from(stmts: Vec<YolkStmt>) -> Self {
        YolkProgram { stmts: stmts }
    }
}

impl FromStr for YolkProgram {
    type Err = YolkError;

    /// Parses a Yolk program from a string.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse(s)
    }
}

impl IntoIterator for YolkProgram {
    type Item = YolkStmt;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    /// Iterates over the statements in a Yolk program.
    fn into_iter(self) -> Self::IntoIter {
        self.stmts.into_iter()
    }
}

/// Represents a Yolk statement.
#[derive(Debug, Clone, PartialEq)]
pub enum YolkStmt {
    Import {
        ident: String,
    },
    Define {
        ident: String,
        params: Vec<String>,
        body: Box<YolkExpr>,
    },
    Let {
        ident: String,
        expr: Box<YolkExpr>,
    },
}

/// Represents a Yolk expression.
#[derive(Debug, Clone, PartialEq)]
pub enum YolkExpr {
    Prefix {
        op: PrefixOp,
        expr: Box<YolkExpr>,
    },
    Fold {
        op: InfixOp,
        args: Vec<YolkExpr>,
    },
    Call {
        ident: String,
        args: Vec<YolkExpr>,
    },
    Infix {
        lhs: Box<YolkExpr>,
        op: InfixOp,
        rhs: Box<YolkExpr>,
    },
    Ident(String),
    Literal(YololNumber),
    Array(Vec<YolkExpr>),
}

/// Represents a Yolol program.
#[derive(Debug, Clone, PartialEq)]
pub struct YololProgram {
    stmts: Vec<YololStmt>,
}

impl YololProgram {
    /// Optimizes a Yolol program
    pub fn optimize(self) -> Self {
        optimize(self)
    }
}

impl From<Vec<YololStmt>> for YololProgram {
    /// Converts Yolol statements to a program.
    fn from(stmts: Vec<YololStmt>) -> Self {
        YololProgram { stmts: stmts }
    }
}

impl TryFrom<YolkProgram> for YololProgram {
    type Error = YolkError;

    /// Converts a Yolk program into a Yolol program.
    fn try_from(program: YolkProgram) -> Result<Self, Self::Error> {
        transpile(program)
    }
}

impl fmt::Display for YololProgram {
    /// Formats a Yolol program as a string.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buffer = String::new();
        let mut line = String::new();
        // Iterate directly over stmts to avoid taking ownership
        for stmt in self.stmts.iter() {
            match stmt {
                YololStmt::Assign { ident, expr } => {
                    let stmt = format!(" {}={}", ident, expr.to_string());
                    if line.len() + stmt.len() >= 70 {
                        buffer.push_str(&format!("{}\n", line.trim()));
                        line.clear();
                    }
                    line.push_str(&stmt);
                }
            }
        }
        if line.len() > 0 {
            buffer.push_str(&format!("{}\n", line.trim()));
        }
        write!(f, "{}", buffer.trim().to_string())
    }
}

impl IntoIterator for YololProgram {
    type Item = YololStmt;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    /// Iterates over the statement in a Yolol program.
    fn into_iter(self) -> Self::IntoIter {
        self.stmts.into_iter()
    }
}

/// Represents a Yolol statement.
#[derive(Debug, Clone, PartialEq)]
pub enum YololStmt {
    Assign { ident: String, expr: Box<YololExpr> },
}

impl fmt::Display for YololStmt {
    /// Formats a Yolol statement as a string.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Assign { ident, expr } => write!(f, "{}={}", ident, expr.to_string()),
        }
    }
}

/// Represents a Yolol expression.
#[derive(Debug, Clone, PartialEq)]
pub enum YololExpr {
    Prefix {
        op: PrefixOp,
        expr: Box<YololExpr>,
    },
    Infix {
        lhs: Box<YololExpr>,
        op: InfixOp,
        rhs: Box<YololExpr>,
    },
    Ident(String),
    Literal(YololNumber),
}

impl fmt::Display for YololExpr {
    /// Formats a Yolol expression as a string.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (s, _) = self.format(0);
        write!(f, "{}", s)
    }
}

impl YololExpr {
    fn format(&self, parent_prec: u32) -> (String, bool) {
        match self {
            Self::Prefix { op, expr } => {
                let prec = op.to_precedence();
                let (expr, child_wrapped) = expr.format(prec);
                let wrapped = prec < parent_prec;
                // Alphabetic ops must be surrounded with whitespace or parentheses
                let is_alpha = op.to_string().chars().all(char::is_alphabetic);
                let spaced = !child_wrapped && is_alpha;
                (
                    format!(
                        "{lparen}{op}{space}{expr}{rparen}",
                        lparen = if wrapped { "(" } else { "" },
                        op = op.to_string(),
                        space = if spaced { " " } else { "" },
                        expr = expr,
                        rparen = if wrapped { ")" } else { "" },
                    ),
                    wrapped,
                )
            }
            Self::Infix { lhs, op, rhs } => {
                let prec = op.to_precedence();
                let (lhs, lhs_wrapped) = lhs.format(prec);
                let (rhs, rhs_wrapped) = rhs.format(prec);
                // If the op is associative, we can reduce "(a+b)+c" to "a+b+c"
                let wrapped = if op.is_associative() {
                    prec < parent_prec
                } else {
                    prec <= parent_prec
                };
                // Alphabetic ops must be surrounded with whitespace or parentheses
                let is_alpha = op.to_string().chars().all(char::is_alphabetic);
                let lhs_spaced = !lhs_wrapped && is_alpha;
                let rhs_spaced = !rhs_wrapped && is_alpha;
                (
                    format!(
                        "{lparen}{lhs}{lhs_space}{op}{rhs_space}{rhs}{rparen}",
                        lparen = if wrapped { "(" } else { "" },
                        lhs = lhs,
                        lhs_space = if lhs_spaced { " " } else { "" },
                        op = op.to_string(),
                        rhs_space = if rhs_spaced { " " } else { "" },
                        rhs = rhs,
                        rparen = if wrapped { ")" } else { "" },
                    ),
                    wrapped,
                )
            }
            Self::Ident(s) => (s.to_string(), false),
            Self::Literal(y) => (y.to_string(), false),
        }
    }
}

/// Represents a prefix operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrefixOp {
    Neg,
    Not,
    Abs,
    Sqrt,
    Sin,
    Cos,
    Tan,
    Asin,
    Acos,
    Atan,
}

impl PrefixOp {
    fn to_precedence(&self) -> u32 {
        match self {
            Self::Neg => 100,
            _ => 90,
        }
    }
}

impl fmt::Display for PrefixOp {
    /// Formats a prefix operation as a string.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Neg => write!(f, "-"),
            Self::Not => write!(f, "not"),
            Self::Abs => write!(f, "abs"),
            Self::Sqrt => write!(f, "sqrt"),
            Self::Sin => write!(f, "sin"),
            Self::Cos => write!(f, "cos"),
            Self::Tan => write!(f, "tan"),
            Self::Asin => write!(f, "asin"),
            Self::Acos => write!(f, "acos"),
            Self::Atan => write!(f, "atan"),
        }
    }
}

/// Represents an infix operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InfixOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Exp,
    LessThan,
    LessEqual,
    GreaterThan,
    GreaterEqual,
    Equal,
    NotEqual,
    And,
    Or,
}

impl InfixOp {
    fn to_precedence(&self) -> u32 {
        match self {
            Self::Exp => 80,
            Self::Mul | Self::Div | Self::Mod => 70,
            Self::Add | Self::Sub => 60,
            Self::LessThan | Self::LessEqual | Self::GreaterThan | Self::GreaterEqual => 50,
            Self::Equal | Self::NotEqual => 40,
            Self::Or => 30,
            Self::And => 20,
        }
    }

    /// Returns whether or not an infix operation is associative.
    pub fn is_associative(&self) -> bool {
        match self {
            Self::Add | Self::Mul => true,
            _ => false,
        }
    }
}

impl fmt::Display for InfixOp {
    /// Formats an infix operation as a string.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Add => write!(f, "+"),
            Self::Sub => write!(f, "-"),
            Self::Mul => write!(f, "*"),
            Self::Div => write!(f, "/"),
            Self::Mod => write!(f, "%"),
            Self::Exp => write!(f, "^"),
            Self::LessThan => write!(f, "<"),
            Self::LessEqual => write!(f, "<="),
            Self::GreaterThan => write!(f, ">"),
            Self::GreaterEqual => write!(f, ">="),
            Self::Equal => write!(f, "=="),
            Self::NotEqual => write!(f, "!="),
            Self::And => write!(f, "and"),
            Self::Or => write!(f, "or"),
        }
    }
}