Revert until fixed
[mono.git] / mcs / mcs / codegen.cs
old mode 100755 (executable)
new mode 100644 (file)
index 3e01f15..4f90c9f
@@ -7,7 +7,11 @@
 // (C) 2001, 2002, 2003 Ximian, Inc.
 // (C) 2004 Novell, Inc.
 //
-//#define PRODUCTION
+
+#if !DEBUG
+       #define PRODUCTION
+#endif
+
 using System;
 using System.IO;
 using System.Collections;
@@ -34,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);
@@ -67,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;
 
                //
@@ -88,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;
                        }
                }
@@ -96,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.");
@@ -130,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;
                        }
 
                        //
@@ -153,6 +157,8 @@ namespace Mono.CSharp {
 
                        if (want_debugging_support)
                                InitializeSymbolWriter (output);
+
+                       return true;
                }
 
                static public void Save (string name)
@@ -172,97 +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 {
-               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);
-               }
-
-               public void EmitThis (ILGenerator ig)
-               {
-                       if (fb != null)
-                               ig.Emit (OpCodes.Ldarg_0);
-               }
-
-               public void EmitStore (ILGenerator ig)
-               {
-                       if (fb == null)
-                               ig.Emit (OpCodes.Stloc, local);
-                       else
-                               ig.Emit (OpCodes.Stfld, fb);
-               }
-
-               public void EmitLoad (ILGenerator ig)
-               {
-                       if (fb == null)
-                               ig.Emit (OpCodes.Ldloc, local);
-                       else 
-                               ig.Emit (OpCodes.Ldfld, fb);
-               }
-
-               public void EmitLoadAddress (ILGenerator ig)
-               {
-                       if (fb == null)
-                               ig.Emit (OpCodes.Ldloca, local);
-                       else 
-                               ig.Emit (OpCodes.Ldflda, fb);
-               }
-               
-               public void EmitCall (ILGenerator ig, 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 (ig);
-                       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;
 
@@ -291,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>
@@ -317,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
@@ -352,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>
@@ -368,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 AnonymousMethod CurrentAnonymousMethod;
+               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
@@ -423,9 +360,17 @@ namespace Mono.CSharp {
                }
                
                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)
                {
@@ -437,8 +382,8 @@ namespace Mono.CSharp {
                        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;
@@ -500,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;
                }
 
@@ -557,16 +506,21 @@ namespace Mono.CSharp {
 
                public void CaptureParameter (string name, Type t, int idx)
                {
-                       
                        capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
                }
+
+               public void CaptureThis ()
+               {
+                       capture_context.CaptureThis (CurrentAnonymousMethod);
+               }
+               
                
                //
                // Use to register a field as captured
                //
                public void CaptureField (FieldExpr fe)
                {
-                       capture_context.AddField (fe);
+                       capture_context.AddField (this, CurrentAnonymousMethod, fe);
                }
 
                //
@@ -618,10 +572,10 @@ namespace Mono.CSharp {
                        return false;
                }
                
-               public void EmitMeta (ToplevelBlock b, InternalParameters ip)
+               public void EmitMeta (ToplevelBlock b)
                {
                        if (capture_context != null)
-                               capture_context.EmitHelperClasses (this);
+                               capture_context.EmitAnonymousHelperClasses (this);
                        b.EmitMeta (this);
 
                        if (HasReturnLabel)
@@ -633,69 +587,69 @@ namespace Mono.CSharp {
                // currently can not cope with ig == null during resolve (which must
                // be fixed for switch statements to work on anonymous methods).
                //
-               public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
+               public void EmitTopBlock (IMethodData md, ToplevelBlock block)
                {
                        if (block == null)
                                return;
                        
                        bool unreachable;
                        
-                       if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
-                               EmitMeta (block, ip);
+                       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,
-                                            InternalParameters ip, Location loc, out bool unreachable)
+                                            Parameters ip, IMethodData md, out bool unreachable)
                {
                        current_phase = Phase.Resolving;
                        
                        unreachable = false;
 
+                       if (resolved)
+                               return true;
+
                        capture_context = block.CaptureContext;
                        
-                       if (!Location.IsNull (loc))
+                       if (!loc.IsNull)
                                CurrentFile = loc.File;
 
 #if PRODUCTION
                        try {
 #endif
-                               int errors = Report.Errors;
+                               if (!block.ResolveMeta (this, ip))
+                                       return false;
 
-                               block.ResolveMeta (block, this, ip);
+                               bool old_do_flow_analysis = DoFlowAnalysis;
+                               DoFlowAnalysis = true;
 
-                               
-                               if (Report.Errors == errors){
-                                       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 = FlowBranching.CreateBranching (
-                                                       null, FlowBranching.BranchingType.Block, block, loc);
-
-                                       if (!block.Resolve (this)) {
-                                               current_flow_branching = null;
-                                               DoFlowAnalysis = old_do_flow_analysis;
-                                               return false;
-                                       }
+                               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;
 
-                                       FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
+                               if (!block.Resolve (this)) {
                                        current_flow_branching = null;
-                                       
                                        DoFlowAnalysis = old_do_flow_analysis;
-
-                                       if (reachability.AlwaysReturns ||
-                                           reachability.AlwaysThrows ||
-                                           reachability.IsUnreachable)
-                                               unreachable = true;
+                                       return false;
                                }
+
+                               FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
+                               current_flow_branching = null;
+
+                               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:");
@@ -710,20 +664,19 @@ namespace Mono.CSharp {
                        }
 #endif
 
-                       if (ReturnType != null && !unreachable){
-                               if (!InIterator){
-                                       if (CurrentAnonymousMethod != null){
-                                               Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
-                                                             CurrentAnonymousMethod.Type);
-                                       } else {
-                                               Report.Error (161, loc, "Not all code paths return a value");
-                                       }
-                                       
+                       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;
                }
 
@@ -752,9 +705,12 @@ 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);
@@ -765,7 +721,7 @@ namespace Mono.CSharp {
                        // Close pending helper classes if we are the toplevel
                        //
                        if (capture_context != null && capture_context.ParentToplevel == null)
-                               capture_context.CloseHelperClasses ();
+                               capture_context.CloseAnonymousHelperClasses ();
                }
 
                /// <summary>
@@ -774,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)
@@ -791,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.
@@ -910,31 +882,6 @@ namespace Mono.CSharp {
                                HasReturnLabel = true;
                }
 
-               //
-               // Creates a field `name' with the type `t' on the proxy class
-               //
-               public FieldBuilder MapVariable (string name, Type t)
-               {
-                       if (InIterator)
-                               return CurrentIterator.MapVariable ("v_", name, t);
-
-                       throw new Exception ("MapVariable for an unknown state");
-               }
-
-               public Expression RemapParameter (int idx)
-               {
-                       FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
-                       fe.InstanceExpression = new ProxyInstance ();
-                       return fe.DoResolve (this);
-               }
-
-               public Expression RemapParameterLValue (int idx, Expression right_side)
-               {
-                       FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
-                       fe.InstanceExpression = new ProxyInstance ();
-                       return fe.DoResolveLValue (this, right_side);
-               }
-               
                //
                // Emits the proper object to address fields on a remapped
                // variable/parameter to field in anonymous-method/iterator proxy classes.
@@ -942,15 +889,7 @@ namespace Mono.CSharp {
                public void EmitThis ()
                {
                        ig.Emit (OpCodes.Ldarg_0);
-                       if (InIterator){
-                               if (!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);
-                               } 
-                       } else if (capture_context != null && CurrentAnonymousMethod != null){
+                       if (capture_context != null && CurrentAnonymousMethod != null){
                                ScopeInfo si = CurrentAnonymousMethod.Scope;
                                while (si != null){
                                        if (si.ParentLink != null)
@@ -970,11 +909,6 @@ namespace Mono.CSharp {
                //
                public void EmitCapturedVariableInstance (LocalInfo li)
                {
-                       if (RemapToProxy){
-                               ig.Emit (OpCodes.Ldarg_0);
-                               return;
-                       }
-                       
                        if (capture_context == null)
                                throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
                        
@@ -1012,7 +946,7 @@ namespace Mono.CSharp {
        }
 
 
-       public abstract class CommonAssemblyModulClass: Attributable {
+       public abstract class CommonAssemblyModulClass : Attributable {
                protected CommonAssemblyModulClass ():
                        base (null)
                {
@@ -1025,7 +959,6 @@ namespace Mono.CSharp {
                                return;
                        }
                        OptAttributes.AddAttributes (attrs);
-                       OptAttributes.CheckTargets (this);
                }
 
                public virtual void Emit (TypeContainer tc) 
@@ -1037,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);
                        }
@@ -1051,18 +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;
 
                ListDictionary declarative_security;
 
-               static string[] attribute_targets = new string [] { "assembly" };
+               // 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 {
@@ -1071,24 +1012,38 @@ 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);
+                       }
 
-                       is_cls_compliant = a.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
                }
 
                // fix bug #56621
@@ -1116,28 +1071,32 @@ namespace Mono.CSharp {
                                }
                        }
                        catch (Exception) {
-                               Report.Error (1548, "Could not strongname the assembly. File `" +
-                                       RootContext.StrongNameKeyFile + "' incorrectly encoded.");
+                               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 (1616, "Compiler option '{0}' overrides '{1}' 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 ();
@@ -1150,7 +1109,8 @@ namespace Mono.CSharp {
                                                case "System.Reflection.AssemblyKeyNameAttribute":
                                                        if (RootContext.StrongNameKeyContainer != null) {
                                                                Report.SymbolRelatedToPreviousError (a.Location, a.Name);
-                                                               Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "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 ();
@@ -1213,27 +1173,29 @@ 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)) {
@@ -1244,6 +1206,17 @@ namespace Mono.CSharp {
                                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);
                }
 
@@ -1275,6 +1248,15 @@ namespace Mono.CSharp {
                                        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 {
@@ -1284,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)
@@ -1302,7 +1287,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override bool IsClsCompliaceRequired(DeclSpace ds)
+               public override bool IsClsComplianceRequired(DeclSpace ds)
                {
                        return CodeGen.Assembly.IsClsCompliant;
                }
@@ -1319,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 (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
-                               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;