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