public CilMethodBody Compile(MethodDefinition method, CilCompilationUnit unit) { var methodBody = new CilMethodBody(method); var context = new CodeGenerationContext(methodBody, _constants, unit.FlagVariable, _flagHelperType); var cilGenerator = new CilCodeGenerator(context); context.CodeGenerator = cilGenerator; // Traverse and recompile the AST. methodBody.Instructions.AddRange(unit.AcceptVisitor(cilGenerator)); // Add variables to the method body. if (context.Variables.Count > 0) { foreach (var variable in context.Variables.Values) { methodBody.LocalVariables.Add(variable); } methodBody.InitializeLocals = true; } methodBody.Instructions.OptimizeMacros(); // Add all generated exception handlers to the method body. var handlers = context.ExceptionHandlers.Values.ToList(); handlers.Sort(new EHComparer()); foreach (var handler in handlers) { if (EnableExceptionHandlerValidation) { AssertValidityExceptionHandler(method, handler); } methodBody.ExceptionHandlers.Add(handler); } if (!EnableStackVerification) { methodBody.ComputeMaxStackOnBuild = false; methodBody.MaxStack = ushort.MaxValue; } return(methodBody); }
public CilCodeGenerator(CodeGenerationContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); _formatter = new CilAstFormatter(context.MethodBody); }