public SScope SpawnScopeWith(String[] names, SObject[] values) { //(names.Length >= values.Length).OrThrows("Too many arguments."); SScope scope = new SScope(this); for (Int32 i = 0; i < values.Length; i++) { scope.variableTable.Add(names[i], values[i]); } return(scope); }
public SObject Find(String name) { SScope current = this; while (current != null) { if (current.variableTable.ContainsKey(name)) { return(current.variableTable[name]); } current = current.Parent; } throw new Exception(name + " is not defined."); }
public SObject Evaluate(SScope scope) { if (this.Children.Count == 0) { Int64 number; if (Int64.TryParse(this.Value, out number)) { return(number); } } else { SExpression first = this.Children[0]; if (SScope.BuiltinFunctions.ContainsKey(first.Value)) { var arguments = this.Children.Skip(1).ToArray(); return(SScope.BuiltinFunctions[first.Value](arguments, scope)); } } throw new Exception("THIS IS JUST TEMPORARY!"); }
public static void KeepInterpretingInConsole(this SScope scope, Func <String, SScope, SObject> evaluate) { while (true) { try { Console.ForegroundColor = ConsoleColor.Gray; Console.Write(">> "); String code; if (!String.IsNullOrWhiteSpace(code = Console.ReadLine())) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(">> " + evaluate(code, scope)); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(">> " + ex.Message); } } }
static void Main(string[] cmdArgs) { Console.WriteLine("解释器:"); //Output(Input()); SScope sScope = new SScope(parent: null) .BuildIn("+", (args, scope) => { var numbers = args.Select(obj => obj.Evaluate(scope)).Cast <SNumber>(); return(numbers.Sum(n => n)); }) .BuildIn("-", (args, scope) => { var numbers = args.Select(obj => obj.Evaluate(scope)).Cast <SNumber>().ToArray(); Int64 firstValue = numbers[0]; if (numbers.Length == 1) { return(-firstValue); } return(firstValue - numbers.Skip(1).Sum(s => s)); }); KeepInterpretingInConsole(sScope, (code, scope) => ParseAsIScheme(code).Evaluate(scope)); }
public SFunction(SExpression sExpression, String[] parameters, SScope scope) { this.Body = sExpression; this.Parameters = parameters; this.Scope = scope; }
public static IEnumerable <SObject> Evaluate(this IEnumerable <SExpression> expressions, SScope scope) { return(expressions.Select(exp => exp.Evaluate(scope))); }
public static IEnumerable <T> Evaluate <T>(this IEnumerable <SExpression> expressions, SScope scope) where T : SObject { return(expressions.Evaluate(scope).Cast <T>()); }
public SScope(SScope parent) { this.Parent = parent; this.variableTable = new Dictionary <string, SObject>(); }