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
//! Expression parsers
//!
//! The primary parser to use in this module is [`expression`], which will parse any
//! expression.  It's used in the examples below.  The other parsers in this module
//! will only parse a specific type of expression.  For example [`function_call`] will
//! only parse an expressions where a function call is the root of the expression tree.
//! # Examples:
//! ```rust
//! let source_code = "x + 1.0 * y";
//! # use lualite::parser::expression::expression;
//! let (_remaining, parsed_ast) = expression(source_code).expect("parse error");
//!
//! # use lualite::ast::{Expression, Identifier, BinaryOperator, FloatLiteral};
//! let expected_ast = Expression::Binary {
//!   left: Box::new(Expression::Identifier(Identifier("x".to_owned()))),
//!   op: BinaryOperator::Add,
//!   right: Box::new(Expression::Binary {
//!     left: Box::new(Expression::Float(FloatLiteral(1.0_f64))),
//!     op: BinaryOperator::Mul,
//!     right: Box::new(Expression::Identifier(Identifier("y".to_owned()))),
//!   })
//! };
//!
//! assert_eq!(parsed_ast, expected_ast);
//! ```
//! Order of operations can be changed with parentheses:
//! ```rust
//! let source_code = "(x + 1.0) * y";
//! # use lualite::parser::expression::expression;
//! let (_remaining, parsed_ast) = expression(source_code).expect("parse error");
//!
//! # use lualite::ast::{Expression, Identifier, BinaryOperator, FloatLiteral};
//! let expected_ast = Expression::Binary {
//!   left: Box::new(Expression::Binary {
//!     left: Box::new(Expression::Identifier(Identifier("x".to_owned()))),
//!     op: BinaryOperator::Add,
//!     right: Box::new(Expression::Float(FloatLiteral(1.0_f64))),
//!   }),
//!   op: BinaryOperator::Mul,
//!   right: Box::new(Expression::Identifier(Identifier("y".to_owned()))),
//! };
//!
//! assert_eq!(parsed_ast, expected_ast);
//! ```

use nom::{
  IResult,
  branch::alt,
  bytes::complete::tag,
  character::complete::space0,
  combinator::{map, opt},
  sequence::{delimited, pair, tuple},
  multi::{many0, separated_list0},
};
use crate::ast::{Expression, BooleanLiteral};
use super::atomic::{identifier, integer, float, string, keyword};
use super::{operator, whitespace};

/// Any possible expression with arbitrary nesting
///
/// Used like so:
/// ```rust
/// # use lualite::parser::expression::expression;
/// let (_, ast) = expression("f(x + 1, true)").expect("parse error");
/// let (_, ast) = expression("array[i - 1] * 2").expect("parse error");
/// let (_, ast) = expression("(a / 2) + (b / 3)").expect("parse error");
/// let (_, ast) = expression("a < b and b < c").expect("parse error");
/// ```
pub fn expression(s: &str) -> IResult<&str, Expression> {
  comparison_expression(s)
}

/// Expressions with the highest precedence
///
/// Consists of literals, identifiers, and parenthesized expressions.
pub fn leaf_expression(s: &str) -> IResult<&str, Expression> {
  alt((
    map(identifier, |ident| Expression::Identifier(ident)),
    map(float, |flt| Expression::Float(flt)),
    map(integer, |int| Expression::Integer(int)),
    map(string, |s| Expression::String(s)),
    map(keyword("true"), |_| Expression::Boolean(BooleanLiteral(true))),
    map(keyword("false"), |_| Expression::Boolean(BooleanLiteral(false))),
    parenthesized,
  ))(s)
}

/// Post-fix operators (call and index)
pub fn postfix_expression(s: &str) -> IResult<&str, Expression> {
  alt((
    function_call,
    index_expression,
    leaf_expression,
  ))(s)
}

/// Function call expression
pub fn function_call(s: &str) -> IResult<&str, Expression> {
  map(
    tuple((
      leaf_expression,
      space0,
      arg_list,
    )),
    |(function, _, args)| Expression::FunctionCall {
      left: Box::new(function),
      args,
    },
  )(s)
}

/// Parenthesized expression to modify operator precedence order
pub fn parenthesized(s: &str) -> IResult<&str, Expression> {
  delimited(
    tag("("),
    expression,
    tag(")"),
  )(s)
}

/// Argument list for a function call
pub fn arg_list(s: &str) -> IResult<&str, Vec<Expression>> {
  delimited(
    tag("("),
    separated_list0(
      tag(","),
      delimited(whitespace, expression, whitespace),
    ),
    tag(")"),
  )(s)
}

/// Indexed container as an r-value
pub fn index_expression(s: &str) -> IResult<&str, Expression> {
  map(
    tuple((
      leaf_expression,
      space0,
      tag("["),
      expression,
      tag("]"),
    )),
    |(array, _, _, index, _)| Expression::Index {
      left: Box::new(array),
      index: Box::new(index),
    },
  )(s)
}

/// An expression raised to the power of another expression
pub fn power_expression(s: &str) -> IResult<&str, Expression> {
  map(
    pair(postfix_expression, opt(pair(operator::power, leaf_expression))),
    |(base, maybe_exponent)| {
      match maybe_exponent {
        Some((op, exponent)) => Expression::Binary {
          left: Box::new(base),
          op,
          right: Box::new(exponent),
        },
        None => base,
      }
    },
  )(s)
}

/// Unary prefix operator expressions
pub fn unary_expression(s: &str) -> IResult<&str, Expression> {
  map(
    pair(many0(operator::unary), power_expression),
    |(op_stack, last)| {
      let mut expr = last;
      for op in op_stack.into_iter().rev() {
        expr = Expression::Unary {
          op,
          right: Box::new(expr),
        };
      }
      expr
    },
  )(s)
}

/// Multiplicative binary operator expressions (*, /, %)
pub fn multiplicative_expression(s: &str) -> IResult<&str, Expression> {
  map(
    pair(power_expression, many0(pair(operator::multiplicative, unary_expression))),
    |(first, remaining)| {
      let mut expr = first;
      for (op, right) in remaining {
        expr = Expression::Binary {
          left: Box::new(expr),
          op,
          right: Box::new(right),
        };
      }
      expr
    }
  )(s)
}

/// Additive binary operator expressions (+, -)
pub fn additive_expression(s: &str) -> IResult<&str, Expression> {
  map(
    pair(multiplicative_expression, many0(pair(operator::additive, multiplicative_expression))),
    |(first, remaining)| {
      let mut expr = first;
      for (op, right) in remaining {
        expr = Expression::Binary {
          left: Box::new(expr),
          op,
          right: Box::new(right),
        };
      }
      expr
    }
  )(s)
}

/// Comparison expressions (==, !=, <, >=, etc.)
pub fn comparison_expression(s: &str) -> IResult<&str, Expression> {
  map(
    pair(additive_expression, opt(pair(operator::comparison, additive_expression))),
    |(left, maybe_right)| {
      match maybe_right {
        Some((op, right)) => Expression::Binary {
          left: Box::new(left),
          op,
          right: Box::new(right),
        },
        None => left,
      }
    },
  )(s)
}