当前位置: 首页>>代码示例>>C#>>正文


C# AstGenerator.CreateNestedContext方法代码示例

本文整理汇总了C#中IronPython.Compiler.Ast.AstGenerator.CreateNestedContext方法的典型用法代码示例。如果您正苦于以下问题:C# AstGenerator.CreateNestedContext方法的具体用法?C# AstGenerator.CreateNestedContext怎么用?C# AstGenerator.CreateNestedContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IronPython.Compiler.Ast.AstGenerator的用法示例。


在下文中一共展示了AstGenerator.CreateNestedContext方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Transform

        internal override MSAst.Expression Transform(AstGenerator ag) {
            string className = _name;
            AstGenerator classGen = new AstGenerator(ag, className, false, "class " + className);
            classGen.Parameter(_parentContextParam);
            // we always need to create a nested context for class defs
            classGen.CreateNestedContext();

            List<MSAst.Expression> init = new List<MSAst.Expression>();
            
            classGen.AddHiddenVariable(ArrayGlobalAllocator._globalContext);
            init.Add(Ast.Assign(ArrayGlobalAllocator._globalContext, Ast.Call(typeof(PythonOps).GetMethod("GetGlobalContext"), _parentContextParam)));
            init.AddRange(classGen.Globals.PrepareScope(classGen));

            CreateVariables(classGen, _parentContextParam, init, true, false);

            List<MSAst.Expression> statements = new List<MSAst.Expression>();
            // Create the body
            MSAst.Expression bodyStmt = classGen.Transform(_body);
            
            // __module__ = __name__
            MSAst.Expression modStmt = GlobalAllocator.Assign(
                classGen.Globals.GetVariable(classGen, _modVariable), 
                classGen.Globals.GetVariable(classGen, _modNameVariable));

            string doc = classGen.GetDocumentation(_body);
            if (doc != null) {
                statements.Add(
                    GlobalAllocator.Assign(
                        classGen.Globals.GetVariable(classGen, _docVariable),
                        AstUtils.Constant(doc)
                    )
                );
            }

            FunctionCode funcCodeObj = new FunctionCode(
                ag.PyContext,
                null,
                null,
                Name,
                ag.GetDocumentation(_body),
                ArrayUtils.EmptyStrings,
                FunctionAttributes.None,
                Span,
                ag.Context.SourceUnit.Path,
                ag.EmitDebugSymbols,
                ag.ShouldInterpret,
                FreeVariables,
                GlobalVariables,
                CellVariables,
                AppendVariables(new List<string>()),
                Variables == null ? 0 : Variables.Count,
                classGen.LoopLocationsNoCreate,
                classGen.HandlerLocationsNoCreate
            );
            MSAst.Expression funcCode = classGen.Globals.GetConstant(funcCodeObj);
            classGen.FuncCodeExpr = funcCode;

            if (_body.CanThrow && ag.PyContext.PythonOptions.Frames) {
                bodyStmt = AstGenerator.AddFrame(classGen.LocalContext, funcCode, bodyStmt);
                classGen.AddHiddenVariable(AstGenerator._functionStack);
            }

            bodyStmt = classGen.WrapScopeStatements(
                Ast.Block(
                    statements.Count == 0 ?
                        AstGenerator.EmptyBlock :
                        Ast.Block(new ReadOnlyCollection<MSAst.Expression>(statements)),
                    modStmt,
                    bodyStmt,
                    classGen.LocalContext    // return value
                )
            );

            var lambda = Ast.Lambda<Func<CodeContext, CodeContext>>(
                classGen.MakeBody(_parentContextParam, init.ToArray(), bodyStmt),
                classGen.Name + "$" + _classId++,
                classGen.Parameters
            );
            
            funcCodeObj.Code = lambda;

            MSAst.Expression classDef = Ast.Call(
                AstGenerator.GetHelperMethod("MakeClass"),
                ag.EmitDebugSymbols ? 
                    (MSAst.Expression)lambda : 
                    Ast.Convert(funcCode, typeof(object)),
                ag.LocalContext,
                AstUtils.Constant(_name),
                Ast.NewArrayInit(
                    typeof(object),
                    ag.TransformAndConvert(_bases, typeof(object))
                ),
                AstUtils.Constant(FindSelfNames())
            );

            classDef = ag.AddDecorators(classDef, _decorators);

            return ag.AddDebugInfoAndVoid(GlobalAllocator.Assign(ag.Globals.GetVariable(ag, _variable), classDef), new SourceSpan(Start, Header));
        }
开发者ID:jxnmaomao,项目名称:ironruby,代码行数:99,代码来源:ClassDefinition.cs

示例2: Transform

        internal override MSAst.Expression Transform(AstGenerator ag) {
            string className = SymbolTable.IdToString(_name);
            AstGenerator builder = new AstGenerator(ag, className, false, "class " + className);

            // we always need to create a nested context for class defs
            builder.CreateNestedContext();

            List<MSAst.Expression> init = new List<MSAst.Expression>();
            CreateVariables(builder, init);

            // Create the body
            MSAst.Expression bodyStmt = builder.Transform(_body);
            MSAst.Expression modStmt = ag.Globals.Assign(ag.Globals.GetVariable(_modVariable), ag.Globals.GetVariable(_modNameVariable));

            string doc = ag.GetDocumentation(_body);
            if (doc != null) {
                init.Add(
                    ag.Globals.Assign(
                        ag.Globals.GetVariable(_docVariable),
                        AstUtils.Constant(doc)
                    )
                );
            }

            bodyStmt = builder.WrapScopeStatements(
                Ast.Block(
                    init.Count == 0 ?
                        AstGenerator.EmptyBlock :
                        Ast.Block(new ReadOnlyCollection<MSAst.Expression>(init)),
                    modStmt,
                    bodyStmt,
                    builder.LocalContext    // return value
                )
            );

            MSAst.LambdaExpression lambda = Ast.Lambda(
                typeof(Func<CodeContext>),
                builder.MakeBody(bodyStmt, true, false),
                builder.Name + "$" + _classId++,
                builder.Parameters
            );

            MSAst.Expression classDef = Ast.Call(
                AstGenerator.GetHelperMethod("MakeClass"),
                lambda,
                ag.LocalContext,
                AstUtils.Constant(SymbolTable.IdToString(_name)),
                Ast.NewArrayInit(
                    typeof(object),
                    ag.TransformAndConvert(_bases, typeof(object))
                ),
                AstUtils.Constant(FindSelfNames())
            );

            classDef = ag.AddDecorators(classDef, _decorators);

            return ag.AddDebugInfo(ag.Globals.Assign(ag.Globals.GetVariable(_variable), classDef), new SourceSpan(Start, Header));
        }
开发者ID:tnachen,项目名称:ironruby,代码行数:58,代码来源:ClassDefinition.cs

示例3: Transform

        internal override MSAst.Expression Transform(AstGenerator ag) {
            string className = SymbolTable.IdToString(_name);
            AstGenerator classGen = new AstGenerator(ag, className, false, "class " + className);
            classGen.Parameter(_parentContextParam);
            // we always need to create a nested context for class defs
            classGen.CreateNestedContext();

            List<MSAst.Expression> init = new List<MSAst.Expression>();
            
            classGen.AddHiddenVariable(ArrayGlobalAllocator._globalContext);
            init.Add(Ast.Assign(ArrayGlobalAllocator._globalContext, Ast.Call(typeof(PythonOps).GetMethod("GetGlobalContext"), _parentContextParam)));
            init.AddRange(classGen.Globals.PrepareScope(classGen));

            CreateVariables(classGen, _parentContextParam, init, true, NeedsLocalsDictionary);

            List<MSAst.Expression> statements = new List<MSAst.Expression>();
            // Create the body
            MSAst.Expression bodyStmt = classGen.Transform(_body);
            
            // __module__ = __name__
            MSAst.Expression modStmt = classGen.Globals.Assign(
                classGen.Globals.GetVariable(classGen, _modVariable), 
                classGen.Globals.GetVariable(classGen, _modNameVariable));

            string doc = classGen.GetDocumentation(_body);
            if (doc != null) {
                statements.Add(
                    classGen.Globals.Assign(
                        classGen.Globals.GetVariable(classGen, _docVariable),
                        AstUtils.Constant(doc)
                    )
                );
            }

            bodyStmt = classGen.WrapScopeStatements(
                Ast.Block(
                    statements.Count == 0 ?
                        AstGenerator.EmptyBlock :
                        Ast.Block(new ReadOnlyCollection<MSAst.Expression>(statements)),
                    modStmt,
                    bodyStmt,
                    classGen.LocalContext    // return value
                )
            );

            var lambda = Ast.Lambda<Func<CodeContext, CodeContext>>(
                classGen.MakeBody(_parentContextParam, init.ToArray(), bodyStmt, false),
                classGen.Name + "$" + _classId++,
                classGen.Parameters
            );

            MSAst.Expression classDef = Ast.Call(
                AstGenerator.GetHelperMethod("MakeClass"),
                ag.EmitDebugSymbols ? 
                    (MSAst.Expression)lambda : 
                    (MSAst.Expression)Ast.Constant(new LazyCode<Func<CodeContext, CodeContext>>(lambda, ag.ShouldInterpret), typeof(object)),
                ag.LocalContext,
                AstUtils.Constant(SymbolTable.IdToString(_name)),
                Ast.NewArrayInit(
                    typeof(object),
                    ag.TransformAndConvert(_bases, typeof(object))
                ),
                AstUtils.Constant(FindSelfNames())
            );

            classDef = ag.AddDecorators(classDef, _decorators);

            return ag.AddDebugInfo(ag.Globals.Assign(ag.Globals.GetVariable(ag, _variable), classDef), new SourceSpan(Start, Header));
        }
开发者ID:jcteague,项目名称:ironruby,代码行数:69,代码来源:ClassDefinition.cs

示例4: TransformToFunctionExpression

        internal MSAst.Expression TransformToFunctionExpression(AstGenerator ag) {
            string name;

            if (IsLambda) {
                name = "<lambda$" + Interlocked.Increment(ref _lambdaId) + ">";
            } else {
                name = SymbolTable.IdToString(_name);
            }

            // Create AST generator to generate the body with
            AstGenerator bodyGen = new AstGenerator(ag, name, IsGenerator, MakeProfilerName(name));
            FunctionAttributes flags = ComputeFlags(_parameters);
            bool needsWrapperMethod = flags != FunctionAttributes.None || _parameters.Length > PythonCallTargets.MaxArgs;
            
            // Transform the parameters.
            // Populate the list of the parameter names and defaults.
            List<MSAst.Expression> defaults = new List<MSAst.Expression>(0);
            List<MSAst.Expression> names = new List<MSAst.Expression>();

            List<MSAst.Expression> init = new List<MSAst.Expression>();
            TransformParameters(ag, bodyGen, defaults, names, needsWrapperMethod, init);

            MSAst.Expression parentContext;
            
            parentContext = MSAst.Expression.Call(typeof(PythonOps).GetMethod("GetParentContextFromFunction"), _functionParam);

            bodyGen.AddHiddenVariable(ArrayGlobalAllocator._globalContext);
            init.Add(Ast.Assign(ArrayGlobalAllocator._globalContext, Ast.Call(typeof(PythonOps).GetMethod("GetGlobalContext"), parentContext)));
            init.AddRange(bodyGen.Globals.PrepareScope(bodyGen));

            // Create variables and references. Since references refer to
            // parameters, do this after parameters have been created.
            CreateVariables(bodyGen, parentContext, init, NeedsLocalsDictionary, NeedsLocalsDictionary);

            // Initialize parameters - unpack tuples.
            // Since tuples unpack into locals, this must be done after locals have been created.
            InitializeParameters(bodyGen, init, needsWrapperMethod);

            List<MSAst.Expression> statements = new List<MSAst.Expression>();

            // 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(bodyGen, SourceSpan.None);
                statements.Add(s1);
            }

            if (NeedsLocalsDictionary || ContainsNestedFreeVariables) {
                bodyGen.CreateNestedContext();
            }

            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 = bodyGen.GetTemporary("$ex", typeof(Exception));
            }

            // Transform the body and add the resulting statements into the list
            if (!TryTransformBody(bodyGen, statements)) {
                // there's an error in the body
                return null;
            }

            if (ag.DebugMode) {
                // add beginning and ending break points for the function.
                if (GetExpressionEnd(statements[statements.Count - 1]) != Body.End) {
                    statements.Add(ag.AddDebugInfo(AstUtils.Empty(), new SourceSpan(Body.End, Body.End)));
                }
            }

            MSAst.Expression body = Ast.Block(new ReadOnlyCollection<MSAst.Expression>(statements.ToArray()));

            // 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(
                            AstGenerator.GetHelperMethod("SaveCurrentException")
                        )
                    ),
                    body
                ).Finally(
                    Ast.Call(
                        AstGenerator.GetHelperMethod("RestoreCurrentException"), extracted
                    )
                );
                body = s;
            }

//.........这里部分代码省略.........
开发者ID:m4dc4p,项目名称:ironruby,代码行数:101,代码来源:FunctionDefinition.cs

示例5: TransformToFunctionExpression

        internal MSAst.Expression TransformToFunctionExpression(AstGenerator ag) {
            string name;

            if (IsLambda) {
                name = "<lambda$" + Interlocked.Increment(ref _lambdaId) + ">";
            } else {
                name = _name;
            }

            if (ag.PyContext.PythonOptions.FullFrames) {
                // force a dictionary if we have enabled full frames for sys._getframe support
                NeedsLocalsDictionary = true;
            }

            // Create AST generator to generate the body with
            AstGenerator bodyGen = new AstGenerator(ag, name, IsGenerator, MakeProfilerName(name));

            FunctionAttributes flags = ComputeFlags(_parameters);
            bool needsWrapperMethod = _parameters.Length > PythonCallTargets.MaxArgs;
            
            // Transform the parameters.
            // Populate the list of the parameter names and defaults.
            List<MSAst.Expression> defaults = new List<MSAst.Expression>(0);
            List<MSAst.Expression> names = new List<MSAst.Expression>();

            List<MSAst.Expression> init = new List<MSAst.Expression>();
            init.Add(Ast.ClearDebugInfo(ag.Document));

            TransformParameters(ag, bodyGen, defaults, names, needsWrapperMethod, init);

            MSAst.Expression parentContext;

            parentContext = MSAst.Expression.Call(_GetParentContextFromFunction, _functionParam);

            bodyGen.AddHiddenVariable(ArrayGlobalAllocator._globalContext);
            init.Add(Ast.Assign(ArrayGlobalAllocator._globalContext, Ast.Call(_GetGlobalContext, parentContext)));
            init.AddRange(bodyGen.Globals.PrepareScope(bodyGen));

            // Create variables and references. Since references refer to
            // parameters, do this after parameters have been created.
            CreateVariables(bodyGen, parentContext, init, NeedsLocalsDictionary, NeedsLocalsDictionary);

            // Initialize parameters - unpack tuples.
            // Since tuples unpack into locals, this must be done after locals have been created.
            InitializeParameters(bodyGen, init, needsWrapperMethod);

            List<MSAst.Expression> statements = new List<MSAst.Expression>();
            // add beginning sequence point
            statements.Add(bodyGen.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(bodyGen, SourceSpan.None);
                statements.Add(s1);
            }

            if (NeedsLocalsDictionary || ContainsNestedFreeVariables) {
                bodyGen.CreateNestedContext();
            }

            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 = bodyGen.GetTemporary("$ex", typeof(Exception));
            }

            // Transform the body and add the resulting statements into the list
            if (!TryTransformBody(bodyGen, statements)) {
                // there's an error in the body
                return null;
            }

            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(
                            AstGenerator.GetHelperMethod("SaveCurrentException")
                        )
                    ),
                    body
                ).Finally(
                    Ast.Call(
//.........这里部分代码省略.........
开发者ID:jxnmaomao,项目名称:ironruby,代码行数:101,代码来源:FunctionDefinition.cs


注:本文中的IronPython.Compiler.Ast.AstGenerator.CreateNestedContext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。