示例#1
0
        public object visitClassStmt(Stmt.Class stmt)
        {
            ClassType enclosingClass = currentClass;

            currentClass = ClassType.CLASS;

            declare(stmt.Name);
            define(stmt.Name);

            if (stmt.SuperClass != null &&
                stmt.Name.Lexeme == stmt.SuperClass.Name.Lexeme)
            {
                Lox.error(stmt.SuperClass.Name,
                          "A class cannot inherit from itself");
            }
            if (stmt.SuperClass != null)
            {
                currentClass = ClassType.SUBCLASS;
                resolve(stmt.SuperClass);
            }

            if (stmt.SuperClass != null)
            {
                beginScope();
                scopes.Peek()["super"] = true;
            }

            beginScope();
            scopes.Peek()["this"] = true;

            foreach (Stmt.Function method in stmt.Methods)
            {
                FunctionType declaration = FunctionType.METHOD;
                if (method.Name.Lexeme == "init")
                {
                    declaration = FunctionType.INITIALIZER;
                }
                resolveFunction(method, declaration);
            }

            endScope();

            if (stmt.SuperClass != null)
            {
                endScope();
            }

            currentClass = enclosingClass;
            return(null);
        }
        public object visitClassStmt(Stmt.Class stmt)
        {
            object superClass = null;

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

            env.define(stmt.Name.Lexeme, null);

            if (stmt.SuperClass != null)
            {
                env = new Envir(env);
                env.define("super", superClass);
            }

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

            foreach (Stmt.Function method in stmt.Methods)
            {
                LoxFunction function = new LoxFunction(method, env,
                                                       method.Name.Lexeme == "init");
                methods[method.Name.Lexeme] = function;
            }

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


            if (stmt.SuperClass != null)
            {
                env = env.Enclosing;
            }

            env.assign(stmt.Name, klass);
            return(null);
        }