示例#1
0
        public Nothing VisitClassStmt(Stmt.Class stmt)
        {
            Declare(stmt.Name);
            Define(stmt.Name);
            ClassType enclosingClass = currentClass;

            currentClass = ClassType.Class;
            if (stmt.Superclass != null)
            {
                currentClass = ClassType.Subclass;
                Resolve(stmt.Superclass);
                BeginScope();
                scopes.Peek().Add("super", true);
            }
            BeginScope();
            scopes.Peek().Add("this", true);
            foreach (var method in stmt.Methods)
            {
                FunctionType declaration = FunctionType.Method;
                if (method.Name.Lexeme.Equals("init"))
                {
                    declaration = FunctionType.Initializer;
                }
                ResolveFunction(method, declaration);
            }

            EndScope();
            if (stmt.Superclass != null)
            {
                EndScope();
            }
            currentClass = enclosingClass;
            return(Nothing.AtAll);
        }
示例#2
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);
        }