TARGET_JVM: add browscap.ini to System.Web
[mono.git] / mcs / mcs / codegen.cs
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
9 //
10
11 #if !DEBUG
12         #define PRODUCTION
13 #endif
14
15 using System;
16 using System.IO;
17 using System.Collections;
18 using System.Collections.Specialized;
19 using System.Reflection;
20 using System.Reflection.Emit;
21 using System.Runtime.InteropServices;
22 using System.Security;
23 using System.Security.Cryptography;
24 using System.Security.Permissions;
25
26 using Mono.Security.Cryptography;
27
28 namespace Mono.CSharp {
29
30         /// <summary>
31         ///    Code generator class.
32         /// </summary>
33         public class CodeGen {
34                 static AppDomain current_domain;
35                 static public SymbolWriter SymbolWriter;
36
37                 public static AssemblyClass Assembly;
38                 public static ModuleClass Module;
39
40                 static CodeGen ()
41                 {
42                         Reset ();
43                 }
44
45                 public static void Reset ()
46                 {
47                         Assembly = new AssemblyClass ();
48                         Module = new ModuleClass (RootContext.Unsafe);
49                 }
50
51                 public static string Basename (string name)
52                 {
53                         int pos = name.LastIndexOf ('/');
54
55                         if (pos != -1)
56                                 return name.Substring (pos + 1);
57
58                         pos = name.LastIndexOf ('\\');
59                         if (pos != -1)
60                                 return name.Substring (pos + 1);
61
62                         return name;
63                 }
64
65                 public static string Dirname (string name)
66                 {
67                         int pos = name.LastIndexOf ('/');
68
69                         if (pos != -1)
70                                 return name.Substring (0, pos);
71
72                         pos = name.LastIndexOf ('\\');
73                         if (pos != -1)
74                                 return name.Substring (0, pos);
75
76                         return ".";
77                 }
78
79                 static public string FileName;
80
81                 //
82                 // Initializes the symbol writer
83                 //
84                 static void InitializeSymbolWriter (string filename)
85                 {
86                         SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
87
88                         //
89                         // If we got an ISymbolWriter instance, initialize it.
90                         //
91                         if (SymbolWriter == null) {
92                                 Report.Warning (
93                                         -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.");
94                                 return;
95                         }
96                 }
97
98                 //
99                 // Initializes the code generator variables
100                 //
101                 static public bool Init (string name, string output, bool want_debugging_support)
102                 {
103                         FileName = output;
104                         AssemblyName an = Assembly.GetAssemblyName (name, output);
105                         if (an == null)
106                                 return false;
107
108                         if (an.KeyPair != null) {
109                                 // If we are going to strong name our assembly make
110                                 // sure all its refs are strong named
111                                 foreach (Assembly a in RootNamespace.Global.Assemblies) {
112                                         AssemblyName ref_name = a.GetName ();
113                                         byte [] b = ref_name.GetPublicKeyToken ();
114                                         if (b == null || b.Length == 0) {
115                                                 Report.Error (1577, "Assembly generation failed " +
116                                                                 "-- Referenced assembly '" +
117                                                                 ref_name.Name +
118                                                                 "' does not have a strong name.");
119                                                 //Environment.Exit (1);
120                                         }
121                                 }
122                         }
123                         
124                         current_domain = AppDomain.CurrentDomain;
125
126                         try {
127                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
128                                         AssemblyBuilderAccess.Save, Dirname (name));
129                         }
130                         catch (ArgumentException) {
131                                 // specified key may not be exportable outside it's container
132                                 if (RootContext.StrongNameKeyContainer != null) {
133                                         Report.Error (1548, "Could not access the key inside the container `" +
134                                                 RootContext.StrongNameKeyContainer + "'.");
135                                         Environment.Exit (1);
136                                 }
137                                 return false;
138                         }
139                         catch (CryptographicException) {
140                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
141                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
142                                         Environment.Exit (1);
143                                 }
144                                 return false;
145                         }
146
147                         //
148                         // Pass a path-less name to DefineDynamicModule.  Wonder how
149                         // this copes with output in different directories then.
150                         // FIXME: figure out how this copes with --output /tmp/blah
151                         //
152                         // If the third argument is true, the ModuleBuilder will dynamically
153                         // load the default symbol writer.
154                         //
155                         Module.Builder = Assembly.Builder.DefineDynamicModule (
156                                 Basename (name), Basename (output), false);
157
158                         if (want_debugging_support)
159                                 InitializeSymbolWriter (output);
160
161                         return true;
162                 }
163
164                 static public void Save (string name)
165                 {
166                         try {
167                                 Assembly.Builder.Save (Basename (name));
168
169                                 if (SymbolWriter != null)
170                                         SymbolWriter.WriteSymbolFile ();
171                         }
172                         catch (COMException) {
173                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
174                                         throw;
175
176                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
177                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
178                                         RootContext.StrongNameKeyFile +
179                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
180                         }
181                         catch (System.IO.IOException io) {
182                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
183                         }
184                         catch (System.UnauthorizedAccessException ua) {
185                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
186                         }
187                 }
188         }
189
190
191         public interface IResolveContext
192         {
193                 DeclSpace DeclContainer { get; }
194                 bool IsInObsoleteScope { get; }
195                 bool IsInUnsafeScope { get; }
196         }
197
198         /// <summary>
199         ///   An Emit Context is created for each body of code (from methods,
200         ///   properties bodies, indexer bodies or constructor bodies)
201         /// </summary>
202         public class EmitContext : IResolveContext {
203
204                 DeclSpace declSpace;
205                 public DeclSpace TypeContainer;
206                 public ILGenerator   ig;
207
208                 [Flags]
209                 public enum Flags : byte {
210                         /// <summary>
211                         ///   This flag tracks the `checked' state of the compilation,
212                         ///   it controls whether we should generate code that does overflow
213                         ///   checking, or if we generate code that ignores overflows.
214                         ///
215                         ///   The default setting comes from the command line option to generate
216                         ///   checked or unchecked code plus any source code changes using the
217                         ///   checked/unchecked statements or expressions.   Contrast this with
218                         ///   the ConstantCheckState flag.
219                         /// </summary>
220                         CheckState = 1 << 0,
221
222                         /// <summary>
223                         ///   The constant check state is always set to `true' and cant be changed
224                         ///   from the command line.  The source code can change this setting with
225                         ///   the `checked' and `unchecked' statements and expressions. 
226                         /// </summary>
227                         ConstantCheckState = 1 << 1,
228
229                         AllCheckStateFlags = CheckState | ConstantCheckState,
230
231                         /// <summary>
232                         ///  Whether we are inside an unsafe block
233                         /// </summary>
234                         InUnsafe = 1 << 2,
235
236                         InCatch = 1 << 3,
237                         InFinally = 1 << 4,
238
239                         /// <summary>
240                         ///   Whether control flow analysis is enabled
241                         /// </summary>
242                         DoFlowAnalysis = 1 << 5,
243
244                         /// <summary>
245                         ///   Whether control flow analysis is disabled on structs
246                         ///   (only meaningful when DoFlowAnalysis is set)
247                         /// </summary>
248                         OmitStructFlowAnalysis = 1 << 6
249                 }
250
251                 Flags flags;
252
253                 /// <summary>
254                 ///   Whether we are emitting code inside a static or instance method
255                 /// </summary>
256                 public bool IsStatic;
257
258                 /// <summary>
259                 ///   Whether the actual created method is static or instance method.
260                 ///   Althoug the method might be declared as `static', if an anonymous
261                 ///   method is involved, we might turn this into an instance method.
262                 ///
263                 ///   So this reflects the low-level staticness of the method, while
264                 ///   IsStatic represents the semantic, high-level staticness.
265                 /// </summary>
266                 public bool MethodIsStatic;
267
268                 /// <summary>
269                 ///   Whether we are emitting a field initializer
270                 /// </summary>
271                 public bool IsFieldInitializer;
272
273                 /// <summary>
274                 ///   The value that is allowed to be returned or NULL if there is no
275                 ///   return type.
276                 /// </summary>
277                 public Type ReturnType;
278
279                 /// <summary>
280                 ///   Points to the Type (extracted from the TypeContainer) that
281                 ///   declares this body of code
282                 /// </summary>
283                 public Type ContainerType;
284                 
285                 /// <summary>
286                 ///   Whether this is generating code for a constructor
287                 /// </summary>
288                 public bool IsConstructor;
289
290                 /// <summary>
291                 ///   Keeps track of the Type to LocalBuilder temporary storage created
292                 ///   to store structures (used to compute the address of the structure
293                 ///   value on structure method invocations)
294                 /// </summary>
295                 public Hashtable temporary_storage;
296
297                 public Block CurrentBlock;
298
299                 public int CurrentFile;
300
301                 /// <summary>
302                 ///   The location where we store the return value.
303                 /// </summary>
304                 LocalBuilder return_value;
305
306                 /// <summary>
307                 ///   The location where return has to jump to return the
308                 ///   value
309                 /// </summary>
310                 public Label ReturnLabel;
311
312                 /// <summary>
313                 ///   If we already defined the ReturnLabel
314                 /// </summary>
315                 public bool HasReturnLabel;
316
317                 /// <summary>
318                 ///   Whether we are inside an iterator block.
319                 /// </summary>
320                 public bool InIterator;
321
322                 public bool IsLastStatement;
323
324                 /// <summary>
325                 ///  Whether we are in a `fixed' initialization
326                 /// </summary>
327                 public bool InFixedInitializer;
328
329                 /// <summary>
330                 ///  Whether we are inside an anonymous method.
331                 /// </summary>
332                 public AnonymousContainer CurrentAnonymousMethod;
333                 
334                 /// <summary>
335                 ///   Location for this EmitContext
336                 /// </summary>
337                 public Location loc;
338
339                 /// <summary>
340                 ///   Inside an enum definition, we do not resolve enumeration values
341                 ///   to their enumerations, but rather to the underlying type/value
342                 ///   This is so EnumVal + EnumValB can be evaluated.
343                 ///
344                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
345                 ///   we relax the rules
346                 /// </summary>
347                 public bool InEnumContext;
348
349                 /// <summary>
350                 ///   Anonymous methods can capture local variables and fields,
351                 ///   this object tracks it.  It is copied from the TopLevelBlock
352                 ///   field.
353                 /// </summary>
354                 public CaptureContext capture_context;
355
356                 public readonly IResolveContext ResolveContext;
357
358                 /// <summary>
359                 ///    The current iterator
360                 /// </summary>
361                 public Iterator CurrentIterator;
362
363                 /// <summary>
364                 ///    Whether we are in the resolving stage or not
365                 /// </summary>
366                 enum Phase {
367                         Created,
368                         Resolving,
369                         Emitting
370                 }
371
372                 bool isAnonymousMethodAllowed = true;
373
374                 Phase current_phase;
375                 FlowBranching current_flow_branching;
376
377                 static int next_id = 0;
378                 int id = ++next_id;
379
380                 public override string ToString ()
381                 {
382                         return String.Format ("EmitContext ({0}:{1}:{2})", id,
383                                               CurrentIterator, capture_context, loc);
384                 }
385                 
386                 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
387                                     Type return_type, int code_flags, bool is_constructor)
388                 {
389                         this.ResolveContext = rc;
390                         this.ig = ig;
391
392                         TypeContainer = parent;
393                         this.declSpace = ds;
394                         if (RootContext.Checked)
395                                 flags |= Flags.CheckState;
396                         flags |= Flags.ConstantCheckState;
397
398                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
399                         MethodIsStatic = IsStatic;
400                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
401                         ReturnType = return_type;
402                         IsConstructor = is_constructor;
403                         CurrentBlock = null;
404                         CurrentFile = 0;
405                         current_phase = Phase.Created;
406
407                         if (parent != null){
408                                 // Can only be null for the ResolveType contexts.
409                                 ContainerType = parent.TypeBuilder;
410                                 if (rc.IsInUnsafeScope)
411                                         flags |= Flags.InUnsafe;
412                         }
413                         loc = l;
414
415                         if (ReturnType == TypeManager.void_type)
416                                 ReturnType = null;
417                 }
418
419                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
420                                     Type return_type, int code_flags, bool is_constructor)
421                         : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
422                 {
423                 }
424
425                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
426                                     Type return_type, int code_flags)
427                         : this (rc, ds, ds, l, ig, return_type, code_flags, false)
428                 {
429                 }
430
431                 public DeclSpace DeclContainer { 
432                         get { return declSpace; }
433                         set { declSpace = value; }
434                 }
435
436                 public bool CheckState {
437                         get { return (flags & Flags.CheckState) != 0; }
438                 }
439
440                 public bool ConstantCheckState {
441                         get { return (flags & Flags.ConstantCheckState) != 0; }
442                 }
443
444                 public bool InUnsafe {
445                         get { return (flags & Flags.InUnsafe) != 0; }
446                 }
447
448                 public bool InCatch {
449                         get { return (flags & Flags.InCatch) != 0; }
450                 }
451
452                 public bool InFinally {
453                         get { return (flags & Flags.InFinally) != 0; }
454                 }
455
456                 public bool DoFlowAnalysis {
457                         get { return (flags & Flags.DoFlowAnalysis) != 0; }
458                 }
459
460                 public bool OmitStructFlowAnalysis {
461                         get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
462                 }
463
464                 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
465                 // it's public so that we can use a struct at the callsite
466                 public struct FlagsHandle : IDisposable
467                 {
468                         EmitContext ec;
469                         Flags invmask, oldval;
470                         internal FlagsHandle (EmitContext ec, Flags mask, Flags val)
471                         {
472                                 this.ec = ec;
473                                 invmask = ~mask;
474                                 oldval = ec.flags & mask;
475                                 ec.flags = (ec.flags & invmask) | (val & mask);
476                         }
477                         public void Dispose ()
478                         {
479                                 ec.flags = (ec.flags & invmask) | oldval;
480                         }
481                 }
482
483                 // Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
484                 public FlagsHandle With (Flags bits, bool enable)
485                 {
486                         return new FlagsHandle (this, bits, enable ? bits : 0);
487                 }
488
489                 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
490                 {
491                         Flags newflags = 
492                                 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
493                                 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
494                         return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
495                 }
496
497                 public bool IsInObsoleteScope {
498                         get { return ResolveContext.IsInObsoleteScope; }
499                 }
500
501                 public bool IsInUnsafeScope {
502                         get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
503                 }
504
505                 public bool IsAnonymousMethodAllowed {
506                         get { return isAnonymousMethodAllowed; }
507                         set { isAnonymousMethodAllowed = value; }
508                 }
509
510                 public FlowBranching CurrentBranching {
511                         get { return current_flow_branching; }
512                 }
513
514                 public bool HaveCaptureInfo {
515                         get { return capture_context != null; }
516                 }
517
518                 public void EmitScopeInitFromBlock (Block b)
519                 {
520                         if (capture_context != null)
521                                 capture_context.EmitScopeInitFromBlock (this, b);
522                 }
523
524                 // <summary>
525                 //   Starts a new code branching.  This inherits the state of all local
526                 //   variables and parameters from the current branching.
527                 // </summary>
528                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
529                 {
530                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
531                         return current_flow_branching;
532                 }
533
534                 // <summary>
535                 //   Starts a new code branching for block `block'.
536                 // </summary>
537                 public FlowBranching StartFlowBranching (Block block)
538                 {
539                         FlowBranching.BranchingType type;
540
541                         if ((CurrentBranching != null) &&
542                             (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
543                                 type = FlowBranching.BranchingType.SwitchSection;
544                         else
545                                 type = FlowBranching.BranchingType.Block;
546
547                         flags |= Flags.DoFlowAnalysis;
548
549                         current_flow_branching = FlowBranching.CreateBranching (
550                                 CurrentBranching, type, block, block.StartLocation);
551                         return current_flow_branching;
552                 }
553
554                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
555                 {
556                         FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
557                         current_flow_branching = branching;
558                         return branching;
559                 }
560
561                 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
562                 {
563                         FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
564                         current_flow_branching = branching;
565                         return branching;
566                 }
567
568                 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
569                 {
570                         FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
571                         current_flow_branching = branching;
572                         return branching;
573                 }
574
575                 // <summary>
576                 //   Ends a code branching.  Merges the state of locals and parameters
577                 //   from all the children of the ending branching.
578                 // </summary>
579                 public FlowBranching.UsageVector DoEndFlowBranching ()
580                 {
581                         FlowBranching old = current_flow_branching;
582                         current_flow_branching = current_flow_branching.Parent;
583
584                         return current_flow_branching.MergeChild (old);
585                 }
586
587                 // <summary>
588                 //   Ends a code branching.  Merges the state of locals and parameters
589                 //   from all the children of the ending branching.
590                 // </summary>
591                 public FlowBranching.Reachability EndFlowBranching ()
592                 {
593                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
594
595                         return vector.Reachability;
596                 }
597
598                 // <summary>
599                 //   Kills the current code branching.  This throws away any changed state
600                 //   information and should only be used in case of an error.
601                 // </summary>
602                 public void KillFlowBranching ()
603                 {
604                         current_flow_branching = current_flow_branching.Parent;
605                 }
606
607                 public void CaptureVariable (LocalInfo li)
608                 {
609                         capture_context.AddLocal (CurrentAnonymousMethod, li);
610                         li.IsCaptured = true;
611                 }
612
613                 public void CaptureParameter (string name, Type t, int idx)
614                 {
615                         capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
616                 }
617
618                 public void CaptureThis ()
619                 {
620                         capture_context.CaptureThis (CurrentAnonymousMethod);
621                 }
622                 
623                 
624                 //
625                 // Use to register a field as captured
626                 //
627                 public void CaptureField (FieldExpr fe)
628                 {
629                         capture_context.AddField (this, CurrentAnonymousMethod, fe);
630                 }
631
632                 //
633                 // Whether anonymous methods have captured variables
634                 //
635                 public bool HaveCapturedVariables ()
636                 {
637                         if (capture_context != null)
638                                 return capture_context.HaveCapturedVariables;
639                         return false;
640                 }
641
642                 //
643                 // Whether anonymous methods have captured fields or this.
644                 //
645                 public bool HaveCapturedFields ()
646                 {
647                         if (capture_context != null)
648                                 return capture_context.HaveCapturedFields;
649                         return false;
650                 }
651
652                 //
653                 // Emits the instance pointer for the host method
654                 //
655                 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
656                 {
657                         if (capture_context != null)
658                                 capture_context.EmitMethodHostInstance (target, am);
659                         else if (IsStatic)
660                                 target.ig.Emit (OpCodes.Ldnull);
661                         else
662                                 target.ig.Emit (OpCodes.Ldarg_0);
663                 }
664
665                 //
666                 // Returns whether the `local' variable has been captured by an anonymous
667                 // method
668                 //
669                 public bool IsCaptured (LocalInfo local)
670                 {
671                         return capture_context.IsCaptured (local);
672                 }
673
674                 public bool IsParameterCaptured (string name)
675                 {
676                         if (capture_context != null)
677                                 return capture_context.IsParameterCaptured (name);
678                         return false;
679                 }
680                 
681                 public void EmitMeta (ToplevelBlock b)
682                 {
683                         if (capture_context != null)
684                                 capture_context.EmitAnonymousHelperClasses (this);
685                         b.EmitMeta (this);
686
687                         if (HasReturnLabel)
688                                 ReturnLabel = ig.DefineLabel ();
689                 }
690
691                 //
692                 // Here until we can fix the problem with Mono.CSharp.Switch, which
693                 // currently can not cope with ig == null during resolve (which must
694                 // be fixed for switch statements to work on anonymous methods).
695                 //
696                 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
697                 {
698                         if (block == null)
699                                 return;
700                         
701                         bool unreachable;
702                         
703                         if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
704                                 EmitMeta (block);
705
706                                 current_phase = Phase.Emitting;
707                                 EmitResolvedTopBlock (block, unreachable);
708                         }
709                 }
710
711                 bool resolved;
712
713                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
714                                              Parameters ip, IMethodData md, out bool unreachable)
715                 {
716                         current_phase = Phase.Resolving;
717                         
718                         unreachable = false;
719
720                         if (resolved)
721                                 return true;
722
723                         capture_context = block.CaptureContext;
724                         
725                         if (!loc.IsNull)
726                                 CurrentFile = loc.File;
727
728 #if PRODUCTION
729                         try {
730 #endif
731                                 if (!block.ResolveMeta (this, ip))
732                                         return false;
733
734                                 using (this.With (EmitContext.Flags.DoFlowAnalysis, true)) {
735                                         FlowBranchingToplevel top_level;
736                                         if (anonymous_method_host != null)
737                                                 top_level = new FlowBranchingToplevel (anonymous_method_host.CurrentBranching, block);
738                                         else 
739                                                 top_level = block.TopLevelBranching;
740
741                                         current_flow_branching = top_level;
742                                         bool ok = block.Resolve (this);
743                                         current_flow_branching = null;
744
745                                         if (!ok)
746                                                 return false;
747
748                                         FlowBranching.Reachability reachability = top_level.End ();
749                                         if (reachability.IsUnreachable)
750                                                 unreachable = true;
751                                 }
752 #if PRODUCTION
753                         } catch (Exception e) {
754                                 Console.WriteLine ("Exception caught by the compiler while compiling:");
755                                 Console.WriteLine ("   Block that caused the problem begin at: " + loc);
756
757                                 if (CurrentBlock != null){
758                                         Console.WriteLine ("                     Block being compiled: [{0},{1}]",
759                                                            CurrentBlock.StartLocation, CurrentBlock.EndLocation);
760                                 }
761                                 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
762                                 throw;
763                         }
764 #endif
765
766                         if (ReturnType != null && !unreachable) {
767                                 if (CurrentAnonymousMethod == null) {
768                                         Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
769                                         return false;
770                                 } else if (!CurrentAnonymousMethod.IsIterator) {
771                                         Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
772                                                 CurrentAnonymousMethod.GetSignatureForError ());
773                                         return false;
774                                 }
775                         }
776
777                         block.CompleteContexts ();
778                         resolved = true;
779                         return true;
780                 }
781
782                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
783                 {
784                         if (block != null)
785                                 block.Emit (this);
786                         
787                         if (HasReturnLabel)
788                                 ig.MarkLabel (ReturnLabel);
789                         
790                         if (return_value != null){
791                                 ig.Emit (OpCodes.Ldloc, return_value);
792                                 ig.Emit (OpCodes.Ret);
793                         } else {
794                                 //
795                                 // If `HasReturnLabel' is set, then we already emitted a
796                                 // jump to the end of the method, so we must emit a `ret'
797                                 // there.
798                                 //
799                                 // Unfortunately, System.Reflection.Emit automatically emits
800                                 // a leave to the end of a finally block.  This is a problem
801                                 // if no code is following the try/finally block since we may
802                                 // jump to a point after the end of the method.
803                                 // As a workaround, we're always creating a return label in
804                                 // this case.
805                                 //
806
807                                 bool in_iterator = (CurrentAnonymousMethod != null) &&
808                                         CurrentAnonymousMethod.IsIterator && InIterator;
809
810                                 if ((block != null) && block.IsDestructor) {
811                                         // Nothing to do; S.R.E automatically emits a leave.
812                                 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
813                                         if (ReturnType != null)
814                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
815                                         ig.Emit (OpCodes.Ret);
816                                 }
817                         }
818
819                         //
820                         // Close pending helper classes if we are the toplevel
821                         //
822                         if (capture_context != null && capture_context.ParentToplevel == null)
823                                 capture_context.CloseAnonymousHelperClasses ();
824                 }
825
826                 /// <summary>
827                 ///   This is called immediately before emitting an IL opcode to tell the symbol
828                 ///   writer to which source line this opcode belongs.
829                 /// </summary>
830                 public void Mark (Location loc, bool check_file)
831                 {
832                         if ((CodeGen.SymbolWriter == null) || loc.IsNull)
833                                 return;
834
835                         if (check_file && (CurrentFile != loc.File))
836                                 return;
837
838                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
839                 }
840
841                 public void DefineLocalVariable (string name, LocalBuilder builder)
842                 {
843                         if (CodeGen.SymbolWriter == null)
844                                 return;
845
846                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
847                 }
848
849                 public void BeginScope ()
850                 {
851                         ig.BeginScope();
852
853                         if (CodeGen.SymbolWriter != null)
854                                 CodeGen.SymbolWriter.OpenScope(ig);
855                 }
856
857                 public void EndScope ()
858                 {
859                         ig.EndScope();
860
861                         if (CodeGen.SymbolWriter != null)
862                                 CodeGen.SymbolWriter.CloseScope(ig);
863                 }
864
865                 /// <summary>
866                 ///   Returns a temporary storage for a variable of type t as 
867                 ///   a local variable in the current body.
868                 /// </summary>
869                 public LocalBuilder GetTemporaryLocal (Type t)
870                 {
871                         if (temporary_storage != null) {
872                                 object o = temporary_storage [t];
873                                 if (o != null) {
874                                         if (o is Stack) {
875                                                 Stack s = (Stack) o;
876                                                 o = s.Count == 0 ? null : s.Pop ();
877                                         } else {
878                                                 temporary_storage.Remove (t);
879                                         }
880                                 }
881                                 if (o != null)
882                                         return (LocalBuilder) o;
883                         }
884                         return ig.DeclareLocal (t);
885                 }
886
887                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
888                 {
889                         Stack s;
890
891                         if (temporary_storage == null) {
892                                 temporary_storage = new Hashtable ();
893                                 temporary_storage [t] = b;
894                                 return;
895                         }
896                         object o = temporary_storage [t];
897                         if (o == null) {
898                                 temporary_storage [t] = b;
899                                 return;
900                         }
901                         if (o is Stack) {
902                                 s = (Stack) o;
903                         } else {
904                                 s = new Stack ();
905                                 s.Push (o);
906                                 temporary_storage [t] = s;
907                         }
908                         s.Push (b);
909                 }
910
911                 /// <summary>
912                 ///   Current loop begin and end labels.
913                 /// </summary>
914                 public Label LoopBegin, LoopEnd;
915
916                 /// <summary>
917                 ///   Default target in a switch statement.   Only valid if
918                 ///   InSwitch is true
919                 /// </summary>
920                 public Label DefaultTarget;
921
922                 /// <summary>
923                 ///   If this is non-null, points to the current switch statement
924                 /// </summary>
925                 public Switch Switch;
926
927                 /// <summary>
928                 ///   ReturnValue creates on demand the LocalBuilder for the
929                 ///   return value from the function.  By default this is not
930                 ///   used.  This is only required when returns are found inside
931                 ///   Try or Catch statements.
932                 ///
933                 ///   This method is typically invoked from the Emit phase, so
934                 ///   we allow the creation of a return label if it was not
935                 ///   requested during the resolution phase.   Could be cleaned
936                 ///   up, but it would replicate a lot of logic in the Emit phase
937                 ///   of the code that uses it.
938                 /// </summary>
939                 public LocalBuilder TemporaryReturn ()
940                 {
941                         if (return_value == null){
942                                 return_value = ig.DeclareLocal (ReturnType);
943                                 if (!HasReturnLabel){
944                                         ReturnLabel = ig.DefineLabel ();
945                                         HasReturnLabel = true;
946                                 }
947                         }
948
949                         return return_value;
950                 }
951
952                 /// <summary>
953                 ///   This method is used during the Resolution phase to flag the
954                 ///   need to define the ReturnLabel
955                 /// </summary>
956                 public void NeedReturnLabel ()
957                 {
958                         if (current_phase != Phase.Resolving){
959                                 //
960                                 // The reason is that the `ReturnLabel' is declared between
961                                 // resolution and emission
962                                 // 
963                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
964                         }
965                         
966                         if (!InIterator && !HasReturnLabel) 
967                                 HasReturnLabel = true;
968                 }
969
970                 //
971                 // Emits the proper object to address fields on a remapped
972                 // variable/parameter to field in anonymous-method/iterator proxy classes.
973                 //
974                 public void EmitThis (bool need_address)
975                 {
976                         ig.Emit (OpCodes.Ldarg_0);
977                         if (capture_context != null && CurrentAnonymousMethod != null){
978                                 ScopeInfo si = CurrentAnonymousMethod.Scope;
979                                 while (si != null){
980                                         if (si.ParentLink != null)
981                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
982                                         if (si.THIS != null){
983                                                 if (need_address && TypeManager.IsValueType (si.THIS.FieldType))
984                                                         ig.Emit (OpCodes.Ldflda, si.THIS);
985                                                 else
986                                                         ig.Emit (OpCodes.Ldfld, si.THIS);
987                                                 break;
988                                         }
989                                         si = si.ParentScope;
990                                 }
991                         } 
992                 }
993
994                 //
995                 // Emits the code necessary to load the instance required
996                 // to access the captured LocalInfo
997                 //
998                 public void EmitCapturedVariableInstance (LocalInfo li)
999                 {
1000                         if (capture_context == null)
1001                                 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
1002                         
1003                         capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
1004                 }
1005
1006                 public void EmitParameter (string name, bool leave_copy, bool prepared, ref LocalTemporary temp)
1007                 {
1008                         capture_context.EmitParameter (this, name, leave_copy, prepared, ref temp);
1009                 }
1010
1011                 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load, ref LocalTemporary  temp)
1012                 {
1013                         capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load, ref temp);
1014                 }
1015
1016                 public void EmitAddressOfParameter (string name)
1017                 {
1018                         capture_context.EmitAddressOfParameter (this, name);
1019                 }
1020                 
1021                 public Expression GetThis (Location loc)
1022                 {
1023                         This my_this;
1024                         if (CurrentBlock != null)
1025                                 my_this = new This (CurrentBlock, loc);
1026                         else
1027                                 my_this = new This (loc);
1028
1029                         if (!my_this.ResolveBase (this))
1030                                 my_this = null;
1031
1032                         return my_this;
1033                 }
1034         }
1035
1036
1037         public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
1038
1039                 protected CommonAssemblyModulClass ():
1040                         base (null)
1041                 {
1042                 }
1043
1044                 public void AddAttributes (ArrayList attrs)
1045                 {
1046                         foreach (Attribute a in attrs)
1047                                 a.AttachTo (this);
1048
1049                         if (attributes == null) {
1050                                 attributes = new Attributes (attrs);
1051                                 return;
1052                         }
1053                         attributes.AddAttributes (attrs);
1054                 }
1055
1056                 public virtual void Emit (TypeContainer tc) 
1057                 {
1058                         if (OptAttributes == null)
1059                                 return;
1060
1061                         OptAttributes.Emit ();
1062                 }
1063                 
1064                 protected Attribute ResolveAttribute (Type a_type)
1065                 {
1066                         if (OptAttributes == null)
1067                                 return null;
1068
1069                         // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1070                         if (!OptAttributes.CheckTargets ())
1071                                 return null;
1072
1073                         Attribute a = OptAttributes.Search (a_type);
1074                         if (a != null) {
1075                                 a.Resolve ();
1076                         }
1077                         return a;
1078                 }
1079
1080                 public override IResolveContext ResolveContext {
1081                         get { return this; }
1082                 }
1083
1084                 #region IResolveContext Members
1085
1086                 public DeclSpace DeclContainer {
1087                         get { return RootContext.ToplevelTypes; }
1088                 }
1089
1090                 public bool IsInObsoleteScope {
1091                         get { return false; }
1092                 }
1093
1094                 public bool IsInUnsafeScope {
1095                         get { return false; }
1096                 }
1097
1098                 #endregion
1099         }
1100                 
1101         public class AssemblyClass : CommonAssemblyModulClass {
1102                 // TODO: make it private and move all builder based methods here
1103                 public AssemblyBuilder Builder;
1104                 bool is_cls_compliant;
1105                 bool wrap_non_exception_throws;
1106
1107                 public Attribute ClsCompliantAttribute;
1108
1109                 ListDictionary declarative_security;
1110
1111                 // Module is here just because of error messages
1112                 static string[] attribute_targets = new string [] { "assembly", "module" };
1113
1114                 public AssemblyClass (): base ()
1115                 {
1116                         wrap_non_exception_throws = true;
1117                 }
1118
1119                 public bool IsClsCompliant {
1120                         get {
1121                                 return is_cls_compliant;
1122                         }
1123                 }
1124
1125                 public bool WrapNonExceptionThrows {
1126                         get {
1127                                 return wrap_non_exception_throws;
1128                         }
1129                 }
1130
1131                 public override AttributeTargets AttributeTargets {
1132                         get {
1133                                 return AttributeTargets.Assembly;
1134                         }
1135                 }
1136
1137                 public override bool IsClsComplianceRequired ()
1138                 {
1139                         return is_cls_compliant;
1140                 }
1141
1142                 public void Resolve ()
1143                 {
1144                         ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1145                         if (ClsCompliantAttribute != null) {
1146                                 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1147                         }
1148
1149 #if NET_2_0
1150                         Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
1151                         if (a != null) {
1152                                 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1153                                 if (val != null)
1154                                         wrap_non_exception_throws = (bool)val;
1155                         }
1156 #endif
1157                 }
1158
1159                 // fix bug #56621
1160                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1161                 {
1162                         try {
1163                                 // check for possible ECMA key
1164                                 if (strongNameBlob.Length == 16) {
1165                                         // will be rejected if not "the" ECMA key
1166                                         an.SetPublicKey (strongNameBlob);
1167                                 }
1168                                 else {
1169                                         // take it, with or without, a private key
1170                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1171                                         // and make sure we only feed the public part to Sys.Ref
1172                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1173                                         
1174                                         // AssemblyName.SetPublicKey requires an additional header
1175                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1176
1177                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1178                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1179                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1180                                         an.SetPublicKey (encodedPublicKey);
1181                                 }
1182                         }
1183                         catch (Exception) {
1184                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1185                                 Environment.Exit (1);
1186                         }
1187                 }
1188
1189                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1190                 public AssemblyName GetAssemblyName (string name, string output) 
1191                 {
1192                         if (OptAttributes != null) {
1193                                 foreach (Attribute a in OptAttributes.Attrs) {
1194                                         // cannot rely on any resolve-based members before you call Resolve
1195                                         if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1196                                                 continue;
1197
1198                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1199                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
1200                                         //       are loaded yet.
1201                                         // TODO: Does not handle quoted attributes properly
1202                                         switch (a.Name) {
1203                                                 case "AssemblyKeyFile":
1204                                                 case "AssemblyKeyFileAttribute":
1205                                                 case "System.Reflection.AssemblyKeyFileAttribute":
1206                                                         if (RootContext.StrongNameKeyFile != null) {
1207                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1208                                                                 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1209                                     "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1210                                                         }
1211                                                         else {
1212                                                                 string value = a.GetString ();
1213                                                                 if (value.Length != 0)
1214                                                                         RootContext.StrongNameKeyFile = value;
1215                                                         }
1216                                                         break;
1217                                                 case "AssemblyKeyName":
1218                                                 case "AssemblyKeyNameAttribute":
1219                                                 case "System.Reflection.AssemblyKeyNameAttribute":
1220                                                         if (RootContext.StrongNameKeyContainer != null) {
1221                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1222                                                                 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1223                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1224                                                         }
1225                                                         else {
1226                                                                 string value = a.GetString ();
1227                                                                 if (value.Length != 0)
1228                                                                         RootContext.StrongNameKeyContainer = value;
1229                                                         }
1230                                                         break;
1231                                                 case "AssemblyDelaySign":
1232                                                 case "AssemblyDelaySignAttribute":
1233                                                 case "System.Reflection.AssemblyDelaySignAttribute":
1234                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1235                                                         break;
1236                                         }
1237                                 }
1238                         }
1239
1240                         AssemblyName an = new AssemblyName ();
1241                         an.Name = Path.GetFileNameWithoutExtension (name);
1242
1243                         // note: delay doesn't apply when using a key container
1244                         if (RootContext.StrongNameKeyContainer != null) {
1245                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1246                                 return an;
1247                         }
1248
1249                         // strongname is optional
1250                         if (RootContext.StrongNameKeyFile == null)
1251                                 return an;
1252
1253                         string AssemblyDir = Path.GetDirectoryName (output);
1254
1255                         // the StrongName key file may be relative to (a) the compiled
1256                         // file or (b) to the output assembly. See bugzilla #55320
1257                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1258
1259                         // (a) relative to the compiled file
1260                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1261                         bool exist = File.Exists (filename);
1262                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1263                                 // (b) relative to the outputed assembly
1264                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1265                                 exist = File.Exists (filename);
1266                         }
1267
1268                         if (exist) {
1269                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1270                                         byte[] snkeypair = new byte [fs.Length];
1271                                         fs.Read (snkeypair, 0, snkeypair.Length);
1272
1273                                         if (RootContext.StrongNameDelaySign) {
1274                                                 // delayed signing - DO NOT include private key
1275                                                 SetPublicKey (an, snkeypair);
1276                                         }
1277                                         else {
1278                                                 // no delay so we make sure we have the private key
1279                                                 try {
1280                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1281                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1282                                                 }
1283                                                 catch (CryptographicException) {
1284                                                         if (snkeypair.Length == 16) {
1285                                                                 // error # is different for ECMA key
1286                                                                 Report.Error (1606, "Could not sign the assembly. " + 
1287                                                                         "ECMA key can only be used to delay-sign assemblies");
1288                                                         }
1289                                                         else {
1290                                                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1291                                                         }
1292                                                         return null;
1293                                                 }
1294                                         }
1295                                 }
1296                         }
1297                         else {
1298                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1299                                 return null;
1300                         }
1301                         return an;
1302                 }
1303
1304                 void Error_AssemblySigning (string text)
1305                 {
1306                         Report.Error (1548, "Error during assembly signing. " + text);
1307                 }
1308
1309                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1310                 {
1311                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1312                                 if (declarative_security == null)
1313                                         declarative_security = new ListDictionary ();
1314
1315                                 a.ExtractSecurityPermissionSet (declarative_security);
1316                                 return;
1317                         }
1318
1319                         if (a.Type == TypeManager.assembly_culture_attribute_type) {
1320                                 string value = a.GetString ();
1321                                 if (value == null || value.Length == 0)
1322                                         return;
1323
1324                                 if (RootContext.Target == Target.Exe) {
1325                                         a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1326                                         return;
1327                                 }
1328                         }
1329
1330                         Builder.SetCustomAttribute (customBuilder);
1331                 }
1332
1333                 public override void Emit (TypeContainer tc)
1334                 {
1335                         base.Emit (tc);
1336
1337                         if (declarative_security != null) {
1338
1339                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1340                                 object builder_instance = Builder;
1341
1342                                 try {
1343                                         // Microsoft runtime hacking
1344                                         if (add_permission == null) {
1345                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1346                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1347
1348                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1349                                                 builder_instance = fi.GetValue (Builder);
1350                                         }
1351
1352                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1353                                                                                                   declarative_security [SecurityAction.RequestOptional],
1354                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1355                                         add_permission.Invoke (builder_instance, args);
1356                                 }
1357                                 catch {
1358                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1359                                 }
1360                         }
1361                 }
1362
1363                 public override string[] ValidAttributeTargets {
1364                         get {
1365                                 return attribute_targets;
1366                         }
1367                 }
1368         }
1369
1370         public class ModuleClass : CommonAssemblyModulClass {
1371                 // TODO: make it private and move all builder based methods here
1372                 public ModuleBuilder Builder;
1373                 bool m_module_is_unsafe;
1374
1375                 public CharSet DefaultCharSet = CharSet.Ansi;
1376                 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1377
1378                 static string[] attribute_targets = new string [] { "module" };
1379
1380                 public ModuleClass (bool is_unsafe)
1381                 {
1382                         m_module_is_unsafe = is_unsafe;
1383                 }
1384
1385                 public override AttributeTargets AttributeTargets {
1386                         get {
1387                                 return AttributeTargets.Module;
1388                         }
1389                 }
1390
1391                 public override bool IsClsComplianceRequired ()
1392                 {
1393                         return CodeGen.Assembly.IsClsCompliant;
1394                 }
1395
1396                 public override void Emit (TypeContainer tc) 
1397                 {
1398                         base.Emit (tc);
1399
1400                         if (!m_module_is_unsafe)
1401                                 return;
1402
1403                         if (TypeManager.unverifiable_code_ctor == null) {
1404                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1405                                 return;
1406                         }
1407                                 
1408                         Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1409                 }
1410                 
1411                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1412                 {
1413                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
1414                                 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1415                                         Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1416                                 }
1417                                 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1418                                         Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1419                                         Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1420                                         return;
1421                                 }
1422                         }
1423
1424                         Builder.SetCustomAttribute (customBuilder);
1425                 }
1426
1427                 /// <summary>
1428                 /// It is called very early therefore can resolve only predefined attributes
1429                 /// </summary>
1430                 public void ResolveAttributes ()
1431                 {
1432 #if NET_2_0
1433                         Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1434                         if (a != null) {
1435                                 DefaultCharSet = a.GetCharSetValue ();
1436                                 switch (DefaultCharSet) {
1437                                         case CharSet.Ansi:
1438                                         case CharSet.None:
1439                                                 break;
1440                                         case CharSet.Auto:
1441                                                 DefaultCharSetType = TypeAttributes.AutoClass;
1442                                                 break;
1443                                         case CharSet.Unicode:
1444                                                 DefaultCharSetType = TypeAttributes.UnicodeClass;
1445                                                 break;
1446                                         default:
1447                                                 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1448                                                 break;
1449                                 }
1450                         }
1451 #endif
1452                 }
1453
1454                 public override string[] ValidAttributeTargets {
1455                         get {
1456                                 return attribute_targets;
1457                         }
1458                 }
1459         }
1460 }