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); }
/// <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)) ); }
private static NewExpression BuildExpression(Type type, ParameterExpression container) { if (!type.IsGenericTypeDefinition) { // No public constructor, i.e. an abstract base class or private constructor; we can't create this ConstructorInfo constructor = GetConstructorInfo(type); if(constructor == null) { return null; } ParameterInfo[] parameters = constructor.GetParameters(); // create the arguments for the constructor List<Expression> arguments = new List<Expression>(); foreach (var paramInfo in parameters) { var p = Expression.Call(container, "Resolve", new Type[] { paramInfo.ParameterType }, new Expression[] { }); arguments.Add(p); } // create the new MyClass( ... ) call return Expression.New(constructor, arguments); } else { return null; } }
public Expression ToExpression(Policies policies, ParameterExpression session, ParameterExpression variable) { var build = ToConcreteBuild(policies, variable); var builder = build.ToExpression(session, Parameters.Context); return Expression.Convert(builder, _pluginType); }
protected override SequenceConvertInfo Convert( ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo, ParameterExpression param) { var predicate = (LambdaExpression)methodCall.Arguments[1].Unwrap(); var info = builder.ConvertSequence(new BuildInfo(buildInfo, methodCall.Arguments[0]), predicate.Parameters[0]); if (info != null) { info.Expression = methodCall.Transform(ex => ConvertMethod(methodCall, 0, info, predicate.Parameters[0], ex)); if (param != null) { if (param.Type != info.Parameter.Type) param = Expression.Parameter(info.Parameter.Type, param.Name); if (info.ExpressionsToReplace != null) foreach (var path in info.ExpressionsToReplace) { path.Path = path.Path.Transform(e => e == info.Parameter ? param : e); path.Expr = path.Expr.Transform(e => e == info.Parameter ? param : e); } } info.Parameter = param; return info; } return null; }
public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values) { if (expression == null) { throw new ArgumentNullException("expression"); } if (keywords == null) { keywords = CreateKeywords(); } this.symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); this.literals = new Dictionary<Expression, string>(); if (parameters != null) { this.ProcessParameters(parameters); } if (values != null) { this.ProcessValues(values); } this.text = expression; this.textLen = this.text.Length; this.SetTextPos(0); this.NextToken(); }
protected override Expression VisitParameter(ParameterExpression node) { if (_expName == null) _expName = node.Name; return node.Name == _expName && node.Type == _parameterExpression.Type ? _parameterExpression : node; }
protected override void VisitParameter (ParameterExpression parameter) { foreach (var param in lambda.Parameters) { if (param.Name == parameter.Name && param != parameter) throw new InvalidOperationException ("Lambda Parameter not in scope"); } }
private static Expression CreateCall(MethodInfo method, ParameterExpression handler, ParameterExpression context, Type handlerType) { if (method.IsGenericMethod) { var handlerParameterType = method.GetParameters()[0].ParameterType; if (handlerParameterType.IsGenericType) { var @interface = handlerType.GetInterfaces().FirstOrDefault( i => i.IsGenericType && i.GetGenericTypeDefinition() == handlerParameterType.GetGenericTypeDefinition()); if (@interface != null) { method = method.MakeGenericMethod(@interface.GetGenericArguments().Single()); } } else { // bind handler as generic type? method = method.MakeGenericMethod(typeof(object)); //Debugger.Break(); } } return Expression.Call(method, handler, context); }
/// <summary> /// If the given variable matches _find, return _replaceWith. Otherwise, continue default visitation behavior. /// </summary> /// <param name="node">The expression node being visited</param> /// <returns></returns> protected override Expression VisitParameter(ParameterExpression node) { if (node == _find) return _replaceWith; return base.VisitParameter(node); }
static EffectParser() { posParam = Expression.Parameter(typeof(PositionComponent), "Position"); moveParam = Expression.Parameter(typeof(MovementComponent), "Movement"); sprParam = Expression.Parameter(typeof(SpriteComponent), "Sprite"); inputParam = Expression.Parameter(typeof(InputComponent), "Input"); collParam = Expression.Parameter(typeof(CollisionComponent), "Collision"); ladderParam = Expression.Parameter(typeof(LadderComponent), "Ladder"); timerParam = Expression.Parameter(typeof(TimerComponent), "Timer"); healthParam = Expression.Parameter(typeof(HealthComponent), "Health"); stateParam = Expression.Parameter(typeof(StateComponent), "State"); weaponParam = Expression.Parameter(typeof(WeaponComponent), "Weapon"); stParam = Expression.Parameter(typeof(int), "StateTime"); lifeParam = Expression.Parameter(typeof(int), "LifeTime"); playerXParam = Expression.Parameter(typeof(float), "PlayerDistX"); playerYParam = Expression.Parameter(typeof(float), "PlayerDistY"); gravParam = Expression.Parameter(typeof(bool), "GravityFlip"); randParam = Expression.Parameter(typeof(double), "Random"); playerParam = Expression.Parameter(typeof(Player), "Game"); dirDict = new Dictionary<string, object> { {"Up", Direction.Up}, {"Down", Direction.Down}, {"Left", Direction.Left}, {"Right", Direction.Right} }; }
public ClosureExpression(Ast.PythonVariable/*!*/ variable, Expression/*!*/ closureCell, ParameterExpression parameter) { Assert.NotNull(closureCell); _variable = variable; _closureCell = closureCell; _parameter = parameter; }
public DataAccessExpressionLibrary(ISystemBus systemBus) { _systemBus = systemBus; CpuParameter = Expression.Variable(typeof(CpuData), "cpu"); SystemBusParameter = Expression.Variable(typeof(ISystemBus), "systemBus"); RegisterAParameter = Expression.Parameter(typeof(Int32), "registerA"); RegisterBParameter = Expression.Variable(typeof(Int32), "registerB"); RegisterCParameter = Expression.Variable(typeof(Int32), "registerC"); RegisterDParameter = Expression.Variable(typeof(Int32), "registerD"); RegisterEParameter = Expression.Variable(typeof(Int32), "registerE"); RegisterHParameter = Expression.Variable(typeof(Int32), "registerH"); RegisterLParameter = Expression.Variable(typeof(Int32), "registerL"); RegisterIXParameter = Expression.Variable(typeof(Int32), "registerIX"); RegisterIYParameter = Expression.Variable(typeof(Int32), "registerIY"); StackPointerRegisterParameter = Expression.Variable(typeof(Int32), "stackPointerRegister"); FlagsRegisterParameter = Expression.Variable(typeof(Int32), "flagsRegister"); TempParameter = Expression.Variable(typeof(Byte), "temp"); readByteMethod = typeof(ISystemBus).GetMethod("ReadByte"); readWordMethod = typeof(ISystemBus).GetMethod("ReadWord"); writeByteMethod = typeof(ISystemBus).GetMethod("WriteByte"); writeWordMethod = typeof(ISystemBus).GetMethod("WriteWord"); readPortMethod = typeof(ISystemBus).GetMethod("ReadPort"); writePortMethod = typeof(ISystemBus).GetMethod("WritePort"); }
/// <summary> /// Initializes a new <see cref="ProjectionPlanCompiler"/> instance. /// </summary> /// <param name="normalizerRewrites">Rewrites introduces by normalizer.</param> private ProjectionPlanCompiler(Dictionary<Expression, Expression> normalizerRewrites) { this.annotations = new Dictionary<Expression, ExpressionAnnotation>(ReferenceEqualityComparer<Expression>.Instance); this.materializerExpression = Expression.Parameter(typeof(object), "mat"); this.normalizerRewrites = normalizerRewrites; this.pathBuilder = new ProjectionPathBuilder(); }
//Func<Type, IEnumerable<object>> fnGetObjects; #region CreateQuery /// <summary> /// called during deserialization. /// </summary> /// <param name="elementType"></param> /// <returns></returns> public dynamic CreateQuery(Type elementType) { dynamic ienumerable = this.fnGetObjects(elementType); Type enumerableType = ienumerable.GetType(); if (!typeof(IEnumerable<>).MakeGenericType(elementType).IsAssignableFrom(enumerableType)) { ienumerable = Enumerable.ToArray(LinqHelper.CastToGenericEnumerable(ienumerable, elementType)); //throw new InvalidOperationException(string.Format("Return value Type is {1}. Expected: {0}", typeof(IEnumerable<>).MakeGenericType(elementType), ienumerable.GetType())); } IQueryable queryable = Queryable.AsQueryable(ienumerable); IQueryProvider provider = (IQueryProvider)queryable.Provider; Type queryType = typeof(Query<>).MakeGenericType(elementType); ConstructorInfo ctor = queryType.GetConstructors()[2];//Query(IQueryProvider provider, Expression expression) ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(typeof(IQueryProvider)), Expression.Parameter(typeof(Expression)) }; NewExpression newexpr = Expression.New(ctor, parameters); LambdaExpression lambda = Expression.Lambda(newexpr, parameters); var newFn = lambda.Compile(); dynamic query = newFn.DynamicInvoke(new object[] { provider, Expression.Constant(queryable) }); return query; }
private static Expression CoalesceInternal(Expression left, Expression right, MethodInfo isTrue, bool isReverse, out ParameterExpression temp) { ContractUtils.RequiresNotNull(left, "left"); ContractUtils.RequiresNotNull(right, "right"); // A bit too strict, but on a safe side. ContractUtils.Requires(left.Type == right.Type, "Expression types must match"); temp = Expression.Variable(left.Type, "tmp_left"); Expression condition; if (isTrue != null) { ContractUtils.Requires(isTrue.ReturnType == typeof(bool), "isTrue", "Predicate must return bool."); ParameterInfo[] parameters = isTrue.GetParameters(); ContractUtils.Requires(parameters.Length == 1, "isTrue", "Predicate must take one parameter."); ContractUtils.Requires(isTrue.IsStatic && isTrue.IsPublic, "isTrue", "Predicate must be public and static."); Type pt = parameters[0].ParameterType; ContractUtils.Requires(TypeUtils.CanAssign(pt, left.Type), "left", "Incorrect left expression type"); condition = Expression.Call(isTrue, Expression.Assign(temp, left)); } else { ContractUtils.Requires(TypeUtils.CanCompareToNull(left.Type), "left", "Incorrect left expression type"); condition = Expression.Equal(Expression.Assign(temp, left), AstUtils.Constant(null, left.Type)); } Expression t, f; if (isReverse) { t = temp; f = right; } else { t = right; f = temp; } return Expression.Condition(condition, t, f); }
public DelegatingConversionVisitor(MappingStrategy strategy, ParameterExpression sourceValueParameter, ParameterExpression mapperParameter, ParameterExpression contextParameter) { this.strategy = strategy; this.sourceValueParameter = sourceValueParameter; this.mapperParameter = mapperParameter; this.contextParameter = contextParameter; }
internal protected override Expression ToExpression(OverloadResolver resolver, RestrictedArguments args, bool[] hasBeenUsed) { if (_tmp == null) { _tmp = resolver.GetTemporary(_elementType, "outParam"); } Debug.Assert(!hasBeenUsed[Index]); hasBeenUsed[Index] = true; Type boxType = typeof(StrongBox<>).MakeGenericType(_elementType); Expression arg = args.GetObject(Index).Expression; return Expression.Condition( Expression.TypeIs(arg, Type), Expression.Assign( _tmp, Expression.Field( AstUtils.Convert(arg, boxType), boxType.GetField("Value") ) ), Expression.Call( typeof(RuntimeHelpers).GetMethod("IncorrectBoxType").MakeGenericMethod(_elementType), AstUtils.Convert(arg, typeof(object)) ) ); }
public override Expression Compile(ParameterExpression stateParameterExpression, LabelTarget returnTarget) { return Expression.IfThenElse( Expression.Convert(this.Condition.Compile(stateParameterExpression, returnTarget), typeof(bool)), this.Statement.Compile(stateParameterExpression, returnTarget), this.ElseStatement.Compile(stateParameterExpression, returnTarget)); }
public ExpressionBuilderParameters(ParameterExpression[] parameters, IQueryProvider queryProvider, Type elementType, IXmlNamespaceResolver namespaceResolver, bool mayRootPathBeImplied, IOperatorImplementationProvider operatorImplementationProvider, Func<Type, IXmlNamespaceResolver, XPathTypeNavigator> navigatorCreator=null) { Debug.Assert(parameters!=null); if (parameters==null) throw new ArgumentNullException("parameters"); Debug.Assert(parameters.Length>0); if (parameters.Length==0) throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, SR.ArrayShouldHaveElementsException, 1, parameters.Length ), "parameters" ); Debug.Assert(queryProvider!=null); if (queryProvider==null) throw new ArgumentNullException("queryProvider"); Debug.Assert(elementType!=null); if (elementType==null) throw new ArgumentNullException("elementType"); Parameters=new ReadOnlyCollection<ParameterExpression>(parameters); ElementType=elementType; QueryProvider=queryProvider; NamespaceResolver=namespaceResolver; MayRootPathBeImplied=mayRootPathBeImplied; OperatorImplementationProvider=operatorImplementationProvider; NavigatorCreator=navigatorCreator; }
private static NewExpression BuildExpression(Type type, ParameterExpression container) { if (!type.IsGenericTypeDefinition) { var constructor = GetConstructorInfo(type); var parameters = constructor.GetParameters(); // create the arguments for the constructor var arguments = new List<Expression>(); foreach (var paramInfo in parameters) { var p = Expression.Call(container, "Resolve", new Type[] { paramInfo.ParameterType }, new Expression[] { }); arguments.Add(p); } // create the new MyClass( ... ) call return Expression.New(constructor, arguments); } else { return null; } }
public override Expression Resolve (ParameterExpression inputParameter, Expression expressionToBeResolved, ClauseGenerationContext clauseGenerationContext) { ArgumentUtility.CheckNotNull ("inputParameter", inputParameter); ArgumentUtility.CheckNotNull ("expressionToBeResolved", expressionToBeResolved); return Source.Resolve (inputParameter, expressionToBeResolved, clauseGenerationContext); }
internal void PushParamExpression(ParameterExpression pe) { StringBuilder basePath = projectionPaths.Last(); basePaths.Add(pe, basePath.ToString()); projectionPaths.Remove(basePath); parameterExpressions.Push(pe); }
protected override Expression VisitParameter(ParameterExpression p) { if(p.Type == _elementType) return new FieldExpression(p, _alias, "*"); return base.VisitParameter(p); }
// TODO: to be tested public override Expression ToLinqExpression( IQueryable queryable, ParameterExpression parameterExpression, string propertyName ) { if( queryable == null ) throw new ArgumentNullException( "queryable" ); if( parameterExpression == null ) throw new ArgumentNullException( "parameterExpression" ); if( String.IsNullOrEmpty( propertyName ) ) { if( propertyName == null ) throw new ArgumentNullException( "propertyName" ); throw new ArgumentException( "PropertyName must not be empty.", "propertyName" ); } string queriedValue = this.Value as string; if( queriedValue == null ) queriedValue = string.Empty; else queriedValue = queriedValue.Remove( queriedValue.IndexOf( '*' ) ); return queryable.CreateEndsWithExpression( parameterExpression, propertyName, queriedValue ); }
internal protected override Expression ToExpression(OverloadResolver resolver, RestrictedArguments args, bool[] hasBeenUsed) { if (_tmp == null) { _tmp = resolver.GetTemporary(_elementType, "outParam"); } Debug.Assert(!hasBeenUsed[Index]); hasBeenUsed[Index] = true; Expression arg = args.GetObject(Index).Expression; return Expression.Condition( Expression.TypeIs(arg, Type), Expression.Assign( _tmp, Expression.Field( AstUtils.Convert(arg, Type), Type.GetField("Value") ) ), Expression.Throw( Expression.Call( new Func<Type, object, Exception>(RuntimeHelpers.MakeIncorrectBoxTypeError).Method, AstUtils.Constant(_elementType), AstUtils.Convert(arg, typeof(object)) ), _elementType ) ); }
public AsyncRunner BuildAsyncRunner() { _task = Expression.Variable(typeof (Task<Status>), "task"); _context = Expression.Parameter(typeof(IContext), "context"); _blocks.Add(Expression.Assign(_handler, Expression.Convert(_handlerParameter, _type))); CreateSetupBlocks(); _blocks.Add(BuildAsyncRunBlock()); _blocks.Add(Expression.Label(_end)); _blocks.Add(_task); var block = Expression.Block(new[] {_handler, _task}, _blocks); var start = Expression.Lambda<Func<object, IContext, Task<Status>>>(block, _handlerParameter, _context).Compile(); _blocks.Clear(); _context = Expression.Parameter(typeof(IContext), "context"); _blocks.Add(Expression.Assign(_handler, Expression.Convert(_handlerParameter, _type))); _status = Expression.Parameter(typeof(Status), "status"); CreateResponseBlocks(); block = Expression.Block(new[] {_handler}, _blocks); var end = Expression.Lambda<Action<object, IContext, Status>>(block, _handlerParameter, _context, _status).Compile(); return new AsyncRunner(start, end); }
/// <summary> /// Initializes a new instance of the <see cref="MongoWhereClauseExpressionTreeVisitor"/> class. /// </summary> /// <param name="configuration">The configuration.</param> private ProjectionBuilder(IMappingStore mappingStore, ParameterExpression documentParameter) { this.mappingStore = mappingStore; this.resultObjectMappingParameter = documentParameter; this.fields = new Document(); this.memberNames = new Stack<string>(); }
/** * приводит лямбду (x, y, ...) => ... к виду: (x, y, ...) => fn(p, q, ...) * где fn - оптимизированная лямбда, p, q - предварительно вычисленные выражения * * пример: * Func<int, int, Func<int, int, int, int>, int> fn = (int x, int y, Func<int, int, int, int> Foo) => Foo(F(x), F(y), F(2 * y)); * Func<int, int, int> optimizedLambda = (int x, int y) => fn(1, 2, (int p, int q, int l) => p > q ? p : (p < l ? l : q)); */ public Expression Optimize(LambdaExpression lambda, string functionName) { if (_methodCalls != null) _methodCalls.Clear(); else _methodCalls = new Dictionary<string, MethodCall>(); _innerLambdaParams = new List<Expression>(); _functionName = functionName; // получаем оптимизированную лямбду Expression fn = BuildInnerLambda(lambda); // копируем параметры для новой лямбды ParameterExpression[] parameters = new ParameterExpression[lambda.Parameters.Count]; lambda.Parameters.CopyTo(parameters, 0); // собираем новую лямбду Expression optimizedLambda = Expression.Lambda( Expression.Invoke(fn, _innerLambdaParams), parameters ); return optimizedLambda; }
public PostfixSelectVisitor(LE.ParameterExpression row, Func<String, IProjection> projectionCreator) { projections = new List<IProjection>(); ProjectionsPropertyNames = new List<String>(); this.projectionCreator = projectionCreator; this.row = row; }
internal virtual void FinishBind(PythonNameBinder binder) { List <ClosureInfo> closureVariables = null; if (FreeVariables != null && FreeVariables.Count > 0) { _localParentTuple = Ast.Parameter(Parent.GetClosureTupleType(), "$tuple"); foreach (var variable in _freeVars) { var parentClosure = Parent._closureVariables; Debug.Assert(parentClosure != null); for (int i = 0; i < parentClosure.Length; i++) { if (parentClosure[i].Variable == variable) { _variableMapping[variable] = new ClosureExpression(variable, Ast.Property(_localParentTuple, String.Format("Item{0:D3}", i)), null); break; } } Debug.Assert(_variableMapping.ContainsKey(variable)); if (closureVariables == null) { closureVariables = new List <ClosureInfo>(); } closureVariables.Add(new ClosureInfo(variable, !(this is ClassDefinition))); } } if (Variables != null) { foreach (PythonVariable variable in Variables.Values) { if (!HasClosureVariable(closureVariables, variable) && !variable.IsGlobal && (variable.AccessedInNestedScope || ExposesLocalVariable(variable))) { if (closureVariables == null) { closureVariables = new List <ClosureInfo>(); } closureVariables.Add(new ClosureInfo(variable, true)); } if (variable.Kind == VariableKind.Local) { Debug.Assert(variable.Scope == this); if (variable.AccessedInNestedScope || ExposesLocalVariable(variable)) { _variableMapping[variable] = new ClosureExpression(variable, Ast.Parameter(typeof(ClosureCell), variable.Name), null); } else { _variableMapping[variable] = Ast.Parameter(typeof(object), variable.Name); } } } } if (closureVariables != null) { _closureVariables = closureVariables.ToArray(); } // no longer needed _references = null; }
public MSAst.Expression CreatePushFrameExpression(MSAst.ParameterExpression functionInfo, MSAst.ParameterExpression debugMarker, IList <MSAst.ParameterExpression> locals, IList <VariableInfo> varInfos, MSAst.Expression runtimeThread) { MSAst.ParameterExpression[] args = new MSAst.ParameterExpression[2 + locals.Count]; args[0] = functionInfo; args[1] = debugMarker; for (int i = 0; i < locals.Count; i++) { args[i + 2] = locals[i]; } return(Ast.Call( typeof(RuntimeOps).GetMethod("LiftVariables"), runtimeThread, Ast.RuntimeVariables(args) )); }
internal static MSAst.Expression /*!*/ MakeAssignment(MSAst.ParameterExpression /*!*/ variable, MSAst.Expression /*!*/ right) { return(Ast.Assign(variable, AstUtils.Convert(right, variable.Type))); }
protected abstract MSAst.Expression Body(MSAst.ParameterExpression res);
private static SysLE.Expression SysExpressionWhere_Analyize(SysLE.Expression exp, StringBuilder builder) { if (exp == null) { return(null); } SysLE.BinaryExpression binEx = exp as SysLE.BinaryExpression; if (binEx != null) { SysExpressionWhere_Analyize(binEx.Left, builder); } switch (exp.NodeType) { case SysLE.ExpressionType.Parameter: { SysLE.ParameterExpression param = (SysLE.ParameterExpression)exp; builder.Append("(" + param.Name); return(null); } case SysLE.ExpressionType.MemberAccess: { SysLE.MemberExpression mexp = (SysLE.MemberExpression)exp; builder.Append("(" + mexp.Member.Name); return(null); } case SysLE.ExpressionType.Constant: { SysLE.ConstantExpression cex = (SysLE.ConstantExpression)exp; if (cex.Value is string) { builder.Append("'" + cex.Value.ToString() + "') "); } else { builder.Append(cex.Value.ToString() + ")"); } return(null); } default: { if (exp.NodeType == SysLE.ExpressionType.Equal) { builder.Append("="); } else if (exp.NodeType == SysLE.ExpressionType.NotEqual) { builder.Append("<>"); } else if (exp.NodeType == SysLE.ExpressionType.LessThan) { builder.Append("<"); } else if (exp.NodeType == SysLE.ExpressionType.LessThanOrEqual) { builder.Append("<="); } else if (exp.NodeType == SysLE.ExpressionType.GreaterThan) { builder.Append(">"); } else if (exp.NodeType == SysLE.ExpressionType.GreaterThanOrEqual) { builder.Append(">="); } else if (exp.NodeType == SysLE.ExpressionType.AndAlso || exp.NodeType == SysLE.ExpressionType.And) { builder.Append("and"); } else if (exp.NodeType == SysLE.ExpressionType.OrElse || exp.NodeType == SysLE.ExpressionType.Or) { builder.Append("or"); } } break; } if (binEx != null) { SysExpressionWhere_Analyize(binEx.Right, builder); } return(binEx); }
/// <summary> /// Adds profiling calls to a Python method. /// Calculates both the time spent only in this method /// </summary> internal MSAst.Expression AddProfiling(MSAst.Expression /*!*/ body, MSAst.ParameterExpression /*!*/ tick, string /*!*/ name, bool unique) { int profileIndex = GetProfilerIndex(name); return(AddOuterProfiling(new InnerMethodProfiler(this, tick, profileIndex).Visit(body), tick, profileIndex)); }
public InnerMethodProfiler(Profiler /*!*/ profiler, MSAst.ParameterExpression /*!*/ tick, int profileIndex) { _profiler = profiler; _tick = tick; _profileIndex = profileIndex; }
public DelayedProfiling(ScopeStatement ast, MSAst.Expression body, MSAst.ParameterExpression tick) { _ast = ast; _body = body; _tick = tick; }
public Expression <Func <Domain.Common.IEvaluationContext, bool> > GetConditionExpression() { linq.ParameterExpression paramX = linq.Expression.Parameter(typeof(IEvaluationContext), "x"); var castOp = linq.Expression.MakeUnary(linq.ExpressionType.Convert, paramX, typeof(DynamicContentEvaluationContext)); var propertyValue = linq.Expression.Property(castOp, typeof(DynamicContentEvaluationContext).GetProperty(_propertyName)); MethodInfo method; linq.Expression methodExp = null; if (string.Equals(MatchCondition, "Contains", StringComparison.InvariantCultureIgnoreCase)) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(Value.ToLowerInvariant())); } else if (string.Equals(MatchCondition, "Matching", StringComparison.InvariantCultureIgnoreCase)) { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(Value.ToLowerInvariant())); } else if (string.Equals(MatchCondition, "ContainsCase", StringComparison.InvariantCultureIgnoreCase)) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); methodExp = linq.Expression.Call(propertyValue, method, linq.Expression.Constant(Value)); } else if (string.Equals(MatchCondition, "MatchingCase", StringComparison.InvariantCultureIgnoreCase)) { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); methodExp = linq.Expression.Call(propertyValue, method, linq.Expression.Constant(Value)); } else if (string.Equals(MatchCondition, "NotContains", StringComparison.InvariantCultureIgnoreCase)) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Not(linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(Value.ToLowerInvariant()))); } else if (string.Equals(MatchCondition, "NotMatching")) { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Not(linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(Value.ToLowerInvariant()))); } else if (string.Equals(MatchCondition, "NotContainsCase")) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); methodExp = linq.Expression.Not(linq.Expression.Call(propertyValue, method, linq.Expression.Constant(Value))); } else { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); methodExp = linq.Expression.Not(linq.Expression.Call(propertyValue, method, linq.Expression.Constant(Value))); } var retVal = linq.Expression.Lambda <Func <IEvaluationContext, bool> >(methodExp, paramX); return(retVal); }
internal static MSAst.Expression TransformFor(ScopeStatement parent, MSAst.ParameterExpression enumerator, Expression list, Expression left, MSAst.Expression body, Statement else_, SourceSpan span, SourceLocation header, MSAst.LabelTarget breakLabel, MSAst.LabelTarget continueLabel, bool isStatement) { // enumerator, isDisposable = Dynamic(GetEnumeratorBinder, list) MSAst.Expression init = Ast.Assign( enumerator, new PythonDynamicExpression1 <KeyValuePair <IEnumerator, IDisposable> >( Binders.UnaryOperationBinder( parent.GlobalParent.PyContext, PythonOperationKind.GetEnumeratorForIteration ), parent.GlobalParent.CompilationMode, AstUtils.Convert(list, typeof(object)) ) ); // while enumerator.MoveNext(): // left = enumerator.Current // body // else: // else MSAst.Expression ls = AstUtils.Loop( parent.GlobalParent.AddDebugInfo( Ast.Call( Ast.Property( enumerator, typeof(KeyValuePair <IEnumerator, IDisposable>).GetProperty("Key") ), typeof(IEnumerator).GetMethod("MoveNext") ), left.Span ), null, Ast.Block( left.TransformSet( SourceSpan.None, Ast.Call( Ast.Property( enumerator, typeof(KeyValuePair <IEnumerator, IDisposable>).GetProperty("Key") ), typeof(IEnumerator).GetProperty("Current").GetGetMethod() ), PythonOperationKind.None ), body, isStatement ? UpdateLineNumber(parent.GlobalParent.IndexToLocation(list.StartIndex).Line) : AstUtils.Empty(), AstUtils.Empty() ), else_, breakLabel, continueLabel ); return(Ast.Block( init, Ast.TryFinally( ls, Ast.Block( Ast.Call(AstMethods.ForLoopDispose, enumerator), Ast.Assign(enumerator, Ast.New(typeof(KeyValuePair <IEnumerator, IDisposable>))) ) ) )); }
public LookupVisitor(PythonAst ast, MSAst.Expression globalContext) { _globalContext = globalContext; _curScope = ast; }
internal MSA.Expression <T> /*!*/ Transform <T>(AstGenerator /*!*/ gen) { Debug.Assert(gen != null); ScopeBuilder scope = new ScopeBuilder(); MSA.ParameterExpression[] parameters; MSA.Expression selfVariable; MSA.Expression rfcVariable; MSA.Expression parentScope; MSA.Expression language; MSA.Expression runtimeScopeVariable; MSA.Expression moduleVariable; MSA.Expression blockParameter; MSA.Expression currentMethodVariable; if (gen.CompilerOptions.IsEval) { parameters = new MSA.ParameterExpression[6]; parameters[0] = Ast.Parameter(typeof(RubyScope), "#scope"); selfVariable = parameters[1] = Ast.Parameter(typeof(object), "#self"); parameters[2] = Ast.Parameter(typeof(RubyModule), "#module"); blockParameter = parameters[3] = Ast.Parameter(typeof(Proc), "#block"); currentMethodVariable = parameters[4] = Ast.Parameter(typeof(RubyMethodInfo), "#method"); rfcVariable = parameters[5] = Ast.Parameter(typeof(RuntimeFlowControl), "#rfc"); if (gen.CompilerOptions.IsModuleEval) { runtimeScopeVariable = scope.DefineHiddenVariable("#scope", typeof(RubyScope)); parentScope = parameters[0]; moduleVariable = parameters[2]; } else { runtimeScopeVariable = parameters[0]; moduleVariable = null; parentScope = null; } language = null; } else { parameters = new MSA.ParameterExpression[2]; parentScope = parameters[0] = Ast.Parameter(typeof(Scope), "#globalScope"); language = parameters[1] = Ast.Parameter(typeof(LanguageContext), "#language"); selfVariable = scope.DefineHiddenVariable("#self", typeof(object)); rfcVariable = scope.DefineHiddenVariable("#rfc", typeof(RuntimeFlowControl)); runtimeScopeVariable = scope.DefineHiddenVariable("#scope", typeof(RubyScope)); blockParameter = null; currentMethodVariable = null; moduleVariable = null; } gen.EnterSourceUnit( scope, selfVariable, runtimeScopeVariable, blockParameter, rfcVariable, currentMethodVariable, gen.CompilerOptions.TopLevelMethodName, // method name null // parameters ); _definedScope.TransformLocals(scope); MSA.Expression scopeFactoryCall; if (gen.CompilerOptions.IsEval) { if (gen.CompilerOptions.IsModuleEval) { scopeFactoryCall = Methods.CreateModuleEvalScope.OpCall( scope.VisibleVariables(), parentScope, selfVariable, moduleVariable ); } else { scopeFactoryCall = null; } } else if (!gen.CompilerOptions.IsIncluded) { scopeFactoryCall = Methods.CreateMainTopLevelScope.OpCall(scope.VisibleVariables(), parentScope, language, selfVariable, rfcVariable, Ast.Constant(gen.SourceUnit.Path, typeof(string)), Ast.Constant(_dataOffset)); } else if (gen.CompilerOptions.IsWrapped) { scopeFactoryCall = Methods.CreateWrappedTopLevelScope.OpCall(scope.VisibleVariables(), parentScope, language, selfVariable, rfcVariable); } else { scopeFactoryCall = Methods.CreateTopLevelScope.OpCall(scope.VisibleVariables(), parentScope, language, selfVariable, rfcVariable); } MSA.Expression prologue, body; if (scopeFactoryCall != null) { prologue = Ast.Assign(runtimeScopeVariable, scopeFactoryCall); } else { prologue = null; } if (gen.SourceUnit.Kind == SourceCodeKind.InteractiveCode) { var resultVariable = scope.DefineHiddenVariable("#result", typeof(object)); var epilogue = Methods.PrintInteractiveResult.OpCall(runtimeScopeVariable, Ast.Dynamic(ConvertToSAction.Instance, typeof(MutableString), gen.CurrentScopeVariable, Ast.Dynamic(RubyCallAction.Make("inspect", RubyCallSignature.WithScope(0)), typeof(object), gen.CurrentScopeVariable, resultVariable ) ) ); body = gen.TransformStatements(prologue, _statements, epilogue, ResultOperation.Store(resultVariable)); } else { body = gen.TransformStatements(prologue, _statements, ResultOperation.Return); } body = gen.AddReturnTarget(scope.CreateScope(body)); gen.LeaveSourceUnit(); return(Ast.Lambda <T>( body, RubyExceptionData.TopLevelMethodName, parameters )); }
public void GetConstantSiteCacheVariables(out MSA.ParameterExpression /*!*/ cacheVar, out MSA.ParameterExpression /*!*/ valueVar) { if (_csCacheVariable == null) { _csCacheVariable = DefineHiddenVariable("c_site", typeof(ConstantSiteCache)); _csValueVariable = DefineHiddenVariable("c_value", typeof(object)); } cacheVar = _csCacheVariable; valueVar = _csValueVariable; }
public linq.Expression <Func <IEvaluationContext, bool> > GetExpression() { linq.ParameterExpression paramX = linq.Expression.Parameter(typeof(IEvaluationContext), "x"); var castOp = linq.Expression.MakeUnary(linq.ExpressionType.Convert, paramX, typeof(DynamicContentEvaluationContext)); var propertyValue = linq.Expression.Property(castOp, typeof(DynamicContentEvaluationContext).GetProperty("GeoState")); MethodInfo method; linq.Expression methodExp; if (string.Equals(MatchConditionValue, MatchCondition.Contains)) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(SelectedState.ToLowerInvariant())); } else if (string.Equals(MatchConditionValue, MatchCondition.Matching)) { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(SelectedState.ToLowerInvariant())); } else if (string.Equals(MatchConditionValue, MatchCondition.ContainsCase)) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); methodExp = linq.Expression.Call(propertyValue, method, linq.Expression.Constant(SelectedState)); } else if (string.Equals(MatchConditionValue, MatchCondition.MatchingCase)) { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); methodExp = linq.Expression.Call(propertyValue, method, linq.Expression.Constant(SelectedState)); } else if (string.Equals(MatchConditionValue, MatchCondition.NotContains)) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Not(linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(SelectedState.ToLowerInvariant()))); } else if (string.Equals(MatchConditionValue, MatchCondition.NotMatching)) { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); var toLowerMethod = typeof(string).GetMethod("ToLowerInvariant"); var toLowerExp = linq.Expression.Call(propertyValue, toLowerMethod); methodExp = linq.Expression.Not(linq.Expression.Call(toLowerExp, method, linq.Expression.Constant(SelectedState.ToLowerInvariant()))); } else if (string.Equals(MatchConditionValue, MatchCondition.NotContainsCase)) { method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); methodExp = linq.Expression.Not(linq.Expression.Call(propertyValue, method, linq.Expression.Constant(SelectedState))); } else { method = typeof(string).GetMethod("Equals", new[] { typeof(string) }); methodExp = linq.Expression.Not(linq.Expression.Call(propertyValue, method, linq.Expression.Constant(SelectedState))); } var retVal = linq.Expression.Lambda <Func <IEvaluationContext, bool> >(methodExp, paramX); return(retVal); }
public override DLR.Expression Generate(AplusScope scope) { Aplus runtime = scope.GetRuntime(); LinkedList <DLR.Expression> result = new LinkedList <DLR.Expression>(); DLR.ParameterExpression scalar = DLR.Expression.Parameter(typeof(AType), "_ScalarResult_"); DLR.ParameterExpression counter = DLR.Expression.Parameter(typeof(int), "COUNTER"); DLR.ParameterExpression exitValue = DLR.Expression.Parameter(typeof(int), "EXITVALUE"); DLR.LabelTarget exitLabel = DLR.Expression.Label(typeof(AType), "EXIT"); DLR.ParameterExpression returnValue = DLR.Expression.Parameter(typeof(AType), "RETURN"); bool incrementMode = true; if (this.expression is MonadicFunction && ((MonadicFunction)this.expression).Token.Type == Tokens.EXPONENTIAL) { // Change the counter's 'way' incrementMode = false; // Remove the Exponential function this.expression = ((MonadicFunction)this.expression).Expression; } if (this.expression is Assign && ((Assign)this.expression).Target is Identifier) { scope.IsAssignment = true; result.AddFirst(this.expression.Generate(scope)); scope.IsAssignment = false; // Remove the assignment and leave the identifier only this.expression = ((Assign)this.expression).Target; } // Save the previous return target DLR.LabelTarget oldTarget = scope.ReturnTarget; // Add an return target for the scope // this will allow the usage of the Result monadic function scope.ReturnTarget = exitLabel; if (this.expression is Identifier) { // Found a case like: VAR do { ... } Identifier variable = (Identifier)this.expression; // Generate a .Dynamic.Get DLR tree (used multiple times so this saves time) DLR.Expression variableGenerated = variable.Generate(scope); DLR.Expression variableAsFloat = DLR.Expression.Property(scalar, "asFloat"); result.AddLast(DLR.Expression.Block( new DLR.ParameterExpression[] { counter, exitValue, returnValue, scalar }, // Test if the constant is an integer DomainTest(variableGenerated, scalar), DLR.Expression.Assign(exitValue, (incrementMode ? // EXITVALUE = round(variable.asFloat) (DLR.Expression)FloatRounding(variableAsFloat) : // EXITVALUE = 0 (DLR.Expression)DLR.Expression.Constant(0, typeof(int)) ) ), DLR.Expression.Assign( counter, (incrementMode ? (DLR.Expression)DLR.Expression.Constant(0, typeof(int)) : (DLR.Expression)DLR.Expression.Decrement(FloatRounding(variableAsFloat)) ) ), // Start the loop DLR.Expression.Loop( DLR.Expression.Block( AST.Assign.GenerateIdentifierAssign( scope, variable, DLR.Expression.Call(typeof(LocalAInteger).GetMethod("Create"), counter), false, false ), DLR.Expression.IfThen( (incrementMode ? // Check if variable >= EXITVALUE is true DLR.Expression.GreaterThanOrEqual( counter, //DLR.Expression.Property(variableGenerated, "asInteger"), exitValue ) : // Check if EXITVALUE(0) > variable is true DLR.Expression.GreaterThan( exitValue, //DLR.Expression.Property(variableGenerated, "asInteger") counter ) ), // The expression was true, exit from the loop with the last value of the expression block DLR.Expression.Break(exitLabel, returnValue) ), // Otherwise run the inner codeblock DLR.Expression.Assign(returnValue, this.codeblock.Generate(scope)), // Update counter (incrementMode ? // ++counter DLR.Expression.PreIncrementAssign(counter) : // --counter DLR.Expression.PreDecrementAssign(counter) ) ), exitLabel ) )); } else { // Simple Iteration DLR.ParameterExpression temp = DLR.Expression.Parameter(typeof(AType), "TMP"); result.AddLast(DLR.Expression.Block( new DLR.ParameterExpression[] { temp, counter, exitValue, returnValue, scalar }, // Save the iteration count into a temporaly variable DLR.Expression.Assign(temp, this.expression.Generate(scope)), // Test if the constant is an integer DomainTest(temp, scalar), // MAXVALUE = temp.asInteger DLR.Expression.Assign(exitValue, FloatRounding(DLR.Expression.Property(scalar, "asFloat"))), // counter = 0 DLR.Expression.Assign(counter, DLR.Expression.Constant(0, typeof(int))), // Start the loop DLR.Expression.Loop( DLR.Expression.Block( // Check if counter >= MAXVALUE is true DLR.Expression.IfThen( DLR.Expression.GreaterThanOrEqual(counter, exitValue), // The expression was true, exit from the loop with the last calculated value DLR.Expression.Break(exitLabel, returnValue) ), // Otherwise run the inner codeblock, save the block's result DLR.Expression.Assign(returnValue, this.codeblock.Generate(scope)), // Increment the counter DLR.Expression.PreIncrementAssign(counter) ), exitLabel ) )); } // Restore the return target scope.ReturnTarget = oldTarget; return(DLR.Expression.Block(result)); }
public MSA.ParameterExpression /*!*/ AddHidden(MSA.ParameterExpression /*!*/ variable) { _hiddenVariables.Add(variable); return(variable); }
public override MSAst.Expression Reduce() { if (_names == _star) { // from a[.b] import * return(GlobalParent.AddDebugInfo( Ast.Call( AstMethods.ImportStar, Parent.LocalContext, AstUtils.Constant(_root.MakeString()), AstUtils.Constant(GetLevel()) ), Span )); } else { // from a[.b] import x [as xx], [ y [ as yy] ] [ , ... ] ReadOnlyCollectionBuilder <MSAst.Expression> statements = new ReadOnlyCollectionBuilder <MSAst.Expression>(); MSAst.ParameterExpression module = Ast.Variable(typeof(object), "module"); // Create initializer of the array of names being passed to ImportWithNames MSAst.Expression[] names = new MSAst.Expression[_names.Length]; for (int i = 0; i < names.Length; i++) { names[i] = AstUtils.Constant(_names[i]); } // module = PythonOps.ImportWithNames(<context>, _root, make_array(_names)) statements.Add( GlobalParent.AddDebugInfoAndVoid( AssignValue( module, LightExceptions.CheckAndThrow( Expression.Call( AstMethods.ImportWithNames, Parent.LocalContext, AstUtils.Constant(_root.MakeString()), Ast.NewArrayInit(typeof(string), names), AstUtils.Constant(GetLevel()) ) ) ), _root.Span ) ); // now load all the names being imported and assign the variables for (int i = 0; i < names.Length; i++) { statements.Add( GlobalParent.AddDebugInfoAndVoid( AssignValue( Parent.GetVariableExpression(_variables[i]), Ast.Call( AstMethods.ImportFrom, Parent.LocalContext, module, names[i] ) ), Span ) ); } statements.Add(AstUtils.Empty()); return(GlobalParent.AddDebugInfo(Ast.Block(new[] { module }, statements.ToArray()), Span)); } }
/// <summary> /// Creates the LambdaExpression which implements the body of the function. /// /// The functions signature is either "object Function(PythonFunction, ...)" /// where there is one object parameter for each user defined parameter or /// object Function(PythonFunction, object[]) for functions which take more /// than PythonCallTargets.MaxArgs arguments. /// </summary> private LightLambdaExpression CreateFunctionLambda() { bool needsWrapperMethod = _parameters.Length > PythonCallTargets.MaxArgs; Delegate originalDelegate; Type delegateType = GetDelegateType(_parameters, needsWrapperMethod, out originalDelegate); MSAst.ParameterExpression localContext = null; ReadOnlyCollectionBuilder <MSAst.ParameterExpression> locals = new ReadOnlyCollectionBuilder <MSAst.ParameterExpression>(); if (NeedsLocalContext) { localContext = LocalCodeContextVariable; locals.Add(localContext); } MSAst.ParameterExpression[] parameters = CreateParameters(needsWrapperMethod, locals); List <MSAst.Expression> init = new List <MSAst.Expression>(); foreach (var param in _parameters) { IPythonVariableExpression pyVar = GetVariableExpression(param.PythonVariable) as IPythonVariableExpression; if (pyVar != null) { var varInit = pyVar.Create(); if (varInit != null) { init.Add(varInit); } } } // Transform the parameters. init.Add(Ast.ClearDebugInfo(GlobalParent.Document)); locals.Add(PythonAst._globalContext); init.Add(Ast.Assign(PythonAst._globalContext, new GetGlobalContextExpression(_parentContext))); GlobalParent.PrepareScope(locals, init); // Create variables and references. Since references refer to // parameters, do this after parameters have been created. CreateFunctionVariables(locals, init); // Initialize parameters - unpack tuples. // Since tuples unpack into locals, this must be done after locals have been created. InitializeParameters(init, needsWrapperMethod, parameters); List <MSAst.Expression> statements = new List <MSAst.Expression>(); // add beginning sequence point var start = GlobalParent.IndexToLocation(StartIndex); statements.Add(GlobalParent.AddDebugInfo( AstUtils.Empty(), new SourceSpan(new SourceLocation(0, start.Line, start.Column), new SourceLocation(0, start.Line, Int32.MaxValue)))); // For generators, we need to do a check before the first statement for Generator.Throw() / Generator.Close(). // The exception traceback needs to come from the generator's method body, and so we must do the check and throw // from inside the generator. if (IsGenerator) { MSAst.Expression s1 = YieldExpression.CreateCheckThrowExpression(SourceSpan.None); statements.Add(s1); } MSAst.ParameterExpression extracted = null; if (!IsGenerator && _canSetSysExcInfo) { // need to allocate the exception here so we don't share w/ exceptions made & freed // during the body. extracted = Ast.Parameter(typeof(Exception), "$ex"); locals.Add(extracted); } if (_body.CanThrow && !(_body is SuiteStatement) && _body.StartIndex != -1) { statements.Add(UpdateLineNumber(GlobalParent.IndexToLocation(_body.StartIndex).Line)); } statements.Add(Body); MSAst.Expression body = Ast.Block(statements); // If this function can modify sys.exc_info() (_canSetSysExcInfo), then it must restore the result on finish. // // Wrap in // $temp = PythonOps.SaveCurrentException() // <body> // PythonOps.RestoreCurrentException($temp) // Skip this if we're a generator. For generators, the try finally is handled by the PythonGenerator class // before it's invoked. This is because the restoration must occur at every place the function returns from // a yield point. That's different than the finally semantics in a generator. if (extracted != null) { MSAst.Expression s = AstUtils.Try( Ast.Assign( extracted, Ast.Call(AstMethods.SaveCurrentException) ), body ).Finally( Ast.Call( AstMethods.RestoreCurrentException, extracted ) ); body = s; } if (_body.CanThrow && GlobalParent.PyContext.PythonOptions.Frames) { body = AddFrame(LocalContext, Ast.Property(_functionParam, typeof(PythonFunction).GetProperty("__code__")), body); locals.Add(FunctionStackVariable); } body = AddProfiling(body); body = WrapScopeStatements(body, _body.CanThrow); body = Ast.Block(body, AstUtils.Empty()); body = AddReturnTarget(body); MSAst.Expression bodyStmt = body; if (localContext != null) { var createLocal = CreateLocalContext(_parentContext); init.Add( Ast.Assign( localContext, createLocal ) ); } init.Add(bodyStmt); bodyStmt = Ast.Block(init); // wrap a scope if needed bodyStmt = Ast.Block(locals.ToReadOnlyCollection(), bodyStmt); return(AstUtils.LightLambda( typeof(object), delegateType, AddDefaultReturn(bodyStmt, typeof(object)), Name + "$" + Interlocked.Increment(ref _lambdaId), parameters )); }
/// <summary> /// Transform multiple python except handlers for a try block into a single catch body. /// </summary> /// <param name="exception">The variable for the exception in the catch block.</param> /// <returns>Null if there are no except handlers. Else the statement to go inside the catch handler</returns> private MSAst.Expression TransformHandlers(MSAst.ParameterExpression exception) { Assert.NotEmpty(_handlers); MSAst.ParameterExpression extracted = Ast.Variable(typeof(object), "$extracted"); var tests = new List <Microsoft.Scripting.Ast.IfStatementTest>(_handlers.Length); MSAst.ParameterExpression converted = null; MSAst.Expression catchAll = null; for (int index = 0; index < _handlers.Length; index++) { TryStatementHandler tsh = _handlers[index]; if (tsh.Test != null) { Microsoft.Scripting.Ast.IfStatementTest ist; // translating: // except Test ... // // generate following AST for the Test (common part): // CheckException(exception, Test) MSAst.Expression test = Ast.Call( AstMethods.CheckException, Parent.LocalContext, extracted, AstUtils.Convert(tsh.Test, typeof(object)) ); if (tsh.Target != null) { // translating: // except Test, Target: // <body> // into: // if ((converted = CheckException(exception, Test)) != null) { // Target = converted; // traceback-header // <body> // } if (converted == null) { converted = Ast.Variable(typeof(object), "$converted"); } ist = AstUtils.IfCondition( Ast.NotEqual( Ast.Assign(converted, test), AstUtils.Constant(null) ), Ast.Block( tsh.Target.TransformSet(SourceSpan.None, converted, PythonOperationKind.None), GlobalParent.AddDebugInfo( GetTracebackHeader( this, exception, tsh.Body ), new SourceSpan(GlobalParent.IndexToLocation(tsh.StartIndex), GlobalParent.IndexToLocation(tsh.HeaderIndex)) ), AstUtils.Empty() ) ); } else { // translating: // except Test: // <body> // into: // if (CheckException(exception, Test) != null) { // traceback-header // <body> // } ist = AstUtils.IfCondition( Ast.NotEqual( test, AstUtils.Constant(null) ), GlobalParent.AddDebugInfo( GetTracebackHeader( this, exception, tsh.Body ), new SourceSpan(GlobalParent.IndexToLocation(tsh.StartIndex), GlobalParent.IndexToLocation(tsh.HeaderIndex)) ) ); } // Add the test to the if statement test cascade tests.Add(ist); } else { Debug.Assert(index == _handlers.Length - 1); Debug.Assert(catchAll == null); // translating: // except: // <body> // into: // { // traceback-header // <body> // } catchAll = GlobalParent.AddDebugInfo( GetTracebackHeader(this, exception, tsh.Body), new SourceSpan(GlobalParent.IndexToLocation(tsh.StartIndex), GlobalParent.IndexToLocation(tsh.HeaderIndex)) ); } } MSAst.Expression body = null; if (tests.Count > 0) { // rethrow the exception if we have no catch-all block if (catchAll == null) { catchAll = Ast.Block( Parent.GetSaveLineNumberExpression(exception, true), Ast.Throw( Ast.Call( typeof(ExceptionHelpers).GetMethod("UpdateForRethrow"), exception ) ) ); } body = AstUtils.If( tests.ToArray(), catchAll ); } else { Debug.Assert(catchAll != null); body = catchAll; } IList <MSAst.ParameterExpression> args; if (converted != null) { args = new ReadOnlyCollectionBuilder <MSAst.ParameterExpression> { converted, extracted }; } else { args = new ReadOnlyCollectionBuilder <MSAst.ParameterExpression> { extracted }; } // Codegen becomes: // extracted = PythonOps.SetCurrentException(exception) // < dynamic exception analysis > return(Ast.Block( args, Ast.Assign( extracted, Ast.Call( AstMethods.SetCurrentException, Parent.LocalContext, exception ) ), body, Ast.Assign(extracted, Ast.Constant(null)), AstUtils.Empty() )); }
public override MSAst.Expression Reduce() { // allocated all variables here so they won't be shared w/ other // locals allocated during the body or except blocks. MSAst.ParameterExpression lineUpdated = null; MSAst.ParameterExpression runElse = null; if (_else != null || (_handlers != null && _handlers.Length > 0)) { lineUpdated = Ast.Variable(typeof(bool), "$lineUpdated_try"); if (_else != null) { runElse = Ast.Variable(typeof(bool), "run_else"); } } // don't allocate locals below here... MSAst.Expression body = _body; MSAst.Expression @else = _else; MSAst.Expression @catch, result; MSAst.ParameterExpression exception; if (_handlers != null && _handlers.Length > 0) { exception = Ast.Variable(typeof(Exception), "$exception"); @catch = TransformHandlers(exception); } else { exception = null; @catch = null; } // We have else clause, must generate guard around it if (@else != null) { Debug.Assert(@catch != null); // run_else = true; // try { // try_body // } catch ( ... ) { // run_else = false; // catch_body // } // if (run_else) { // else_body // } result = Ast.Block( Ast.Assign(runElse, AstUtils.Constant(true)), // save existing line updated, we could choose to do this only for nested exception handlers. PushLineUpdated(false, lineUpdated), LightExceptions.RewriteExternal( AstUtils.Try( Parent.AddDebugInfo(AstUtils.Empty(), new SourceSpan(Span.Start, GlobalParent.IndexToLocation(_headerIndex))), body, AstUtils.Constant(null) ).Catch(exception, Ast.Assign(runElse, AstUtils.Constant(false)), @catch, // restore existing line updated after exception handler completes PopLineUpdated(lineUpdated), Ast.Assign(exception, Ast.Constant(null, typeof(Exception))), AstUtils.Constant(null) ) ), AstUtils.IfThen(runElse, @else ), AstUtils.Empty() ); } else if (@catch != null) // no "else" clause // try { // <try body> // } catch (Exception e) { // ... catch handling ... // } // { result = LightExceptions.RewriteExternal( AstUtils.Try( GlobalParent.AddDebugInfo(AstUtils.Empty(), new SourceSpan(Span.Start, GlobalParent.IndexToLocation(_headerIndex))), // save existing line updated PushLineUpdated(false, lineUpdated), body, AstUtils.Constant(null) ).Catch(exception, @catch, // restore existing line updated after exception handler completes PopLineUpdated(lineUpdated), Ast.Call(AstMethods.ExceptionHandled, Parent.LocalContext), Ast.Assign(exception, Ast.Constant(null, typeof(Exception))), AstUtils.Constant(null) ) ); } else { result = body; } return(Ast.Block( GetVariables(lineUpdated, runElse), AddFinally(result), AstUtils.Default(typeof(void)) )); }
/// <summary> /// Gets a filter expression for an attribute value. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="filterValues">The filter values.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <returns></returns> public override System.Linq.Expressions.Expression AttributeFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, System.Linq.Expressions.ParameterExpression parameterExpression) { if (filterValues.Count >= 2) { string comparisonValue = filterValues[0]; if (comparisonValue != "0") { Guid guid = filterValues[1].AsGuid(); int personId = new PersonAliasService(new RockContext()).Queryable() .Where(a => a.Guid.Equals(guid)) .Select(a => a.PersonId) .FirstOrDefault(); if (personId > 0) { ComparisonType comparisonType = comparisonValue.ConvertToEnum <ComparisonType>(ComparisonType.EqualTo); MemberExpression propertyExpression = Expression.Property(parameterExpression, "ValueAsPersonId"); ConstantExpression constantExpression = Expression.Constant(personId, typeof(int)); return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, constantExpression)); } } } return(new NoAttributeFilterExpression()); }
private static ReadOnlyCollectionBuilder <MSAst.ParameterExpression> GetVariables(MSAst.ParameterExpression lineUpdated, MSAst.ParameterExpression runElse) { var paramList = new ReadOnlyCollectionBuilder <MSAst.ParameterExpression>(); if (lineUpdated != null) { paramList.Add(lineUpdated); } if (runElse != null) { paramList.Add(runElse); } return(paramList); }
private MSAst.Expression SetMemberOperator(MSAst.Expression right, PythonOperationKind op, MSAst.ParameterExpression temp) { return(GlobalParent.Set( _name, temp, GlobalParent.Operation( typeof(object), op, GlobalParent.Get( _name, temp ), right ) )); }
internal MSA.Expression <T> /*!*/ Transform <T>(AstGenerator /*!*/ gen) { Debug.Assert(gen != null); ScopeBuilder scope = DefineLocals(); MSA.ParameterExpression[] parameters; MSA.ParameterExpression selfVariable; MSA.ParameterExpression runtimeScopeVariable; MSA.ParameterExpression blockParameter; if (gen.CompilerOptions.FactoryKind == TopScopeFactoryKind.None || gen.CompilerOptions.FactoryKind == TopScopeFactoryKind.ModuleEval) { parameters = new MSA.ParameterExpression[4]; runtimeScopeVariable = parameters[0] = Ast.Parameter(typeof(RubyScope), "#scope"); selfVariable = parameters[1] = Ast.Parameter(typeof(object), "#self"); parameters[2] = Ast.Parameter(typeof(RubyModule), "#module"); blockParameter = parameters[3] = Ast.Parameter(typeof(Proc), "#block"); } else { parameters = new MSA.ParameterExpression[2]; runtimeScopeVariable = parameters[0] = Ast.Parameter(typeof(RubyScope), "#scope"); selfVariable = parameters[1] = Ast.Parameter(typeof(object), "#self"); blockParameter = null; } gen.EnterSourceUnit( scope, selfVariable, runtimeScopeVariable, blockParameter, gen.CompilerOptions.TopLevelMethodName, // method name for blocks null // parameters for super calls ); MSA.Expression body; if (_statements.Count > 0) { if (gen.PrintInteractiveResult) { var resultVariable = scope.DefineHiddenVariable("#result", typeof(object)); var epilogue = Methods.PrintInteractiveResult.OpCall(runtimeScopeVariable, AstUtils.LightDynamic(ConvertToSAction.Make(gen.Context), typeof(MutableString), CallSiteBuilder.InvokeMethod(gen.Context, "inspect", RubyCallSignature.WithScope(0), gen.CurrentScopeVariable, resultVariable ) ) ); body = gen.TransformStatements(null, _statements, epilogue, ResultOperation.Store(resultVariable)); } else { body = gen.TransformStatements(_statements, ResultOperation.Return); } // TODO: var exceptionVariable = Ast.Parameter(typeof(Exception), "#exception"); body = AstUtils.Try( body ).Filter(exceptionVariable, Methods.TraceTopLevelCodeFrame.OpCall(runtimeScopeVariable, exceptionVariable), Ast.Empty() ); } else { body = AstUtils.Constant(null); } // scope initialization: MSA.Expression prologue; switch (gen.CompilerOptions.FactoryKind) { case TopScopeFactoryKind.None: case TopScopeFactoryKind.ModuleEval: prologue = Methods.InitializeScopeNoLocals.OpCall(runtimeScopeVariable, EnterInterpretedFrameExpression.Instance); break; case TopScopeFactoryKind.Hosted: case TopScopeFactoryKind.File: case TopScopeFactoryKind.WrappedFile: prologue = Methods.InitializeScope.OpCall( runtimeScopeVariable, scope.MakeLocalsStorage(), scope.GetVariableNamesExpression(), EnterInterpretedFrameExpression.Instance ); break; case TopScopeFactoryKind.Main: prologue = Methods.InitializeScope.OpCall( runtimeScopeVariable, scope.MakeLocalsStorage(), scope.GetVariableNamesExpression(), EnterInterpretedFrameExpression.Instance ); if (_dataOffset >= 0) { prologue = Ast.Block( prologue, Methods.SetDataConstant.OpCall( runtimeScopeVariable, gen.SourcePathConstant, AstUtils.Constant(_dataOffset) ) ); } break; default: throw Assert.Unreachable; } // BEGIN blocks: if (gen.FileInitializers != null) { var b = new AstBlock(); b.Add(prologue); b.Add(gen.FileInitializers); b.Add(body); body = b; } body = gen.AddReturnTarget(scope.CreateScope(body)); gen.LeaveSourceUnit(); return(Ast.Lambda <T>(body, GetEncodedName(gen), parameters)); }
internal virtual lambda.Expression CompileStringBlock(lambda.ParameterExpression paramString1, lambda.ParameterExpression paramString2) { throw new EvaluateException("Syntax Error"); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override System.Linq.Expressions.Expression GetExpression(Type entityType, Data.IService serviceInstance, System.Linq.Expressions.ParameterExpression parameterExpression, string selection) { string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 1) { var accountGuids = selectionValues[0].Split(',').Select(a => a.AsGuid()).ToList(); var accountIds = new FinancialAccountService((RockContext)serviceInstance.Context).GetByGuids(accountGuids).Select(a => a.Id).ToList(); var qry = new FinancialPledgeService((RockContext)serviceInstance.Context).Queryable() .Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value)); Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.FinancialPledge>(qry, parameterExpression, "p"); return(extractedFilterExpression); } return(null); }
internal MSAst.Expression MakeAssignment(MSAst.ParameterExpression variable, MSAst.Expression right, SourceSpan span) { return(GlobalParent.AddDebugInfoAndVoid(Ast.Assign(variable, AstUtils.Convert(right, variable.Type)), span)); }
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); // 3. Call GetEnumeratorValues on the right side (stored in temp) MSAst.Expression enumeratorValues = Expression.Convert(LightExceptions.CheckAndThrow( Expression.Call( emitIndividualSets ? AstMethods.GetEnumeratorValues : AstMethods.GetEnumeratorValuesNoComplexSets, // method // arguments Parent.LocalContext, right_temp, AstUtils.Constant(_items.Length) ) ), 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)); }
internal static MSAst.Expression PopLineUpdated(MSAst.ParameterExpression saveCurrent) { return(Ast.Assign(LineNumberUpdated, saveCurrent)); }
internal virtual lambda.Expression CompileNumericBlock(lambda.ParameterExpression paramNumeric1, lambda.ParameterExpression paramNumeric2) { throw new EvaluateException("Syntax Error"); }