예제 #1
0
        /// <summary>
        /// Parses the fluent function call.
        /// </summary>
        /// <returns></returns>
        public override Expr Parse()
        {
            // 1. Is it a function call?
            _tokenIt.Advance(_result.TokenCount);
            var nameExp = new VariableExpr(_result.Name);
            var exp     = _parser.ParseFuncExpression(nameExp, null);

            return(exp);
        }
예제 #2
0
        public void Interpret_VariableInContext_ReturnsVariable()
        {
            var mock     = new Mock <Context.IContext>();
            var variable = new Value(ValueTypes.Bool, true);

            mock.Setup(context => context.LookUpVariable("andriy")).Returns(variable);
            var subject = new VariableExpr("andriy");

            Assert.That(subject.Interpret(mock.Object), Is.EqualTo(variable));
        }
예제 #3
0
 public object visit_variable(VariableExpr variable_expr)
 {
     // check if the variable exists, but hasn't been assigned
     if (scopes.Count > 0 && (scopes.Peek().ContainsKey((string)variable_expr.name.value) && scopes.Peek()[(string)variable_expr.name.value] == false))
     {
         throw new RuntimeException("Cannot intialise '" + variable_expr.name + "' variable value with itself");
     }
     // Resolve the variable to the interpreter
     resolve_local_position(variable_expr, variable_expr.name);
     return(null);
 }
예제 #4
0
        static void TestParse2()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Test Multivariate Calculus:");
            Console.ForegroundColor = ConsoleColor.Gray;
            VariableExpr x = "x", y = "y";

            Console.ForegroundColor = ConsoleColor.Cyan;
            var w_input = "x^2 + 2*x*y + x/y";

            Console.WriteLine($"Input: {w_input}");
            Console.ForegroundColor = ConsoleColor.Gray;
            var w = Expr.Parse(w_input);

            Console.WriteLine($"w={w}");
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine($"vars={string.Join(",", w.GetVariables().AsEnumerable())}");
            Console.ForegroundColor = ConsoleColor.Gray;
            var wx = w.Partial(x);

            Console.WriteLine($"wx={wx}");
            var wy = w.Partial(y);

            Console.WriteLine($"wy={wy}");
            var wp = w.TotalDerivative(x, y);

            Console.WriteLine($"wp={wp}");

            var f_input = "(x^2-pi)/(x^2+pi)";

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine($"Input: {f_input}");
            Console.ForegroundColor = ConsoleColor.Gray;
            var f = Expr.Parse(f_input);

            Console.WriteLine($"f={f}");
            var fx = f["x"];

            Console.WriteLine($"f(0.5)={fx(0.5)}");
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            var df = f.Partial(x);

            Console.WriteLine($"df={df}");
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            var fp = f.TotalDerivative();

            Console.WriteLine($"fp={fp}");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine();
        }
예제 #5
0
        static void TestUnaryFunctions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Test Unary Functions:");
            Console.ForegroundColor = ConsoleColor.Gray;
            VariableExpr a = "a";
            double       x = 2 / Math.PI;
            string       fstr = $"f({x})", fpstr = $"f'({x})";

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write($"{"f",-12} ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write($"{"f'",-28} ");
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write($"{fstr,-22} ");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($"{fpstr,-28}");
            Console.WriteLine();
            foreach (var op in Enum.GetValues(typeof(UnaryOp)) as UnaryOp[])
            {
                if (op == UnaryOp.Undefined)
                {
                    continue;
                }
                if (op == UnaryOp.Sum)
                {
                    continue;
                }
                if (op == UnaryOp.Transpose)
                {
                    continue;
                }
                var f_expr = Expr.Unary(op, a);
                var dfda   = f_expr.Partial(a);
                var f      = f_expr[a];
                var fp     = dfda[a];
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write($"{f_expr,-12} ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write($"{dfda,-28:g4} ");
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.Write($"{f(x),-22:g4} ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write($"{fp(x),-28:g4}");
                Console.WriteLine();
            }
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine();
        }
예제 #6
0
        /// <summary>
        /// Evaluate
        /// </summary>
        /// <returns></returns>
        public object VisitVariable(VariableExpr expr)
        {
            // Case 1: memory variable has highest precendence
            var name = expr.Name;

            if (this.Ctx.Memory.Contains(name))
            {
                var val = this.Ctx.Memory.Get <object>(name);
                return(val);
            }
            // Case 2: check function now.
            if (expr.SymScope.IsFunction(name))
            {
            }
            throw ExceptionHelper.BuildRunTimeException(expr, "variable : " + name + " does not exist");
        }
예제 #7
0
    // Get the value from a given namespace & identifier
    public object visit_namespace_value(NamespaceValueExpr namespace_value_expr)
    {
        // Get the first namespace
        WavyNamespace next_namespace = (WavyNamespace)evaluate(namespace_value_expr.namespc);
        // The expression value of the first namespace
        Expression namespace_value = namespace_value_expr.value;

        while (namespace_value is NamespaceValueExpr)
        {
            // Get the name of the namespace in the nested namespace expression
            VariableExpr nested_namespace_name = ((VariableExpr)((NamespaceValueExpr)namespace_value).namespc);
            // Get the next namespace from the scope of the previous
            next_namespace = (WavyNamespace)next_namespace.scope.get(nested_namespace_name.name);
            // Set the namespace value to the next value
            namespace_value = ((NamespaceValueExpr)namespace_value).value;
        }
        return(next_namespace.scope.get(((VariableExpr)namespace_value).name));
    }
예제 #8
0
    private Expression unary()
    {
        while (expect(Token.Type.ConnectiveNot) || expect(Token.Type.BitwiseNot) || expect(Token.Type.Increment) || expect(Token.Type.Decrement))
        {
            // If we have an increment, we want an assign expression
            if (expect(Token.Type.Increment) || expect(Token.Type.Decrement))
            {
                Token      un_operator = consume();
                Token      op          = (un_operator.type == Token.Type.Increment) ? new Token(Token.Type.Plus, null) : new Token(Token.Type.Minus, null);
                Expression to_crement  = mul_div_mod_rem();

                // Check the type of the incrementing expression
                // If we are incrementing to a non-object variable
                if (to_crement.GetType() == typeof(VariableExpr))
                {
                    VariableExpr var = (VariableExpr)to_crement;
                    return(new AssignExpr(var.name, new BinaryExpr(to_crement, op, new LiteralExpr(1))));
                }
                // If we are incrementing a namespace value
                else if (to_crement.GetType() == typeof(NamespaceValueExpr))
                {
                    NamespaceValueExpr var = (NamespaceValueExpr)to_crement;
                    return(new AssignNamespaceExpr(var, new BinaryExpr(to_crement, op, new LiteralExpr(1))));
                }
                // If we are incrementing a member variable
                else if (to_crement.GetType() == typeof(ObjGetExpr))
                {
                    ObjGetExpr member = (ObjGetExpr)to_crement;
                    return(new ObjSetExpr(member.obj, member.identifier, new BinaryExpr(to_crement, op, new LiteralExpr(1))));
                }
                else
                {
                    throw new ParseExceptionUnexpectedToken("Increment assignment cannot be applied to " + to_crement.GetType());
                }
            }
            else
            {
                Token      op    = consume();
                Expression right = unary();
                return(new UnaryExpr(op, right));
            }
        }
        return(call());
    }
예제 #9
0
    private Expression mul_div_mod_rem()
    {
        Expression higher_precedence = unary();

        while (expect(Token.Type.Multiply) || expect(Token.Type.Divide) || expect(Token.Type.Mod) || expect(Token.Type.NoRemainder))
        {
            Token op = consume();
            // Check for compound assignment
            if (consume(Token.Type.Assignment) != null)
            {
                Expression value = unary();
                // Check the type of the higher precidence
                // If we are assigning to a non-object variable
                if (higher_precedence.GetType() == typeof(VariableExpr))
                {
                    VariableExpr var = (VariableExpr)higher_precedence;
                    return(new AssignExpr(var.name, new BinaryExpr(higher_precedence, op, value)));
                }
                // If we are assigning to a namespace value
                else if (higher_precedence.GetType() == typeof(NamespaceValueExpr))
                {
                    NamespaceValueExpr var = (NamespaceValueExpr)higher_precedence;
                    return(new AssignNamespaceExpr(var, new BinaryExpr(higher_precedence, op, value)));
                }
                // If we are assigning to a member variable
                else if (higher_precedence.GetType() == typeof(ObjGetExpr))
                {
                    ObjGetExpr member = (ObjGetExpr)higher_precedence;
                    return(new ObjSetExpr(member.obj, member.identifier, new BinaryExpr(higher_precedence, op, value)));
                }
                else
                {
                    throw new ParseExceptionUnexpectedToken("Compound assignment cannot be applied to " + higher_precedence.GetType());
                }
            }
            else
            {
                Expression right = unary();
                higher_precedence = new BinaryExpr(higher_precedence, op, right);
            }
        }
        return(higher_precedence);
    }
예제 #10
0
        public object Visit(ForStmt stmt)
        {
            LLVMValueRef func = LLVM.GetBasicBlockParent(LLVM.GetInsertBlock(_builder));

            new VarDeclarationStmt(stmt.StartVal.DataType, stmt.VarName, new List <IExpression>()
            {
            }).Accept(this);

            // Blocks
            LLVMBasicBlockRef condBB   = LLVM.AppendBasicBlock(func, "cond");
            LLVMBasicBlockRef branchBB = LLVM.AppendBasicBlock(func, "branch");
            LLVMBasicBlockRef mergeBB  = LLVM.AppendBasicBlock(func, "forcont");

            // Build condition
            LLVM.BuildBr(_builder, condBB);
            LLVM.PositionBuilderAtEnd(_builder, condBB);
            LLVMValueRef counter = new VariableExpr(stmt.VarName).Accept(this);
            LLVMValueRef maxVal  = stmt.MaxVal.Accept(this);
            LLVMValueRef incr    = stmt.Increment == null
                                ? LLVM.ConstInt(stmt.StartVal.DataType.BaseType.ToLLVMType(), 1, LLVMBoolTrue)
                                : stmt.Increment.Accept(this);

            LLVMValueRef condition = LLVM.BuildICmp(_builder, LLVMIntPredicate.LLVMIntSLT, counter, maxVal, "tmpcmp");

            LLVM.BuildCondBr(_builder, condition, branchBB, mergeBB);

            // branch
            LLVM.PositionBuilderAtEnd(_builder, branchBB); // Position builder at block
            stmt.Branch.Accept(this);                      // Generate branch code

            // Increment counter
            LLVMValueRef newVal = LLVM.BuildAdd(_builder, counter, incr, "tmpadd");

            LLVM.BuildStore(_builder, newVal, _namedValues[stmt.VarName.Lexeme].ValueRef);

            LLVM.BuildBr(_builder, condBB);

            LLVM.PositionBuilderAtEnd(_builder, mergeBB);

            return(null);
        }
예제 #11
0
 private Expression unary()
 {
     while (expect(Token.Type.ConnectiveNot) || expect(Token.Type.BitwiseNot) || expect(Token.Type.Increment) || expect(Token.Type.Decrement))
     {
         // If we have an increment, we want an assign expression
         if (expect(Token.Type.Increment) || expect(Token.Type.Decrement))
         {
             Token        un_operator = consume();
             Token        op          = (un_operator.type == Token.Type.Increment) ? new Token(Token.Type.Plus, null) : new Token(Token.Type.Minus, null);
             VariableExpr identifier  = (VariableExpr)unary();
             return(new AssignExpr(identifier.name, new BinaryExpr(identifier, op, new LiteralExpr(1))));
         }
         else
         {
             Token      op    = consume();
             Expression right = unary();
             return(new UnaryExpr(op, right));
         }
     }
     return(call());
 }
예제 #12
0
        public DataType Visit(VariableExpr expr)
        {
            Tuple <DataType, bool> info = _scope.Get(expr.Name.Lexeme);
            DataType dataType           = info.Item1;

            if (expr.ArrayIndexes != null)
            {
                foreach (IExpression arrIndex in expr.ArrayIndexes)
                {
                    arrIndex.Accept(this);
                }
            }

            //dataType.ArrayDepth = dataType.ArrayDepth - expr.ArrayIndexes.Count; // Adjust depth after accounting for indexing.
            expr.Name.DataType = dataType;
            expr.IsArgumentVar = info.Item2;

            expr.DataType = dataType;

            return(ArrayIndexesOrDefault(expr.ArrayIndexes, dataType));
        }
예제 #13
0
    public void visit_using(UsingStmt using_stmt)
    {
        // NOTE: This code is literally the same as 'visit_namespace_value', & thus should be optimised
        // Get the first namespace
        WavyNamespace next_namespace = (WavyNamespace)evaluate(using_stmt._namespace);
        // The expression value of the first namespace
        Expression namespace_value = using_stmt._namespace;

        while (namespace_value is NamespaceValueExpr)
        {
            // Get the name of the namespace in the nested namespace expression
            VariableExpr nested_namespace_name = ((VariableExpr)((NamespaceValueExpr)namespace_value).namespc);
            // Get the next namespace from the scope of the previous
            next_namespace = (WavyNamespace)next_namespace.scope.get(nested_namespace_name.name);
            // Set the namespace value to the next value
            namespace_value = ((NamespaceValueExpr)namespace_value).value;
        }
        // Finally, set the using namespace scope to the final NamespaceValueExpr value, which is a namespace name in VariableExpr form
        this.using_namespace = ((WavyNamespace)(next_namespace.scope.get(((VariableExpr)namespace_value).name))).scope;
        Console.WriteLine("done using!");
    }
예제 #14
0
        static void TestBinaryFunctions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Test Binary Functions:");
            Console.ForegroundColor = ConsoleColor.Gray;
            VariableExpr a = "a", b = "b";
            double       x = 5, y = 2;
            string       fstr = $"f({x},{y})", fpstr = $"f'({x},{y})";

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write($"{"f",-12} ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write($"{"f'",-28} ");
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write($"{fstr,-22} ");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($"{fpstr,-28}");
            Console.WriteLine();
            foreach (var op in Enum.GetValues(typeof(BinaryOp)) as BinaryOp[])
            {
                if (op == BinaryOp.Undefined)
                {
                    continue;
                }
                var f_expr = Expr.Binary(op, a, b);
                var dfda   = f_expr.Partial(a);
                var f      = f_expr[a, b];
                var fp     = dfda[a, b];
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write($"{f_expr,-12} ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write($"{dfda,-28:g4} ");
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.Write($"{f(x,y),-22:g4} ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write($"{fp(x,y),-28:g4}");
                Console.WriteLine();
            }
            Console.WriteLine();
        }
예제 #15
0
        public LLVMValueRef Visit(VariableExpr expr)
        {
            NamedValue   namedValue = _namedValues[expr.Name.Lexeme];
            LLVMValueRef valueRef   = namedValue.ValueRef;

            if (expr.ArrayIndexes != null && expr.ArrayIndexes.Count > 0)
            {
                //var indices = new LLVMValueRef[] {
                valueRef = GetArrayItem(valueRef, namedValue.ArrayDepth, expr.ArrayIndexes);
                //};
                //valueRef = LLVM.BuildGEP(_builder, valueRef, indices, "geptmp");
            }

            if (!expr.IsArgumentVar)
            {
                valueRef = LLVM.BuildLoad(_builder, valueRef, "l" + expr.Name.Lexeme);
            }

            valueRef = CastIfNeeded(valueRef, expr.Cast);

            return(valueRef);
        }
예제 #16
0
    // When assigning to a value in a specific namespace
    public object visit_namespace_assign(AssignNamespaceExpr assign_namespace_expr)
    {
        // NOTE: This code is literally the same as 'visit_namespace_value', & thus should be optimised
        // Get the first namespace
        WavyNamespace next_namespace = (WavyNamespace)evaluate(assign_namespace_expr.identifier.namespc);
        // The expression value of the first namespace
        Expression namespace_value = assign_namespace_expr.identifier.value;

        while (namespace_value is NamespaceValueExpr)
        {
            // Get the name of the namespace in the nested namespace expression
            VariableExpr nested_namespace_name = ((VariableExpr)((NamespaceValueExpr)namespace_value).namespc);
            // Get the next namespace from the scope of the previous
            next_namespace = (WavyNamespace)next_namespace.scope.get(nested_namespace_name.name);
            // Set the namespace value to the next value
            namespace_value = ((NamespaceValueExpr)namespace_value).value;
        }
        object value = evaluate(assign_namespace_expr.value);

        // Assign the value to the evaluated expression value
        next_namespace.scope.assign(((VariableExpr)namespace_value).name, value);
        return(value);
    }
예제 #17
0
파일: Resolver.cs 프로젝트: sula0/Lox
        protected override object MatchVariableExpr(VariableExpr expr)
        {
            if (_scopes.Count != 0)
            {
                var scope = _scopes.Peek();

                bool?initialized = null;

                if (scope.TryGetValue(expr.Name.Lexeme, out var temp))
                {
                    initialized = temp;
                }

                if (initialized == false)
                {
                    Lox.Error(expr.Name, "Cannot read local variable in its own initializer.");
                }
            }

            ResolveLocal(expr, expr.Name);

            return(null);
        }
예제 #18
0
파일: Parser.cs 프로젝트: kongyt/AtomScript
        private ClassDeclarationStmt MatchClassDeclaration()
        {
            Token name = Consume(TokenType.IDENTIFIER, "Expect class name.");

            VariableExpr superclass = null;

            if (Match(TokenType.COLON))
            {
                Consume(TokenType.IDENTIFIER, "Expect superclass name.");
                superclass = new VariableExpr(ReadPrevToken());
            }

            Consume(TokenType.LEFT_BRACE, "Expect '{' before class body.");

            List <FuncDeclarationStmt> methods = new List <FuncDeclarationStmt>();

            while (Match(TokenType.FUNC))
            {
                methods.Add(MatchFuncDeclaration("method"));
            }
            Consume(TokenType.RIGHT_BRACE, "Expect '}' after class body.");

            return(new ClassDeclarationStmt(name, superclass, methods));
        }
예제 #19
0
        public void Can_Validate_Variable_Does_Not_Exist()
        {
            var symScope = new Symbols();

            symScope.DefineVariable("result");

            var semacts = new SemActs();
            var a       = new VariableExpr("a");

            a.Ref      = new ScriptRef("", 1, 1);
            a.SymScope = symScope.Current;

            var zero = new ConstantExpr(2);

            zero.Ref      = new ScriptRef("", 1, 5);
            zero.SymScope = symScope.Current;

            var divExpr = new BinaryExpr(a, Operator.Divide, zero);

            divExpr.SymScope = symScope.Current;

            var assignExpr = new AssignExpr(true, new VariableExpr("result"), divExpr);

            assignExpr.SymScope = symScope.Current;
            var stmts = new List <Expr>();

            stmts.Add(assignExpr);

            var success = semacts.Validate(stmts);
            var results = semacts.Results;

            Assert.IsFalse(success);
            Assert.IsFalse(results.Success);
            Assert.IsTrue(results.HasResults);
            Assert.AreEqual(results.Results.Count, 1);
        }
예제 #20
0
        static void TestParse3()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Test Kinematics:");
            Console.ForegroundColor = ConsoleColor.Gray;
            VariableExpr q = "q", r = "r";
            VariableExpr qp = q.Rate(), rp = r.Rate();
            VariableExpr qpp = qp.Rate(), rpp = rp.Rate();

            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine($"Variables: {string.Join(", ", q, r)}");
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine($"Rates: {string.Join(", ", qp, rp)}");
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine($"Accelerations: {string.Join(", ", qpp, rpp)}");

            Expr pos = Expr.FromArray(r * Expr.Sin(q), -r * Expr.Cos(q));

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"pos = {pos}");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Expr vel = pos.TotalDerivative();

            Console.WriteLine($"vel = {vel}");
            Console.ForegroundColor = ConsoleColor.Blue;
            Expr J = vel.Jacobian(rp, qp);

            Console.WriteLine($"jacobian = {J}");

            Console.ForegroundColor = ConsoleColor.Green;
            Expr acc = vel.TotalDerivative();

            Console.WriteLine($"acc = {acc}");

            Console.WriteLine();
        }
예제 #21
0
 public object VisitVariable(VariableExpr expr)
 {
     return(null);
 }
예제 #22
0
 public override void Visit(VariableExpr expr)
 {
     _referencedVariables.Add(expr.Name);
 }
예제 #23
0
        /// <summary>
        /// 1. var name;
        /// 2. var age = 21;
        /// 3. canDrink = age >= 21;
        /// 4. canVote = CanVote(age);
        /// </summary>
        /// <returns></returns>
        public Expr ParseAssignment(bool expectVar, bool expectId = true, Expr varExp = null)
        {
            string name = null;

            if (expectVar)
            {
                _tokenIt.Expect(Tokens.Var);
            }
            if (expectId)
            {
                name   = _tokenIt.ExpectId();
                varExp = new VariableExpr(name);
            }

            // Case 1: var name;
            if (_tokenIt.IsEndOfStmtOrBlock())
            {
                return(new AssignExpr(expectVar, varExp, null));
            }

            // Case 2: var name = <expression>
            Expr valueExp = null;

            if (_tokenIt.NextToken.Token == Tokens.Assignment)
            {
                _tokenIt.Advance();
                valueExp = _parser.ParseExpression(Terminators.ExpVarDeclarationEnd, passNewLine: false);
                //if (valueExp is MemberAccessExpr)
                //    ((MemberAccessExpr)valueExp).IsAssignment = true;
            }
            // ; ? only 1 declaration / initialization.
            if (_tokenIt.IsEndOfStmtOrBlock())
            {
                return new AssignExpr(expectVar, varExp, valueExp)
                       {
                           Ctx = Ctx
                       }
            }
            ;

            // Multiple
            // Example 1: var a,b,c;
            // Example 2: var a = 1, b = 2, c = 3;
            _tokenIt.Expect(Tokens.Comma);
            var declarations = new List <Tuple <Expr, Expr> >();

            declarations.Add(new Tuple <Expr, Expr>(varExp, valueExp));

            while (true)
            {
                // Reset to null.
                varExp = null; valueExp = null;
                name   = _tokenIt.ExpectId();
                varExp = new VariableExpr(name);

                // , or expression?
                if (_tokenIt.NextToken.Token == Tokens.Assignment)
                {
                    _tokenIt.Advance();
                    valueExp = _parser.ParseExpression(Terminators.ExpVarDeclarationEnd, passNewLine: false);
                }
                // Add to list
                declarations.Add(new Tuple <Expr, Expr>(varExp, valueExp));

                if (_tokenIt.IsEndOfStmtOrBlock())
                {
                    break;
                }

                _tokenIt.Expect(Tokens.Comma);
            }
            return(new AssignExpr(expectVar, declarations));
        }
 public object visit_variable(VariableExpr variable_expr)
 {
     return(lookup_variable(variable_expr.name, variable_expr));
 }
예제 #25
0
 public virtual void Visit(VariableExpr expr)
 {
 }
예제 #26
0
 public NamespaceValueExpr(VariableExpr namespc, Token identifier)
 {
     this.namespc    = namespc;
     this.identifier = identifier;
 }
예제 #27
0
        static void TestCubicSpline()
        {
            const int colWidth = 12;

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Cubic Spline:");
            Console.ForegroundColor = ConsoleColor.Gray;
            VariableExpr a = "a";

            var xi  = new double[] { 0, 2 };
            var yi  = new double[] { 1, 7 };
            var ypi = new double[] { 0, 0 };
            var h   = xi[1] - xi[0];

            Console.WriteLine("Given Boundary Conditions:");
            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.Write($"{"x",-colWidth} ");
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.Write($"{"y",-colWidth} ");
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.Write($"{"yp",-colWidth} ");
            Console.WriteLine();
            for (int i = 0; i < xi.Length; i++)
            {
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                Console.Write($"{xi[i],-colWidth:g4} ");
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.Write($"{yi[i],-colWidth:g4} ");
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.Write($"{ypi[i],-colWidth:g4} ");
                Console.WriteLine();
            }
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("Calculated Interpolation:");
            Expr ξ     = a / h;
            var  basis = Expr.FromArray(
                ((1 - ξ) ^ 2) * (2 * ξ + 1),
                (ξ ^ 2) * (3 - 2 * ξ),
                h * ξ * ((1 - ξ) ^ 2),
                h * (ξ ^ 2) * (ξ - 1));
            var coef = new Expr[] { yi[0], yi[1], ypi[0], ypi[1] };

            Expr y_expr = Expr.Dot(basis, coef);

            Console.WriteLine($"y={y_expr}");
            var  y_fun   = y_expr["a"];
            Expr dy_expr = y_expr.Partial("a");

            Console.WriteLine($"yp={dy_expr}");
            var dy_fun = dy_expr["a"];

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write($"{"x",-colWidth} ");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write($"{"y",-colWidth} ");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($"{"yp",-colWidth} ");
            Console.WriteLine();
            for (int i = 0; i < 12; i++)
            {
                double t  = (double)i / 11;
                double x  = (1 - t) * xi[0] + t * xi[1];
                double y  = y_fun(x);
                double yp = dy_fun(x);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write($"{x,-colWidth:g4} ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write($"{y,-colWidth:g4} ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write($"{yp,-colWidth:g4} ");
                Console.WriteLine();
            }
            Console.ForegroundColor = ConsoleColor.Gray;
        }
예제 #28
0
파일: Matcher.cs 프로젝트: sula0/Lox
 protected abstract object MatchVariableExpr(VariableExpr variableExpr);
예제 #29
0
        /// <summary>
        /// run step 123.
        /// </summary>
        /// <returns></returns>
        public override Expr Parse()
        {
            var startToken = _tokenIt.NextToken;

            _tokenIt.ExpectIdText("repeat");
            Expr     varname  = null;
            Expr     startVal = null;
            Expr     endVal   = null;
            Expr     incVal   = null;
            Operator op       = Operator.LessThanEqual;

            // Case 1: repeat to 10
            if (_tokenIt.NextToken.Token.Text == "to")
            {
                var result = ParseTo();
                startVal = new ConstantExpr(1.0);
                _parser.SetScriptPosition(startVal, startToken);
                op     = result.Item1;
                endVal = result.Item2;
                incVal = result.Item3;
            }
            // Case 2: repeat 1 to 10
            else if (_tokenIt.NextToken.Token.Kind == TokenKind.LiteralNumber)
            {
                var num    = _tokenIt.ExpectNumber();
                var result = ParseTo();
                startVal = new ConstantExpr(num);
                _parser.SetScriptPosition(startVal, startToken);
                op     = result.Item1;
                endVal = result.Item2;
                incVal = result.Item3;
            }
            // Case 3: repeat ndx to 10
            else if (_tokenIt.NextToken.Token.Kind == TokenKind.Ident)
            {
                var variableName = _tokenIt.ExpectId();
                varname = new VariableExpr(variableName);
                _parser.SetScriptPosition(varname, startToken);
                if (_tokenIt.NextToken.Token.Type == TokenTypes.Assignment)
                {
                    _tokenIt.Advance();

                    // Upto "to"
                    startVal = ParseExpr(_terminatorForTo);
                }
                else
                {
                    startVal = new ConstantExpr(0);
                    _parser.SetScriptPosition(startVal, startToken);
                }
                var result = ParseTo();
                op     = result.Item1;
                endVal = result.Item2;
                incVal = result.Item3;
            }
            // auto-create variable name.
            if (varname == null)
            {
                varname = new VariableExpr("it");
                _parser.SetScriptPosition(varname, startToken);
            }

            // Now setup the stmts
            var ctx       = _parser.Context;
            var startStmt = new AssignExpr(true, varname, startVal);

            _parser.SetScriptPositionFromNode(startStmt, varname);
            startStmt.Ctx = ctx;

            var condition = new CompareExpr(varname, op, endVal);

            _parser.SetScriptPositionFromNode(condition, endVal);
            varname.Ctx   = ctx;
            condition.Ctx = ctx;

            var incExp = new UnaryExpr(varname.ToQualifiedName(), incVal, Operator.PlusEqual, _parser.Context);

            _parser.SetScriptPositionFromNode(incExp, incVal);
            var incStmt = new AssignExpr(false, new VariableExpr(varname.ToQualifiedName()), incExp);

            _parser.SetScriptPositionFromNode(incStmt, incExp);
            incStmt.Ctx = ctx;

            var loopStmt = new ForExpr(startStmt, condition, incStmt);

            ParseBlock(loopStmt);
            return(loopStmt);
        }
예제 #30
0
 public ClassDeclarationStmt(Token name, VariableExpr superclass, List <FuncDeclarationStmt> methods)
 {
     this.name       = name;
     this.superclass = superclass;
     this.methods    = methods;
 }