Пример #1
0
        public object Visit(Expr.Assign expr)
        {
            object value = Evaluate(expr.value);

            int?distance = _locals.Get(expr);

            if (distance != null)
            {
                _environment.AssignAt(distance.Value, expr.Name, value);
            }
            else
            {
                _globals.Assign(expr.Name, value);
            }


            return(value);
        }
Пример #2
0
        public object Visit(Stmt.Class stmt)
        {
            _environment.Define(stmt.Name.Lexeme, null);

            // Superclass
            object superclass = null;

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

                _environment = new LoxEnvironment(_environment);
                _environment.Define("super", superclass);
            }


            // Methods
            HashMap <string, LoxFunction> methods = new HashMap <string, LoxFunction>();

            foreach (Stmt.Function method in stmt.Methods)
            {
                LoxFunction function = new LoxFunction(method, _environment, method.Name.Lexeme.Equals("init"));
                methods.Put(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);
        }