Ejemplo n.º 1
0
        public dynamic Visit(UnaryExpr expr)
        {
            var node = Visit((ExpressionBase)expr);

            node.Text = expr.Type.ToString();
            return(node);
        }
    public object visit_unary(UnaryExpr unary_expr)
    {
        object right = evaluate(unary_expr.right);

        switch (unary_expr.op.type)
        {
        case Token.Type.ConnectiveNot:
        {
            return(!get_truth(right));
        }

        case Token.Type.BitwiseNot:
        {
            return(!get_truth(right));
        }

        case Token.Type.Increment:
        {
            // This needs fixing as we actually need to assign the value
            return((double)right + 1);
        }

        case Token.Type.Decrement:
        {
            // This needs fixing as we actually need to assign the value
            return((double)right - 1);
        }
        }
        return(null);
    }
Ejemplo n.º 3
0
        public Word Visit(UnaryExpr unaryExpr)
        {
            var result = unaryExpr.RightExpr.Accept(this);

            if (IsError(result))
            {
                return(result);
            }
            PyObj pyObj;

            if (IsMemoryBlock(result))//comentar ese if else si se hace la desereferencia en atomic expr.
            {
                pyObj = ((MemoryBlock)result).Value;
            }
            else
            {
                pyObj = (PyObj)result;
            }
            //pyObj = (PyObj)result;//Descomentar esta linea si se hace la desereferencia en atomic expr.
            result = pyObj.UnaryOperation(unaryExpr.UnaryOperator);
            if (IsError(result))
            {
                return(ErrorFactory.Create(unaryExpr, (MyError)result));
            }
            return((PyObj)result);
        }
Ejemplo n.º 4
0
        public void TestNotExpr()
        {
            // not (1 > 2)
            var programSource = new TokenList()
            {
                { TokenType.Identifier, "x" },
                { TokenType.OpAssignment },
                { TokenType.OpNot },
                { TokenType.LParen },
                { TokenType.IntLiteral, "1" },
                { TokenType.OpMore },
                { TokenType.IntLiteral, "2" },
                { TokenType.RParen }
            };
            Parser      parser  = new Parser(CreateMockScanner(programSource), new ErrorHandler());
            ProgramNode program = parser.Parse();

            var comp = new BinaryExpr(0, 0);

            comp.Left  = new IntLiteralExpr(0, 0, 1);
            comp.Right = new IntLiteralExpr(0, 0, 2);
            comp.Op    = Operator.More;
            var unary = new UnaryExpr(0, 0);

            unary.Op   = Operator.Not;
            unary.Expr = comp;
            var assignment = new AssignmentStmt(0, 0);

            assignment.AssignmentExpr = unary;
            assignment.Variable       = new VariableExpr(0, 0, "x");
            expected.Block.Statements.Add(assignment);
            program.ShouldBeEquivalentTo(expected);
        }
        // parse
        private string Parse()
        {
            foreach (string token in Tokens)
            {
                if (IsNumber(token))
                {
                    Stack.Push(new Number(token));
                }
                else if (token == "X")
                {
                    Stack.Push(new Number(token));
                }
                else if (IsUnary(token))
                {
                    Stack.Push(UnaryExpr.Create(Stack, token));
                }
                else
                {
                    Stack.Push(BinExpr.Create(Stack, token));
                }
            }

            StringBuilder sb = new StringBuilder();

            Stack.Pop().Write(sb);
            return(sb.ToString());
        }
Ejemplo n.º 6
0
        public static LString IncrementString(UnaryExpr expr, LString sourceVal, IAstVisitor visitor)
        {
            // Check 1: Can only do += on strings.
            if (expr.Op != Operator.PlusEqual)
            {
                throw new LangException("Syntax Error", "string operation with " + expr.Op.ToString() + " not supported", expr.Ref.ScriptName, expr.Ref.Line, expr.Ref.CharPos);
            }

            //expr.DataType = typeof(string);
            var val = expr.Expression.Evaluate(visitor) as LObject;

            // Check 2: Check for null
            if (val == LObjects.Null)
            {
                return(sourceVal);
            }

            // Check 3: Limit size if string
            Ctx.Limits.CheckStringLength(expr, sourceVal.Value, val.GetValue().ToString());

            // Finally do the appending.
            var appended = sourceVal.Value + val.GetValue().ToString();

            sourceVal.Value = appended;
            expr.Ctx.Memory.SetValue(expr.Name, sourceVal);
            return(sourceVal);
        }
Ejemplo n.º 7
0
 public Filter BuildFilter()
 {
     if (tokens.Count == 0)
     {
         return(new True());
     }
     if (tokens.Count == 1)
     {
         if (tokens[0] is Expression)
         {
             return((tokens[0] as Expression).BuildFilter());
         }
         else if (tokens[0] is TokenVal)
         {
             return(Checker.Create((tokens[0] as TokenVal).Val));
         }
         throw new FormatException($"语法错误'{tokens[0]}'");
     }
     if (tokens[1] is TokenLogical)
     {
         List <Tuple <LogicalOperator, Filter> > list = new List <Tuple <LogicalOperator, Filter> >();
         LogicalOperator op = LogicalOperator.And;
         for (int i = 0; i < tokens.Count; i++)
         {
             list.Add(new Tuple <LogicalOperator, Filter>(op, (tokens[i] as Expression).BuildFilter()));
             i++;
             if (i < tokens.Count)
             {
                 op = (tokens[i] as TokenLogical).Operator;
             }
         }
         return(new Logic(list));
     }
     if (tokens[1] is TokenCompare)
     {
         if (tokens.Count < 3)
         {
             throw new FormatException($"表达式不完整!");
         }
         if (tokens.Count > 3)
         {
             throw new FormatException($"语法错误'{tokens[3]}'");
         }
         return(Checker.Create((tokens[0] as TokenVal).Val, (tokens[1] as TokenCompare).Operator, (tokens[2] as TokenVal).Val));
     }
     if (tokens[0] is TokenUnary)
     {
         if (tokens.Count == 2 && tokens[1] is Expression)
         {
             return(UnaryExpr.Create((tokens[0] as TokenUnary).Operator, (tokens[1] as Expression).BuildFilter()));
         }
         if (tokens.Count == 3 && tokens[1] is TokenVal && tokens[2] is Expression)
         {
             return(UnaryExpr.Create((tokens[0] as TokenUnary).Operator, (tokens[2] as Expression).BuildFilter(), (tokens[1] as TokenVal).Val));
         }
         throw new FormatException($"错误的用法'{tokens[0]}'");
     }
     throw new FormatException($"语法错误'{tokens[0]}'");
 }
Ejemplo n.º 8
0
        public string Visit(UnaryExpr node)
        {
            var exp = Visit(node.exp);
            var ret = method.Add_local("expr", true);

            method.Add_Instruction(new CIL_UnaryExpr(ret, node.op, exp));
            return(ret);
        }
 public dynamic Visit(UnaryExpr expr)
 {
     if (expr.FirstType != SymbolType.Double && expr.FirstType != SymbolType.Integer)
     {
         throw new ParseException(
                   $"Невозможно произвести операцию между типами {expr.FirstType} и {expr.SecondType}",
                   expr.Node);
     }
     return(expr.FirstType == SymbolType.Double ? SymbolType.Double : SymbolType.Integer);
 }
Ejemplo n.º 10
0
        private void Unary(Memory memory, string left, double inc, Operator op, double expected)
        {
            var ctx = new Context();

            ctx.Memory = memory;
            var exp = new UnaryExpr(left, inc, op, ctx);

            Assert.AreEqual(expected, exp.EvaluateAs <double>());
            Assert.AreEqual(expected, memory.GetAs <LNumber>(left).Value);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates a unary expression with symbol scope, context, script refernce set.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Expr Unary(string name, Expr incExpr, double incValue, Operator op, TokenData token)
        {
            var exp = new UnaryExpr();

            exp.Name       = name;
            exp.Op         = op;
            exp.Increment  = incValue;
            exp.Expression = incExpr;
            SetupContext(exp, token);
            return(exp);
        }
Ejemplo n.º 12
0
        public override void Visit(UnaryExpr expr)
        {
            expr.right.Accept(this);
            switch (expr.op.type)
            {
            case TokenType.MINUS:
                chunk.WriteOpCode(OpCode.NEGATE);
                break;

            case TokenType.BANG:
                // TODO
                break;
            }
        }
        public dynamic Visit(UnaryExpr expr)
        {
            if (OptimizeMode.ExpressionSimplify)
            {
                var literal = expr.First as LiteralExpr;
                if (literal != null)
                {
                    literal.Value = -literal.Value;
                    return(literal);
                }
            }

            return(expr);
        }
Ejemplo n.º 14
0
    public static bool IsConstant(Expression e)
    {
        UnaryExpr  unary  = e as UnaryExpr;
        BinaryExpr binary = e as BinaryExpr;

        if (unary != null)
        {
            return(IsConstant(unary.E));
        }
        if (binary != null)
        {
            return(IsConstant(binary.E0) && IsConstant(binary.E1));
        }
        return(e is LiteralExpr);
    }
Ejemplo n.º 15
0
 private static bool ShallowEq(UnaryExpr expr1, UnaryExpr expr2)
 {
     if (expr1 is ConversionExpr && expr2 is ConversionExpr)
     {
         return(ShallowEq((ConversionExpr)expr1, (ConversionExpr)expr2));
     }
     else if (expr1 is UnaryOpExpr && expr2 is UnaryOpExpr)
     {
         return(ShallowEq((UnaryOpExpr)expr1, (UnaryOpExpr)expr2));
     }
     else
     {
         return(false); // UnaryExpr is abstract
     }
 }
Ejemplo n.º 16
0
        public LLVMValueRef Visit(UnaryExpr expr)
        {
            LLVMValueRef value = expr.Expression.Accept(this);

            if (expr.Operator.Type == TokenType.Bang) // !expr
            {
                value = LLVM.BuildNot(_builder, value, "nottmp");
            }
            else
            {
                value = LLVM.BuildNeg(_builder, value, "negtmp"); // -expr
            }

            return(value);
        }
Ejemplo n.º 17
0
        public object VisitUnaryExpr(UnaryExpr expr)
        {
            var right = Evaluate(expr.Right);

            switch (expr.Operator.Type)
            {
            case TokenType.Bang:
                return(!IsTruthy(right));

            case TokenType.Minus:
                CheckNumberOperand(expr.Operator, right);
                return(-(double)right);
            }

            return(null);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Rule: UnaryExpr -> ((UNARYOP))? Atom ;
        /// </summary>
        protected override object EvalUnaryExpr(ParseTree tree, params object[] paramlist)
        {
            if (GetNode(TokenType.UNARYOP) == null)
            {
                return((ExpressionBase)GetNode(TokenType.Atom).Eval(tree));
            }

            var unaryExpr = new UnaryExpr
            {
                First         = (ExpressionBase)GetNode(TokenType.Atom).Eval(tree),
                Node          = this,
                OperationText = GetNode(TokenType.UNARYOP).Token.Text
            };

            return(unaryExpr);
        }
Ejemplo n.º 19
0
        internal static UnaryOperatorSymbol BindUnaryOperation(UnaryExpr expr, UnaryOperatorKind kind, BindOptions options)
        {
            if (options.HasFlag(BindOptions.Logic))
            {
                Convert(ref expr.Expr, Compilation.Get(NativeType.Boolean), options);
            }

            var res = UnaryOperation(kind, ref expr.Expr, options);

            if (res != null)
            {
                return(res);
            }

            throw UnaryOperationError(expr, kind, options);
        }
Ejemplo n.º 20
0
 private object Evaluate(Expr expression)
 {
     return(expression switch
     {
         BinaryExpr binaryExpr => Evaluate(binaryExpr),
         BlockExpr blockExpr => Evaluate(blockExpr),
         BreakExpr breakExpr => Evaluate(breakExpr),
         CallExpr callExpr => Evaluate(callExpr),
         ContinueExpr continueExpr => Evaluate(continueExpr),
         Identifier identifier => Evaluate(identifier),
         IfExpr ifExpr => Evaluate(ifExpr),
         LambdaExpr lambdaExpr => Evaluate(lambdaExpr),
         Literal literal => Evaluate(literal),
         ReturnExpr returnExpr => Evaluate(returnExpr),
         UnaryExpr unaryExpr => Evaluate(unaryExpr),
         _ => throw new ArgumentOutOfRangeException(nameof(expression))
     });
        public void TestIncorrectUnaryExpression()
        {
            var program = new ProgramNode(0, 0);

            program.Block = new BlockStmt(0, 0);
            var declaration = CreateVarDeclaration("var1", new SimpleType(0, 0, ExprType.Bool));
            var expr        = new UnaryExpr(0, 0);

            expr.Expr = new IntLiteralExpr(0, 0, 1);
            expr.Op   = Operator.Not;
            var assign = new AssignmentStmt(0, 0);

            assign.AssignmentExpr = expr;
            assign.Variable       = new VariableExpr(0, 0, "var1");
            program.Block.Statements.Add(declaration);
            program.Block.Statements.Add(assign);
            AssertErrorContains(program, "Can't apply operator Not on type Int");
        }
Ejemplo n.º 22
0
        public static LNumber IncrementNumber(UnaryExpr expr, LNumber val, IAstVisitor visitor)
        {
            var inc = expr.Increment == 0 ? 1 : expr.Increment;

            if (expr.Expression != null)
            {
                var incval = expr.Expression.Evaluate(visitor);

                inc = ((LNumber)incval).Value;
            }

            // 1. Calculate the unary value
            val = ComLib.Lang.Runtime.EvalHelper.CalcUnary(val, expr.Op, inc);

            // 2. Set the value back into scope
            expr.Ctx.Memory.SetValue(expr.Name, val);
            return(val);
        }
        public void TestCorrectUnaryExpression()
        {
            var program = new ProgramNode(0, 0);

            program.Block = new BlockStmt(0, 0);
            var declaration = CreateVarDeclaration("var1", new SimpleType(0, 0, ExprType.Bool));
            var expr        = new UnaryExpr(0, 0);

            expr.Expr = new VariableExpr(0, 0, "true");
            expr.Op   = Operator.Not;
            var assign = new AssignmentStmt(0, 0);

            assign.AssignmentExpr = expr;
            assign.Variable       = new VariableExpr(0, 0, "var1");
            program.Block.Statements.Add(declaration);
            program.Block.Statements.Add(assign);
            AssertNoErrors(program);
        }
Ejemplo n.º 24
0
        public dynamic Visit(UnaryExpr expr)
        {
            var first = Visit((dynamic)expr.First) as Operand;

            switch (expr.Type)
            {
            case UnaryType.PlusPlus:
                return(first.PostIncrement());

            case UnaryType.Minus:
                return(-first);

            case UnaryType.MinusMinus:
                return(first.PreDecrement());

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 25
0
        public DataType Visit(UnaryExpr expr)
        {
            DataType exprDataType = expr.Expression.Accept(this);

            if (expr.Operator.Type == TokenType.Bang) // !expr
            {
                if (exprDataType.BaseType != BaseType.Int1 && exprDataType.BaseType != BaseType.Boolean)
                {
                    Reporter.Error(expr.Operator.Position, "Expected type 'bool' or 'i1' after '!'.");
                }
            }
            else if (expr.Operator.Type == TokenType.Minus) // -expr
            {
                if (!exprDataType.BaseType.IsNumber())
                {
                    Reporter.Error(expr.Operator.Position, "Expected number after '-'.");
                }
            }

            return(exprDataType);
        }
Ejemplo n.º 26
0
        public IType Visit(UnaryExpr node)
        {
            IType type_exp = this.Visit(node.exp);

            if (type_exp == null)
            {
                return(null);
            }

            if (node.op == "~" && type_exp.Name != "Int")
            {
                Logger += "En la expresion " + node.ToString() + "-> error de tipos (La expresion no es Int)\n";
                return(null);
            }
            else if (node.op == "not" && type_exp.Name != "Bool")
            {
                Logger += "En la expresion " + node.ToString() + "-> error de tipos (La expresion no es Bool)\n";
                return(null);
            }

            return(type_exp);
        }
Ejemplo n.º 27
0
        public static object HandleLogicalNot(UnaryExpr expr, IAstVisitor visitor)
        {
            var result = expr.Expression.Evaluate(visitor) as LObject;

            // Check 1:  This is actually an assert and should not happen.
            if (result == null)
            {
                throw ExceptionHelper.BuildRunTimeException(expr, "Null value encountered");
            }

            var retVal = false;

            // Only handle bool for logical not !true !false
            if (result.Type == LTypes.Bool)
            {
                retVal = !((LBool)result).Value;
            }
            else if (result == LObjects.Null)
            {
                retVal = true;
            }

            return(new LBool(retVal));
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Evaluate
        /// </summary>
        /// <returns></returns>
        public object VisitUnary(UnaryExpr expr)
        {
            // Logical not?
            if (expr.Op == Operator.LogicalNot)
            {
                return(ComLib.Lang.Runtime.EvalHelper.HandleLogicalNot(expr, this));
            }

            var valobj = (LObject)expr.Ctx.Memory.Get <object>(expr.Name);

            // Double ?
            if (valobj.Type == LTypes.Number)
            {
                return(ComLib.Lang.Runtime.EvalHelper.IncrementNumber(expr, (LNumber)valobj, this));
            }

            // String ?
            if (valobj.Type == LTypes.String)
            {
                return(ComLib.Lang.Runtime.EvalHelper.IncrementString(expr, (LString)valobj, this));
            }

            throw new LangException("Syntax Error", "Unexpected operation", expr.Ref.ScriptName, expr.Ref.Line, expr.Ref.CharPos);
        }
Ejemplo n.º 29
0
    public override Null Visit(UnaryExpr node)
    {
        base.Visit(node);

        // Invert the flow for boolean not
        if (node.op == UnaryOp.Not) {
            if (next.GetTrue() != next.GetFalse()) {
                next.Set(new FlowNode(next.GetFalse(), next.GetTrue()));
            }
        }

        return null;
    }
Ejemplo n.º 30
0
 internal UnaryOperatorSymbol BindUnaryOperation(UnaryExpr expr, UnaryOperatorKind kind)
 {
     return(BindUnaryOperation(expr, kind, Options.Binding));
 }
Ejemplo n.º 31
0
 public object VisitUnary(UnaryExpr expr)
 {
     return(null);
 }
Ejemplo n.º 32
0
 public static void ErrorUnaryOpNotFound(this Log log, UnaryExpr node)
 {
     if (node.value.computedType is ErrorType) {
         return;
     }
     log.Error(node.location, "no match for operator " + node.op.AsString() + " that takes arguments \"(" +
         node.value.computedType + ")\"");
 }
Ejemplo n.º 33
0
 public override void Visit(UnaryExpr unaryExpr)
 {
     unaryExpr.Expr.Accept(this);
     unaryExpr.ExprValue = Evaluator.EvaluateExpression(unaryExpr.Expr, unaryExpr.Op);
 }
Ejemplo n.º 34
0
 private Expression ParseExpression()
 {
     Expression expr;
     if (Accept(Token.Types.OpNot))
     {
         UnaryExpr unary = new UnaryExpr(AcceptedToken.Line, AcceptedToken.Column);
         unary.Op = Operator.Not;
         unary.Expr = ParseFactor();
         expr = unary;
     }
     else
     {
         expr = ParseTerm();
         BinaryExpr tail = ParseTermTail(expr);
         if (tail != null)
         {
             expr = tail;
         }
     }
     BinaryExpr logical = ParseLogical(expr);
     if (logical != null)
     {
         return logical;
     }
     else
     {
         return expr;
     }
 }
 public override void Visit(UnaryExpr unaryExpr)
 {
     unaryExpr.Expr.Accept(this);
     unaryExpr.Type = Checker.TypeCheck(unaryExpr.Expr, unaryExpr.Op);
 }
Ejemplo n.º 36
0
    public override Null Visit(UnaryExpr node)
    {
        context = null;
        node.computedType = new ErrorType();
        base.Visit(node);

        switch (node.op) {
            case UnaryOp.Negative:
                if (node.value.computedType.IsNumeric()) {
                    node.computedType = node.value.computedType;
                } else {
                    log.ErrorUnaryOpNotFound(node);
                }
                break;
            case UnaryOp.Not:
                if (node.value.computedType.IsBool()) {
                    node.computedType = node.value.computedType;
                } else {
                    log.ErrorUnaryOpNotFound(node);
                }
                break;
        }

        return null;
    }
Ejemplo n.º 37
0
 public void Visit(UnaryExpr unaryExpr)
 {
     TreeLevel++;
     PrintNode("UnaryExpr");
     PrintNode(unaryExpr.Op.ToString(), true);
     unaryExpr.Expr.Accept(this);
     TreeLevel--;
 }