public LoxFunction Bind(LoxInstance instance)
        {
            VariableEnvironment environment = new VariableEnvironment(closure);

            environment.Define("this", instance);
            return(new LoxFunction(declaration, environment, isInitializer));
        }
        public object Call(Interpreter interpreter, List <object> arguments)
        {
            VariableEnvironment environment = new VariableEnvironment(closure);

            for (int i = 0; i < declaration.parameters.Count; i++)
            {
                environment.Define(declaration.parameters[i].lexeme, arguments[i]);
            }
            try
            {
                interpreter.ExecuteBlock(declaration.body, environment);
            }
            catch (Return returnValue)
            {
                // Allow an empty return ("return;") in a constructor. When this happens, return "this".
                if (isInitializer)
                {
                    return(closure.GetAt(0, "this"));
                }

                return(returnValue.value);
            }

            return(null);
        }
Esempio n. 3
0
        public Interpreter()
        {
            this.globals     = new VariableEnvironment();
            this.environment = globals;

            //Define built-in function to get the time in milliseconds
            globals.Define("clock", new ClockFn());
        }
        VariableEnvironment Ancestor(int distance)
        {
            VariableEnvironment environment = this;

            for (int i = 0; i < distance; i++)
            {
                environment = environment.enclosing;
            }

            return(environment);
        }
Esempio n. 5
0
        public void ExecuteBlock(List <Stmt> statements, VariableEnvironment environment)
        {
            //save the last environment (to be restored later)
            VariableEnvironment previous = this.environment;

            try
            {
                //change environment to the given one, and execute statments with this new environment
                this.environment = environment;
                foreach (Stmt statement in statements)
                {
                    Execute(statement);
                }
            }
            finally
            {
                //even if there's an exception, we need to restore the last environment before continuing
                this.environment = previous;
            }
        }
 public VariableEnvironment(VariableEnvironment enclosing)
 {
     this.enclosing = enclosing;
 }
 public VariableEnvironment()
 {
     enclosing = null;
 }
 public LoxFunction(Stmt.Function declaration, VariableEnvironment closure, Boolean isInitializer)
 {
     this.closure       = closure;
     this.declaration   = declaration;
     this.isInitializer = isInitializer;
 }