/// <summary> /// Creates an expression that copies a coplex array value from the source to the target. The value will be cloned as well using the dictionary to reuse already cloned objects. /// </summary> /// <param name="sourceField"></param> /// <param name="targetField"></param> /// <param name="type"></param> /// <param name="objectDictionary"></param> /// <returns></returns> internal static Expression CreateCopyComplexArrayTypeFieldExpression(Expression sourceField, Expression targetField, Type type, ParameterExpression objectDictionary) { return Expression.IfThenElse( Expression.Call(objectDictionary, _dictionaryContainsKey, sourceField), Expression.Assign(targetField, Expression.Convert(Expression.Call(objectDictionary, _dictionaryGetItem, sourceField), type)), Expression.Assign(targetField, Expression.Convert(Expression.Call(Expression.Call(_getTypeClonerMethodInfo, Expression.Call(sourceField, _getTypeMethodInfo)), _invokeMethodInfo, sourceField, objectDictionary), type)) ); }
internal static Expression CreateSetFieldExpression(Expression clone, Expression value, FieldInfo fieldInfo) { // workaround for readonly fields: use reflection, this is a lot slower but the only way except using il directly if (fieldInfo.IsInitOnly) return Expression.Call(Expression.Constant(fieldInfo), _fieldInfoSetValueMethod, clone, Expression.Convert(value, TypeHelper.ObjectType)); return Expression.Assign(Expression.Field(clone, fieldInfo), value); }
internal ForCSharpStatement(ReadOnlyCollection<ParameterExpression> variables, ReadOnlyCollection<Expression> initializers, Expression test, ReadOnlyCollection<Expression> iterators, Expression body, LabelTarget breakLabel, LabelTarget continueLabel) : base(test, body, breakLabel, continueLabel) { Variables = variables; Initializers = initializers; Iterators = iterators; }
static ElementInit PropertyToElementInit(PropertyInfo propertyInfo, Expression instance) { return Expression.ElementInit(DictionaryAddMethod, Expression.Constant(propertyInfo.Name), Expression.Call(ToStringOrNullMethod, Expression.Convert(Expression.Property(instance, propertyInfo), typeof(object)))); }
private Expression CreatePropertyAccessExpression(Expression instance, string propertyName) { CallSiteBinder binder = Binder.GetMember(CSharpBinderFlags.None, propertyName, typeof(DynamicPropertyAccessExpressionBuilder), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }); return Expression.Dynamic(binder, typeof(object), new[] { instance }); }
public override Expression CompileBulkImporter(EnumStorage enumStorage, Expression writer, ParameterExpression document, ParameterExpression alias, ParameterExpression serializer) { var method = writeMethod.MakeGenericMethod(typeof(string)); var dbType = Expression.Constant(DbType); return Expression.Call(writer, method, alias, dbType); }
void Output(Expression<Func<ContentItem, bool>> expr) { Debug.WriteLine("expr: " + expr); Debug.WriteLine(expr.Body); Debug.WriteLine(expr.Parameters[0]); var mce = expr.Body as MethodCallExpression; Debug.WriteLine("mce: " + mce); Debug.WriteLine(mce.Arguments.Count); Debug.WriteLine(mce.Arguments[0]); Debug.WriteLine(mce.Method); Debug.WriteLine(mce.Object); var mce2 = mce.Arguments[0] as MethodCallExpression; Debug.WriteLine("mce2: " + mce2); Debug.WriteLine(mce2.Arguments.Count); Debug.WriteLine(mce2.Arguments[0]); Debug.WriteLine(mce2.Method); Debug.WriteLine(mce2.Object); var me = mce2.Arguments[0] as MemberExpression; Debug.WriteLine("me: " + me); Debug.WriteLine(me.Expression); Debug.WriteLine(me.Member); var me2 = me.Expression as MemberExpression; Debug.WriteLine("me2: " + me2); Debug.WriteLine(me2.Expression); Debug.WriteLine(me2.Member); var pe = me2.Expression as ParameterExpression; Debug.WriteLine("pe: " + pe); Debug.WriteLine(pe.Name); Debug.WriteLine(pe.Type); }
public override Expression VisitExpression(Expression expression) { if (expression == null) { return null; } switch ((NhExpressionType)expression.NodeType) { case NhExpressionType.Average: case NhExpressionType.Min: case NhExpressionType.Max: case NhExpressionType.Sum: case NhExpressionType.Count: case NhExpressionType.Distinct: return VisitNhAggregate((NhAggregatedExpression)expression); case NhExpressionType.New: return VisitNhNew((NhNewExpression)expression); case NhExpressionType.Star: return VisitNhStar((NhStarExpression)expression); } // Keep this variable for easy examination during debug. var expr = base.VisitExpression(expression); return expr; }
internal Binding(Expression linqExpression, DbExpression cqtExpression) { //Contract.Requires(linqExpression != null); //Contract.Requires(cqtExpression != null); LinqExpression = linqExpression; CqtExpression = cqtExpression; }
private void Gather(Expression expression) { BinaryExpression b = expression as BinaryExpression; if (b != null) { switch (b.NodeType) { case ExpressionType.Equal: case ExpressionType.NotEqual: if (IsExternalColumn(b.Left) && GetColumn(b.Right) != null) { this.columns.Add(GetColumn(b.Right)); } else if (IsExternalColumn(b.Right) && GetColumn(b.Left) != null) { this.columns.Add(GetColumn(b.Left)); } break; case ExpressionType.And: case ExpressionType.AndAlso: if (b.Type == typeof(bool) || b.Type == typeof(bool?)) { this.Gather(b.Left); this.Gather(b.Right); } break; } } }
public static string ExpressionToString(Expression expr) { if (propertyDebugView == null) propertyDebugView = typeof(Expression).GetTypeInfo().FindDeclaredProperty("DebugView", ReflectionFlag.NoException | ReflectionFlag.NonPublic | ReflectionFlag.Instance); return (string)propertyDebugView.GetValue(expr, null); }
protected override Expression Visit(Expression exp) { if(exp != null) return base.Visit(exp); return exp; }
// private static methods private static Boolean CanBeEvaluatedLocally(Expression expression, IQueryProvider queryProvider) { // any operation on a query can't be done locally var constantExpression = expression as ConstantExpression; if (constantExpression != null) { var query = constantExpression.Value as IQueryable; if (query != null && (queryProvider == null || query.Provider == queryProvider)) { return false; } } var methodCallExpression = expression as MethodCallExpression; if (methodCallExpression != null) { Type declaringType = methodCallExpression.Method.DeclaringType; if (declaringType == typeof (Enumerable) || declaringType == typeof (Queryable)) { return false; } } if (expression.NodeType == ExpressionType.Convert && expression.Type == typeof (Object)) { return true; } if (expression.NodeType == ExpressionType.Parameter || expression.NodeType == ExpressionType.Lambda) { return false; } return true; }
public IEnumerable<ErrorLog> Get( Expression<Func<ErrorLog, bool>> filter = null, Func<IQueryable<ErrorLog>, IOrderedQueryable<ErrorLog>> orderBy = null, string includeProperties = "") { return _unitOfWork.ErrorLogRepository.Get(filter, orderBy, includeProperties); }
// private static methods private static Type GetDocumentType(Expression expression) { // look for the innermost nested constant of type MongoQueryable<T> and return typeof(T) var constantExpression = expression as ConstantExpression; if (constantExpression != null) { var constantType = constantExpression.Type; if (constantType.IsGenericType) { var genericTypeDefinition = constantType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(MongoQueryable<>)) { return constantType.GetGenericArguments()[0]; } } } var methodCallExpression = expression as MethodCallExpression; if (methodCallExpression != null && methodCallExpression.Arguments.Count != 0) { return GetDocumentType(methodCallExpression.Arguments[0]); } var message = string.Format("Unable to find document type of expression: {0}.", ExpressionFormatter.ToString(expression)); throw new ArgumentOutOfRangeException(message); }
internal UnaryExpression(ExpressionType nodeType, Expression expression, Type type, MethodInfo method) { _operand = expression; _method = method; _nodeType = nodeType; _type = type; }
public static void Parse(SortedSet<string> list, Expression expr) { if (expr == null) return; BinaryExpression eb = expr as BinaryExpression; MemberExpression em = expr as MemberExpression; UnaryExpression eu = expr as UnaryExpression; MethodCallExpression ec = expr as MethodCallExpression; if (em != null) // member expression { list.Add(em.Member.Name); } else if (eb != null) // binary expression { Parse(list, eb.Left); Parse(list, eb.Right); } else if (eu != null) // unary expression { Parse(list, eu.Operand); } else if (ec != null) // call expression { foreach (var a in ec.Arguments) Parse(list, a); } return; }
// public methods /// <summary> /// Pretty prints an Expression. /// </summary> /// <param name="node">The Expression to pretty print.</param> /// <returns>A string containing the pretty printed Expression.</returns> public string PrettyPrint(Expression node) { _sb = new StringBuilder(); _indentation = ""; Visit(node); return _sb.ToString(); }
public override Expression BuildExpression(Expression expression, int level) { var expr = Sequence.BuildExpression(expression, level); if (expression == null) { var q = from col in SqlQuery.Select.Columns where !col.CanBeNull() select SqlQuery.Select.Columns.IndexOf(col); var idx = q.DefaultIfEmpty(-1).First(); if (idx == -1) idx = SqlQuery.Select.Add(new SqlValue((int?) 1)); var n = ConvertToParentIndex(idx, this); var e = Expression.Call( ExpressionBuilder.DataReaderParam, ReflectionHelper.DataReader.IsDBNull, Expression.Constant(n)) as Expression; var defaultValue = _defaultValue ?? Expression.Constant(null, expr.Type); expr = Expression.Condition(e, defaultValue, expr); } return expr; }
EvaluationResult EvaluateUnsupported(Expression expression) { try { return EvaluationResult.Success(expression.Type, Expression.Lambda<Func<object>>(expression.Box()).Compile()()); } catch(Exception e) { return EvaluationResult.Failure(expression, e); } }
protected override Expression VisitBlockHelperExpression(BlockHelperExpression bhex) { var fb = new FunctionBuilder(CompilationContext.Configuration); var body = fb.Compile(((BlockExpression)bhex.Body).Expressions, CompilationContext.BindingContext); var inversion = fb.Compile(((BlockExpression)bhex.Inversion).Expressions, CompilationContext.BindingContext); var helper = CompilationContext.Configuration.BlockHelpers[bhex.HelperName.Replace("#", "")]; var arguments = new Expression[] { Expression.Property( CompilationContext.BindingContext, typeof(BindingContext).GetProperty("TextWriter")), Expression.New( typeof(HelperOptions).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0], body, inversion), Expression.Property( CompilationContext.BindingContext, typeof(BindingContext).GetProperty("Value")), Expression.NewArrayInit(typeof(object), bhex.Arguments) }; if (helper.Target != null) { return Expression.Call( Expression.Constant(helper.Target), helper.Method, arguments); } else { return Expression.Call( helper.Method, arguments); } }
public override SqlInfo[] ConvertToSql(Expression expression, int level, ConvertFlags flags) { return SubQuery .ConvertToIndex(expression, level, flags) .Select(idx => new SqlInfo { Sql = SubQuery.SqlQuery.Select.Columns[idx.Index], Member = idx.Member }) .ToArray(); }
public GroupJoinExpressionNode ( MethodCallExpressionParseInfo parseInfo, Expression innerSequence, LambdaExpression outerKeySelector, LambdaExpression innerKeySelector, LambdaExpression resultSelector) : base(parseInfo) { ArgumentUtility.CheckNotNull ("innerSequence", innerSequence); ArgumentUtility.CheckNotNull ("outerKeySelector", outerKeySelector); ArgumentUtility.CheckNotNull ("innerKeySelector", innerKeySelector); ArgumentUtility.CheckNotNull ("resultSelector", resultSelector); if (outerKeySelector.Parameters.Count != 1) throw new ArgumentException ("Outer key selector must have exactly one parameter.", "outerKeySelector"); if (innerKeySelector.Parameters.Count != 1) throw new ArgumentException ("Inner key selector must have exactly one parameter.", "innerKeySelector"); if (resultSelector.Parameters.Count != 2) throw new ArgumentException ("Result selector must have exactly two parameters.", "resultSelector"); var joinResultSelector = Expression.Lambda (Expression.Constant (null), outerKeySelector.Parameters[0], innerKeySelector.Parameters[0]); JoinExpressionNode = new JoinExpressionNode (parseInfo, innerSequence, outerKeySelector, innerKeySelector, joinResultSelector); ResultSelector = resultSelector; _cachedResultSelector = new ResolvedExpressionCache<Expression> (this); }
/// <summary> /// Adds an additional Instance constructed by a Lambda Expression using IContext /// </summary> /// <param name="func"></param> /// <returns></returns> public LambdaInstance<object> Add(Expression<Func<IContext, object>> func) { var instance = new LambdaInstance<object>(func); Add(instance); return instance; }
private bool IsExternalColumn(Expression exp) { var col = GetColumn(exp); if (col != null && !this.aliases.Contains(col.Alias)) return true; return false; }
/// <summary> /// Visit an expression. For each expression first make sure that it has been /// translated and parameter replaced. We do this recusively... /// </summary> /// <param name="expression"></param> /// <returns></returns> public override Expression Visit(Expression expression) { // // Sometimes we are called with a null - we ignore that! :-) // if (expression == null) return null; /// /// See if there are any parameter replacements that can be done out-of-band /// var expr = ParameterReplacementExpressionVisitor.ReplaceParameters(expression, CodeContext); // // Next, attempt to translate the expr (if needed). This deals with moving from // one pre-done space to another. // string oldExpr = ""; while (expr.ToString() != oldExpr) { oldExpr = expr.ToString(); expr = TranslatingExpressionVisitor.Translate(expr, CodeContext.CacheCookies, e => e.Resolve(GeneratedCode, CodeContext, MEFContainer)); } // // Now do the rest of the parsing. // return base.Visit(expr); }
protected override Expression Visit(Expression exp) { if (_candidates.Contains(exp)) { if (exp.NodeType == (ExpressionType)MongoExpressionType.Field) { var field = (FieldExpression)exp; FieldExpression mapped; if (_map.TryGetValue(field, out mapped)) return mapped; Alias alias = _existingAliases.Contains(field.Alias) ? field.Alias : _newAlias; var fieldName = GetUniqueFieldName(field.Name); _fields.Add(new FieldDeclaration(fieldName, field)); return new FieldExpression(exp, alias, field.Name); } else { var fieldName = GetNextFieldName(); _fields.Add(new FieldDeclaration(fieldName, exp)); return new FieldExpression(exp, _newAlias, fieldName); } } return base.Visit(exp); }
internal TryExpression(Type type, Expression body, Expression @finally, Expression fault, ReadOnlyCollection<CatchBlock> handlers) { _type = type; _body = body; _handlers = handlers; _finally = @finally; _fault = fault; }
public Expression ResolvePotentialEntity (Expression expression) { ArgumentUtility.CheckNotNull ("expression", expression); var strippedExpression = StripConversions (expression); var namedExpression = strippedExpression as NamedExpression; if (namedExpression != null) { var result = ResolvePotentialEntity (namedExpression.Expression); if (result != namedExpression.Expression) return new NamedExpression (namedExpression.Name, result); return expression; } var entityExpression = strippedExpression as SqlEntityExpression; if (entityExpression != null) return entityExpression.GetIdentityExpression (); var entityConstantExpression = strippedExpression as SqlEntityConstantExpression; if (entityConstantExpression != null) return entityConstantExpression.IdentityExpression; var entityRefMemberExpression = strippedExpression as SqlEntityRefMemberExpression; if (entityRefMemberExpression != null) return GetIdentityExpressionForReferencedEntity (entityRefMemberExpression); var sqlSubStatementExpression = strippedExpression as SqlSubStatementExpression; if (sqlSubStatementExpression != null) return CheckAndSimplifyEntityWithinSubStatement (sqlSubStatementExpression); return expression; }
/// <summary> /// Provides language specific query translation. Use this to apply language specific rewrites or /// to make assertions/validations about the query. /// </summary> /// <param name="expression"></param> /// <returns></returns> public virtual Expression Translate(Expression expression) { // remove redundant layers again before cross apply rewrite expression = UnusedColumnRemover.Remove(expression); expression = RedundantColumnRemover.Remove(expression); expression = RedundantSubqueryRemover.Remove(expression); // convert cross-apply and outer-apply joins into inner & left-outer-joins if possible var rewritten = CrossApplyRewriter.Rewrite(this._language, expression); // convert cross joins into inner joins rewritten = CrossJoinRewriter.Rewrite(rewritten); if (rewritten != expression) { expression = rewritten; // do final reduction expression = UnusedColumnRemover.Remove(expression); expression = RedundantSubqueryRemover.Remove(expression); expression = RedundantJoinRemover.Remove(expression); expression = RedundantColumnRemover.Remove(expression); } return expression; }
public T Find(Expression <Func <T, bool> > criteria) { return(_query.FirstOrDefault(criteria)); }
public LambdaExpressionVistor(L.ParameterExpression context, EvaluateOptions options) { _context = context; _options = options; }
public override void Visit(BinaryExpression expression) { expression.LeftExpression.Accept(this); var left = _result; expression.RightExpression.Accept(this); var right = _result; switch (expression.Type) { case BinaryExpressionType.And: _result = L.Expression.AndAlso(left, right); break; case BinaryExpressionType.Or: _result = L.Expression.OrElse(left, right); break; case BinaryExpressionType.NotEqual: _result = WithCommonNumericType(left, right, L.Expression.NotEqual, expression.Type); break; case BinaryExpressionType.LesserOrEqual: _result = WithCommonNumericType(left, right, L.Expression.LessThanOrEqual, expression.Type); break; case BinaryExpressionType.GreaterOrEqual: _result = WithCommonNumericType(left, right, L.Expression.GreaterThanOrEqual, expression.Type); break; case BinaryExpressionType.Lesser: _result = WithCommonNumericType(left, right, L.Expression.LessThan, expression.Type); break; case BinaryExpressionType.Greater: _result = WithCommonNumericType(left, right, L.Expression.GreaterThan, expression.Type); break; case BinaryExpressionType.Equal: _result = WithCommonNumericType(left, right, L.Expression.Equal, expression.Type); break; case BinaryExpressionType.Minus: if (Checked) { _result = WithCommonNumericType(left, right, L.Expression.SubtractChecked); } else { _result = WithCommonNumericType(left, right, L.Expression.Subtract); } break; case BinaryExpressionType.Plus: if (Checked) { _result = WithCommonNumericType(left, right, L.Expression.AddChecked); } else { _result = WithCommonNumericType(left, right, L.Expression.Add); } break; case BinaryExpressionType.Modulo: _result = WithCommonNumericType(left, right, L.Expression.Modulo); break; case BinaryExpressionType.Div: _result = WithCommonNumericType(left, right, L.Expression.Divide); break; case BinaryExpressionType.Times: if (Checked) { _result = WithCommonNumericType(left, right, L.Expression.MultiplyChecked); } else { _result = WithCommonNumericType(left, right, L.Expression.Multiply); } break; case BinaryExpressionType.BitwiseOr: _result = L.Expression.Or(left, right); break; case BinaryExpressionType.BitwiseAnd: _result = L.Expression.And(left, right); break; case BinaryExpressionType.BitwiseXOr: _result = L.Expression.ExclusiveOr(left, right); break; case BinaryExpressionType.LeftShift: _result = L.Expression.LeftShift(left, right); break; case BinaryExpressionType.RightShift: _result = L.Expression.RightShift(left, right); break; default: throw new ArgumentOutOfRangeException(); } }
private Microsoft.Scripting.Ast.LightExpression <Func <CodeContext, CodeContext> > MakeClassBody() { // we always need to create a nested context for class defs var init = new List <MSAst.Expression>(); var locals = new ReadOnlyCollectionBuilder <MSAst.ParameterExpression>(); locals.Add(LocalCodeContextVariable); locals.Add(PythonAst._globalContext); init.Add(Ast.Assign(PythonAst._globalContext, new GetGlobalContextExpression(_parentContextParam))); GlobalParent.PrepareScope(locals, init); CreateVariables(locals, init); var createLocal = CreateLocalContext(_parentContextParam); init.Add(Ast.Assign(LocalCodeContextVariable, createLocal)); List <MSAst.Expression> statements = new List <MSAst.Expression>(); // Create the body MSAst.Expression bodyStmt = _body; // __module__ = __name__ MSAst.Expression modStmt = AssignValue(GetVariableExpression(_modVariable), GetVariableExpression(_modNameVariable)); string doc = GetDocumentation(_body); if (doc != null) { statements.Add( AssignValue( GetVariableExpression(_docVariable), AstUtils.Constant(doc) ) ); } if (_body.CanThrow && GlobalParent.PyContext.PythonOptions.Frames) { bodyStmt = AddFrame(LocalContext, FuncCodeExpr, bodyStmt); locals.Add(FunctionStackVariable); } bodyStmt = WrapScopeStatements( Ast.Block( Ast.Block(init), statements.Count == 0 ? EmptyBlock : Ast.Block(new ReadOnlyCollection <MSAst.Expression>(statements)), modStmt, bodyStmt, LocalContext ), _body.CanThrow ); var lambda = AstUtils.LightLambda <Func <CodeContext, CodeContext> >( typeof(CodeContext), Ast.Block( locals, bodyStmt ), Name + "$" + Interlocked.Increment(ref _classId), new[] { _parentContextParam } ); return(lambda); }
Exp GlobalAccess(string name) { return(Exp.Property(_G, "Item", Exp.Constant(name))); }
internal MSAst.Expression TransformAndDynamicConvert(Expression expression, Type /*!*/ type) { Debug.Assert(expression != null); MSAst.Expression res = expression; // Do we need conversion? if (!CanAssign(type, expression.Type)) { // ensure we're reduced before we check for dynamic expressions. var reduced = expression.Reduce(); if (reduced is LightDynamicExpression) { reduced = reduced.Reduce(); } // Add conversion step to the AST MSAst.DynamicExpression ae = reduced as MSAst.DynamicExpression; ReducableDynamicExpression rde = reduced as ReducableDynamicExpression; if ((ae != null && ae.Binder is PythonBinaryOperationBinder) || (rde != null && rde.Binder is PythonBinaryOperationBinder)) { // create a combo site which does the conversion PythonBinaryOperationBinder binder; IList <MSAst.Expression> args; if (ae != null) { binder = (PythonBinaryOperationBinder)ae.Binder; args = ArrayUtils.ToArray(ae.Arguments); } else { binder = (PythonBinaryOperationBinder)rde.Binder; args = rde.Args; } ParameterMappingInfo[] infos = new ParameterMappingInfo[args.Count]; for (int i = 0; i < infos.Length; i++) { infos[i] = ParameterMappingInfo.Parameter(i); } res = Expression.Dynamic( GlobalParent.PyContext.BinaryOperationRetType( binder, GlobalParent.PyContext.Convert( type, ConversionResultKind.ExplicitCast ) ), type, args ); } else { res = GlobalParent.Convert( type, ConversionResultKind.ExplicitCast, reduced ); } } return(res); }
/// <summary> /// Removes the frames from generated code for when we're compiling the tracing delegate /// which will track the frames it's self. /// </summary> internal static MSAst.Expression RemoveFrame(MSAst.Expression expression) { return(new FramedCodeVisitor().Visit(expression)); }
public T Find <T>(Expression <Func <T, bool> > criteria) where T : class { return(All <T>().Where(criteria).FirstOrDefault()); }
public IEnumerable <T> FindAll(Expression <Func <T, bool> > criteria, int offset = 0, int limit = 0, Sorting <T> orderBy = null) { var query = _query.Where(criteria); return(_repository.Page(query, offset, limit, orderBy)); }
public IEnumerable <T> FindAll <T>(Expression <Func <T, bool> > criteria, int offset = 0, int limit = 0, Sorting <T> orderBy = null) where T : class { var query = All <T>().Where(criteria); return(this.Page(query, offset, limit, orderBy)); }
public override void Visit(ValueExpression expression) { _result = L.Expression.Constant(expression.Value); }
public SiteInfo(DynamicMetaObjectBinder /*!*/ binder, MSAst.Expression /*!*/ expr, FieldInfo /*!*/ field, int index, Type /*!*/ delegateType, Type /*!*/ siteType) : this(binder, expr, field, index, delegateType) { _siteType = siteType; }
public static IQueryable <T> WhereIf <T>(this IQueryable <T> source, bool condition, Linq.Expressions.Expression <Func <T, int, bool> > predicate) { return(condition ? source.Where(predicate) : source); }
internal override MSAst.Expression TransformSet(SourceSpan span, MSAst.Expression right, PythonOperationKind op) { // if we just have a simple named multi-assignment (e.g. a, b = 1,2) // then go ahead and step over the entire statement at once. If we have a // more complex statement (e.g. a.b, c.d = 1, 2) then we'll step over the // sets individually as they could be property sets the user wants to step // into. TODO: Enable stepping of the right hand side? bool emitIndividualSets = false; foreach (Expression e in _items) { if (IsComplexAssignment(e)) { emitIndividualSets = true; break; } } SourceSpan rightSpan = SourceSpan.None; SourceSpan leftSpan = (Span.Start.IsValid && span.IsValid) ? new SourceSpan(Span.Start, span.End) : SourceSpan.None; SourceSpan totalSpan = SourceSpan.None; if (emitIndividualSets) { rightSpan = span; leftSpan = SourceSpan.None; totalSpan = (Span.Start.IsValid && span.IsValid) ? new SourceSpan(Span.Start, span.End) : SourceSpan.None; } // 1. Evaluate the expression and assign the value to the temp. MSAst.ParameterExpression right_temp = Ast.Variable(typeof(object), "unpacking"); // 2. Add the assignment "right_temp = right" into the suite/block MSAst.Expression assignStmt1 = MakeAssignment(right_temp, right); int expected = _items.Length; int argcntafter = -1; for (var i = 0; i < _items.Length; i++) { var item = _items[i]; if (item is StarredExpression) { expected = i; argcntafter = _items.Length - i - 1; break; } } // 3. Call GetEnumeratorValues on the right side (stored in temp) MSAst.Expression enumeratorValues = Expression.Convert(LightExceptions.CheckAndThrow( Expression.Call( // method argcntafter != -1 ? AstMethods.UnpackIterable : emitIndividualSets ? AstMethods.GetEnumeratorValues : AstMethods.GetEnumeratorValuesNoComplexSets, // arguments Parent.LocalContext, right_temp, AstUtils.Constant(expected), AstUtils.Constant(argcntafter) ) ), typeof(object[])); // 4. Create temporary variable for the array MSAst.ParameterExpression array_temp = Ast.Variable(typeof(object[]), "array"); // 5. Assign the value of the method call (mce) into the array temp // And add the assignment "array_temp = Ops.GetEnumeratorValues(...)" into the block MSAst.Expression assignStmt2 = MakeAssignment( array_temp, enumeratorValues, rightSpan ); ReadOnlyCollectionBuilder <MSAst.Expression> sets = new ReadOnlyCollectionBuilder <MSAst.Expression>(_items.Length + 1); for (int i = 0; i < _items.Length; i++) { // target = array_temp[i] Expression target = _items[i]; if (target == null) { continue; } // 6. array_temp[i] MSAst.Expression element = Ast.ArrayAccess( array_temp, // array expression AstUtils.Constant(i) // index ); // 7. target = array_temp[i], and add the transformed assignment into the list of sets MSAst.Expression set = target.TransformSet( emitIndividualSets ? // span target.Span : SourceSpan.None, element, PythonOperationKind.None ); sets.Add(set); } // 9. add the sets as their own block so they can be marked as a single span, if necessary. sets.Add(AstUtils.Empty()); MSAst.Expression itemSet = GlobalParent.AddDebugInfo(Ast.Block(sets.ToReadOnlyCollection()), leftSpan); // 10. Return the suite statement (block) return(GlobalParent.AddDebugInfo(Ast.Block(new[] { array_temp, right_temp }, assignStmt1, assignStmt2, itemSet, AstUtils.Empty()), totalSpan)); }
public ILoadService <T> Include <TProperty>(Expression <Func <T, TProperty> > path) where TProperty : class { var properties = path.Body.ToString().Split('.').Where(p => !p.StartsWith("Select")).Select(p => p.TrimEnd(')')).ToArray(); if (properties.Length == 2) { if (typeof(IEnumerable).IsAssignableFrom(typeof(TProperty))) { ((IQueryable <T>)_fetchMany.Invoke(null, new object[] { _query, path })).ToFuture(); } else { _query.Fetch(path).ToFuture(); } } else if (properties.Length > 2) { var current = typeof(T); IQueryable <T> query = null; for (var i = 1; i < properties.Length; i++) { if (i == 1) { if (typeof(IEnumerable).IsAssignableFrom(typeof(TProperty))) { query = (IQueryable <T>)_fetchMany.Invoke(null, new object[] { _query, path }); current = typeof(TProperty).GetGenericArguments()[0]; } else { query = _query.Fetch(path); current = typeof(TProperty); } } else { var property = current.GetProperty(properties[i]); if (property == null) { break; } var propertyType = property.PropertyType; var parameter = Expression.Parameter(current); var body = Expression.Convert(Expression.PropertyOrField(parameter, properties[i]), propertyType); var selector = Expression.Lambda(body, parameter); if (typeof(IEnumerable).IsAssignableFrom(propertyType)) { query = (IQueryable <T>)_thenFetchMany.Invoke(null, new object[] { query, selector }); current = propertyType.GetGenericArguments()[0]; } else { query = (IQueryable <T>)_thenFetch.Invoke(null, new object[] { query, selector }); current = propertyType; } } } query.ToFuture(); } return(this); }
public long Count <T>(Expression <Func <T, bool> > criteria) where T : class { return(All <T>().LongCount(criteria)); }
/// <summary> /// Creates a method frame for tracking purposes and enforces recursion /// </summary> internal static MSAst.Expression AddFrame(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) { return(new FramedCodeExpression(localContext, codeObject, body)); }
private MSA.Expression /*!*/ TransformExceptionHandling(AstGenerator /*!*/ gen, ResultOperation resultOperation) { Assert.NotNull(gen); MSA.Expression exceptionThrownVariable = gen.CurrentScope.DefineHiddenVariable("#exception-thrown", typeof(bool)); MSA.Expression exceptionRethrowVariable = gen.CurrentScope.DefineHiddenVariable("#exception-rethrow", typeof(bool)); MSA.Expression retryingVariable = gen.CurrentScope.DefineHiddenVariable("#retrying", typeof(bool)); MSA.Expression oldExceptionVariable = gen.CurrentScope.DefineHiddenVariable("#old-exception", typeof(Exception)); MSA.ParameterExpression unwinder, exceptionVariable; MSA.Expression transformedBody; MSA.Expression transformedEnsure; MSA.Expression transformedElse; if (_ensureStatements != null) { transformedEnsure = Ast.Block( // ensure: Ast.Assign(oldExceptionVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), gen.TransformStatements(_ensureStatements, ResultOperation.Ignore), Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable), // rethrow: AstUtils.IfThen( Ast.AndAlso( exceptionRethrowVariable, Ast.NotEqual(oldExceptionVariable, AstUtils.Constant(null)) ), Ast.Throw(oldExceptionVariable) ) ); } else { // rethrow: transformedEnsure = AstUtils.IfThen( Ast.AndAlso( exceptionRethrowVariable, Ast.NotEqual( Ast.Assign(oldExceptionVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), AstUtils.Constant(null, typeof(Exception))) ), Ast.Throw(oldExceptionVariable) ); } if (_elseStatements != null) { transformedElse = gen.TransformStatements(_elseStatements, resultOperation); } else { transformedElse = AstUtils.Empty(); } // body should do return, but else-clause is present => we cannot do return from the guarded statements: // (the value of the last expression in the body cannot be the last executed expression statement => we can ignore it): transformedBody = gen.TransformStatements(_statements, (_elseStatements != null) ? ResultOperation.Ignore : resultOperation); MSA.Expression enterRescue = null, leaveRescue = null; var retryLabel = Ast.Label("retry"); // make rescue clause: MSA.Expression transformedRescue; if (_rescueClauses != null) { // outer-most EH blocks sets and clears runtime flag RuntimeFlowControl.InTryRescue: if (gen.CurrentRescue == null) { enterRescue = Methods.EnterRescue.OpCall(gen.CurrentScopeVariable); leaveRescue = Methods.LeaveRescue.OpCall(gen.CurrentScopeVariable); } else { enterRescue = leaveRescue = AstUtils.Empty(); } gen.EnterRescueClause(retryingVariable, retryLabel); var handlers = new IfStatementTest[_rescueClauses.Count]; for (int i = 0; i < handlers.Length; i++) { handlers[i] = _rescueClauses[i].Transform(gen, resultOperation); } transformedRescue = AstUtils.Try( enterRescue, AstUtils.If(handlers, Ast.Assign(exceptionRethrowVariable, AstUtils.Constant(true))) ).Filter(unwinder = Ast.Parameter(typeof(EvalUnwinder), "#u"), Ast.Equal(Ast.Field(unwinder, EvalUnwinder.ReasonField), AstUtils.Constant(BlockReturnReason.Retry)), Ast.Block( Ast.Assign(retryingVariable, AstUtils.Constant(true)), Ast.Continue(retryLabel), AstUtils.Empty() ) ); gen.LeaveRescueClause(); } else { transformedRescue = Ast.Assign(exceptionRethrowVariable, AstUtils.Constant(true)); } if (_elseStatements != null) { transformedElse = AstUtils.Unless(exceptionThrownVariable, transformedElse); } var result = Ast.Block( Ast.Label(retryLabel), AstUtils.Try( Ast.Assign(exceptionThrownVariable, AstUtils.Constant(false)), Ast.Assign(exceptionRethrowVariable, AstUtils.Constant(false)), Ast.Assign(retryingVariable, AstUtils.Constant(false)), // save exception (old_$! is not used unless there is a rescue clause): (_rescueClauses == null) ? (MSA.Expression)AstUtils.Empty() : Ast.Assign(oldExceptionVariable, Methods.GetCurrentException.OpCall(gen.CurrentScopeVariable)), AstUtils.Try( Ast.Block(transformedBody, AstUtils.Empty()) ).Filter(exceptionVariable = Ast.Parameter(typeof(Exception), "#e"), Methods.CanRescue.OpCall(gen.CurrentScopeVariable, exceptionVariable), Ast.Assign(exceptionThrownVariable, AstUtils.Constant(true)), transformedRescue, AstUtils.Empty() ).FinallyIf((_rescueClauses != null), // restore previous exception if the current one has been handled: AstUtils.Unless(exceptionRethrowVariable, Methods.SetCurrentException.OpCall(gen.CurrentScopeVariable, oldExceptionVariable) ), leaveRescue ), // unless (exception_thrown) do <else-statements> end transformedElse, AstUtils.Empty() ).FilterIf((_rescueClauses != null || _elseStatements != null), exceptionVariable = Ast.Parameter(typeof(Exception), "#e"), Methods.CanRescue.OpCall(gen.CurrentScopeVariable, exceptionVariable), Ast.Assign(exceptionRethrowVariable, AstUtils.Constant(true)), AstUtils.Empty() ).FinallyWithJumps( AstUtils.Unless(retryingVariable, transformedEnsure) ) ); return(result); }
Exp AsBool(Exp expr) { return(Exp.Property(expr, "b")); }
public MSAst.Expression Register(MSAst.Expression registeredTo) { return(MSAst.Expression.Dynamic(LanguageContext.CreateSetMemberBinder(Name, false, true, true), typeof(object), registeredTo, TransformProperty(registeredTo))); }
internal static MSAst.Expression /*!*/ AssignValue(MSAst.Expression /*!*/ expression, MSAst.Expression value) { Debug.Assert(expression != null); Debug.Assert(value != null); IPythonVariableExpression pyGlobal = expression as IPythonVariableExpression; if (pyGlobal != null) { return(pyGlobal.Assign(value)); } return(Ast.Assign(expression, value)); }
public bool CanHandleConstructionOf(Expression expression) { return(false); }
public MSAst.Expression /*!*/ Dynamic(DynamicMetaObjectBinder /*!*/ binder, Type /*!*/ retType, MSAst.Expression /*!*/ arg0) { if (retType == typeof(object)) { return(new PythonDynamicExpression1(binder, this, arg0)); } else if (retType == typeof(bool)) { return(new PythonDynamicExpression1 <bool>(binder, this, arg0)); } return(ReduceDynamic(binder, retType, arg0)); }
public SiteInfoLarge(DynamicMetaObjectBinder /*!*/ binder, MSAst.Expression /*!*/ expr, FieldInfo /*!*/ field, int index, Type /*!*/ delegateType) : base(binder, expr, field, index, delegateType) { }
internal MSAst.Expression MakeAssignment(MSAst.ParameterExpression variable, MSAst.Expression right, SourceSpan span) { return(GlobalParent.AddDebugInfoAndVoid(Ast.Assign(variable, AstUtils.Convert(right, variable.Type)), span)); }
private L.Expression WithCommonNumericType(L.Expression left, L.Expression right, Func <L.Expression, L.Expression, L.Expression> action, BinaryExpressionType expressiontype = BinaryExpressionType.Unknown) { left = UnwrapNullable(left); right = UnwrapNullable(right); if (_options.HasFlag(EvaluateOptions.BooleanCalculation)) { if (left.Type == typeof(bool)) { left = L.Expression.Condition(left, L.Expression.Constant(1.0), L.Expression.Constant(0.0)); } if (right.Type == typeof(bool)) { right = L.Expression.Condition(right, L.Expression.Constant(1.0), L.Expression.Constant(0.0)); } } var precedence = new[] { typeof(decimal), typeof(double), typeof(float), typeof(ulong), typeof(long), typeof(uint), typeof(int), typeof(ushort), typeof(short), typeof(byte), typeof(sbyte) }; int l = Array.IndexOf(precedence, left.Type); int r = Array.IndexOf(precedence, right.Type); if (l >= 0 && r >= 0) { var type = precedence[Math.Min(l, r)]; if (left.Type != type) { left = L.Expression.Convert(left, type); } if (right.Type != type) { right = L.Expression.Convert(right, type); } } L.Expression comparer = null; if (IgnoreCaseString) { if (Ordinal) { comparer = L.Expression.Property(null, typeof(StringComparer), "OrdinalIgnoreCase"); } else { comparer = L.Expression.Property(null, typeof(StringComparer), "CurrentCultureIgnoreCase"); } } else { comparer = L.Expression.Property(null, typeof(StringComparer), "Ordinal"); } if (comparer != null && (typeof(string).Equals(left.Type) || typeof(string).Equals(right.Type))) { switch (expressiontype) { case BinaryExpressionType.Equal: return(L.Expression.Call(comparer, typeof(StringComparer).GetRuntimeMethod("Equals", new[] { typeof(string), typeof(string) }), new L.Expression[] { left, right })); case BinaryExpressionType.NotEqual: return(L.Expression.Not(L.Expression.Call(comparer, typeof(StringComparer).GetRuntimeMethod("Equals", new[] { typeof(string), typeof(string) }), new L.Expression[] { left, right }))); case BinaryExpressionType.GreaterOrEqual: return(L.Expression.GreaterThanOrEqual(L.Expression.Call(comparer, typeof(StringComparer).GetRuntimeMethod("Compare", new[] { typeof(string), typeof(string) }), new L.Expression[] { left, right }), L.Expression.Constant(0))); case BinaryExpressionType.LesserOrEqual: return(L.Expression.LessThanOrEqual(L.Expression.Call(comparer, typeof(StringComparer).GetRuntimeMethod("Compare", new[] { typeof(string), typeof(string) }), new L.Expression[] { left, right }), L.Expression.Constant(0))); case BinaryExpressionType.Greater: return(L.Expression.GreaterThan(L.Expression.Call(comparer, typeof(StringComparer).GetRuntimeMethod("Compare", new[] { typeof(string), typeof(string) }), new L.Expression[] { left, right }), L.Expression.Constant(0))); case BinaryExpressionType.Lesser: return(L.Expression.LessThan(L.Expression.Call(comparer, typeof(StringComparer).GetRuntimeMethod("Compare", new[] { typeof(string), typeof(string) }), new L.Expression[] { left, right }), L.Expression.Constant(0))); } } return(action(left, right)); }
internal static MSAst.Expression /*!*/ MakeAssignment(MSAst.ParameterExpression /*!*/ variable, MSAst.Expression /*!*/ right) { return(Ast.Assign(variable, AstUtils.Convert(right, variable.Type))); }
public FramedCodeExpression(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) { _localContext = localContext; _codeObject = codeObject; _body = body; }
public abstract MSAst.Expression GetGlobal(MSAst.Expression globalContext, int arrayIndex, PythonVariable variable, PythonGlobal global);
private L.Expression[] PrepareMethodArgumentsIfValid(ParameterInfo[] parameters, L.Expression[] arguments) { if (!parameters.Any() && !arguments.Any()) { return(arguments); } if (!parameters.Any()) { return(null); } bool paramsMatchArguments = true; var lastParameter = parameters.Last(); bool hasParamsKeyword = lastParameter.IsDefined(typeof(ParamArrayAttribute)); if (hasParamsKeyword && parameters.Length > arguments.Length) { return(null); } L.Expression[] newArguments = new L.Expression[parameters.Length]; L.Expression[] paramsKeywordArgument = null; Type paramsElementType = null; int paramsParameterPosition = 0; if (!hasParamsKeyword) { paramsMatchArguments &= parameters.Length == arguments.Length; if (!paramsMatchArguments) { return(null); } } else { paramsParameterPosition = lastParameter.Position; paramsElementType = lastParameter.ParameterType.GetElementType(); paramsKeywordArgument = new L.Expression[arguments.Length - parameters.Length + 1]; } for (int i = 0; i < arguments.Length; i++) { var isParamsElement = hasParamsKeyword && i >= paramsParameterPosition; var argumentType = arguments[i].Type; var parameterType = isParamsElement ? paramsElementType : parameters[i].ParameterType; paramsMatchArguments &= argumentType == parameterType; if (!paramsMatchArguments) { return(null); } if (!isParamsElement) { newArguments[i] = arguments[i]; } else { paramsKeywordArgument[i - paramsParameterPosition] = arguments[i]; } } if (hasParamsKeyword) { newArguments[paramsParameterPosition] = L.Expression.NewArrayInit(paramsElementType, paramsKeywordArgument); } return(newArguments); }