public object VisitClassStmt(Class stmt) { Environment.Define(stmt.Name.Lexeme, null); Dictionary <String, CoxFunction> methods = new Dictionary <String, CoxFunction>(); Object superclass = null; if (stmt.Superclass != null) { superclass = Evaluate(stmt.Superclass); if (!(superclass is CoxClass)) { throw new RuntimeError(stmt.Name, "Superclass must be a class."); } Environment = new Environment(Environment); Environment.Define("super", superclass); } foreach (Function method in stmt.Methods) { CoxFunction function = new CoxFunction(method, Environment, method.Name.Lexeme.Equals("init")); methods.Add(method.Name.Lexeme, function); } CoxClass klass = new CoxClass(stmt.Name.Lexeme, (CoxClass)superclass, methods); if (superclass != null) { Environment = Environment.Enclosing; } Environment.Assign(stmt.Name, klass); return(null); }
public object VisitFunctionStmt(Function stmt) { Environment.Define(stmt.Name.Lexeme, null); CoxFunction function = new CoxFunction(stmt, Environment, false); Environment.Assign(stmt.Name, function); return(null); }
public int RequiredArguments() { CoxFunction initializer = Methods["init"]; if (initializer == null) { return(0); } return(initializer.RequiredArguments()); }
public Object Call(Interpreter interpreter, List <Object> arguments) { CoxInstance instance = new CoxInstance(this); CoxFunction initializer = Methods["init"]; if (initializer != null) { initializer.Bind(instance).Call(interpreter, arguments); } return(instance); }
public Object GetProperty(Token name) { if (Fields.ContainsKey(name.Lexeme)) { return(Fields[name.Lexeme]); } CoxFunction method = Klass.FindMethod(this, name.Lexeme); if (method != null) { return(method); } throw new RuntimeError(name, "Undefined property '" + name.Lexeme + "'."); }
public object VisitSuperExpr(Super expr) { int distance = Locals[expr]; CoxClass superclass = (CoxClass)Environment.GetAt(distance, "super"); // "this" is always one level nearer than "super"'s environment. CoxInstance receiver = (CoxInstance)Environment.GetAt(distance - 1, "this"); CoxFunction method = superclass.FindMethod(receiver, expr.Method.Lexeme); if (method == null) { throw new RuntimeError(expr.Method, $"Undefined property '{expr.Method.Lexeme}'."); } return(method); }