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