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