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