internal override MSAst.Expression TransformSet(AstGenerator ag, SourceSpan span, MSAst.Expression right, Operators op) { MSAst.Expression variable = _reference.Variable; MSAst.Expression assignment; Type vt = variable != null ? variable.Type : typeof(object); if (op != Operators.None) { right = Binders.Operation( ag.BinderState, vt, StandardOperators.FromOperator(op), Transform(ag, vt), right ); } if (variable != null) { assignment = AstUtils.Assign(variable, AstGenerator.ConvertIfNeeded(right, variable.Type)); } else { assignment = AstUtils.Assign(_name, right); } SourceSpan aspan = span.IsValid ? new SourceSpan(Span.Start, span.End) : SourceSpan.None; return ag.AddDebugInfoAndVoid(assignment, aspan); }
internal override MSA.Expression/*!*/ TransformWriteVariable(AstGenerator/*!*/ gen, MSA.Expression/*!*/ rightValue) { if (gen.CompilerOptions.IsEval || gen.GetCurrentNonSingletonModule() != null) { return Methods.SetClassVariable.OpCall(AstFactory.Box(rightValue), gen.CurrentScopeVariable, AstUtils.Constant(Name)); } else { return Methods.SetObjectClassVariable.OpCall(AstFactory.Box(rightValue), gen.CurrentScopeVariable, AstUtils.Constant(Name)); } }
public AplusScope(AplusScope parent, string name, Aplus runtime = null, DLR.ParameterExpression runtimeParam = null, DLR.ParameterExpression moduleParam = null, DLR.LabelTarget returnTarget = null, bool isEval = false, bool isMethod = false, bool isAssignment = false) { this.parent = parent; this.name = name; this.runtime = runtime; this.runtimeParam = runtimeParam; this.moduleParam = moduleParam; this.returnTarget = returnTarget; this.variables = new Dictionary<string, DLR.ParameterExpression>(); this.callbackInfo = new CallbackInfoStorage(); this.iseval = isEval; this.ismethod = isMethod; this.isAssignment = isAssignment; InheritProperties(parent); }
private MSA.Expression/*!*/ TransformBody(AstGenerator/*!*/ gen, MSA.Expression/*!*/ methodDefinitionVariable) { string encodedName = RubyExceptionData.EncodeMethodName(gen.SourceUnit, _name, Location); ScopeBuilder scope = new ScopeBuilder(); MSA.Expression parentScope = gen.CurrentScopeVariable; MSA.ParameterExpression[] parameters = DefineParameters(gen, scope); MSA.Expression currentMethodVariable = scope.DefineHiddenVariable("#method", typeof(RubyMethodInfo)); MSA.Expression rfcVariable = scope.DefineHiddenVariable("#rfc", typeof(RuntimeFlowControl)); MSA.Expression scopeVariable = scope.DefineHiddenVariable("#scope", typeof(RubyMethodScope)); MSA.Expression selfParameter = parameters[0]; MSA.Expression blockParameter = parameters[1]; gen.EnterMethodDefinition( scope, selfParameter, scopeVariable, blockParameter, rfcVariable, currentMethodVariable, _name, _parameters ); DefinedScope.TransformLocals(scope); MSA.ParameterExpression unwinder = scope.DefineHiddenVariable("#unwinder", typeof(MethodUnwinder)); MSA.Expression body = AstFactory.MakeUserMethodBody( gen, Location.End.Line, blockParameter, rfcVariable, unwinder, Ast.Block( Ast.Assign(currentMethodVariable, methodDefinitionVariable), Ast.Assign(scopeVariable, Methods.CreateMethodScope.OpCall( scope.VisibleVariables(), parentScope, currentMethodVariable, rfcVariable, selfParameter, blockParameter) ), _parameters.TransformOptionalsInitialization(gen), gen.TraceEnabled ? Methods.TraceMethodCall.OpCall(scopeVariable, Ast.Convert(AstUtils.Constant(gen.SourceUnit.Path), typeof(string)), AstUtils.Constant(Location.Start.Line)) : AstUtils.Empty(), Body.TransformResult(gen, ResultOperation.Return), AstUtils.Empty() ), ResultOperation.Return, (gen.Profiler != null) ? gen.Profiler.GetTickIndex(encodedName) : -1, (gen.Profiler != null) ? scope.DefineHiddenVariable("#stamp", typeof(long)) : null, gen.ReturnLabel ); body = gen.AddReturnTarget(scope.CreateScope(body)); gen.LeaveMethodDefinition(); return CreateLambda( encodedName, parameters, body ); }
/*!*/ internal override MSA.Expression TransformWriteVariable(AstGenerator/*!*/ gen, MSA.Expression/*!*/ rightValue) { Assert.NotNull(gen, rightValue); // no-op return rightValue; }
public static MSA.Expression/*!*/ IsTrue(MSA.Expression/*!*/ expression) { if (expression.Type == typeof(bool)) { return expression; } else { return Methods.IsTrue.OpCall(Box(expression)); } }
private object InvokeTarget(MSAst.LambdaExpression code, Scope scope) { if (scope == _optimizedContext.Scope) { EnsureCompiled(); if (_context.SourceUnit.Kind == SourceCodeKind.Expression) { return OptimizedEvalWrapper(); } return _optimizedTarget(); } // if we're running different code then re-compile the code under a new scope if (_unoptimizedCode == null) { // TODO: Copy instead of mutate ((PythonCompilerOptions)_context.Options).Optimized = false; Interlocked.CompareExchange( ref _unoptimizedCode, _ast.TransformToAst(CompilationMode.Lookup, _context), null ); } if (_context.SourceUnit.Kind == SourceCodeKind.Expression) { return EvalWrapper(scope); } return _unoptimizedCode.Run(scope); }
public override ScriptCode/*!*/ MakeScriptCode(MSAst.Expression/*!*/ body, CompilerContext/*!*/ context, PythonAst/*!*/ ast) { MSAst.Expression finalBody = Ast.Block( new[] { _globalCtx }, Ast.Assign( _globalCtx, Ast.Call(typeof(PythonOps).GetMethod("CreateTopLevelCodeContext"), _globalScope, _language ) ), body ); PythonCompilerOptions pco = ((PythonCompilerOptions)context.Options); string name = pco.ModuleName ?? "<unnamed>"; var lambda = Ast.Lambda<Func<Scope, LanguageContext, object>>( finalBody, name, new[] { _globalScope, _language } ); Func<Scope, LanguageContext, object> func; // TODO: adaptive compilation should be eanbled /*PythonContext pc = (PythonContext)context.SourceUnit.LanguageContext; if (pc.ShouldInterpret(pco, context.SourceUnit)) { func = CompilerHelpers.LightCompile(lambda); } else*/ { func = lambda.Compile(context.SourceUnit.EmitDebugSymbols); } return new PythonScriptCode(func, context.SourceUnit); }
public static MSA.Expression/*!*/ IsFalse(MSA.Expression/*!*/ expression) { if (expression.Type == typeof(bool)) { return Ast.Not(expression); } else { return Methods.IsFalse.OpCall(AstUtils.Box(expression)); } }
public override ScriptCode/*!*/ MakeScriptCode(MSAst.Expression/*!*/ body, CompilerContext/*!*/ context, PythonAst/*!*/ ast) { PythonCompilerOptions pco = ((PythonCompilerOptions)context.Options); PythonContext pc = (PythonContext)context.SourceUnit.LanguageContext; if (body is MSAst.ConstantExpression) { object value = ((MSAst.ConstantExpression)body).Value; return new PythonScriptCode(codeCtx => value, context.SourceUnit); } var lambda = Ast.Lambda<Func<CodeContext, object>>( Utils.Convert(body, typeof(object)), pco.ModuleName ?? "<unnamed>", ArrayGlobalAllocator._globalContextList ); Func<CodeContext, object> func; if (pc.ShouldInterpret(pco, context.SourceUnit)) { func = CompilerHelpers.LightCompile(lambda); } else { func = lambda.Compile(context.SourceUnit.EmitDebugSymbols); } return new PythonScriptCode(func, context.SourceUnit); }
internal RubyMethodBody(MethodDeclaration/*!*/ ast, MSA.SymbolDocumentInfo document, RubyEncoding/*!*/ encoding) { Assert.NotNull(ast, encoding); _ast = ast; _document = document; _encoding = encoding; }
internal override MSAst.Expression TransformSet(SourceSpan span, MSAst.Expression right, PythonOperationKind op) { if (op == PythonOperationKind.None) { return GlobalParent.AddDebugInfoAndVoid( GlobalParent.Set( typeof(object), _name, _target, right ), span ); } else { MSAst.ParameterExpression temp = Ast.Variable(typeof(object), "inplace"); return GlobalParent.AddDebugInfo( Ast.Block( new[] { temp }, Ast.Assign(temp, _target), SetMemberOperator(right, op, temp), AstUtils.Empty() ), Span.Start, span.End ); } }
/// <summary> /// Constructs a DLR Expression tree representing setting a variable inside a context. /// </summary> /// <param name="runtime"></param> /// <param name="variableContainer">The container where the lookup should be performed</param> /// <param name="contextParts"> /// Contains 2 strings: /// 1. The name of the context /// 2. The name of the variable inside the context /// </param> /// <param name="value">Expression containing the value of the variable</param> /// <remarks> /// The returned DLR Expression tree will try to fetch the context inside the container. /// If the context does not exists, this will result an exception. /// If the exception occured, the context will be created inside the catch block. /// After this the context surely exists, so we can simply set the variable to the provided value. /// /// </remarks> /// <returns>>Expression tree for setting a value for the given context parts</returns> internal static DLR.Expression SetVariable(Aplus runtime, DLR.Expression variableContainer, string[] contextParts, DLR.Expression value) { // Get the context DLR.Expression getContext = DLR.Expression.TryCatch( DLR.Expression.Dynamic( runtime.GetMemberBinder(contextParts[0]), typeof(object), variableContainer ), DLR.Expression.Catch( // Context not found, create one! typeof(Error.Value), DLR.Expression.Dynamic( runtime.SetMemberBinder(contextParts[0]), typeof(object), variableContainer, DLR.Expression.Constant(new ScopeStorage()) ) ) ); DLR.Expression setVariable = DLR.Expression.Dynamic( runtime.SetMemberBinder(contextParts[1]), typeof(object), getContext, value ); return setVariable; }
public override ScriptCode/*!*/ MakeScriptCode(MSAst.Expression/*!*/ lambda, CompilerContext/*!*/ compilerContext, PythonAst/*!*/ ast) { PythonContext context = (PythonContext)compilerContext.SourceUnit.LanguageContext; Type t = _typeGen.FinishType(); #if SILVERLIGHT _finalType.Value = t; #endif // create the CodeContext for this optimized module InitOptimizedCodeContext(t); t.GetField("__global_context").SetValue(null, _context); // publish the cached constants foreach (var ci in _constants) { FieldInfo fi = t.GetField(ci.Value.Field.Name); fi.SetValue(null, ci.Key); } // publish all of the call site instances foreach (SiteInfo si in _sites) { FieldInfo fi = t.GetField(si.Field.Name); fi.SetValue(null, CallSite.Create(si.DelegateType, si.Binder)); } // initialize all of the cached symbol IDs. ScriptingRuntimeHelpers.InitializeSymbols(t); string name = ((PythonCompilerOptions)compilerContext.Options).ModuleName ?? "<unnamed>"; var func = Ast.Lambda<Func<object>>(lambda, name, new MSAst.ParameterExpression[0]); return new RuntimeScriptCode(compilerContext, func, ast, _context); }
public override ScriptCode/*!*/ MakeScriptCode(MSAst.Expression/*!*/ body, CompilerContext/*!*/ context, PythonAst/*!*/ ast, Dictionary<int, bool> handlerLocations, Dictionary<int, Dictionary<int, bool>> loopAndFinallyLocations) { // create the CodeContext PythonGlobal[] globalArray = new PythonGlobal[_globals.Count]; // now fill in the dictionary and create the array foreach (var global in _globals) { globalArray[global.Value.Index] = _globalVals[global.Key]; } _array.Array = globalArray; // finally build the funcion that's closed over the array and string name = ((PythonCompilerOptions)context.Options).ModuleName ?? "<unnamed>"; var func = Ast.Lambda<Func<FunctionCode, object>>( Ast.Block( new[] { _globalArray, _globalContext }, Ast.Assign(_globalArray, Ast.Constant(globalArray)), Ast.Assign(_globalContext, Ast.Constant(_context)), Utils.Convert(body, typeof(object)) ), name, new [] { AstGenerator._functionCode } ); return new RuntimeScriptCode(context, func, ast, _context); }
private MSA.ParameterExpression[]/*!*/ DefineParameters(out MSA.Expression/*!*/ selfVariable, out MSA.Expression/*!*/ blockParamVariable) { var parameters = new MSA.ParameterExpression[ HiddenParameterCount + (HasFormalParametersInArray ? 1 : _parameters.LeftValues.Count) + (HasUnsplatParameter ? 1 : 0) ]; // hidden parameters: // #proc must be the first one - it is used as instance target for method invocation: blockParamVariable = parameters[0] = Ast.Parameter(typeof(BlockParam), "#proc"); selfVariable = parameters[1] = Ast.Parameter(typeof(object), "#self"); int i = HiddenParameterCount; if (HasFormalParametersInArray) { parameters[i++] = Ast.Parameter(typeof(object[]), "#parameters"); } else { for (; i < parameters.Length; i++) { parameters[i] = Ast.Parameter(typeof(object), "#" + (i - HiddenParameterCount)); } } if (HasUnsplatParameter) { parameters[i] = Ast.Parameter(typeof(RubyArray), "#array"); } return parameters; }
public override ScriptCode/*!*/ MakeScriptCode(MSAst.Expression/*!*/ body, CompilerContext/*!*/ context, PythonAst/*!*/ ast) { // create the CodeContext PythonGlobal[] globalArray = new PythonGlobal[_globals.Count]; // now fill in the dictionary and create the array foreach (var global in _globals) { SymbolId globalName = SymbolTable.StringToId(global.Key); globalArray[global.Value.Index] = _globalVals[globalName]; } _array.Array = globalArray; // finally build the funcion that's closed over the array and string name = ((PythonCompilerOptions)context.Options).ModuleName ?? "<unnamed>"; var func = Ast.Lambda<Func<object>>( Ast.Block( new[] { _globalArray, _globalContext }, Ast.Assign(_globalArray, Ast.Constant(globalArray)), Ast.Assign(_globalContext, Ast.Constant(_context)), body ), name, new MSAst.ParameterExpression[0] ); return new RuntimeScriptCode(context, func, ast, _context); }
/// <summary> /// If the argument is Memory-mapped file and the mode is read only, we clone it. /// The clone creates an ordinary array. /// </summary> /// <param name="argument"></param> /// <returns></returns> public static DLR.Expression CloneMemoryMappedFile(DLR.Expression argument) { DLR.ParameterExpression argumentParam = DLR.Expression.Parameter(typeof(AType), "__VALUE__"); return DLR.Expression.Block( new DLR.ParameterExpression[] { argumentParam }, DLR.Expression.Assign(argumentParam, argument), DLR.Expression.IfThen( DLR.Expression.AndAlso( DLR.Expression.Property(argumentParam, "IsMemoryMappedFile"), DLR.Expression.Equal( DLR.Expression.Property( DLR.Expression.Convert( DLR.Expression.Property(argumentParam, "Data"), typeof(IMapped) ), "Mode" ), DLR.Expression.Constant(MemoryMappedFileMode.Read) ) ), DLR.Expression.Assign( DLR.Expression.Property(argumentParam, "Data"), DLR.Expression.Property( DLR.Expression.Call( argumentParam, typeof(AType).GetMethod("Clone") ), "Data" ) ) ), argumentParam ); }
public static MSA.Expression/*!*/ Logical(MSA.Expression/*!*/ left, MSA.Expression/*!*/ right, bool isConjunction) { if (isConjunction) { return Ast.AndAlso(left, right); } else { return Ast.OrElse(left, right); } }
public override ScriptCode/*!*/ MakeScriptCode(MSAst.Expression/*!*/ body, CompilerContext/*!*/ context, PythonAst/*!*/ ast) { MSAst.ParameterExpression scope = Ast.Parameter(typeof(Scope), "$scope"); MSAst.ParameterExpression language = Ast.Parameter(typeof(LanguageContext), "$language "); // finally build the funcion that's closed over the array and var func = Ast.Lambda<Func<Scope, LanguageContext, object>>( Ast.Block( new[] { GlobalArray }, Ast.Assign( GlobalArray, Ast.Call( null, typeof(PythonOps).GetMethod("GetGlobalArray"), scope ) ), Utils.Convert(body, typeof(object)) ), ((PythonCompilerOptions)context.Options).ModuleName, new MSAst.ParameterExpression[] { scope, language } ); PythonCompilerOptions pco = context.Options as PythonCompilerOptions; return new SavableScriptCode(func, context.SourceUnit, GetNames(), pco.ModuleName); }
internal override MSAst.Expression TransformSet(AstGenerator ag, SourceSpan span, MSAst.Expression right, PythonOperationKind op) { MSAst.Expression assignment; if (op != PythonOperationKind.None) { right = ag.Operation( typeof(object), op, Transform(ag, typeof(object)), right ); } if (_reference.PythonVariable != null) { assignment = ag.Globals.Assign( ag.Globals.GetVariable(_reference.PythonVariable), AstGenerator.ConvertIfNeeded(right, typeof(object)) ); } else { assignment = Ast.Call( null, typeof(ScriptingRuntimeHelpers).GetMethod("SetName"), new [] { ag.LocalContext, ag.Globals.GetSymbol(_name), AstUtils.Convert(right, typeof(object)) } ); } SourceSpan aspan = span.IsValid ? new SourceSpan(Span.Start, span.End) : SourceSpan.None; return ag.AddDebugInfoAndVoid(assignment, aspan); }
public override MSAst.Expression GetGlobal(MSAst.Expression globalContext, int arrayIndex, PythonVariable variable, PythonGlobal global) { return new LookupGlobalVariable( globalContext, variable.Name, variable.Kind == VariableKind.Local ); }
private AstParameters/*!*/ DefineParameters(out MSA.ParameterExpression/*!*/ selfVariable, out MSA.ParameterExpression/*!*/ blockParamVariable) { var parameters = new AstParameters( HiddenParameterCount + (HasFormalParametersInArray ? 1 : _parameters.LeftValues.Count) + (HasUnsplatParameter ? 1 : 0) ); // hidden parameters: // #proc must be the first one - it is used as instance target for method invocation: parameters.Add(blockParamVariable = Ast.Parameter(typeof(BlockParam), "#proc")); parameters.Add(selfVariable = Ast.Parameter(typeof(object), "#self")); if (HasFormalParametersInArray) { parameters.Add(Ast.Parameter(typeof(object[]), "#parameters")); } else { for (int i = 0; i < _parameters.LeftValues.Count; i++) { parameters.Add(Ast.Parameter(typeof(object), "#" + i)); } } if (HasUnsplatParameter) { parameters.Add(Ast.Parameter(typeof(RubyArray), "#array")); } return parameters; }
internal override MSAst.Expression TransformSet(AstGenerator ag, SourceSpan span, MSAst.Expression right, Operators op) { if (op == Operators.None) { return ag.AddDebugInfoAndVoid( Binders.Set( ag.BinderState, typeof(object), SymbolTable.IdToString(_name), ag.Transform(_target), right ), span ); } else { MSAst.ParameterExpression temp = ag.GetTemporary("inplace"); return ag.AddDebugInfo( Ast.Block( Ast.Assign(temp, ag.Transform(_target)), SetMemberOperator(ag, right, op, temp), Ast.Empty() ), Span.Start, span.End ); } }
// arguments: complex arguments (expressions, maplets, splat, block) // singleArgument: siple argument (complex are not used) // assignmentRhsArgument: rhs of the assignment: target.method=(rhs) internal static MSA.Expression/*!*/ TransformRead(Expression/*!*/ node, AstGenerator/*!*/ gen, bool hasImplicitSelf, string/*!*/ methodName, MSA.Expression/*!*/ transformedTarget, Arguments arguments, Block block, MSA.Expression singleArgument, MSA.Expression assignmentRhsArgument) { Debug.Assert(assignmentRhsArgument == null || block == null, "Block not allowed in assignment"); Debug.Assert(singleArgument == null || arguments == null && assignmentRhsArgument == null); Assert.NotNull(gen, transformedTarget); Assert.NotEmpty(methodName); // Pass args in this order: // 1. instance // 2. block (if present) // 3. passed args: normal args, maplets, array // 4. RHS of assignment (if present) MSA.Expression blockArgVariable; MSA.Expression transformedBlock; if (block != null) { blockArgVariable = gen.CurrentScope.DefineHiddenVariable("#block-def", typeof(Proc)); transformedBlock = block.Transform(gen); } else { blockArgVariable = transformedBlock = null; } var siteBuilder = new CallSiteBuilder(gen, transformedTarget, blockArgVariable); if (arguments != null) { arguments.TransformToCall(gen, siteBuilder); } else if (singleArgument != null) { siteBuilder.Add(singleArgument); } MSA.Expression rhsVariable = null; if (assignmentRhsArgument != null) { rhsVariable = gen.CurrentScope.DefineHiddenVariable("#rhs", assignmentRhsArgument.Type); siteBuilder.RhsArgument = Ast.Assign(rhsVariable, assignmentRhsArgument); } var dynamicSite = siteBuilder.MakeCallAction(methodName, hasImplicitSelf); #if FEATURE_CALL_SITE_TRACER if (gen.Context.CallSiteCreated != null) { gen.Context.CallSiteCreated(node, dynamicSite); } #endif MSA.Expression result = gen.DebugMark(dynamicSite, methodName); if (block != null) { result = gen.DebugMark(MakeCallWithBlockRetryable(gen, result, blockArgVariable, transformedBlock, block.IsDefinition), "#RB: method call with a block ('" + methodName + "')"); } if (assignmentRhsArgument != null) { result = Ast.Block(result, rhsVariable); } return result; }
public DynamicGetMemberExpression(PythonGetMemberBinder/*!*/ binder, CompilationMode/*!*/ mode, MSAst.Expression/*!*/ target, MSAst.Expression codeContext) { Assert.NotNull(binder, mode, target, codeContext); _binder = binder; _mode = mode; _target = target; _codeContext = codeContext; }
internal override MSAst.Expression TransformSet(AstGenerator ag, SourceSpan span, MSAst.Expression right, PythonOperationKind op) { if (Items.Length == 0) { ag.AddError("can't assign to ()", Span); return null; } return base.TransformSet(ag, span, right, op); }
public MSAst.Expression/*!*/ Delete(MSAst.Expression/*!*/ expression) { IPythonVariableExpression pyGlobal = expression as IPythonVariableExpression; if (pyGlobal != null) { return pyGlobal.Delete(); } return Ast.Assign(expression, Ast.Field(null, typeof(Uninitialized).GetField("Instance"))); }
public MSAst.Expression/*!*/ Assign(MSAst.Expression/*!*/ expression, MSAst.Expression value) { IPythonVariableExpression pyGlobal = expression as IPythonVariableExpression; if(pyGlobal != null) { return pyGlobal.Assign(value); } return Ast.Assign(expression, value); }
internal override MSAst.Expression Transform(MSAst.Expression body) { MSAst.ParameterExpression temp = Ast.Parameter(typeof(KeyValuePair<IEnumerator, IDisposable>), "list_comprehension_for"); return Ast.Block( new[] { temp }, ForStatement.TransformFor(Parent, temp, _list, _lhs, body, null, Span, GlobalParent.IndexToLocation(_lhs.EndIndex), null, null, false) ); }