Revert until fixed
[mono.git] / mcs / mcs / codegen.cs
old mode 100755 (executable)
new mode 100644 (file)
index f4f75c0..4f90c9f
@@ -4,16 +4,24 @@
 // Author:
 //   Miguel de Icaza (miguel@ximian.com)
 //
-// (C) 2001 Ximian, Inc.
+// (C) 2001, 2002, 2003 Ximian, Inc.
+// (C) 2004 Novell, Inc.
 //
 
+#if !DEBUG
+       #define PRODUCTION
+#endif
+
 using System;
 using System.IO;
 using System.Collections;
+using System.Collections.Specialized;
 using System.Reflection;
 using System.Reflection.Emit;
 using System.Runtime.InteropServices;
+using System.Security;
 using System.Security.Cryptography;
+using System.Security.Permissions;
 
 using Mono.Security.Cryptography;
 
@@ -30,6 +38,11 @@ namespace Mono.CSharp {
                public static ModuleClass Module;
 
                static CodeGen ()
+               {
+                       Reset ();
+               }
+
+               public static void Reset ()
                {
                        Assembly = new AssemblyClass ();
                        Module = new ModuleClass (RootContext.Unsafe);
@@ -63,13 +76,6 @@ namespace Mono.CSharp {
                        return ".";
                }
 
-               static string TrimExt (string name)
-               {
-                       int pos = name.LastIndexOf ('.');
-
-                       return name.Substring (0, pos);
-               }
-
                static public string FileName;
 
                //
@@ -84,7 +90,7 @@ namespace Mono.CSharp {
                        //
                        if (SymbolWriter == null) {
                                Report.Warning (
-                                       -18, "Could not find the symbol writer assembly (Mono.CSharp.Debugger.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CSharp.Debugger directory.");
+                                       -18, 1, "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CompilerServices.SymbolWriter directory.");
                                return;
                        }
                }
@@ -92,19 +98,21 @@ namespace Mono.CSharp {
                //
                // Initializes the code generator variables
                //
-               static public void Init (string name, string output, bool want_debugging_support)
+               static public bool Init (string name, string output, bool want_debugging_support)
                {
                        FileName = output;
                        AssemblyName an = Assembly.GetAssemblyName (name, output);
+                       if (an == null)
+                               return false;
 
                        if (an.KeyPair != null) {
                                // If we are going to strong name our assembly make
                                // sure all its refs are strong named
-                               foreach (Assembly a in TypeManager.GetAssemblies ()) {
+                               foreach (Assembly a in RootNamespace.Global.Assemblies) {
                                        AssemblyName ref_name = a.GetName ();
                                        byte [] b = ref_name.GetPublicKeyToken ();
                                        if (b == null || b.Length == 0) {
-                                               Report.Warning (1577, "Assembly generation failed " +
+                                               Report.Error (1577, "Assembly generation failed " +
                                                                "-- Referenced assembly '" +
                                                                ref_name.Name +
                                                                "' does not have a strong name.");
@@ -126,14 +134,14 @@ namespace Mono.CSharp {
                                                RootContext.StrongNameKeyContainer + "'.");
                                        Environment.Exit (1);
                                }
-                               throw;
+                               return false;
                        }
                        catch (CryptographicException) {
                                if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
                                        Report.Error (1548, "Could not use the specified key to strongname the assembly.");
                                        Environment.Exit (1);
                                }
-                               throw;
+                               return false;
                        }
 
                        //
@@ -149,6 +157,8 @@ namespace Mono.CSharp {
 
                        if (want_debugging_support)
                                InitializeSymbolWriter (output);
+
+                       return true;
                }
 
                static public void Save (string name)
@@ -168,99 +178,21 @@ namespace Mono.CSharp {
                        catch (System.IO.IOException io) {
                                Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
                        }
+                       catch (System.UnauthorizedAccessException ua) {
+                               Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
+                       }
 
                        if (SymbolWriter != null)
                                SymbolWriter.WriteSymbolFile ();
                }
        }
 
-       //
-       // Provides "local" store across code that can yield: locals
-       // or fields, notice that this should not be used by anonymous
-       // methods to create local storage, those only require
-       // variable mapping.
-       //
-       public class VariableStorage {
-               ILGenerator ig;
-               FieldBuilder fb;
-               LocalBuilder local;
-               
-               static int count;
-               
-               public VariableStorage (EmitContext ec, Type t)
-               {
-                       count++;
-                       if (ec.InIterator)
-                               fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
-                       else
-                               local = ec.ig.DeclareLocal (t);
-                       ig = ec.ig;
-               }
-
-               public void EmitThis ()
-               {
-                       if (fb != null)
-                               ig.Emit (OpCodes.Ldarg_0);
-               }
-
-               public void EmitStore ()
-               {
-                       if (fb == null)
-                               ig.Emit (OpCodes.Stloc, local);
-                       else
-                               ig.Emit (OpCodes.Stfld, fb);
-               }
-
-               public void EmitLoad ()
-               {
-                       if (fb == null)
-                               ig.Emit (OpCodes.Ldloc, local);
-                       else 
-                               ig.Emit (OpCodes.Ldfld, fb);
-               }
-
-               public void EmitLoadAddress ()
-               {
-                       if (fb == null)
-                               ig.Emit (OpCodes.Ldloca, local);
-                       else 
-                               ig.Emit (OpCodes.Ldflda, fb);
-               }
-               
-               public void EmitCall (MethodInfo mi)
-               {
-                       // FIXME : we should handle a call like tostring
-                       // here, where boxing is needed. However, we will
-                       // never encounter that with the current usage.
-                       
-                       bool value_type_call;
-                       EmitThis ();
-                       if (fb == null) {
-                               value_type_call = local.LocalType.IsValueType;
-                               
-                               if (value_type_call)
-                                       ig.Emit (OpCodes.Ldloca, local);
-                               else
-                                       ig.Emit (OpCodes.Ldloc, local);
-                       } else {
-                               value_type_call = fb.FieldType.IsValueType;
-                               
-                               if (value_type_call)
-                                       ig.Emit (OpCodes.Ldflda, fb);
-                               else
-                                       ig.Emit (OpCodes.Ldfld, fb);
-                       }
-                       
-                       ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
-               }
-       }
-       
        /// <summary>
        ///   An Emit Context is created for each body of code (from methods,
        ///   properties bodies, indexer bodies or constructor bodies)
        /// </summary>
        public class EmitContext {
-               public DeclSpace DeclSpace;
+               public readonly DeclSpace DeclSpace;
                public DeclSpace TypeContainer;
                public ILGenerator   ig;
 
@@ -289,6 +221,16 @@ namespace Mono.CSharp {
                /// </summary>
                public bool IsStatic;
 
+               /// <summary>
+               ///   Whether the actual created method is static or instance method.
+               ///   Althoug the method might be declared as `static', if an anonymous
+               ///   method is involved, we might turn this into an instance method.
+               ///
+               ///   So this reflects the low-level staticness of the method, while
+               ///   IsStatic represents the semantic, high-level staticness.
+               /// </summary>
+               public bool MethodIsStatic;
+
                /// <summary>
                ///   Whether we are emitting a field initializer
                /// </summary>
@@ -315,7 +257,12 @@ namespace Mono.CSharp {
                ///   Whether we're control flow analysis enabled
                /// </summary>
                public bool DoFlowAnalysis;
-               
+
+               /// <summary>
+               ///   Whether we're control flow analysis disabled on struct
+               /// </summary>
+               public bool OmitStructFlowAnalysis;
+
                /// <summary>
                ///   Keeps track of the Type to LocalBuilder temporary storage created
                ///   to store structures (used to compute the address of the structure
@@ -350,12 +297,6 @@ namespace Mono.CSharp {
 
                public bool IsLastStatement;
 
-               /// <summary>
-               ///   Whether remapping of locals, parameters and fields is turned on.
-               ///   Used by iterators and anonymous methods.
-               /// </summary>
-               public bool RemapToProxy;
-
                /// <summary>
                ///  Whether we are inside an unsafe block
                /// </summary>
@@ -366,23 +307,21 @@ namespace Mono.CSharp {
                /// </summary>
                public bool InFixedInitializer;
 
+               public bool InRefOutArgumentResolving;
+
+               public bool InCatch;
+               public bool InFinally;
+
                /// <summary>
                ///  Whether we are inside an anonymous method.
                /// </summary>
-               public bool InAnonymousMethod;
+               public AnonymousContainer CurrentAnonymousMethod;
                
                /// <summary>
                ///   Location for this EmitContext
                /// </summary>
                public Location loc;
 
-               /// <summary>
-               ///   Used to flag that it is ok to define types recursively, as the
-               ///   expressions are being evaluated as part of the type lookup
-               ///   during the type resolution process
-               /// </summary>
-               public bool ResolvingTypeTree;
-               
                /// <summary>
                ///   Inside an enum definition, we do not resolve enumeration values
                ///   to their enumerations, but rather to the underlying type/value
@@ -393,9 +332,44 @@ namespace Mono.CSharp {
                /// </summary>
                public bool InEnumContext;
 
+               /// <summary>
+               ///   Anonymous methods can capture local variables and fields,
+               ///   this object tracks it.  It is copied from the TopLevelBlock
+               ///   field.
+               /// </summary>
+               public CaptureContext capture_context;
+
+               /// <summary>
+               /// Trace when method is called and is obsolete then this member suppress message
+               /// when call is inside next [Obsolete] method or type.
+               /// </summary>
+               public bool TestObsoleteMethodUsage = true;
+
+               /// <summary>
+               ///    The current iterator
+               /// </summary>
                public Iterator CurrentIterator;
 
+               /// <summary>
+               ///    Whether we are in the resolving stage or not
+               /// </summary>
+               enum Phase {
+                       Created,
+                       Resolving,
+                       Emitting
+               }
+               
+               Phase current_phase;
                FlowBranching current_flow_branching;
+
+               static int next_id = 0;
+               int id = ++next_id;
+
+               public override string ToString ()
+               {
+                       return String.Format ("EmitContext ({0}:{1}:{2})", id,
+                                             CurrentIterator, capture_context, loc);
+               }
                
                public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
                                    Type return_type, int code_flags, bool is_constructor)
@@ -406,14 +380,15 @@ namespace Mono.CSharp {
                        DeclSpace = ds;
                        CheckState = RootContext.Checked;
                        ConstantCheckState = true;
-                       
+
                        IsStatic = (code_flags & Modifiers.STATIC) != 0;
+                       MethodIsStatic = IsStatic;
                        InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
-                       RemapToProxy = InIterator;
                        ReturnType = return_type;
                        IsConstructor = is_constructor;
                        CurrentBlock = null;
                        CurrentFile = 0;
+                       current_phase = Phase.Created;
                        
                        if (parent != null){
                                // Can only be null for the ResolveType contexts.
@@ -424,7 +399,7 @@ namespace Mono.CSharp {
                                        InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
                        }
                        loc = l;
-                       
+
                        if (ReturnType == TypeManager.void_type)
                                ReturnType = null;
                }
@@ -447,6 +422,12 @@ namespace Mono.CSharp {
                        }
                }
 
+               public bool HaveCaptureInfo {
+                       get {
+                               return capture_context != null;
+                       }
+               }
+
                // <summary>
                //   Starts a new code branching.  This inherits the state of all local
                //   variables and parameters from the current branching.
@@ -464,12 +445,16 @@ namespace Mono.CSharp {
                {
                        FlowBranching.BranchingType type;
 
-                       if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
+                       if ((CurrentBranching != null) &&
+                           (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
                                type = FlowBranching.BranchingType.SwitchSection;
                        else
                                type = FlowBranching.BranchingType.Block;
 
-                       current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
+                       DoFlowAnalysis = true;
+
+                       current_flow_branching = FlowBranching.CreateBranching (
+                               CurrentBranching, type, block, block.StartLocation);
                        return current_flow_branching;
                }
 
@@ -513,45 +498,160 @@ namespace Mono.CSharp {
                        current_flow_branching = current_flow_branching.Parent;
                }
 
-               public void EmitTopBlock (Block block, InternalParameters ip, Location loc)
+               public void CaptureVariable (LocalInfo li)
                {
-                       bool unreachable = false;
+                       capture_context.AddLocal (CurrentAnonymousMethod, li);
+                       li.IsCaptured = true;
+               }
 
-                       if (!Location.IsNull (loc))
-                               CurrentFile = loc.File;
+               public void CaptureParameter (string name, Type t, int idx)
+               {
+                       capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
+               }
 
-                       if (block != null){
-                           try {
-                               int errors = Report.Errors;
+               public void CaptureThis ()
+               {
+                       capture_context.CaptureThis (CurrentAnonymousMethod);
+               }
+               
+               
+               //
+               // Use to register a field as captured
+               //
+               public void CaptureField (FieldExpr fe)
+               {
+                       capture_context.AddField (this, CurrentAnonymousMethod, fe);
+               }
 
-                               block.EmitMeta (this, ip);
+               //
+               // Whether anonymous methods have captured variables
+               //
+               public bool HaveCapturedVariables ()
+               {
+                       if (capture_context != null)
+                               return capture_context.HaveCapturedVariables;
+                       return false;
+               }
 
-                               if (Report.Errors == errors){
-                                       bool old_do_flow_analysis = DoFlowAnalysis;
-                                       DoFlowAnalysis = true;
+               //
+               // Whether anonymous methods have captured fields or this.
+               //
+               public bool HaveCapturedFields ()
+               {
+                       if (capture_context != null)
+                               return capture_context.HaveCapturedFields;
+                       return false;
+               }
 
-                                       current_flow_branching = FlowBranching.CreateBranching (
-                                               null, FlowBranching.BranchingType.Block, block, loc);
+               //
+               // Emits the instance pointer for the host method
+               //
+               public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
+               {
+                       if (capture_context != null)
+                               capture_context.EmitMethodHostInstance (target, am);
+                       else if (IsStatic)
+                               target.ig.Emit (OpCodes.Ldnull);
+                       else
+                               target.ig.Emit (OpCodes.Ldarg_0);
+               }
 
-                                       if (!block.Resolve (this)) {
-                                               current_flow_branching = null;
-                                               DoFlowAnalysis = old_do_flow_analysis;
-                                               return;
-                                       }
+               //
+               // Returns whether the `local' variable has been captured by an anonymous
+               // method
+               //
+               public bool IsCaptured (LocalInfo local)
+               {
+                       return capture_context.IsCaptured (local);
+               }
+
+               public bool IsParameterCaptured (string name)
+               {
+                       if (capture_context != null)
+                               return capture_context.IsParameterCaptured (name);
+                       return false;
+               }
+               
+               public void EmitMeta (ToplevelBlock b)
+               {
+                       if (capture_context != null)
+                               capture_context.EmitAnonymousHelperClasses (this);
+                       b.EmitMeta (this);
+
+                       if (HasReturnLabel)
+                               ReturnLabel = ig.DefineLabel ();
+               }
+
+               //
+               // Here until we can fix the problem with Mono.CSharp.Switch, which
+               // currently can not cope with ig == null during resolve (which must
+               // be fixed for switch statements to work on anonymous methods).
+               //
+               public void EmitTopBlock (IMethodData md, ToplevelBlock block)
+               {
+                       if (block == null)
+                               return;
+                       
+                       bool unreachable;
+                       
+                       if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
+                               EmitMeta (block);
+
+                               current_phase = Phase.Emitting;
+                               EmitResolvedTopBlock (block, unreachable);
+                       }
+               }
+
+               bool resolved;
+
+               public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
+                                            Parameters ip, IMethodData md, out bool unreachable)
+               {
+                       current_phase = Phase.Resolving;
+                       
+                       unreachable = false;
+
+                       if (resolved)
+                               return true;
 
-                                       FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
+                       capture_context = block.CaptureContext;
+                       
+                       if (!loc.IsNull)
+                               CurrentFile = loc.File;
+
+#if PRODUCTION
+                       try {
+#endif
+                               if (!block.ResolveMeta (this, ip))
+                                       return false;
+
+                               bool old_do_flow_analysis = DoFlowAnalysis;
+                               DoFlowAnalysis = true;
+
+                               if (anonymous_method_host != null)
+                                       current_flow_branching = FlowBranching.CreateBranching (
+                                               anonymous_method_host.CurrentBranching,
+                                               FlowBranching.BranchingType.Block, block, loc);
+                               else 
+                                       current_flow_branching = block.TopLevelBranching;
+
+                               if (!block.Resolve (this)) {
                                        current_flow_branching = null;
-                                       
                                        DoFlowAnalysis = old_do_flow_analysis;
+                                       return false;
+                               }
 
-                                       block.Emit (this);
+                               FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
+                               current_flow_branching = null;
 
-                                       if (reachability.AlwaysReturns ||
-                                           reachability.AlwaysThrows ||
-                                           reachability.IsUnreachable)
-                                               unreachable = true;
-                               }
-                           } catch (Exception e) {
+                               DoFlowAnalysis = old_do_flow_analysis;
+
+                               if (reachability.AlwaysReturns ||
+                                   reachability.AlwaysThrows ||
+                                   reachability.IsUnreachable)
+                                       unreachable = true;
+#if PRODUCTION
+                       } catch (Exception e) {
                                        Console.WriteLine ("Exception caught by the compiler while compiling:");
                                        Console.WriteLine ("   Block that caused the problem begin at: " + loc);
                                        
@@ -560,21 +660,34 @@ namespace Mono.CSharp {
                                                                   CurrentBlock.StartLocation, CurrentBlock.EndLocation);
                                        }
                                        Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
-                                       Console.WriteLine (Report.FriendlyStackTrace (e));
-                                       
-                                       Environment.Exit (1);
-                           }
+                                       throw;
                        }
-
-                       if (ReturnType != null && !unreachable){
-                               if (!InIterator){
-                                       Report.Error (161, loc, "Not all code paths return a value");
-                                       return;
+#endif
+
+                       if (ReturnType != null && !unreachable) {
+                               if (CurrentAnonymousMethod == null) {
+                                       Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
+                                       return false;
+                               } else if (!CurrentAnonymousMethod.IsIterator) {
+                                       Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
+                                               CurrentAnonymousMethod.GetSignatureForError ());
+                                       return false;
                                }
                        }
 
+                       block.CompleteContexts ();
+                       resolved = true;
+                       return true;
+               }
+
+               public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
+               {
+                       if (block != null)
+                               block.Emit (this);
+                       
                        if (HasReturnLabel)
                                ig.MarkLabel (ReturnLabel);
+                       
                        if (return_value != null){
                                ig.Emit (OpCodes.Ldloc, return_value);
                                ig.Emit (OpCodes.Ret);
@@ -592,14 +705,23 @@ namespace Mono.CSharp {
                                // this case.
                                //
 
+                               bool in_iterator = (CurrentAnonymousMethod != null) &&
+                                       CurrentAnonymousMethod.IsIterator && InIterator;
+
                                if ((block != null) && block.IsDestructor) {
                                        // Nothing to do; S.R.E automatically emits a leave.
-                               } else if (HasReturnLabel || (!unreachable && !InIterator)) {
+                               } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
                                        if (ReturnType != null)
                                                ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
                                        ig.Emit (OpCodes.Ret);
                                }
                        }
+
+                       //
+                       // Close pending helper classes if we are the toplevel
+                       //
+                       if (capture_context != null && capture_context.ParentToplevel == null)
+                               capture_context.CloseAnonymousHelperClasses ();
                }
 
                /// <summary>
@@ -608,13 +730,13 @@ namespace Mono.CSharp {
                /// </summary>
                public void Mark (Location loc, bool check_file)
                {
-                       if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
+                       if ((CodeGen.SymbolWriter == null) || loc.IsNull)
                                return;
 
                        if (check_file && (CurrentFile != loc.File))
                                return;
 
-                       CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
+                       CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
                }
 
                public void DefineLocalVariable (string name, LocalBuilder builder)
@@ -625,6 +747,22 @@ namespace Mono.CSharp {
                        CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
                }
 
+               public void BeginScope ()
+               {
+                       ig.BeginScope();
+
+                       if (CodeGen.SymbolWriter != null)
+                               CodeGen.SymbolWriter.OpenScope(ig);
+               }
+
+               public void EndScope ()
+               {
+                       ig.EndScope();
+
+                       if (CodeGen.SymbolWriter != null)
+                               CodeGen.SymbolWriter.CloseScope(ig);
+               }
+
                /// <summary>
                ///   Returns a temporary storage for a variable of type t as 
                ///   a local variable in the current body.
@@ -706,85 +844,92 @@ namespace Mono.CSharp {
                ///   return value from the function.  By default this is not
                ///   used.  This is only required when returns are found inside
                ///   Try or Catch statements.
+               ///
+               ///   This method is typically invoked from the Emit phase, so
+               ///   we allow the creation of a return label if it was not
+               ///   requested during the resolution phase.   Could be cleaned
+               ///   up, but it would replicate a lot of logic in the Emit phase
+               ///   of the code that uses it.
                /// </summary>
                public LocalBuilder TemporaryReturn ()
                {
                        if (return_value == null){
                                return_value = ig.DeclareLocal (ReturnType);
-                               ReturnLabel = ig.DefineLabel ();
-                               HasReturnLabel = true;
+                               if (!HasReturnLabel){
+                                       ReturnLabel = ig.DefineLabel ();
+                                       HasReturnLabel = true;
+                               }
                        }
 
                        return return_value;
                }
 
+               /// <summary>
+               ///   This method is used during the Resolution phase to flag the
+               ///   need to define the ReturnLabel
+               /// </summary>
                public void NeedReturnLabel ()
                {
-                       if (!InIterator && !HasReturnLabel) {
-                               ReturnLabel = ig.DefineLabel ();
-                               HasReturnLabel = true;
+                       if (current_phase != Phase.Resolving){
+                               //
+                               // The reason is that the `ReturnLabel' is declared between
+                               // resolution and emission
+                               // 
+                               throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
                        }
+                       
+                       if (!InIterator && !HasReturnLabel) 
+                               HasReturnLabel = true;
                }
 
                //
-               // Creates a field `name' with the type `t' on the proxy class
+               // Emits the proper object to address fields on a remapped
+               // variable/parameter to field in anonymous-method/iterator proxy classes.
                //
-               public FieldBuilder MapVariable (string name, Type t)
+               public void EmitThis ()
                {
-                       if (InIterator)
-                               return CurrentIterator.MapVariable ("v_", name, t);
-
-                       throw new Exception ("MapVariable for an unknown state");
+                       ig.Emit (OpCodes.Ldarg_0);
+                       if (capture_context != null && CurrentAnonymousMethod != null){
+                               ScopeInfo si = CurrentAnonymousMethod.Scope;
+                               while (si != null){
+                                       if (si.ParentLink != null)
+                                               ig.Emit (OpCodes.Ldfld, si.ParentLink);
+                                       if (si.THIS != null){
+                                               ig.Emit (OpCodes.Ldfld, si.THIS);
+                                               break;
+                                       }
+                                       si = si.ParentScope;
+                               }
+                       } 
                }
 
                //
-               // Invoke this routine to remap a VariableInfo into the
-               // proper MemberAccess expression
+               // Emits the code necessary to load the instance required
+               // to access the captured LocalInfo
                //
-               public Expression RemapLocal (LocalInfo local_info)
+               public void EmitCapturedVariableInstance (LocalInfo li)
                {
-                       FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
-                       fe.InstanceExpression = new ProxyInstance ();
-                       return fe.DoResolve (this);
+                       if (capture_context == null)
+                               throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
+                       
+                       capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
                }
 
-               public Expression RemapLocalLValue (LocalInfo local_info, Expression right_side)
+               public void EmitParameter (string name)
                {
-                       FieldExpr fe = new FieldExpr (local_info.FieldBuilder, loc);
-                       fe.InstanceExpression = new ProxyInstance ();
-                       return fe.DoResolveLValue (this, right_side);
+                       capture_context.EmitParameter (this, name);
                }
 
-               public Expression RemapParameter (int idx)
+               public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
                {
-                       FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
-                       fe.InstanceExpression = new ProxyInstance ();
-                       return fe.DoResolve (this);
+                       capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
                }
 
-               public Expression RemapParameterLValue (int idx, Expression right_side)
+               public void EmitAddressOfParameter (string name)
                {
-                       FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
-                       fe.InstanceExpression = new ProxyInstance ();
-                       return fe.DoResolveLValue (this, right_side);
+                       capture_context.EmitAddressOfParameter (this, name);
                }
                
-               //
-               // Emits the proper object to address fields on a remapped
-               // variable/parameter to field in anonymous-method/iterator proxy classes.
-               //
-               public void EmitThis ()
-               {
-                       ig.Emit (OpCodes.Ldarg_0);
-                       if (InIterator && !IsStatic){
-                               FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
-                               if (TypeManager.IsValueType (this_field.FieldType))
-                                       ig.Emit (OpCodes.Ldflda, this_field);
-                               else
-                                       ig.Emit (OpCodes.Ldfld, this_field);
-                       }
-               }
-
                public Expression GetThis (Location loc)
                {
                        This my_this;
@@ -801,7 +946,7 @@ namespace Mono.CSharp {
        }
 
 
-       public abstract class CommonAssemblyModulClass: Attributable {
+       public abstract class CommonAssemblyModulClass : Attributable {
                protected CommonAssemblyModulClass ():
                        base (null)
                {
@@ -814,7 +959,6 @@ namespace Mono.CSharp {
                                return;
                        }
                        OptAttributes.AddAttributes (attrs);
-                       OptAttributes.CheckTargets (this);
                }
 
                public virtual void Emit (TypeContainer tc) 
@@ -826,13 +970,17 @@ namespace Mono.CSharp {
                        OptAttributes.Emit (ec, this);
                }
                 
-               protected Attribute GetClsCompliantAttribute ()
+               protected Attribute ResolveAttribute (Type a_type)
                {
                        if (OptAttributes == null)
                                return null;
 
-                       EmitContext temp_ec = new EmitContext (new RootTypes (), Mono.CSharp.Location.Null, null, null, 0, false);
-                       Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
+                       // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
+                       if (!OptAttributes.CheckTargets (this))
+                               return null;
+
+                       EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
+                       Attribute a = OptAttributes.Search (a_type, temp_ec);
                        if (a != null) {
                                a.Resolve (temp_ec);
                        }
@@ -840,16 +988,22 @@ namespace Mono.CSharp {
                }
        }
                 
-       public class AssemblyClass: CommonAssemblyModulClass {
+       public class AssemblyClass : CommonAssemblyModulClass {
                // TODO: make it private and move all builder based methods here
                public AssemblyBuilder Builder;
                bool is_cls_compliant;
+               bool wrap_non_exception_throws;
+
+               public Attribute ClsCompliantAttribute;
 
-               static string[] attribute_targets = new string [] { "assembly" };
+               ListDictionary declarative_security;
+
+               // Module is here just because of error messages
+               static string[] attribute_targets = new string [] { "assembly", "module" };
 
                public AssemblyClass (): base ()
                {
-                       is_cls_compliant = false;
+                       wrap_non_exception_throws = true;
                }
 
                public bool IsClsCompliant {
@@ -858,42 +1012,91 @@ namespace Mono.CSharp {
                        }
                }
 
+               public bool WrapNonExceptionThrows {
+                       get {
+                               return wrap_non_exception_throws;
+                       }
+               }
+
                public override AttributeTargets AttributeTargets {
                        get {
                                return AttributeTargets.Assembly;
                        }
                }
 
-               public override bool IsClsCompliaceRequired(DeclSpace ds)
+               public override bool IsClsComplianceRequired(DeclSpace ds)
                {
                        return is_cls_compliant;
                }
 
-               public void ResolveClsCompliance ()
+               public void Resolve ()
                {
-                       Attribute a = GetClsCompliantAttribute ();
-                       if (a == null)
-                               return;
+                       ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
+                       if (ClsCompliantAttribute != null) {
+                               is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
+                       }
+
+#if NET_2_0
+                       Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
+                       if (a != null) {
+                               object val = a.GetPropertyValue ("WrapNonExceptionThrows");
+                               if (val != null)
+                                       wrap_non_exception_throws = (bool)val;
+                       }
+#endif
+               }
 
-                       is_cls_compliant = a.GetClsCompliantAttributeValue (null);
+               // fix bug #56621
+               private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
+               {
+                       try {
+                               // check for possible ECMA key
+                               if (strongNameBlob.Length == 16) {
+                                       // will be rejected if not "the" ECMA key
+                                       an.SetPublicKey (strongNameBlob);
+                               }
+                               else {
+                                       // take it, with or without, a private key
+                                       RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
+                                       // and make sure we only feed the public part to Sys.Ref
+                                       byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
+                                       
+                                       // AssemblyName.SetPublicKey requires an additional header
+                                       byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
+
+                                       byte[] encodedPublicKey = new byte [12 + publickey.Length];
+                                       Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
+                                       Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
+                                       an.SetPublicKey (encodedPublicKey);
+                               }
+                       }
+                       catch (Exception) {
+                               Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
+                               Environment.Exit (1);
+                       }
                }
 
+               // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
                public AssemblyName GetAssemblyName (string name, string output) 
                {
                        if (OptAttributes != null) {
                                foreach (Attribute a in OptAttributes.Attrs) {
-                                       if (a.Target != AttributeTargets.Assembly)
+                                       // cannot rely on any resolve-based members before you call Resolve
+                                       if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
                                                continue;
-                                       // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
-                                       //       However, this is invoked by CodeGen.Init, at which time none of the namespaces
+
+                                       // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
+                                       //       However, this is invoked by CodeGen.Init, when none of the namespaces
                                        //       are loaded yet.
+                                       // TODO: Does not handle quoted attributes properly
                                        switch (a.Name) {
                                                case "AssemblyKeyFile":
                                                case "AssemblyKeyFileAttribute":
                                                case "System.Reflection.AssemblyKeyFileAttribute":
                                                        if (RootContext.StrongNameKeyFile != null) {
                                                                Report.SymbolRelatedToPreviousError (a.Location, a.Name);
-                                                               Report.Warning (Message.CS1616_Option_overrides_options_given_in_source, "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
+                                                               Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
+                                    "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
                                                        }
                                                        else {
                                                                string value = a.GetString ();
@@ -906,7 +1109,8 @@ namespace Mono.CSharp {
                                                case "System.Reflection.AssemblyKeyNameAttribute":
                                                        if (RootContext.StrongNameKeyContainer != null) {
                                                                Report.SymbolRelatedToPreviousError (a.Location, a.Name);
-                                                               Report.Warning (Message.CS1616_Option_overrides_options_given_in_source, "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
+                                                               Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
+                                                                       "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
                                                        }
                                                        else {
                                                                string value = a.GetString ();
@@ -958,25 +1162,7 @@ namespace Mono.CSharp {
 
                                        if (RootContext.StrongNameDelaySign) {
                                                // delayed signing - DO NOT include private key
-                                               try {
-                                                       // check for possible ECMA key
-                                                       if (snkeypair.Length == 16) {
-                                                               // will be rejected if not "the" ECMA key
-                                                               an.KeyPair = new StrongNameKeyPair (snkeypair);
-                                                       }
-                                                       else {
-                                                               // take it, with or without, a private key
-                                                               RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
-                                                               // and make sure we only feed the public part to Sys.Ref
-                                                               byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
-                                                               an.KeyPair = new StrongNameKeyPair (publickey);
-                                                       }
-                                               }
-                                               catch (Exception) {
-                                                       Report.Error (1548, "Could not strongname the assembly. File `" +
-                                                               RootContext.StrongNameKeyFile + "' incorrectly encoded.");
-                                                       Environment.Exit (1);
-                                               }
+                                               SetPublicKey (an, snkeypair);
                                        }
                                        else {
                                                // no delay so we make sure we have the private key
@@ -987,32 +1173,92 @@ namespace Mono.CSharp {
                                                catch (CryptographicException) {
                                                        if (snkeypair.Length == 16) {
                                                                // error # is different for ECMA key
-                                                               Report.Error (1606, "Could not strongname the assembly. " + 
+                                                               Report.Error (1606, "Could not sign the assembly. " + 
                                                                        "ECMA key can only be used to delay-sign assemblies");
                                                        }
                                                        else {
-                                                               Report.Error (1548, "Could not strongname the assembly. File `" +
-                                                                       RootContext.StrongNameKeyFile +
-                                                                       "' doesn't have a private key.");
+                                                               Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
                                                        }
-                                                       Environment.Exit (1);
+                                                       return null;
                                                }
                                        }
                                }
                        }
                        else {
-                               Report.Error (1548, "Could not strongname the assembly. File `" +
-                                       RootContext.StrongNameKeyFile + "' not found.");
-                               Environment.Exit (1);
+                               Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
+                               return null;
                        }
                        return an;
                }
 
+               void Error_AssemblySigning (string text)
+               {
+                       Report.Error (1548, "Error during assembly signing. " + text);
+               }
+
                public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
                {
+                       if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
+                               if (declarative_security == null)
+                                       declarative_security = new ListDictionary ();
+
+                               a.ExtractSecurityPermissionSet (declarative_security);
+                               return;
+                       }
+
+                       if (a.Type == TypeManager.assembly_culture_attribute_type) {
+                               string value = a.GetString ();
+                               if (value == null || value.Length == 0)
+                                       return;
+
+                               if (RootContext.Target == Target.Exe) {
+                                       a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
+                                       return;
+                               }
+                       }
+
                        Builder.SetCustomAttribute (customBuilder);
                }
 
+               public override void Emit (TypeContainer tc)
+               {
+                       base.Emit (tc);
+
+                       if (declarative_security != null) {
+
+                               MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
+                               object builder_instance = Builder;
+
+                               try {
+                                       // Microsoft runtime hacking
+                                       if (add_permission == null) {
+                                               Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
+                                               add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
+
+                                               FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
+                                               builder_instance = fi.GetValue (Builder);
+                                       }
+
+                                       object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
+                                                                                                 declarative_security [SecurityAction.RequestOptional],
+                                                                                                 declarative_security [SecurityAction.RequestRefuse] };
+                                       add_permission.Invoke (builder_instance, args);
+                               }
+                               catch {
+                                       Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
+                               }
+                       }
+
+#if NET_2_0
+                       if (!OptAttributes.Contains (TypeManager.runtime_compatibility_attr_type, null)) {
+                               ConstructorInfo ci = TypeManager.runtime_compatibility_attr_type.GetConstructor (TypeManager.NoTypes);
+                               PropertyInfo pi = TypeManager.runtime_compatibility_attr_type.GetProperty ("WrapNonExceptionThrows");
+                               Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], 
+                                       new PropertyInfo [] { pi }, new object[] { true } ));
+                       }
+#endif
+               }
+
                public override string[] ValidAttributeTargets {
                        get {
                                return attribute_targets;
@@ -1020,11 +1266,14 @@ namespace Mono.CSharp {
                }
        }
 
-       public class ModuleClass: CommonAssemblyModulClass {
+       public class ModuleClass : CommonAssemblyModulClass {
                // TODO: make it private and move all builder based methods here
                public ModuleBuilder Builder;
                bool m_module_is_unsafe;
 
+               public CharSet DefaultCharSet = CharSet.Ansi;
+               public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
+
                static string[] attribute_targets = new string [] { "module" };
 
                public ModuleClass (bool is_unsafe)
@@ -1038,7 +1287,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override bool IsClsCompliaceRequired(DeclSpace ds)
+               public override bool IsClsComplianceRequired(DeclSpace ds)
                {
                        return CodeGen.Assembly.IsClsCompliant;
                }
@@ -1055,19 +1304,52 @@ namespace Mono.CSharp {
                                return;
                        }
                                
-                       ApplyAttributeBuilder (null, new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
+                       Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
                }
                 
                public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
                {
-                       if (a != null && a.Type == TypeManager.cls_compliant_attribute_type) {
-                               Report.Warning (Message.CS3012_You_must_specify_the_CLSCompliant_attribute_on_the_assembly_not_the_module_to_enable_CLS_compliance_checking, a.Location);
-                               return;
+                       if (a.Type == TypeManager.cls_compliant_attribute_type) {
+                               if (CodeGen.Assembly.ClsCompliantAttribute == null) {
+                                       Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
+                               }
+                               else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
+                                       Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
+                                       Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
+                                       return;
+                               }
                        }
 
                        Builder.SetCustomAttribute (customBuilder);
                }
 
+               /// <summary>
+               /// It is called very early therefore can resolve only predefined attributes
+               /// </summary>
+               public void ResolveAttributes ()
+               {
+#if NET_2_0
+                       Attribute a = ResolveAttribute (TypeManager.default_charset_type);
+                       if (a != null) {
+                               DefaultCharSet = a.GetCharSetValue ();
+                               switch (DefaultCharSet) {
+                                       case CharSet.Ansi:
+                                       case CharSet.None:
+                                               break;
+                                       case CharSet.Auto:
+                                               DefaultCharSetType = TypeAttributes.AutoClass;
+                                               break;
+                                       case CharSet.Unicode:
+                                               DefaultCharSetType = TypeAttributes.UnicodeClass;
+                                               break;
+                                       default:
+                                               Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
+                                               break;
+                               }
+                       }
+#endif
+               }
+
                public override string[] ValidAttributeTargets {
                        get {
                                return attribute_targets;