private static IBinaryExpression InvertRelation(IBinaryExpression be) { var op = be.Operator; switch (op) { case BinaryOperator.LessThan: return(BinExp(be, BinaryOperator.GreaterThanOrEqual)); case BinaryOperator.LessThanOrEqual: return(BinExp(be, BinaryOperator.GreaterThan)); case BinaryOperator.GreaterThan: return(BinExp(be, BinaryOperator.LessThanOrEqual)); case BinaryOperator.GreaterThanOrEqual: return(BinExp(be, BinaryOperator.LessThan)); case BinaryOperator.Equality: return(BinExp(be, BinaryOperator.Inequality)); case BinaryOperator.Inequality: return(BinExp(be, BinaryOperator.Equality)); } return(be); }
static void Main(string[] args) { SearchClient temp = new SearchClient(); foreach (string token in temp.SearchExpressionPreparing("rd || (soarin && !pie) || kirin")) { Console.Write(token + "+"); } Console.WriteLine(); IBinaryExpression tree = temp.GetBinaryExpressionTree(temp.SearchExpressionPreparing("rd || (soarin && !pie)")); List <string> tags = new List <string>(); tags.Add("rd0"); tree.Search(tags); Console.WriteLine(tree.Search(tags)); tags.Clear(); tags.Add("rd"); tree.Search(tags); Console.WriteLine(tree.Search(tags)); tags.Clear(); tags.Add("soarin"); tags.Add("pie"); tree.Search(tags); Console.WriteLine(tree.Search(tags)); }
private static IBinaryExpression BinExp(IBinaryExpression be, BinaryOperator op) { var left = Simplify(be.Left); var right = Simplify(be.Right); return(new BinaryExpression(left, right, op)); }
public override Expression VisitBinaryExpression(IBinaryExpression binaryExpressionParam, IMetadataResolver context) { Expression left = binaryExpressionParam.LeftOperand.Accept(this, context); Expression right = binaryExpressionParam.RightOperand.Accept(this, context); return(new BinaryExpressionBuilder(binaryExpressionParam, left, right).Build()); }
protected override IExpression VisitBinary(IBinaryExpression binaryExpression) { DescriptionAttribute descriptionAttribute; FieldInfo fieldInfo; if ((object)binaryExpression == null) throw new ArgumentNullException("binaryExpression"); this.Strings.Append(OPEN); this.Visit(binaryExpression.LeftExpression); fieldInfo = typeof(BinaryOperator).GetField(binaryExpression.BinaryOperator.ToString()); if ((object)fieldInfo == null) throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported.", binaryExpression.BinaryOperator)); descriptionAttribute = Reflexion.GetOneAttribute<DescriptionAttribute>(fieldInfo); if ((object)descriptionAttribute == null) throw new NotSupportedException(string.Format("The binary operator '{0}' is not described.", binaryExpression.BinaryOperator)); this.Strings.Append(descriptionAttribute.Description); this.Visit(binaryExpression.RightExpression); this.Strings.Append(CLOSE); return binaryExpression; }
private static IExpression HandleOp(IBinaryExpression op) { var e1 = op.Left; var e2 = op.Right; var e1s = e1.Simplify(); var e2s = e2.Simplify(); // if op.Left or op.Right can been simplified then try and simplify further if (e1s != e1 || e2s != e2) { switch (op) { case Add _: return(new Add(e1s, e2s).Simplify()); case Sub _: return(new Sub(e1s, e2s).Simplify()); case Mul _: return(new Mul(e1s, e2s).Simplify()); case Div _: return(new Div(e1s, e2s).Simplify()); case Pow _: return(new Pow(e1s, e2s).Simplify()); } } // No furher simplification possible so just return op. return(op); }
protected override IExpression ConvertUnary(IUnaryExpression iue) { iue = (IUnaryExpression)base.ConvertUnary(iue); if (iue.Operator == UnaryOperator.BooleanNot) { if (iue.Expression is ILiteralExpression) { ILiteralExpression expr = (ILiteralExpression)iue.Expression; if (expr.Value is bool) { return(Builder.LiteralExpr(!(bool)expr.Value)); } } else if (iue.Expression is IUnaryExpression) { IUnaryExpression iue2 = (IUnaryExpression)iue.Expression; if (iue2.Operator == UnaryOperator.BooleanNot) // double negation { return(iue2.Expression); } } else if (iue.Expression is IBinaryExpression) { IBinaryExpression ibe = (IBinaryExpression)iue.Expression; BinaryOperator negatedOp; if (Recognizer.TryNegateOperator(ibe.Operator, out negatedOp)) { // replace !(i==0) with (i != 0) return(Builder.BinaryExpr(ibe.Left, negatedOp, ibe.Right)); } } } return(iue); }
public IBinaryExpression GetBinaryExpressionTree(List <string> tokens) { IBinaryExpression root = null; root = this.PreBuild(tokens).GetExpressionTree(); return(root); }
/// <summary> /// Create the while statement syntax for a while loop with a binary expression. /// </summary> /// <param name="binaryExpression">The binary expression.</param> /// <param name="body">Body of the while loop.</param> /// <returns>The declared while statement.</returns> public WhileStatementSyntax While(IBinaryExpression binaryExpression, BlockSyntax body) { if (binaryExpression == null) { throw new ArgumentNullException(nameof(binaryExpression)); } return(WhileStatement(binaryExpression.GetBinaryExpression(), body)); }
/// <summary> /// Create the statement syntax for a if-conditional with a single statement. /// </summary> /// <param name="binaryExpression">The binary expression to generate.</param> /// <param name="expressionStatement">Statement inside the if.</param> /// <returns>The declared statement syntax.</returns> public StatementSyntax If(IBinaryExpression binaryExpression, ExpressionStatementSyntax expressionStatement) { if (binaryExpression == null) { throw new ArgumentNullException(nameof(binaryExpression)); } return(IfStatement(binaryExpression.GetBinaryExpression(), expressionStatement)); }
public IExpression Evaluate <T, U>(IBinaryExpression <T, U> ex, IContext context) { IBinaryFunctionExpression <T, U> TheFunction = ex.Function; ILiteralExpression <T> literalLeft = this.get <T>(ex.Left, this, context); ILiteralExpression <T> literalRight = this.get <T>(ex.Right, this, context); ILiteralBinaryFunctionExpression <T, U> literalBinaryFunction = this.get <T, U>(ex.Function, this, context); return(literalBinaryFunction.Invoke(literalLeft.Item, literalRight.Item)); }
public override IExpression Visit(IBinaryExpression expr, int context) { return(new BinaryExpression { LeftOperand = Anonymize(expr.LeftOperand), Operator = expr.Operator, RightOperand = Anonymize(expr.RightOperand) }); }
private static void WriteBinary(LanguageWriter w, IBinaryExpression exp) { WriteExpression(w, exp.Left, prec_binop[exp.Operator] > GetExpressionPrecedence(exp.Left)); w.Write(" "); WriteBinaryOperator(w, exp.Operator); w.Write(" "); WriteExpression(w, exp.Right, prec_binop[exp.Operator] >= GetExpressionPrecedence(exp.Right)); }
/// <summary> /// Initializes a new instance of the <see cref="BinaryExpressionArgument"/> class. /// </summary> /// <param name="binaryExpression">The binary expression.</param> /// <param name="namedArgument">Specificy the argument for a partical parameter.</param> public BinaryExpressionArgument(IBinaryExpression binaryExpression, string namedArgument = null) : base(namedArgument) { if (binaryExpression == null) { throw new ArgumentNullException(nameof(binaryExpression)); } _binaryExpression = binaryExpression; }
public static IExpression BuildBinaryExpression(List <Token> tokens, ref int index, IExpression leftExpr, Stack <int?> precedenceStack) { IBinaryExpressionCreator bxc = binaryExpressionCreators[tokens[index++].Value]; IBinaryExpression bx = bxc.Create(); bx.Left = leftExpr; precedenceStack.Push(bx.Precedence); bx.BuildExpression(tokens, ref index, precedenceStack); precedenceStack.Pop(); return(bx); }
private void ChainConditional(IBinaryExpression e, IExpression cond) { // Replace the current test expression in our if with our new // binary expression (e) by moving it to the left condition // of our new binary expression, and setting the right to cond. var @if = Peek <IfExpression>(); e.Left = @if.Test; e.Right = cond; @if.Test = e; }
public static IExpression BuildBinaryExpression(TokenList tokens, IExpression leftExpr, Stack <int?> precedenceStack) { IBinaryExpressionCreator bxc = binaryExpressionCreators[tokens.Current.Value]; IBinaryExpression bx = bxc.Create(); bx.Left = leftExpr; precedenceStack.Push(bx.Precedence); bx.PrepareExpression(tokens, precedenceStack); precedenceStack.Pop(); return(bx); }
private static IExpression InvertBoolOrRelation(IBinaryExpression be) { var op = be.Operator; switch (op) { case BinaryOperator.BooleanOr: return(Not(be, BinaryOperator.BooleanAnd)); case BinaryOperator.BooleanAnd: return(Not(be, BinaryOperator.BooleanOr)); } return(InvertRelation(be)); }
private static int FitsOnOneLine(IBinaryExpression expression, int remainingSpace) { var space = remainingSpace; space = FitsOnOneLine(expression.Left, space); space -= 2; if (space > 0) { space = FitsOnOneLine(expression.Right, space); } return(space); }
internal static void ForEachConjunct(IExpression expr, Action <IExpression> action) { IBinaryExpression ibe = expr as IBinaryExpression; if (ibe == null || ibe.Operator != BinaryOperator.BooleanAnd) { action(expr); } else { ForEachConjunct(ibe.Left, action); ForEachConjunct(ibe.Right, action); } }
private void ForEachAttributeOfCodeElementAndContents(object codeElement, Action <ICompilerAttribute> action) { if ((attributes == null) || (codeElement == null)) { return; } foreach (var attr in attributes.GetAll <ICompilerAttribute>(codeElement)) { action(attr); } if (codeElement is IStatement) { if (codeElement is IExpressionStatement) { IExpressionStatement ies = (IExpressionStatement)codeElement; ForEachAttributeOfCodeElement(ies.Expression, action); if (ies.Expression is IVariableDeclarationExpression) { ForEachAttributeOfCodeElement(((IVariableDeclarationExpression)ies.Expression).Variable, action); } else if (ies.Expression is IAssignExpression) { IAssignExpression iae = (IAssignExpression)ies.Expression; if (iae.Target is IVariableDeclarationExpression) { ForEachAttributeOfCodeElement(((IVariableDeclarationExpression)iae.Target).Variable, action); } if (iae.Expression is IMethodInvokeExpression) { ForEachAttributeOfCodeElement(iae.Expression, action); } } } else if (codeElement is IForStatement) { IForStatement ifs = (IForStatement)codeElement; ForEachAttributeOfCodeElementAndContents(ifs.Initializer, action); IBinaryExpression ibe = (IBinaryExpression)ifs.Condition; ForEachAttributeOfCodeElementAndContents(ibe.Right, action); } } if (codeElement is IMethodDeclaration) { IMethodDeclaration imd = (IMethodDeclaration)codeElement; foreach (IParameterDeclaration ipd in imd.Parameters) { ForEachAttributeOfCodeElement(ipd, action); } } }
protected override IExpression ConvertBinary(IBinaryExpression ibe) { ibe = (IBinaryExpression)base.ConvertBinary(ibe); if (ibe.Left is ILiteralExpression && ibe.Right is ILiteralExpression) { try { return(Builder.LiteralExpr(evaluator.Evaluate(ibe))); } catch { } } return(ibe); }
public override void VisitBinaryExpression(IBinaryExpression binaryExpressionParam, FoldingHighlightingConsumer context) { if (binaryExpressionParam.OperatorSign.GetText() == "!=") { if (binaryExpressionParam.RightOperand.GetText() == "0") { if (binaryExpressionParam.LeftOperand is IParenthesizedExpression parenthesizedExpression) { if (parenthesizedExpression.Expression is IBinaryExpression binaryAddition) { if (binaryAddition.OperatorSign.GetText() == "&") { DocumentRange documentRange = binaryExpressionParam.GetDocumentRange(); context.AddDefaultPriorityFolding(FoldId, documentRange, binaryAddition.RightOperand.GetText() + " ∈ " + binaryAddition.LeftOperand.GetText()); return; } } } } } if (binaryExpressionParam?.OperatorSign?.GetText() == "==") { if (binaryExpressionParam?.RightOperand?.GetText() == "0") { if (binaryExpressionParam?.LeftOperand is IParenthesizedExpression parenthesizedExpression) { if (parenthesizedExpression?.Expression is IBinaryExpression binaryAddition) { if (binaryAddition.OperatorSign.GetText() == "&") { DocumentRange documentRange = binaryExpressionParam.GetDocumentRange(); context.AddDefaultPriorityFolding(FoldId, documentRange, binaryAddition.RightOperand.GetText() + " ∉ " + binaryAddition.LeftOperand.GetText()); return; } } } } } base.VisitBinaryExpression(binaryExpressionParam, context); }
/// <summary> /// Converts for loops into parallel for loops. /// </summary> /// <param name="ifs">The for loop to convert</param> /// <returns>The converted statement</returns> protected override IStatement ConvertFor(IForStatement ifs) { if (context.InputAttributes.Has <ConvergenceLoop>(ifs) || context.InputAttributes.Has <HasOffsetIndices>(ifs) || (ifs is IBrokenForStatement)) { return(base.ConvertFor(ifs)); } IVariableDeclaration loopVar = Recognizer.LoopVariable(ifs); if (context.InputAttributes.Has <Sequential>(loopVar)) { return(base.ConvertFor(ifs)); } // Convert this loop to a parallel for loop IExpression loopSize = null; IExpression loopStart = null; if (Recognizer.IsForwardLoop(ifs)) { loopStart = Recognizer.LoopStartExpression(ifs); loopSize = Recognizer.LoopSizeExpression(ifs); } else if (ifs.Condition is IBinaryExpression) { IBinaryExpression ibe = (IBinaryExpression)ifs.Condition; if (ibe.Operator == BinaryOperator.GreaterThanOrEqual) { // loop is "for(int i = end; i >= start; i--)" loopStart = ibe.Right; loopSize = Builder.BinaryExpr(Recognizer.LoopStartExpression(ifs), BinaryOperator.Add, Builder.LiteralExpr(1)); } } if (loopSize == null) { return(base.ConvertFor(ifs)); } IAnonymousMethodExpression bodyDelegate = Builder.AnonMethodExpr(typeof(Action <int>)); bodyDelegate.Body = ifs.Body; bodyDelegate.Parameters.Add(Builder.Param(loopVar.Name, loopVar.VariableType)); Delegate d = new Func <int, int, Action <int>, ParallelLoopResult>(Parallel.For); IMethodInvokeExpression parallelFor = Builder.StaticMethod(d, loopStart, loopSize, bodyDelegate); IStatement st = Builder.ExprStatement(parallelFor); return(st); }
/// <summary>Handles the specified expression.</summary> /// <param name="binaryExpression">The invocation expression.</param> /// <param name="statementParameters">The parameters.</param> /// <returns>Returns the string.</returns> public ExpressionDescriptor Handle(IBinaryExpression binaryExpression, Dictionary<string, string> statementParameters) { var left = binaryExpression.LeftOperand; if (left == null) { return null; } var right = binaryExpression.RightOperand; if (right == null) { return null; } var leftStatement = ExpressionTemplateBuilder.Handle(left, statementParameters); if (leftStatement == null) { return null; } var rightStatement = ExpressionTemplateBuilder.Handle(right, statementParameters); if (rightStatement == null) { return null; } var result = new ExpressionDescriptor { Template = string.Format("{0} {1} {2}", leftStatement.Template, binaryExpression.OperatorSign.GetTokenType().TokenRepresentation, rightStatement.Template) }; foreach (var variable in rightStatement.TemplateVariables) { result.TemplateVariables[variable.Key] = variable.Value; } foreach (var variable in leftStatement.TemplateVariables) { result.TemplateVariables[variable.Key] = variable.Value; } return result; }
public override bool Equals(object obj) { if (this == obj) { return(true); } IBinaryExpression expression = obj as IBinaryExpression; if (expression == null) { return(false); } return (this.Left.Equals(expression.Left) && this.Right.Equals(expression.Right) && this.Operator.Equals(expression.Operator)); }
/// <summary> /// Create the expression statement syntax to assign a reference to a binary expression. /// </summary> /// <param name="reference">Reference that should be assigned.</param> /// <param name="binaryExpression">The binary expression.</param> /// <returns>The generated assign declaration syntax.</returns> public ExpressionStatementSyntax Assign(VariableReference reference, IBinaryExpression binaryExpression) { if (reference == null) { throw new ArgumentNullException(nameof(reference)); } if (binaryExpression == null) { throw new ArgumentNullException(nameof(binaryExpression)); } return (ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ReferenceGenerator.Create(reference), binaryExpression.GetBinaryExpression()))); }
private static void WriteSwitch_case(LanguageWriter w, IExpression con_case) { IBinaryExpression exp_bi = con_case as IBinaryExpression; if (exp_bi != null) { if (exp_bi.Operator == BinaryOperator.BooleanOr) { WriteSwitch_case(w, exp_bi.Left); WriteSwitch_case(w, exp_bi.Right); return; } } w.WriteKeyword("case"); w.Write(" "); ExpressionWriter.WriteExpression(w, con_case, false); w.Write(":"); w.WriteLine(); }
public ConditionBinding(IExpression condition) { lhs = condition; rhs = Builder.LiteralExpr(true); if (condition is IBinaryExpression) { IBinaryExpression ibe = (IBinaryExpression)condition; if ((ibe.Operator == BinaryOperator.IdentityEquality) || (ibe.Operator == BinaryOperator.ValueEquality)) { lhs = ibe.Left; rhs = ibe.Right; } } else if (condition is IUnaryExpression) { IUnaryExpression iue = (IUnaryExpression)condition; if (iue.Operator == UnaryOperator.BooleanNot) { lhs = iue.Expression; rhs = Builder.LiteralExpr(false); } } }
public static IExpression Simplify(IBinaryExpression e) { var op = e.Operator; if (IsBooleanOperator(op)) { var left = Simplify(e.Left); var right = Simplify(e.Right); if (IsNot(left) && IsRelation(right)) { op = InvertBooleanOperator(op); left = Not(left); right = InvertRelation(right as IBinaryExpression); return(new BinaryExpression(left, right, op)); } if (!ReferenceEquals(left, e.Left) || !ReferenceEquals(right, e.Right)) { return(new BinaryExpression(left, right, op)); } return(e); } var e2 = SimplifyEquality(e.Left, e.Right, op); if (e2 != null) { return(e2); } e2 = SimplifyEquality(e.Right, e.Left, op); if (e2 != null) { return(e2); } return(e); }
private static bool IsAssignmentImpl(IBinaryExpression binaryexpression) { return binaryexpression.IsAssignment; }
private void WriteBinaryExpression(IBinaryExpression expression, IFormatter formatter) { formatter.Write("("); this.WriteExpression(expression.Left, formatter); formatter.Write(" "); this.WriteBinaryOperator(expression.Operator, formatter); formatter.Write(" "); this.WriteExpression(expression.Right, formatter); formatter.Write(")"); }
protected override IExpression VisitBinary(IBinaryExpression binaryExpression) { if ((object)binaryExpression == null) throw new ArgumentNullException("binaryExpression"); this.Strings.Append("("); this.Visit(binaryExpression.LeftExpression); switch (binaryExpression.BinaryOperator) { case BinaryOperator.Add: this.Strings.Append(" + "); break; case BinaryOperator.Sub: this.Strings.Append(" - "); break; case BinaryOperator.Div: this.Strings.Append(" / "); break; case BinaryOperator.Mul: this.Strings.Append(" * "); break; case BinaryOperator.Mod: this.Strings.Append(" % "); break; case BinaryOperator.And: this.Strings.Append(" AND "); break; case BinaryOperator.Or: this.Strings.Append(" OR "); break; case BinaryOperator.Eq: this.Strings.Append(" = "); break; case BinaryOperator.Ne: this.Strings.Append(" <> "); break; case BinaryOperator.Gt: this.Strings.Append(" > "); break; case BinaryOperator.Ge: this.Strings.Append(" >= "); break; case BinaryOperator.Lt: this.Strings.Append(" < "); break; case BinaryOperator.Le: this.Strings.Append(" <= "); break; case BinaryOperator.StrLk: this.Strings.Append(" LIKE "); break; case BinaryOperator.Band: this.Strings.Append(" & "); break; case BinaryOperator.Bor: this.Strings.Append(" | "); break; case BinaryOperator.Bxor: this.Strings.Append(" ^ "); break; default: throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported.", binaryExpression.BinaryOperator)); } this.Visit(binaryExpression.RightExpression); this.Strings.Append(")"); return binaryExpression; }
public virtual void VisitBinaryExpression(IBinaryExpression e) { VisitExpression(e.Left); VisitExpression(e.Right); }
public virtual void VisitBinaryExpression(IBinaryExpression value) { this.VisitExpression(value.Left); this.VisitExpression(value.Right); }
protected abstract IExpression VisitBinary(IBinaryExpression binaryExpression);
/// <summary> /// Only converts the contained statements in a for loop, leaving the initializer, /// condition and increment statements unchanged. /// </summary> /// <remarks>This method includes a number of checks to ensure the loop is valid e.g. that the initializer, condition and increment /// are all of the appropriate form.</remarks> protected override IStatement ConvertFor(IForStatement ifs) { IForStatement fs = Builder.ForStmt(); context.SetPrimaryOutput(fs); // Check condition is valid fs.Condition = ifs.Condition; if ((!(fs.Condition is IBinaryExpression)) || (((IBinaryExpression)fs.Condition).Operator != BinaryOperator.LessThan)) { Error("For statement condition must be of the form 'indexVar<loopSize', was " + fs.Condition); } // Check increment is valid fs.Increment = ifs.Increment; IExpressionStatement ies = fs.Increment as IExpressionStatement; bool validIncrement = false; if (ies != null) { if (ies.Expression is IAssignExpression) { IAssignExpression iae = (IAssignExpression)ies.Expression; IBinaryExpression ibe = RemoveCast(iae.Expression) as IBinaryExpression; validIncrement = (ibe != null) && (ibe.Operator == BinaryOperator.Add); } else if (ies.Expression is IUnaryExpression) { IUnaryExpression iue = (IUnaryExpression)ies.Expression; validIncrement = (iue.Operator == UnaryOperator.PostIncrement); } } if (!validIncrement) { Error("For statement increment must be of the form 'varname++' or 'varname=varname+1', was " + fs.Increment + "."); } // Check initializer is valid fs.Initializer = ifs.Initializer; ies = fs.Initializer as IExpressionStatement; if (ies == null) { Error("For statement initializer must be an expression statement, was " + fs.Initializer.GetType()); } else { if (!(ies.Expression is IAssignExpression)) { Error("For statement initializer must be an assignment, was " + fs.Initializer.GetType().Name); } else { IAssignExpression iae2 = (IAssignExpression)ies.Expression; if (!(iae2.Target is IVariableDeclarationExpression)) { Error("For statement initializer must be a variable declaration, was " + iae2.Target.GetType().Name); } if (!Recognizer.IsLiteral(iae2.Expression, 0)) { Error("Loop index must start at 0, was " + iae2.Expression); } } } fs.Body = ConvertBlock(ifs.Body); return(fs); }
public virtual IExpression TransformBinaryExpression(IBinaryExpression value) { value.Left = this.TransformExpression(value.Left); value.Right = this.TransformExpression(value.Right); return value; }