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