Beispiel #1
0
        public MyVoid VisitFunctionStmt(Stmt.Function stmt)
        {
            // Capture the environment when the function is declared, for closures
            LoxFunction function = new LoxFunction(stmt, environment, isInitializer: false);

            environment.Define(stmt.name.lexeme, function);
            return(null);
        }
        public int Arity()
        {
            LoxFunction initializer = FindMethod("init");

            if (initializer == null)
            {
                return(0);
            }
            return(initializer.Arity());
        }
        public object Call(Interpreter interpreter, List <object> arguments)
        {
            LoxInstance instance    = new LoxInstance(this);
            LoxFunction initializer = FindMethod("init");

            if (initializer != null)
            {
                initializer.bind(instance).call(intepreter, arguments);
            }

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

            return(instance);
        }
Beispiel #4
0
        //Get property, given some token on this particular instance
        public object Get(Token name)
        {
            if (fields.TryGetValue(name.lexeme, out object value))
            {
                return(value);
            }

            LoxFunction method = klass.FindMethod(name.lexeme);

            if (method != null)
            {
                return(method.Bind(this));
            }

            //If instance doesn't have property, it's an error
            throw new RuntimeError(name, $"Undefined property '{name.lexeme}'");
        }
Beispiel #5
0
        public MyVoid VisitClassStmt(Stmt.Class stmt)
        {
            environment.Define(stmt.name.lexeme, null);

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

            foreach (Stmt.Function method in stmt.methods)
            {
                LoxFunction function = new LoxFunction(method, environment, isInitializer: method.name.lexeme == "init");
                methods[method.name.lexeme] = function;
            }

            LoxClass klass = new LoxClass(stmt.name.lexeme, methods);

            environment.Assign(stmt.name, new LoxClass(stmt.name.lexeme, methods));
            return(null);
        }