Esempio n. 1
0
        public Nothing VisitFunctionStmt(Stmt.Function stmt)
        {
            LoxFunction function = new LoxFunction(stmt, environment, false);

            environment.Define(stmt.Name.Lexeme, function);

            return(Nothing.AtAll);
        }
Esempio n. 2
0
        public object VisitSuperExpr(Expr.Super expr)
        {
            int      distance   = locals[expr];
            LoxClass superclass = (LoxClass)environment.GetAt(distance, "super");
            // "this" is always one level nearer than "super"'s environment.
            LoxInstance objekt = (LoxInstance)environment.GetAt(distance - 1, "this");
            LoxFunction method = superclass.FindMethod(objekt, expr.Method.Lexeme);

            if (method == null)
            {
                throw new RuntimeError(expr.Method, $"Undefined property '{expr.Method.Lexeme}'.");
            }

            return(method);
        }
Esempio n. 3
0
        public object Get(Token name)
        {
            if (fields.ContainsKey(name.Lexeme))
            {
                return(fields[name.Lexeme]);
            }

            LoxFunction method = loxClass.FindMethod(this, name.Lexeme);

            if (method != null)
            {
                return(method);
            }

            throw new RuntimeError(name, $"Undefined property '{name.Lexeme}'.");
        }
Esempio n. 4
0
        public Nothing VisitClassStmt(Stmt.Class stmt)
        {
            environment.Define(stmt.Name.Lexeme, null);
            object superclass = null;

            if (stmt.Superclass != null)
            {
                superclass = Evaluate(stmt.Superclass);
                if (!(superclass is LoxClass))
                {
                    throw new RuntimeError(stmt.Name, "Superclass must be a class.");
                }

                environment = new Environment(environment);
                environment.Define("super", superclass);
            }

            Dictionary <string, LoxFunction> methods = new Dictionary <string, LoxFunction>();

            foreach (var method in stmt.Methods)
            {
                LoxFunction function = new LoxFunction(method, environment, method.Name.Lexeme.Equals("init"));
                methods.Add(method.Name.Lexeme, function);
            }

            LoxClass klass = new LoxClass(stmt.Name.Lexeme, (LoxClass)superclass, methods);

            if (superclass != null)
            {
                environment = environment.Enclosing;
            }

            environment.Assign(stmt.Name, klass);

            return(Nothing.AtAll);
        }