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
use crate::*;
use std::collections::HashMap;


pub struct EvalContext
{
	locals: HashMap<String, expr::Value>
}


impl EvalContext
{
	pub fn new() -> EvalContext
	{
		EvalContext
		{
			locals: HashMap::new()
		}
	}
	
	
	pub fn set_local<S>(&mut self, name: S, value: expr::Value)
	where S: Into<String>
	{
		self.locals.insert(name.into(), value);
	}
	
	
	pub fn get_local(&self, name: &str) -> Result<expr::Value, ()>
	{
		match self.locals.get(name)
		{
			Some(value) => Ok(value.clone()),
			None => Err(())
		}
	}
}


pub struct EvalVariableInfo<'a>
{
	pub report: diagn::RcReport,
	pub hierarchy_level: usize,
	pub hierarchy: &'a Vec<String>,
	pub span: &'a diagn::Span,
}


pub struct EvalFunctionInfo<'a>
{
	pub report: diagn::RcReport,
	pub func: expr::Value,
	pub args: Vec<expr::Value>,
	pub span: &'a diagn::Span,
}


impl expr::Expr
{
	pub fn eval<FVar, FFn>(
		&self,
		report: diagn::RcReport,
		ctx: &mut EvalContext,
		eval_var: &FVar,
		eval_fn: &FFn)
		-> Result<expr::Value, ()>
	where
		FVar: Fn(&EvalVariableInfo) -> Result<expr::Value, bool>,
		FFn: Fn(&EvalFunctionInfo) -> Result<expr::Value, bool>
	{
		match self
		{
			&expr::Expr::Literal(_, ref value) => Ok(value.clone()),
			
			&expr::Expr::Variable(ref span, hierarchy_level, ref hierarchy) =>
			{
				if hierarchy_level == 0 && hierarchy.len() == 1
				{
					match ctx.get_local(&hierarchy[0])
					{
						Ok(value) => return Ok(value),
						Err(()) => {}
					}
				}

				let info = EvalVariableInfo
				{
					report: report.clone(),
					hierarchy_level,
					hierarchy,
					span,
				};

				match eval_var(&info)
				{
					Ok(value) => Ok(value),
					Err(handled) =>
					{
						if !handled
							{ report.error_span("unknown variable", &span); }
							
						Err(())
					}
				}
			}
			
			&expr::Expr::UnaryOp(ref span, _, op, ref inner_expr) =>
			{
				match inner_expr.eval(report.clone(), ctx, eval_var, eval_fn)?
				{
					expr::Value::Integer(ref x) => match op
					{
						expr::UnaryOp::Neg => Ok(expr::Value::make_integer(-x)),
						expr::UnaryOp::Not => Ok(expr::Value::make_integer(!x))
					},
					
					expr::Value::Bool(b) => match op
					{
						expr::UnaryOp::Not => Ok(expr::Value::Bool(!b)),
						_ => Err(report.error_span("invalid argument type to operator", &span))
					},
					
					_ => Err(report.error_span("invalid argument type to operator", &span))
				}
			}
			
			&expr::Expr::BinaryOp(ref span, ref op_span, op, ref lhs_expr, ref rhs_expr) =>
			{
				if op == expr::BinaryOp::Assign
				{
					use std::ops::Deref;
					
					match lhs_expr.deref()
					{
						&expr::Expr::Variable(_, hierarchy_level, ref hierarchy) =>
						{
							if hierarchy_level == 0 && hierarchy.len() == 1
							{
								let value = rhs_expr.eval(report.clone(), ctx, eval_var, eval_fn)?;
								ctx.set_local(hierarchy[0].clone(), value);
								return Ok(expr::Value::Void);
							}
							
							Err(report.error_span("symbol cannot be assigned to", &lhs_expr.span()))
						}
						
						_ => Err(report.error_span("invalid assignment destination", &lhs_expr.span()))
					}
				}
				
				else if op == expr::BinaryOp::LazyOr || op == expr::BinaryOp::LazyAnd
				{
					let lhs = lhs_expr.eval(report.clone(), ctx, eval_var, eval_fn)?;
					
					match (op, &lhs)
					{
						(expr::BinaryOp::LazyOr,  &expr::Value::Bool(true))  => return Ok(lhs),
						(expr::BinaryOp::LazyAnd, &expr::Value::Bool(false)) => return Ok(lhs),
						(expr::BinaryOp::LazyOr,  &expr::Value::Bool(false)) => { }
						(expr::BinaryOp::LazyAnd, &expr::Value::Bool(true))  => { }
						_ => return Err(report.error_span("invalid argument type to operator", &lhs_expr.span()))
					}
					
					let rhs = rhs_expr.eval(report.clone(), ctx, eval_var, eval_fn)?;
					
					match (op, &rhs)
					{
						(expr::BinaryOp::LazyOr,  &expr::Value::Bool(true))  => Ok(rhs),
						(expr::BinaryOp::LazyAnd, &expr::Value::Bool(false)) => Ok(rhs),
						(expr::BinaryOp::LazyOr,  &expr::Value::Bool(false)) => Ok(rhs),
						(expr::BinaryOp::LazyAnd, &expr::Value::Bool(true))  => Ok(rhs),
						_ => Err(report.error_span("invalid argument type to operator", &rhs_expr.span()))
					}
				}
				
				else
				{
					match (lhs_expr.eval(report.clone(), ctx, eval_var, eval_fn)?, rhs_expr.eval(report.clone(), ctx, eval_var, eval_fn)?)
					{
						(expr::Value::Integer(ref lhs), expr::Value::Integer(ref rhs)) =>
						{
							match op
							{
								expr::BinaryOp::Add => Ok(expr::Value::make_integer(lhs + rhs)),
								expr::BinaryOp::Sub => Ok(expr::Value::make_integer(lhs - rhs)),
								expr::BinaryOp::Mul => Ok(expr::Value::make_integer(lhs * rhs)),
								
								expr::BinaryOp::Div => match lhs.checked_div(rhs)
								{
									Some(x) => Ok(expr::Value::make_integer(x)),
									None => Err(report.error_span("division by zero", &op_span.join(&rhs_expr.span())))
								},
								
								expr::BinaryOp::Mod => match lhs.checked_rem(rhs)
								{
									Some(x) => Ok(expr::Value::make_integer(x)),
									None => Err(report.error_span("modulo by zero", &op_span.join(&rhs_expr.span())))
								},
								
								expr::BinaryOp::Shl => match lhs.checked_shl(rhs)
								{
									Some(x) => Ok(expr::Value::make_integer(x)),
									None => Err(report.error_span("invalid shift value", &op_span.join(&rhs_expr.span())))
								},
								
								expr::BinaryOp::Shr => match lhs.checked_shr(rhs)
								{
									Some(x) => Ok(expr::Value::make_integer(x)),
									None => Err(report.error_span("invalid shift value", &op_span.join(&rhs_expr.span())))
								},
								
								expr::BinaryOp::And  => Ok(expr::Value::make_integer(lhs & rhs)),
								expr::BinaryOp::Or   => Ok(expr::Value::make_integer(lhs | rhs)),
								expr::BinaryOp::Xor  => Ok(expr::Value::make_integer(lhs ^ rhs)),
								expr::BinaryOp::Eq   => Ok(expr::Value::Bool(lhs == rhs)),
								expr::BinaryOp::Ne   => Ok(expr::Value::Bool(lhs != rhs)),
								expr::BinaryOp::Lt   => Ok(expr::Value::Bool(lhs <  rhs)),
								expr::BinaryOp::Le   => Ok(expr::Value::Bool(lhs <= rhs)),
								expr::BinaryOp::Gt   => Ok(expr::Value::Bool(lhs >  rhs)),
								expr::BinaryOp::Ge   => Ok(expr::Value::Bool(lhs >= rhs)),
								
								expr::BinaryOp::Concat =>
								{
									// FIXME: wrongly evaluates lhs and rhs again, with possible duplicated side-effects
									//let lhs_sliced = lhs_expr.eval_slice(report.clone(), ctx, eval_var, eval_fn)?;
									//let rhs_sliced = rhs_expr.eval_slice(report.clone(), ctx, eval_var, eval_fn)?;

									match (lhs.size, rhs.size)
									{
										(Some(lhs_width), Some(rhs_width)) => Ok(expr::Value::make_integer(lhs.concat((lhs_width - 1, 0), &rhs, (rhs_width - 1, 0)))),
										(None, _) => Err(report.error_span("argument to concatenation with unspecified size", &lhs_expr.span())),
										(_, None) => Err(report.error_span("argument to concatenation with unspecified size", &rhs_expr.span()))
									}
								}

								_ => Err(report.error_span("invalid argument types to operator", &span))
							}
						}
						
						(expr::Value::Bool(lhs), expr::Value::Bool(rhs)) =>
						{
							match op
							{
								expr::BinaryOp::And => Ok(expr::Value::Bool(lhs & rhs)),
								expr::BinaryOp::Or  => Ok(expr::Value::Bool(lhs | rhs)),
								expr::BinaryOp::Xor => Ok(expr::Value::Bool(lhs ^ rhs)),
								expr::BinaryOp::Eq  => Ok(expr::Value::Bool(lhs == rhs)),
								expr::BinaryOp::Ne  => Ok(expr::Value::Bool(lhs != rhs)),
								_ => Err(report.error_span("invalid argument types to operator", &span))
							}
						}
						
						_ => Err(report.error_span("invalid argument types to operator", &span))
					}
				}
			}
			
			&expr::Expr::TernaryOp(_, ref cond, ref true_branch, ref false_branch) =>
			{
				match cond.eval(report.clone(), ctx, eval_var, eval_fn)?
				{
					expr::Value::Bool(true)  => true_branch.eval(report.clone(), ctx, eval_var, eval_fn),
					expr::Value::Bool(false) => false_branch.eval(report.clone(), ctx, eval_var, eval_fn),
					_ => Err(report.error_span("invalid condition type", &cond.span()))
				}
			}
			
			&expr::Expr::BitSlice(ref span, _, left, right, ref inner) =>
			{
				match inner.eval(report.clone(), ctx, eval_var, eval_fn)?
				{
					expr::Value::Integer(ref x) => Ok(expr::Value::make_integer(x.slice(left, right))),
					_ => Err(report.error_span("invalid argument type to slice", &span))
				}
			}
			
			&expr::Expr::SoftSlice(_, _, _, _, ref inner) =>
			{
				inner.eval(report, ctx, eval_var, eval_fn)
			}
			
			&expr::Expr::Block(_, ref exprs) =>
			{
				let mut result = expr::Value::Void;
				
				for expr in exprs
					{ result = expr.eval(report.clone(), ctx, eval_var, eval_fn)?; }
					
				Ok(result)
			}
			
			&expr::Expr::Call(ref span, ref target, ref arg_exprs) =>
			{
				let func = target.eval(report.clone(), ctx, eval_var, eval_fn)?;

				match func
				{
					expr::Value::Function(_) =>
					{
						let mut args = Vec::new();
						for expr in arg_exprs
							{ args.push(expr.eval(report.clone(), ctx, eval_var, eval_fn)?); }

						let info = EvalFunctionInfo
						{
							report: report.clone(),
							func,
							args,
							span,
						};
							
						match eval_fn(&info)
						{
							Ok(value) => Ok(value),
							Err(_handled) => Err(())
						}
					}
					
					_ => Err(report.error_span("expression is not callable", &target.span()))
				}
			}
		}
	}


	/*pub fn eval_slice<FVar, FFn>(&self, report: RcReport, ctx: &mut ExpressionEvalContext, eval_var: &FVar, eval_fn: &FFn) -> Result<expr::Value, ()>
		where
		FVar: Fn(RcReport, &str, &Span) -> Result<expr::Value, bool>,
		FFn: Fn(RcReport, usize, Vec<expr::Value>, &Span) -> Result<expr::Value, bool>
	{
		match self
		{
			&expr::Expr::SoftSlice(ref span, _, left, right, ref inner) =>
			{
				match inner.eval(report.clone(), ctx, eval_var, eval_fn)?
				{
					expr::Value::Integer(ref x) => Ok(expr::Value::make_integer(x.slice(left, right))),
					_ => Err(report.error_span("invalid argument type to slice", &span))
				}
			}

			_ => self.eval(report, ctx, eval_var, eval_fn)
		}
	}*/
}


impl expr::Value
{
	pub fn min_size(&self) -> usize
	{
		match &self
		{
			&expr::Value::Integer(bigint) => bigint.min_size(),
			_ => panic!("not an integer")
		}
	}
	

	pub fn get_bit(&self, index: usize) -> bool
	{
		match self
		{
			&expr::Value::Integer(ref bigint) => bigint.get_bit(index),
			_ => panic!("not an integer")
		}
	}
}