public Addition (Expression left, Expression right) : base(left, right) { }
public Subtraction (Expression left, Expression right) : base(left, right) { }
public AssignmentFunction (string id, string[] parameters, Expression body) { Id = id; Parameters = parameters; Body = body; }
public Division (Expression left, Expression right) : base(left, right) { }
private Func<double> Compile (Expression expression) { if (expression is Const) return () => (expression as Const).Value; if (expression is Addition) { var addition = expression as Addition; var left = Compile (addition.Left); var right = Compile (addition.Right); return () => left () + right (); } if (expression is Subtraction) { var subtraction = expression as Subtraction; var left = Compile (subtraction.Left); var right = Compile (subtraction.Right); return () => left () - right (); } if (expression is Multiplication) { var multiplication = expression as Multiplication; var left = Compile (multiplication.Left); var right = Compile (multiplication.Right); return () => left () * right (); } if (expression is Division) { var division = expression as Division; var left = Compile (division.Left); var right = Compile (division.Right); return () => left () / right (); } if (expression is Variable) { var variable = expression as Variable; return () => { return CurrentScope.GetVariable (variable.Id); }; } if (expression is Function) { var function = expression as Function; var arg_list = function.Args.Select (arg => Compile (arg)).ToList (); return () => { var func = functions.FirstOrDefault (f => f.Id == function.Id && f.Parameters.Count () == arg_list.Count); if (func == null) return 0; var parentScope = CurrentScope; CurrentScope = new Scope () { Parent = parentScope}; var i = 0; foreach (var p in func.Parameters) { var value = arg_list [i] (); CurrentScope.SetVariable (p, value); i++; } var result = func.Body (); CurrentScope.Parent = null; CurrentScope = parentScope; return result; }; } return null; }
public AssignmentVariable (string id, Expression expression) { Id = id; Expression = expression; }
public BinaryOperation (Expression left, Expression right) { Left = left; Right = right; }
public ExpressionStatement (Expression expression) { Expression = expression; }
public Function (string id, Expression[] args) { Id = id; Args = args; }
public Multiplication (Expression left, Expression right) : base(left, right) { }