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