Esempio n. 1
0
        public object Call(Interpreter interpreter, List <object> arguments)
        {
            LoxEnvironment environment = new LoxEnvironment(closure);

            for (int i = 0; i < declaration.Params.Count; i++)
            {
                environment.Define(declaration.Params[i].Lexeme, arguments[i]);
            }

            try
            {
                interpreter.ExecuteBlock(declaration.Body, environment);
            }
            catch (ReturnException returnValue)
            {
                if (isInitializer)
                {
                    return(closure.GetAt(0, "this"));
                }

                return(returnValue.Value);
            }

            if (isInitializer)
            {
                return(closure.GetAt(0, "this"));
            }

            return(null);
        }
Esempio n. 2
0
        public LoxFunction Bind(LoxInstance instance)
        {
            LoxEnvironment environment = new LoxEnvironment(closure);

            environment.Define("this", instance);

            return(new LoxFunction(declaration, environment, isInitializer));
        }
Esempio n. 3
0
        public object VisitClassStmt(Class stmt)
        {
            object superclass = null;

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

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

            if (stmt.Superclass != null)
            {
                environment = new LoxEnvironment(environment);
                environment.Define("super", superclass);
            }

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

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

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

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

            environment.Assign(stmt.Name, @class);

            return(null);
        }
Esempio n. 4
0
 public Interpreter()
 {
     Globals.Define("clock", new Clock());
     Globals.Define("power", new Power());
     environment = Globals;
 }