Пример #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 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(null);
        }