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