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