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