Exemple #1
0
        public object VisitAssignExpr(Assign expr)
        {
            object value = Evaluate(expr.Value);

            if (locals.TryGetValue(expr, out int distance))
            {
                environment.AssignAt(distance, expr.Name, value);
            }
            else
            {
                Globals.Assign(expr.Name, value);
            }

            return(value);
        }
Exemple #2
0
        public void Assign(Token name, object value)
        {
            if (values.ContainsKey(name.Lexeme))
            {
                values[name.Lexeme] = value;

                return;
            }

            if (Enclosing != null)
            {
                Enclosing.Assign(name, value);

                return;
            }

            throw new RuntimeException(name, $"Undefined variable '{name.Lexeme}'.");
        }
Exemple #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);
        }