예제 #1
0
        public object VisitClassStmt(Stmt.Class stmt)
        {
            environment.Define(stmt.Name.lexeme, null);
            object superclass = null;

            if (stmt.Superclass != null)
            {
                superclass = Evaluate(stmt.Superclass);
                if (!(superclass is BasilClass))
                {
                    throw new RuntimeError(stmt.Name, "Superclass must be a class.");
                }
                environment = new Environment(environment);
                environment.Define("super", superclass);
            }
            Dictionary <string, BasilFunction> methods = new Dictionary <string, BasilFunction>();

            foreach (var method in stmt.Methods)
            {
                BasilFunction function = new BasilFunction(method, environment, method.name.lexeme.Equals("init"));
                methods.Add(method.name.lexeme, function);
            }
            BasilClass klass = new BasilClass(stmt.Name.lexeme, (BasilClass)superclass, methods);

            if (superclass != null)
            {
                environment = environment.Enclosing;
            }
            environment.Assign(stmt.Name, klass);
            return(null);
        }
예제 #2
0
        public object VisitSuperExpr(Expr.Super expr)
        {
            int        distance   = locals[expr];
            BasilClass superclass = (BasilClass)environment.GetAt(distance, "super");
            // "this" is always one level nearer than "super"'s environment.
            BasilInstance objekt = (BasilInstance)environment.GetAt(distance - 1, "this");
            BasilFunction method = superclass.FindMethod(objekt, expr.Method.lexeme);

            if (method == null)
            {
                throw new RuntimeError(expr.Method, $"Undefined property '{expr.Method.lexeme}'.");
            }
            return(method);
        }
예제 #3
0
 public BasilInstance(BasilClass klass)
 {
     this.klass = klass;
 }
예제 #4
0
 public BasilClass(string name, BasilClass superclass, Dictionary <string, BasilFunction> methods)
 {
     Name            = name;
     this.superclass = superclass;
     this.methods    = methods;
 }