public override void VisitConditionalExpression(ConditionalExpression conditionalExpression) { var token = CreateConditionalBlock(conditionalExpression.Condition.GetText()); _tokenList.Add(token); VisitChildren(token.FalseStatements, conditionalExpression.FalseExpression); VisitChildren(token.TrueStatements, conditionalExpression.TrueExpression); }
protected ConditionalExpression UpdateConditional(ConditionalExpression c, Expression test, Expression ifTrue, Expression ifFalse) { if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; }
public override void VisitConditionalExpression (ConditionalExpression conditionalExpression) { base.VisitConditionalExpression (conditionalExpression); if (!conditionalExpression.TrueExpression.Match (conditionalExpression.FalseExpression).Success) return; var action = new CodeAction (ctx.TranslateString ("Replace '?:' with branch"), script => script.Replace (conditionalExpression, conditionalExpression.TrueExpression.Clone ())); AddIssue (conditionalExpression, ctx.TranslateString ("'?:' expression has identical true and false branches"), new [] { action }); }
public Tuple<Expression, Expression> GetExpressions (ConditionalExpression cond) { var condition = cond.Condition as BinaryOperatorExpression; var compareNode = condition.Left is NullReferenceExpression ? condition.Right : condition.Left; if (compareNode.IsMatch (cond.TrueExpression)) { // a != null ? a : other return new Tuple<Expression, Expression> (cond.TrueExpression, cond.FalseExpression); } // a == null ? other : a return new Tuple<Expression, Expression> (cond.FalseExpression, cond.TrueExpression); }
public override void VisitConditionalExpression(ConditionalExpression conditionalExpression) { Match m = pattern.Match(conditionalExpression); if (m.Success) { var a = m.Get<Expression>("a").Single(); var other = m.Get<Expression>("other").Single(); AddIssue(conditionalExpression, ctx.TranslateString("Convert to '??' expression"), script => { var expr = new BinaryOperatorExpression (a.Clone (), BinaryOperatorType.NullCoalescing, other.Clone ()); script.Replace (conditionalExpression, expr); }); } base.VisitConditionalExpression (conditionalExpression); }
public void Parse(ref string[] program) { string ifstring = ParseUtils.GetToken(ref program); if (!ifstring.Equals("if", StringComparison.Ordinal)) throw new ParseException("If Statement should always start with if, found " + ifstring + " instead."); string openbracket = ParseUtils.GetToken(ref program); if (!openbracket.Equals("(", StringComparison.Ordinal)) throw new ParseException("if statement must be followed by a condition in brackets, found " + openbracket + " instead."); _Condition = ConditionBuilder.Parse(ref program); string closebracket = ParseUtils.GetToken(ref program); if (!closebracket.Equals(")", StringComparison.Ordinal)) throw new ParseException("if statement found a conditional expression without a closing bracket, found " + closebracket + " instead."); _Block = new RuleBlock(); _Block.Parse(ref program); }
public override void VisitConditionalExpression (ConditionalExpression conditionalExpression) { var resolveResult = ctx.Resolve (conditionalExpression.Condition); if (resolveResult.ConstantValue is bool) { var condition = (bool)resolveResult.ConstantValue; Expression resultExpr, unreachableExpr; if (condition) { resultExpr = conditionalExpression.TrueExpression; unreachableExpr = conditionalExpression.FalseExpression; } else { resultExpr = conditionalExpression.FalseExpression; unreachableExpr = conditionalExpression.TrueExpression; } unreachableNodes.Add (unreachableExpr); AddIssue (unreachableExpr, ctx.TranslateString ("Remove unreachable code"), script => script.Replace (conditionalExpression, resultExpr.Clone ())); } base.VisitConditionalExpression (conditionalExpression); }
public bool IsCandidate (ConditionalExpression node) { var condition = node.Condition as BinaryOperatorExpression; var compareNode = condition.Left is NullReferenceExpression ? condition.Right : condition.Left; if (compareNode.IsMatch (node.TrueExpression)) { // a == null ? a : other if (condition.Operator == BinaryOperatorType.Equality) return false; // a != null ? a : other return compareNode.IsMatch (node.TrueExpression); } else { // a == null ? other : a if (condition.Operator == BinaryOperatorType.Equality) return compareNode.IsMatch (node.FalseExpression); // a != null ? other : a return false; } }
private void FindColumns(Expression expression, IList <TableColumn> columnList) { if (expression is ParameterExpression) { ParameterExpression e = expression as ParameterExpression; string selector = e.Name; for (int i = 0; i < this.tables.Count; i++) { if (this.selectors[i] == selector) { AddAllColumns(this.tables[i], columnList); break; } } } else if (expression.NodeType == ExpressionType.MemberAccess) { this.FindColumns(expression as MemberExpression, columnList); } else if (expression is MethodCallExpression) { this.FindColumns(expression as MethodCallExpression, columnList); } else if (expression is BinaryExpression) { BinaryExpression e = expression as BinaryExpression; this.FindColumns(e.Left, columnList); this.FindColumns(e.Right, columnList); } else if (expression is UnaryExpression) { UnaryExpression e = expression as UnaryExpression; this.FindColumns(e.Operand, columnList); } else if (expression is ConditionalExpression) { ConditionalExpression e = expression as ConditionalExpression; this.FindColumns(e.Test, columnList); this.FindColumns(e.IfTrue, columnList); this.FindColumns(e.IfFalse, columnList); } else if (expression is InvocationExpression) { InvocationExpression e = expression as InvocationExpression; this.FindColumns(e.Expression, columnList); this.FindColumns(e.Arguments, columnList); } else if (expression is LambdaExpression) { LambdaExpression e = expression as LambdaExpression; this.FindColumns(e.Body, columnList); } else if (expression is ListInitExpression) { ListInitExpression e = expression as ListInitExpression; this.FindColumns(e.NewExpression, columnList); foreach (ElementInit ei in e.Initializers) { this.FindColumns(ei.Arguments, columnList); } } else if (expression is MemberInitExpression) { MemberInitExpression e = expression as MemberInitExpression; this.FindColumns(e.NewExpression, columnList); foreach (MemberAssignment b in e.Bindings) { this.FindColumns(b.Expression, columnList); } } else if (expression is NewExpression) { NewExpression e = expression as NewExpression; this.FindColumns(e.Arguments, columnList); } else if (expression is NewArrayExpression) { NewArrayExpression e = expression as NewArrayExpression; this.FindColumns(e.Expressions, columnList); } else if (expression is TypeBinaryExpression) { TypeBinaryExpression e = expression as TypeBinaryExpression; this.FindColumns(e.Expression, columnList); } }
public override void VisitConditionalExpression(ConditionalExpression conditionalExpression) { HandleExpressionNode(conditionalExpression); }
private Func <DbDataReader, T> GetReader(DbDataReader reader) { Delegate resDelegate; List <string> readerColumns = new List <string>(); for (int index = 0; index < reader.FieldCount; index++) { readerColumns.Add(reader.GetName(index)); } // a list of LINQ expressions that will be used for each data row var statements = new List <Expression>(); // get the indexer property of DbDataReader var indexerProperty = typeof(DbDataReader).GetProperty("Item", new[] { typeof(string) }); // Parameter expression to create instance of object ParameterExpression instanceParam = Expression.Variable(typeof(T)); ParameterExpression readerParam = Expression.Parameter(typeof(DbDataReader)); // create and assign new instance of variable BinaryExpression createInstance = Expression.Assign(instanceParam, Expression.New(typeof(T))); statements.Add(createInstance); // loop through each of the properties in T to determine how to populate the new instance properties var properties = typeof(T).GetProperties(); var columnNames = this.GetColumnNames(properties); foreach (var property in properties) { string columnName = columnNames[property.Name]; //string columnName = property.Name; if (readerColumns.Contains(columnName.ToLower())) { // get the instance.Property MemberExpression setProperty = Expression.Property(instanceParam, property); // the database column name will be what is in the columnNames list -- defaults to the property name IndexExpression readValue = Expression.MakeIndex(readerParam, indexerProperty, new[] { Expression.Constant(columnName) }); ConstantExpression nullValue = Expression.Constant(DBNull.Value, typeof(System.DBNull)); BinaryExpression valueNotNull = Expression.NotEqual(readValue, nullValue); if (property.PropertyType.Name.ToLower().Equals("string")) { ConditionalExpression assignProperty = Expression.IfThenElse(valueNotNull, Expression.Assign(setProperty, Expression.Convert(readValue, property.PropertyType)), Expression.Assign(setProperty, Expression.Constant("", typeof(System.String)))); statements.Add(assignProperty); } else { ConditionalExpression assignProperty = Expression.IfThen(valueNotNull, Expression.Assign(setProperty, Expression.Convert(readValue, property.PropertyType))); statements.Add(assignProperty); } } } var returnStatement = instanceParam; statements.Add(returnStatement); var body = Expression.Block(instanceParam.Type, new[] { instanceParam }, statements.ToArray()); var lambda = Expression.Lambda <Func <DbDataReader, T> >(body, readerParam); resDelegate = lambda.Compile(); return((Func <DbDataReader, T>)resDelegate); }
public virtual void Enter(ConditionalExpression conditionalExpression) { }
public void VisitConditionalExpression(ConditionalExpression condExpr) { condExpr.Condition.AcceptWalker(this); condExpr.TrueExpression.AcceptWalker(this); condExpr.FalseExpression.AcceptWalker(this); }
public override void PostWalk(ConditionalExpression node) { }
override public void LeaveConditionalExpression(ConditionalExpression node) { CheckExpressionType(node.TrueValue); CheckExpressionType(node.FalseValue); }
public virtual Expression ConvertStringToEnumConversion(ConditionalExpression conversion) => conversion;
/// <summary> /// ConditionalExpression visit method /// </summary> /// <param name="c">The ConditionalExpression expression to visit</param> /// <returns>The visited ConditionalExpression expression </returns> internal override Expression VisitConditional(ConditionalExpression c) { this.cantTranslateExpression = true; return(c); }
public virtual void VisitConditionalExpression(ConditionalExpression conditionalExpression) { VisitExpression(conditionalExpression.Test); VisitExpression(conditionalExpression.Consequent); VisitExpression(conditionalExpression.Alternate); }
public override void VisitConditionalExpression(ConditionalExpression conditionalExpression) { base.VisitConditionalExpression(conditionalExpression); CheckCondition(conditionalExpression.Condition); }
public override bool Walk(ConditionalExpression node) { writer.WriteLine("ConditionalExpression"); return(base.Walk(node)); }
public void TestThatConstructorAllowMissingElseExpression() { var expr = new ConditionalExpression(AnyExpression, AnyExpression, new None()); expr.ElseExpression.HasValue.Should().BeFalse(); }
// Conditional operator public override void VisitConditionalExpression(ConditionalExpression conditionalExpression) { // Associativity here is a bit tricky: // (a ? b : c ? d : e) == (a ? b : (c ? d : e)) // (a ? b ? c : d : e) == (a ? (b ? c : d) : e) // Only ((a ? b : c) ? d : e) strictly needs the additional parentheses if (InsertParenthesesForReadability) { // Precedence of ?: can be confusing; so always put parentheses in nice-looking mode. ParenthesizeIfRequired(conditionalExpression.Condition, Primary); ParenthesizeIfRequired(conditionalExpression.TrueExpression, Primary); ParenthesizeIfRequired(conditionalExpression.FalseExpression, Primary); } else { ParenthesizeIfRequired(conditionalExpression.Condition, Conditional + 1); ParenthesizeIfRequired(conditionalExpression.TrueExpression, Conditional); ParenthesizeIfRequired(conditionalExpression.FalseExpression, Conditional); } base.VisitConditionalExpression(conditionalExpression); }
public virtual void VisitConditionalExpression(ConditionalExpression conditionalExpression) { if (this.ThrowException) { throw (Exception)this.CreateException(conditionalExpression); } }
// returns null if no need to rewrite that branch, otherwise // returns a re-written branch private Expression Walk(Expression expression) { if (expression == null) { return(null); } Expression tmp; if (subst.TryGetValue(expression, out tmp)) { return(tmp); } switch (expression.NodeType) { case ExpressionType.MemberAccess: { MemberExpression me = (MemberExpression)expression; Expression target = Walk(me.Expression); return(target == null ? null : Expression.MakeMemberAccess(target, me.Member)); } case ExpressionType.Constant: case ExpressionType.Parameter: return(null); // never a need to rewrite if not already matched case ExpressionType.Add: return(Walk(expression, Expression.Add)); case ExpressionType.Divide: return(Walk(expression, Expression.Divide)); case ExpressionType.Multiply: return(Walk(expression, Expression.Multiply)); case ExpressionType.Subtract: return(Walk(expression, Expression.Subtract)); // why aren't these used? //case ExpressionType.AddChecked: return Walk(expression, Expression.AddChecked); //case ExpressionType.MultiplyChecked: return Walk(expression, Expression.MultiplyChecked); //case ExpressionType.SubtractChecked: return Walk(expression, Expression.SubtractChecked); case ExpressionType.And: return(Walk(expression, Expression.And)); case ExpressionType.Or: return(Walk(expression, Expression.Or)); case ExpressionType.ExclusiveOr: return(Walk(expression, Expression.ExclusiveOr)); case ExpressionType.Equal: return(Walk(expression, Expression.Equal)); case ExpressionType.NotEqual: return(Walk(expression, Expression.NotEqual)); case ExpressionType.AndAlso: return(Walk(expression, Expression.AndAlso)); case ExpressionType.OrElse: return(Walk(expression, Expression.OrElse)); case ExpressionType.Power: return(Walk(expression, Expression.Power)); case ExpressionType.Modulo: return(Walk(expression, Expression.Modulo)); case ExpressionType.GreaterThan: return(Walk(expression, Expression.GreaterThan)); case ExpressionType.GreaterThanOrEqual: return(Walk(expression, Expression.GreaterThanOrEqual)); case ExpressionType.LessThan: return(Walk(expression, Expression.LessThan)); case ExpressionType.LessThanOrEqual: return(Walk(expression, Expression.LessThanOrEqual)); case ExpressionType.LeftShift: return(Walk(expression, Expression.LeftShift)); case ExpressionType.RightShift: return(Walk(expression, Expression.RightShift)); case ExpressionType.Not: return(Walk(expression, Expression.Not)); case ExpressionType.UnaryPlus: return(Walk(expression, Expression.UnaryPlus)); case ExpressionType.Negate: return(Walk(expression, Expression.Negate)); case ExpressionType.NegateChecked: return(Walk(expression, Expression.NegateChecked)); case ExpressionType.Convert: return(Walk(expression, Expression.Convert)); case ExpressionType.ConvertChecked: return(Walk(expression, Expression.ConvertChecked)); case ExpressionType.Coalesce: return(Walk(expression, Expression.Coalesce)); case ExpressionType.Conditional: { ConditionalExpression ce = (ConditionalExpression)expression; Expression test = Walk(ce.Test), ifTrue = Walk(ce.IfTrue), ifFalse = Walk(ce.IfFalse); if (test == null && ifTrue == null && ifFalse == null) { return(null); } return(Expression.Condition(test ?? ce.Test, ifTrue ?? ce.IfTrue, ifFalse ?? ce.IfFalse)); } case ExpressionType.Call: { MethodCallExpression mce = (MethodCallExpression)expression; Expression instance = Walk(mce.Object); List <Expression> args = mce.Arguments.Select(arg => Walk(arg)).ToList(); if (instance == null && !args.Any(arg => arg != null)) { return(null); } return(Expression.Call(instance, mce.Method, args)); } case ExpressionType.ArrayIndex: case ExpressionType.ArrayLength: case ExpressionType.Invoke: case ExpressionType.Lambda: case ExpressionType.ListInit: case ExpressionType.MemberInit: case ExpressionType.New: case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.TypeIs: throw new NotImplementedException("Not implemented: " + expression.NodeType); default: throw new NotSupportedException("Not supported: " + expression.NodeType); } }
protected internal virtual void PostWalk(ConditionalExpression node) { }
public ConditionalBlock(IEmitter emitter, ConditionalExpression conditionalExpression) : base(emitter, conditionalExpression) { this.Emitter = emitter; this.ConditionalExpression = conditionalExpression; }
public virtual void PostWalk(ConditionalExpression node) { }
void IExpressionVisitor.VisitConditionalExpression(ConditionalExpression cond) { throw new NotImplementedException(); }
public void VisitConditionalExpression(ConditionalExpression conditionalExpression) { StartNode(conditionalExpression); conditionalExpression.Condition.AcceptVisitor(this); Space(policy.SpaceBeforeConditionalOperatorCondition); WriteToken(ConditionalExpression.QuestionMarkRole); Space(policy.SpaceAfterConditionalOperatorCondition); conditionalExpression.TrueExpression.AcceptVisitor(this); Space(policy.SpaceBeforeConditionalOperatorSeparator); WriteToken(ConditionalExpression.ColonRole); Space(policy.SpaceAfterConditionalOperatorSeparator); conditionalExpression.FalseExpression.AcceptVisitor(this); EndNode(conditionalExpression); }
private static ConditionalExpression Clone(ConditionalExpression expression) { return(new ConditionalExpression(Clone(expression.Condition), Clone(expression.Left), Clone(expression.Right))); }
protected virtual bool CompareConditional(ConditionalExpression a, ConditionalExpression b) { return(Compare(a.Test, b.Test) && Compare(a.IfTrue, b.IfTrue) && Compare(a.IfFalse, b.IfFalse)); }
/// <summary> /// Generates a Conditional Expression that will retrieve the given entity value by type and set it into the current property. /// </summary> /// <param name="type">The entity type</param> /// <param name="property">The property to deserialize into</param> /// <param name="instanceParam">An Expression that represents the entity instance</param> /// <param name="currentEntityProperty">An Expression that represents the current EntityProperty expression</param> /// <returns></returns> private static Expression GeneratePropertyReadExpressionByType(Type type, PropertyInfo property, Expression instanceParam, Expression currentEntityProperty) { if (property.PropertyType == typeof(string)) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.String)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_StringPI.FindGetProp())))); } else if (property.PropertyType == typeof(byte[])) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Binary)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_BinaryPI.FindGetProp())))); } else if (property.PropertyType == typeof(bool?)) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Boolean)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_BoolPI.FindGetProp())))); } else if (property.PropertyType == typeof(bool)) { MethodInfo hasValuePI = typeof(bool?).FindProperty("HasValue").FindGetProp(); MethodInfo valuePI = typeof(bool?).FindProperty("Value").FindGetProp(); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Boolean)), Expression.IfThen(Expression.IsTrue(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_BoolPI.FindGetProp()), hasValuePI)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_BoolPI.FindGetProp()), valuePI))))); } else if (property.PropertyType == typeof(DateTime?)) { MethodInfo hasValuePI = typeof(DateTimeOffset?).FindProperty("HasValue").FindGetProp(); MethodInfo valuePI = typeof(DateTimeOffset?).FindProperty("Value").FindGetProp(); MethodInfo utcDateTimePI = typeof(DateTimeOffset).FindProperty("UtcDateTime").FindGetProp(); ParameterExpression tempVal = Expression.Variable(typeof(DateTime?), "tempVal"); ConditionalExpression valToSetExpr = Expression.IfThenElse( // entityProperty.DateTimeOffsetValue.HasValue Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_DateTimeOffsetPI.FindGetProp()), hasValuePI), // then //entityProperty.DateTimeOffsetValue.Value.UtcDateTime Expression.Assign(tempVal, Expression.TypeAs(Expression.Call(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_DateTimeOffsetPI.FindGetProp()), valuePI), utcDateTimePI), typeof(DateTime?))), // else Expression.Assign(tempVal, Expression.TypeAs(Expression.Constant(null), typeof(DateTime?)))); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.DateTime)), Expression.Block(new[] { tempVal }, valToSetExpr, Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), tempVal)))); } else if (property.PropertyType == typeof(DateTime)) { MethodInfo valuePI = typeof(DateTimeOffset?).FindProperty("Value").FindGetProp(); MethodInfo utcDateTimePI = typeof(DateTimeOffset).FindProperty("UtcDateTime").FindGetProp(); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.DateTime)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), // entityProperty.DateTimeOffsetValue.Value.UtcDateTime Expression.Call(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_DateTimeOffsetPI.FindGetProp()), valuePI), utcDateTimePI)))); } else if (property.PropertyType == typeof(DateTimeOffset?)) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.DateTime)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_DateTimeOffsetPI.FindGetProp())))); } else if (property.PropertyType == typeof(DateTimeOffset)) { MethodInfo hasValuePI = typeof(DateTimeOffset?).FindProperty("HasValue").FindGetProp(); MethodInfo valuePI = typeof(DateTimeOffset?).FindProperty("Value").FindGetProp(); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.DateTime)), Expression.IfThen(Expression.IsTrue(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_DateTimeOffsetPI.FindGetProp()), hasValuePI)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_DateTimeOffsetPI.FindGetProp()), valuePI))))); } else if (property.PropertyType == typeof(double?)) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Double)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_DoublePI.FindGetProp())))); } else if (property.PropertyType == typeof(double)) { MethodInfo hasValuePI = typeof(double?).FindProperty("HasValue").FindGetProp(); MethodInfo valuePI = typeof(double?).FindProperty("Value").FindGetProp(); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Double)), Expression.IfThen(Expression.IsTrue(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_DoublePI.FindGetProp()), hasValuePI)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_DoublePI.FindGetProp()), valuePI))))); } else if (property.PropertyType == typeof(Guid?)) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Guid)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_GuidPI.FindGetProp())))); } else if (property.PropertyType == typeof(Guid)) { MethodInfo hasValuePI = typeof(Guid?).FindProperty("HasValue").FindGetProp(); MethodInfo valuePI = typeof(Guid?).FindProperty("Value").FindGetProp(); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Guid)), Expression.IfThen(Expression.IsTrue(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_GuidPI.FindGetProp()), hasValuePI)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_GuidPI.FindGetProp()), valuePI))))); } else if (property.PropertyType == typeof(int?)) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Int32)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_Int32PI.FindGetProp())))); } else if (property.PropertyType == typeof(int)) { MethodInfo hasValuePI = typeof(int?).FindProperty("HasValue").FindGetProp(); MethodInfo valuePI = typeof(int?).FindProperty("Value").FindGetProp(); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Int32)), Expression.IfThen(Expression.IsTrue(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_Int32PI.FindGetProp()), hasValuePI)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_Int32PI.FindGetProp()), valuePI))))); } else if (property.PropertyType == typeof(long?)) { return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Int64)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(currentEntityProperty, EntityProperty_Int64PI.FindGetProp())))); } else if (property.PropertyType == typeof(long)) { MethodInfo hasValuePI = typeof(long?).FindProperty("HasValue").FindGetProp(); MethodInfo valuePI = typeof(long?).FindProperty("Value").FindGetProp(); return(Expression.IfThen(Expression.Equal(Expression.Call(currentEntityProperty, EntityProperty_PropTypeGetter), Expression.Constant(EdmType.Int64)), Expression.IfThen(Expression.IsTrue(Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_Int64PI.FindGetProp()), hasValuePI)), Expression.Call(Expression.Convert(instanceParam, type), property.FindSetProp(), Expression.Call(Expression.Call(currentEntityProperty, EntityProperty_Int64PI.FindGetProp()), valuePI))))); } return(null); }
protected override Expression VisitConditionalExpression(ConditionalExpression expression) { return(VisitUnhandledItem <ConditionalExpression, Expression>(expression, "VisitConditionalExpression", BaseVisitConditionalExpression)); }
public void AddCondition(ConditionalExpression condition) { _additionalConditions.Add(condition); condition.SetParent(this); }
private Expression create(DecisionNode node) { if (!node.IsLeaf) { int attributeIndex = node.Branches.AttributeIndex; // Create all comparison expressions BinaryExpression[] comparisons = new BinaryExpression[node.Branches.Count]; Expression[] childExpression = new Expression[node.Branches.Count]; for (int i = 0; i < comparisons.Length; i++) { DecisionNode child = node.Branches[i]; var expr = Expression.ArrayIndex(inputs, Expression.Constant(attributeIndex)); var cons = Expression.Constant(child.Value); switch (child.Comparison) { case ComparisonKind.Equal: comparisons[i] = Expression.Equal(expr, cons); break; case ComparisonKind.GreaterThan: comparisons[i] = Expression.GreaterThan(expr, cons); break; case ComparisonKind.GreaterThanOrEqual: comparisons[i] = Expression.GreaterThanOrEqual(expr, cons); break; case ComparisonKind.LessThan: comparisons[i] = Expression.LessThan(expr, cons); break; case ComparisonKind.LessThanOrEqual: comparisons[i] = Expression.LessThanOrEqual(expr, cons); break; case ComparisonKind.NotEqual: comparisons[i] = Expression.NotEqual(expr, cons); break; default: throw new InvalidOperationException("Unexpected node comparison type."); } childExpression[i] = create(node.Branches[i]); } // Create expression for else expressions ConstructorInfo ex = typeof(ArgumentException).GetConstructor(new[] { typeof(string), typeof(string) }); var lastElse = Expression.IfThenElse(comparisons[comparisons.Length - 1], childExpression[comparisons.Length - 1], Expression.Throw(Expression.New(ex, Expression.Constant("Input contains a value outside of expected ranges."), Expression.Constant("input")))); ConditionalExpression currentIf = null; for (int i = comparisons.Length - 2; i >= 0; i--) { currentIf = Expression.IfThenElse(comparisons[i], childExpression[i], lastElse); lastElse = currentIf; } return(currentIf); } else // node is a leaf { if (node.Output.HasValue) { return(Expression.Return(label, Expression.Constant(node.Output.Value), typeof(int))); } return(Expression.Return(label, Expression.Constant(-1), typeof(int))); } }
public void TypeTestInConditional() { Expression expr = new ConditionalExpression { Condition = new IdentifierExpression("a").IsType( new ComposedType { BaseType = new PrimitiveType("int"), HasNullableSpecifier = true } ), TrueExpression = new IdentifierExpression("b"), FalseExpression = new IdentifierExpression("c") }; Assert.AreEqual("a is int? ? b : c", InsertRequired(expr)); Assert.AreEqual("(a is int?) ? b : c", InsertReadable(expr)); policy.SpaceBeforeConditionalOperatorCondition = false; policy.SpaceAfterConditionalOperatorCondition = false; policy.SpaceBeforeConditionalOperatorSeparator = false; policy.SpaceAfterConditionalOperatorSeparator = false; Assert.AreEqual("a is int? ?b:c", InsertRequired(expr)); Assert.AreEqual("(a is int?)?b:c", InsertReadable(expr)); }
/** * Call back method that must be called as soon as the given <code> * ConditionalExpression</code> object has been traversed. * * @param pConditionalExpression The <code>ConditionalExpression</code> * object that has just been traversed. */ public void actionPerformed( ConditionalExpression pConditionalExpression) { // Nothing to do. }
public override bool Walk(ConditionalExpression node) { node.Parent = _currentScope; return base.Walk(node); }
public ConditionalExpressionProxy(ConditionalExpression node) { _node = node; }
public override bool Enter(ConditionalExpression node) { Print("ConditionalExpression"); level++; return true; }
protected Expression BaseVisitConditionalExpression(ConditionalExpression arg) { return(base.VisitConditionalExpression(arg)); }
/// <summary> /// ConditionalExpression visit method /// </summary> /// <param name="c">The ConditionalExpression expression to visit</param> /// <returns>The visited ConditionalExpression expression </returns> internal override Expression VisitConditional(ConditionalExpression c) { throw new NotSupportedException(Strings.ALinq_ConditionalNotSupported); }
public virtual void Exit(ConditionalExpression node) { }
private bool CompareConditional(ConditionalExpression a, ConditionalExpression b) => Compare(a.Test, b.Test) && Compare(a.IfTrue, b.IfTrue) && Compare(a.IfFalse, b.IfFalse);
public override void PostWalk(ConditionalExpression node) { node.Parent = _currentScope; base.PostWalk(node); }
// ConditionalExpression public override bool Walk(ConditionalExpression node) { return(Location >= node.StartIndex && Location <= node.EndIndex); }
public override void Exit(ConditionalExpression node) { level--; }
// ConditionalExpression public virtual bool Walk(ConditionalExpression node) { return(true); }
// ConditionalExpression protected internal virtual bool Walk(ConditionalExpression node) { return true; }
// ConditionalExpression public override bool Walk(ConditionalExpression node) { return(false); }
// ConditionalExpression public override bool Walk(ConditionalExpression node) { return false; }
public override void PostWalk(ConditionalExpression node) { }
// ConditionalExpression public virtual bool Walk(ConditionalExpression node) { return true; }
public virtual void PostWalk(ConditionalExpression node) { }
public virtual void VisitConditionalExpression (ConditionalExpression conditionalExpression) { VisitChildren (conditionalExpression); }
// returns null if no need to rewrite that branch, otherwise // returns a re-written branch private Expression Walk(Expression expression) { if (expression == null) { return(null); } Expression tmp; if (subst.TryGetValue(expression, out tmp)) { return(tmp); } switch (expression.NodeType) { case ExpressionType.Constant: case ExpressionType.Parameter: { return(expression); // never a need to rewrite if not already matched } case ExpressionType.MemberAccess: { MemberExpression me = (MemberExpression)expression; Expression target = Walk(me.Expression); return(target == null ? null : Expression.MakeMemberAccess(target, me.Member)); } case ExpressionType.Add: case ExpressionType.Divide: case ExpressionType.Multiply: case ExpressionType.Subtract: case ExpressionType.AddChecked: case ExpressionType.MultiplyChecked: case ExpressionType.SubtractChecked: case ExpressionType.And: case ExpressionType.Or: case ExpressionType.ExclusiveOr: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.AndAlso: case ExpressionType.OrElse: case ExpressionType.Power: case ExpressionType.Modulo: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.LeftShift: case ExpressionType.RightShift: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: { BinaryExpression binExp = (BinaryExpression)expression; Expression left = Walk(binExp.Left), right = Walk(binExp.Right); return((left == null && right == null) ? null : Expression.MakeBinary( binExp.NodeType, left ?? binExp.Left, right ?? binExp.Right, binExp.IsLiftedToNull, binExp.Method, binExp.Conversion)); } case ExpressionType.Not: case ExpressionType.UnaryPlus: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.TypeAs: case ExpressionType.ArrayLength: { UnaryExpression unExp = (UnaryExpression)expression; Expression operand = Walk(unExp.Operand); return(operand == null ? null : Expression.MakeUnary(unExp.NodeType, operand, unExp.Type, unExp.Method)); } case ExpressionType.Conditional: { ConditionalExpression ce = (ConditionalExpression)expression; Expression test = Walk(ce.Test), ifTrue = Walk(ce.IfTrue), ifFalse = Walk(ce.IfFalse); if (test == null && ifTrue == null && ifFalse == null) { return(null); } return(Expression.Condition(test ?? ce.Test, ifTrue ?? ce.IfTrue, ifFalse ?? ce.IfFalse)); } case ExpressionType.Call: { MethodCallExpression mce = (MethodCallExpression)expression; Expression instance = Walk(mce.Object); Expression[] args = Walk(mce.Arguments); if (instance == null && !HasValue(args)) { return(null); } return(Expression.Call(instance, mce.Method, CoalesceTerms(args, mce.Arguments))); } case ExpressionType.TypeIs: { TypeBinaryExpression tbe = (TypeBinaryExpression)expression; tmp = Walk(tbe.Expression); return(tmp == null ? null : Expression.TypeIs(tmp, tbe.TypeOperand)); } case ExpressionType.New: { NewExpression ne = (NewExpression)expression; Expression[] args = Walk(ne.Arguments); if (HasValue(args)) { return(null); } return(ne.Members == null?Expression.New(ne.Constructor, CoalesceTerms(args, ne.Arguments)) : Expression.New(ne.Constructor, CoalesceTerms(args, ne.Arguments), ne.Members)); } case ExpressionType.ListInit: { ListInitExpression lie = (ListInitExpression)expression; NewExpression ctor = (NewExpression)Walk(lie.NewExpression); var inits = lie.Initializers.Select(init => new { Original = init, NewArgs = Walk(init.Arguments) }).ToArray(); if (ctor == null && !inits.Any(init => HasValue(init.NewArgs))) { return(null); } ElementInit[] initArr = inits.Select(init => Expression.ElementInit( init.Original.AddMethod, CoalesceTerms(init.NewArgs, init.Original.Arguments))).ToArray(); return(Expression.ListInit(ctor ?? lie.NewExpression, initArr)); } case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: /* not quite right... leave as not-implemented for now * { * NewArrayExpression nae = (NewArrayExpression)expression; * Expression[] expr = Walk(nae.Expressions); * if (!HasValue(expr)) return null; * return expression.NodeType == ExpressionType.NewArrayBounds * ? Expression.NewArrayBounds(nae.Type, CoalesceTerms(expr, nae.Expressions)) * : Expression.NewArrayInit(nae.Type, CoalesceTerms(expr, nae.Expressions)); * }*/ case ExpressionType.Invoke: case ExpressionType.Lambda: case ExpressionType.MemberInit: case ExpressionType.Quote: throw new NotImplementedException("Not implemented: " + expression.NodeType); default: throw new NotSupportedException("Not supported: " + expression.NodeType); } }
public override object Visit (Conditional conditionalExpression) { var result = new ConditionalExpression (); result.AddChild ((INode)conditionalExpression.Expr.Accept (this), ConditionalExpression.Roles.Condition); var location = LocationsBag.GetLocations (conditionalExpression); result.AddChild (new CSharpTokenNode (Convert (conditionalExpression.Location), 1), ConditionalExpression.Roles.QuestionMark); result.AddChild ((INode)conditionalExpression.TrueExpr.Accept (this), ConditionalExpression.FalseExpressionRole); if (location != null) result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), ConditionalExpression.Roles.Colon); result.AddChild ((INode)conditionalExpression.FalseExpr.Accept (this), ConditionalExpression.FalseExpressionRole); return result; }
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { ConditionalExpression o = other as ConditionalExpression; return(o != null && this.Condition.DoMatch(o.Condition, match) && this.TrueExpression.DoMatch(o.TrueExpression, match) && this.FalseExpression.DoMatch(o.FalseExpression, match)); }
bool ExtractExpression (Statement statement, out Expression leftSide, out Expression rightSide) { ExpressionStatement expression = statement as ExpressionStatement; if (expression != null) { AssignmentExpression assignment = expression.Expression as AssignmentExpression; if (assignment != null) { if (assignment.Operator == AssignmentOperatorType.Add) { leftSide = assignment.Left; rightSide = assignment.Right; return true; } if (assignment.Operator == AssignmentOperatorType.Subtract) { leftSide = assignment.Left; rightSide = new UnaryOperatorExpression(UnaryOperatorType.Minus, assignment.Right.Clone()); return true; } leftSide = null; rightSide = null; return false; } UnaryOperatorExpression unary = expression.Expression as UnaryOperatorExpression; if (unary != null) { leftSide = unary.Expression; if (unary.Operator == UnaryOperatorType.Increment || unary.Operator == UnaryOperatorType.PostIncrement) { rightSide = new PrimitiveExpression(1); return true; } else if (unary.Operator == UnaryOperatorType.Decrement || unary.Operator == UnaryOperatorType.PostDecrement) { rightSide = new PrimitiveExpression(-1); return true; } else { leftSide = null; rightSide = null; return false; } } } if (statement is EmptyStatement || statement.IsNull) { leftSide = null; rightSide = null; return true; } BlockStatement block = statement as BlockStatement; if (block != null) { leftSide = null; rightSide = null; foreach (Statement child in block.Statements) { Expression newLeft, newRight; if (!ExtractExpression(child, out newLeft, out newRight)) { leftSide = null; rightSide = null; return false; } if (newLeft == null) { continue; } if (leftSide == null) { leftSide = newLeft; rightSide = newRight; } else if (SameNode(leftSide, newLeft)) { rightSide = new BinaryOperatorExpression(ParenthesizeIfNeeded(rightSide).Clone(), BinaryOperatorType.Add, ParenthesizeIfNeeded(newRight).Clone()); } else { return false; } } return true; } IfElseStatement condition = statement as IfElseStatement; if (condition != null) { Expression ifLeft, ifRight; if (!ExtractExpression(condition.TrueStatement, out ifLeft, out ifRight)) { leftSide = null; rightSide = null; return false; } Expression elseLeft, elseRight; if (!ExtractExpression(condition.FalseStatement, out elseLeft, out elseRight)) { leftSide = null; rightSide = null; return false; } if (ifLeft == null && elseLeft == null) { leftSide = null; rightSide = null; return true; } if (ifLeft != null && elseLeft != null && !SameNode(ifLeft, elseLeft)) { leftSide = null; rightSide = null; return false; } ifRight = ifRight ?? new PrimitiveExpression(0); elseRight = elseRight ?? new PrimitiveExpression(0); leftSide = ifLeft ?? elseLeft; rightSide = new ConditionalExpression(condition.Condition.Clone(), ifRight.Clone(), elseRight.Clone()); return true; } leftSide = null; rightSide = null; return false; }
internal static Expression BindMember(Expression source, MemberInfo member) { switch (source.NodeType) { case ExpressionType.MemberInit: MemberInitExpression min = (MemberInitExpression)source; for (int i = 0, n = min.Bindings.Count; i < n; i++) { MemberAssignment assign = min.Bindings[i] as MemberAssignment; if (assign != null && MembersMatch(assign.Member, member)) { return(assign.Expression); } } break; case ExpressionType.New: NewExpression nex = (NewExpression)source; if (nex.Members != null) { for (int i = 0, n = nex.Members.Count; i < n; i++) { if (MembersMatch(nex.Members[i], member)) { return(nex.Arguments[i]); } } } else if (nex.Type.IsGenericType && nex.Type.GetGenericTypeDefinition() == typeof(Grouping <,>)) { if (member.Name == "Key") { return(nex.Arguments[0]); } } break; case (ExpressionType)DbExpressionType.Projection: // member access on a projection turns into a new projection w/ member access applied ProjectionExpression proj = (ProjectionExpression)source; Expression newProjector = BindMember(proj.Projector, member); return(new ProjectionExpression(proj.Source, newProjector)); case (ExpressionType)DbExpressionType.OuterJoined: OuterJoinedExpression oj = (OuterJoinedExpression)source; Expression em = BindMember(oj.Expression, member); if (em is ColumnExpression) { return(em); } return(new OuterJoinedExpression(oj.Test, em)); case ExpressionType.Conditional: ConditionalExpression cex = (ConditionalExpression)source; return(Expression.Condition(cex.Test, BindMember(cex.IfTrue, member), BindMember(cex.IfFalse, member))); case ExpressionType.Constant: ConstantExpression con = (ConstantExpression)source; if (con.Value == null) { Type memberType = TypeHelper.GetMemberType(member); return(Expression.Constant(GetDefault(memberType), memberType)); } break; } return(Expression.MakeMemberAccess(source, member)); }