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
use lexer::tokenize;

use ast::{Args, Evaluate, EvaluationResult, Node, Root, Scope};
use error::Error;
use std::{collections::VecDeque, string::ToString};
use tokens::{Operator, Token, TokenList};

type NodeList = Vec<Node>;

pub fn eval<'a>(expr: &'a str, scope: &'a Scope) -> EvaluationResult {
    parse_tokens(tokenize(expr, scope)?, scope)?.eval()
}

pub fn compile<'a>(expr: &'a str, scope: &'a Scope) -> Result<Root<'a>, Error> {
    parse_tokens(tokenize(expr, scope)?, scope)
}

fn make_node(token: Token, args: Option<Args>) -> Node {
    Node { token, args }
}

fn encounter_func(f: String, operands: &mut NodeList) -> Result<(), Error> {
    let mut args = Args::with_capacity(2);

    // ASSUMPTION: at least one argument per function
    args.push_front(operands
        .pop()
        .ok_or_else(|| Error::NotEnoughFunctionParams(f.clone()))?);

    while let Some(last) = operands.pop() {
        if last.token != Token::Comma {
            operands.push(last);
            break;
        }
        else {
            args.push_front(operands
                .pop()
                .ok_or_else(|| Error::FunctionSyntaxError(f.clone()))?);
        }
    }

    operands.push(make_node(Token::Function(f), Some(args)));
    Ok(())
}

fn right_paren(
    operators: &mut TokenList,
    operands: &mut NodeList,
) -> Result<(), Error> {
    while let Some(top) = operators.pop() {
        match top {
            Token::LeftParenthesis => break,
            Token::Function(f) => encounter_func(f, operands)?,
            Token::Operator(op) => add_operator(op, operands)?,
            _ => {},
        }
    }
    Ok(())
}

fn add_operator(
    operator: Operator,
    operands: &mut NodeList,
) -> Result<(), Error> {
    let num_operands = operator.num_operands();

    let mut args: VecDeque<Node> =
        VecDeque::with_capacity(num_operands as usize);

    for _ in 0..num_operands {
        args.push_front(operands
            .pop()
            .ok_or_else(|| Error::MissingOperands(operator.to_string()))?);
    }

    Ok(operands.push(make_node(Token::Operator(operator), Some(args))))
}

fn encounter_operator(
    cur_operator: Operator,
    operators: &mut TokenList,
    operands: &mut NodeList,
) -> Result<(), Error> {
    while let Some(top) = operators.pop() {
        match top {
            Token::Operator(top_operator) => {
                if top_operator > cur_operator
                    || (top_operator == cur_operator
                        && !cur_operator.is_right_associative())
                {
                    add_operator(top_operator, operands)?
                }
                else {
                    operators.push(Token::Operator(top_operator));
                    break;
                }
            },
            Token::Function(f) => encounter_func(f, operands)?,
            _ => {
                operators.push(top);
                break;
            },
        }
    }

    debug!("Push op to stack: {:?}", cur_operator);
    operators.push(Token::Operator(cur_operator));
    Ok(())
}

fn parse_tokens<'a>(
    tokens: TokenList,
    scope: &'a Scope,
) -> Result<Root<'a>, Error> {
    let mut operators: TokenList = Vec::new();
    let mut operands: NodeList = Vec::new();

    for token in tokens {
        debug!("TOKEN: {:?}", token);
        match token {
            Token::Number(num) => operands.push(Node {
                token: Token::Number(num),
                args: None,
            }),
            Token::Variable(var) => operands.push(Node {
                token: Token::Variable(var),
                args: None,
            }),
            Token::RightParenthesis => {
                right_paren(&mut operators, &mut operands)?
            },
            Token::LeftParenthesis => operators.push(token),
            Token::Operator(op1) => {
                encounter_operator(op1, &mut operators, &mut operands)?;
            },
            Token::Function(f) => operators.push(Token::Function(f)),
            Token::Comma => operands.push(make_node(token, None)),
        };
        debug!("stack: {:?}", operators);
        debug!("output: {:?}", operands);
        debug!("----------");
    }

    while let Some(Token::Operator(operator)) = operators.pop() {
        add_operator(operator, &mut operands)?
    }

    // TODO: revisit this when the final output can also be a string
    operands.pop().map_or_else(
        || Err(Error::EmptyExpression),
        |node| Ok(Root { node, scope }),
    )
}