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