2005-07-14 Sureshkumar T <tsureshkumar@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 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
9 //
10 //#define PRODUCTION
11 using System;
12 using System.IO;
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Runtime.InteropServices;
18 using System.Security;
19 using System.Security.Cryptography;
20 using System.Security.Permissions;
21
22 using Mono.Security.Cryptography;
23
24 namespace Mono.CSharp {
25
26         /// <summary>
27         ///    Code generator class.
28         /// </summary>
29         public class CodeGen {
30                 static AppDomain current_domain;
31                 static public SymbolWriter SymbolWriter;
32
33                 public static AssemblyClass Assembly;
34                 public static ModuleClass Module;
35
36                 static CodeGen ()
37                 {
38                         Reset ();
39                 }
40
41                 public static void Reset ()
42                 {
43                         Assembly = new AssemblyClass ();
44                         Module = new ModuleClass (RootContext.Unsafe);
45                 }
46
47                 public static string Basename (string name)
48                 {
49                         int pos = name.LastIndexOf ('/');
50
51                         if (pos != -1)
52                                 return name.Substring (pos + 1);
53
54                         pos = name.LastIndexOf ('\\');
55                         if (pos != -1)
56                                 return name.Substring (pos + 1);
57
58                         return name;
59                 }
60
61                 public static string Dirname (string name)
62                 {
63                         int pos = name.LastIndexOf ('/');
64
65                         if (pos != -1)
66                                 return name.Substring (0, pos);
67
68                         pos = name.LastIndexOf ('\\');
69                         if (pos != -1)
70                                 return name.Substring (0, pos);
71
72                         return ".";
73                 }
74
75                 static public string FileName;
76
77                 //
78                 // Initializes the symbol writer
79                 //
80                 static void InitializeSymbolWriter (string filename)
81                 {
82                         SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
83
84                         //
85                         // If we got an ISymbolWriter instance, initialize it.
86                         //
87                         if (SymbolWriter == null) {
88                                 Report.Warning (
89                                         -18, "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.");
90                                 return;
91                         }
92                 }
93
94                 //
95                 // Initializes the code generator variables
96                 //
97                 static public bool Init (string name, string output, bool want_debugging_support)
98                 {
99                         FileName = output;
100                         AssemblyName an = Assembly.GetAssemblyName (name, output);
101                         if (an == null)
102                                 return false;
103
104                         if (an.KeyPair != null) {
105                                 // If we are going to strong name our assembly make
106                                 // sure all its refs are strong named
107                                 foreach (Assembly a in TypeManager.GetAssemblies ()) {
108                                         AssemblyName ref_name = a.GetName ();
109                                         byte [] b = ref_name.GetPublicKeyToken ();
110                                         if (b == null || b.Length == 0) {
111                                                 Report.Warning (1577, "Assembly generation failed " +
112                                                                 "-- Referenced assembly '" +
113                                                                 ref_name.Name +
114                                                                 "' does not have a strong name.");
115                                                 //Environment.Exit (1);
116                                         }
117                                 }
118                         }
119                         
120                         current_domain = AppDomain.CurrentDomain;
121
122                         try {
123                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
124                                         AssemblyBuilderAccess.Save, Dirname (name));
125                         }
126                         catch (ArgumentException) {
127                                 // specified key may not be exportable outside it's container
128                                 if (RootContext.StrongNameKeyContainer != null) {
129                                         Report.Error (1548, "Could not access the key inside the container `" +
130                                                 RootContext.StrongNameKeyContainer + "'.");
131                                         Environment.Exit (1);
132                                 }
133                                 return false;
134                         }
135                         catch (CryptographicException) {
136                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
137                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
138                                         Environment.Exit (1);
139                                 }
140                                 return false;
141                         }
142
143                         //
144                         // Pass a path-less name to DefineDynamicModule.  Wonder how
145                         // this copes with output in different directories then.
146                         // FIXME: figure out how this copes with --output /tmp/blah
147                         //
148                         // If the third argument is true, the ModuleBuilder will dynamically
149                         // load the default symbol writer.
150                         //
151                         Module.Builder = Assembly.Builder.DefineDynamicModule (
152                                 Basename (name), Basename (output), false);
153
154                         if (want_debugging_support)
155                                 InitializeSymbolWriter (output);
156
157                         return true;
158                 }
159
160                 static public void Save (string name)
161                 {
162                         try {
163                                 Assembly.Builder.Save (Basename (name));
164                         }
165                         catch (COMException) {
166                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
167                                         throw;
168
169                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
170                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
171                                         RootContext.StrongNameKeyFile +
172                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
173                         }
174                         catch (System.IO.IOException io) {
175                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
176                         }
177                         catch (System.UnauthorizedAccessException ua) {
178                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
179                         }
180
181                         if (SymbolWriter != null)
182                                 SymbolWriter.WriteSymbolFile ();
183                 }
184         }
185
186         /// <summary>
187         ///   An Emit Context is created for each body of code (from methods,
188         ///   properties bodies, indexer bodies or constructor bodies)
189         /// </summary>
190         public class EmitContext {
191                 public DeclSpace DeclSpace;
192                 public DeclSpace TypeContainer;
193                 public ILGenerator   ig;
194
195                 /// <summary>
196                 ///   This variable tracks the `checked' state of the compilation,
197                 ///   it controls whether we should generate code that does overflow
198                 ///   checking, or if we generate code that ignores overflows.
199                 ///
200                 ///   The default setting comes from the command line option to generate
201                 ///   checked or unchecked code plus any source code changes using the
202                 ///   checked/unchecked statements or expressions.   Contrast this with
203                 ///   the ConstantCheckState flag.
204                 /// </summary>
205                 
206                 public bool CheckState;
207
208                 /// <summary>
209                 ///   The constant check state is always set to `true' and cant be changed
210                 ///   from the command line.  The source code can change this setting with
211                 ///   the `checked' and `unchecked' statements and expressions. 
212                 /// </summary>
213                 public bool ConstantCheckState;
214
215                 /// <summary>
216                 ///   Whether we are emitting code inside a static or instance method
217                 /// </summary>
218                 public bool IsStatic;
219
220                 /// <summary>
221                 ///   Whether the actual created method is static or instance method.
222                 ///   Althoug the method might be declared as `static', if an anonymous
223                 ///   method is involved, we might turn this into an instance method.
224                 ///
225                 ///   So this reflects the low-level staticness of the method, while
226                 ///   IsStatic represents the semantic, high-level staticness.
227                 /// </summary>
228                 public bool MethodIsStatic;
229
230                 /// <summary>
231                 ///   Whether we are emitting a field initializer
232                 /// </summary>
233                 public bool IsFieldInitializer;
234
235                 /// <summary>
236                 ///   The value that is allowed to be returned or NULL if there is no
237                 ///   return type.
238                 /// </summary>
239                 public Type ReturnType;
240
241                 /// <summary>
242                 ///   Points to the Type (extracted from the TypeContainer) that
243                 ///   declares this body of code
244                 /// </summary>
245                 public Type ContainerType;
246                 
247                 /// <summary>
248                 ///   Whether this is generating code for a constructor
249                 /// </summary>
250                 public bool IsConstructor;
251
252                 /// <summary>
253                 ///   Whether we're control flow analysis enabled
254                 /// </summary>
255                 public bool DoFlowAnalysis;
256
257                 /// <summary>
258                 ///   Keeps track of the Type to LocalBuilder temporary storage created
259                 ///   to store structures (used to compute the address of the structure
260                 ///   value on structure method invocations)
261                 /// </summary>
262                 public Hashtable temporary_storage;
263
264                 public Block CurrentBlock;
265
266                 public int CurrentFile;
267
268                 /// <summary>
269                 ///   The location where we store the return value.
270                 /// </summary>
271                 LocalBuilder return_value;
272
273                 /// <summary>
274                 ///   The location where return has to jump to return the
275                 ///   value
276                 /// </summary>
277                 public Label ReturnLabel;
278
279                 /// <summary>
280                 ///   If we already defined the ReturnLabel
281                 /// </summary>
282                 public bool HasReturnLabel;
283
284                 /// <summary>
285                 ///   Whether we are inside an iterator block.
286                 /// </summary>
287                 public bool InIterator;
288
289                 public bool IsLastStatement;
290
291                 /// <summary>
292                 ///  Whether we are inside an unsafe block
293                 /// </summary>
294                 public bool InUnsafe;
295
296                 /// <summary>
297                 ///  Whether we are in a `fixed' initialization
298                 /// </summary>
299                 public bool InFixedInitializer;
300
301                 public bool InRefOutArgumentResolving;
302
303                 public bool InCatch;
304                 public bool InFinally;
305
306                 /// <summary>
307                 ///  Whether we are inside an anonymous method.
308                 /// </summary>
309                 public AnonymousContainer CurrentAnonymousMethod;
310                 
311                 /// <summary>
312                 ///   Location for this EmitContext
313                 /// </summary>
314                 public Location loc;
315
316                 /// <summary>
317                 ///   Inside an enum definition, we do not resolve enumeration values
318                 ///   to their enumerations, but rather to the underlying type/value
319                 ///   This is so EnumVal + EnumValB can be evaluated.
320                 ///
321                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
322                 ///   we relax the rules
323                 /// </summary>
324                 public bool InEnumContext;
325
326                 /// <summary>
327                 ///   Anonymous methods can capture local variables and fields,
328                 ///   this object tracks it.  It is copied from the TopLevelBlock
329                 ///   field.
330                 /// </summary>
331                 public CaptureContext capture_context;
332
333                 /// <summary>
334                 /// Trace when method is called and is obsolete then this member suppress message
335                 /// when call is inside next [Obsolete] method or type.
336                 /// </summary>
337                 public bool TestObsoleteMethodUsage = true;
338
339                 /// <summary>
340                 ///    The current iterator
341                 /// </summary>
342                 public Iterator CurrentIterator;
343
344                 /// <summary>
345                 ///    Whether we are in the resolving stage or not
346                 /// </summary>
347                 enum Phase {
348                         Created,
349                         Resolving,
350                         Emitting
351                 }
352                 
353                 Phase current_phase;
354                 FlowBranching current_flow_branching;
355
356                 static int next_id = 0;
357                 int id = ++next_id;
358
359                 public override string ToString ()
360                 {
361                         return String.Format ("EmitContext ({0}:{1}:{2})", id,
362                                               CurrentIterator, capture_context, loc);
363                 }
364                 
365                 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
366                                     Type return_type, int code_flags, bool is_constructor)
367                 {
368                         this.ig = ig;
369
370                         TypeContainer = parent;
371                         DeclSpace = ds;
372                         CheckState = RootContext.Checked;
373                         ConstantCheckState = true;
374
375                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
376                         MethodIsStatic = IsStatic;
377                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
378                         ReturnType = return_type;
379                         IsConstructor = is_constructor;
380                         CurrentBlock = null;
381                         CurrentFile = 0;
382                         current_phase = Phase.Created;
383                         
384                         if (parent != null){
385                                 // Can only be null for the ResolveType contexts.
386                                 ContainerType = parent.TypeBuilder;
387                                 if (parent.UnsafeContext)
388                                         InUnsafe = true;
389                                 else
390                                         InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
391                         }
392                         loc = l;
393
394                         if (ReturnType == TypeManager.void_type)
395                                 ReturnType = null;
396                 }
397
398                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
399                                     Type return_type, int code_flags, bool is_constructor)
400                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
401                 {
402                 }
403
404                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
405                                     Type return_type, int code_flags)
406                         : this (tc, tc, l, ig, return_type, code_flags, false)
407                 {
408                 }
409
410                 public FlowBranching CurrentBranching {
411                         get {
412                                 return current_flow_branching;
413                         }
414                 }
415
416                 public bool HaveCaptureInfo {
417                         get {
418                                 return capture_context != null;
419                         }
420                 }
421
422                 // <summary>
423                 //   Starts a new code branching.  This inherits the state of all local
424                 //   variables and parameters from the current branching.
425                 // </summary>
426                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
427                 {
428                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
429                         return current_flow_branching;
430                 }
431
432                 // <summary>
433                 //   Starts a new code branching for block `block'.
434                 // </summary>
435                 public FlowBranching StartFlowBranching (Block block)
436                 {
437                         FlowBranching.BranchingType type;
438
439                         if ((CurrentBranching != null) &&
440                             (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
441                                 type = FlowBranching.BranchingType.SwitchSection;
442                         else
443                                 type = FlowBranching.BranchingType.Block;
444
445                         DoFlowAnalysis = true;
446
447                         current_flow_branching = FlowBranching.CreateBranching (
448                                 CurrentBranching, type, block, block.StartLocation);
449                         return current_flow_branching;
450                 }
451
452                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
453                 {
454                         FlowBranchingException branching = new FlowBranchingException (
455                                 CurrentBranching, stmt);
456                         current_flow_branching = branching;
457                         return branching;
458                 }
459
460                 // <summary>
461                 //   Ends a code branching.  Merges the state of locals and parameters
462                 //   from all the children of the ending branching.
463                 // </summary>
464                 public FlowBranching.UsageVector DoEndFlowBranching ()
465                 {
466                         FlowBranching old = current_flow_branching;
467                         current_flow_branching = current_flow_branching.Parent;
468
469                         return current_flow_branching.MergeChild (old);
470                 }
471
472                 // <summary>
473                 //   Ends a code branching.  Merges the state of locals and parameters
474                 //   from all the children of the ending branching.
475                 // </summary>
476                 public FlowBranching.Reachability EndFlowBranching ()
477                 {
478                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
479
480                         return vector.Reachability;
481                 }
482
483                 // <summary>
484                 //   Kills the current code branching.  This throws away any changed state
485                 //   information and should only be used in case of an error.
486                 // </summary>
487                 public void KillFlowBranching ()
488                 {
489                         current_flow_branching = current_flow_branching.Parent;
490                 }
491
492                 public void CaptureVariable (LocalInfo li)
493                 {
494                         capture_context.AddLocal (CurrentAnonymousMethod, li);
495                         li.IsCaptured = true;
496                 }
497
498                 public void CaptureParameter (string name, Type t, int idx)
499                 {
500                         capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
501                 }
502
503                 public void CaptureThis ()
504                 {
505                         capture_context.CaptureThis ();
506                 }
507                 
508                 
509                 //
510                 // Use to register a field as captured
511                 //
512                 public void CaptureField (FieldExpr fe)
513                 {
514                         capture_context.AddField (fe);
515                 }
516
517                 //
518                 // Whether anonymous methods have captured variables
519                 //
520                 public bool HaveCapturedVariables ()
521                 {
522                         if (capture_context != null)
523                                 return capture_context.HaveCapturedVariables;
524                         return false;
525                 }
526
527                 //
528                 // Whether anonymous methods have captured fields or this.
529                 //
530                 public bool HaveCapturedFields ()
531                 {
532                         if (capture_context != null)
533                                 return capture_context.HaveCapturedFields;
534                         return false;
535                 }
536
537                 //
538                 // Emits the instance pointer for the host method
539                 //
540                 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
541                 {
542                         if (capture_context != null)
543                                 capture_context.EmitMethodHostInstance (target, am);
544                         else if (IsStatic)
545                                 target.ig.Emit (OpCodes.Ldnull);
546                         else
547                                 target.ig.Emit (OpCodes.Ldarg_0);
548                 }
549
550                 //
551                 // Returns whether the `local' variable has been captured by an anonymous
552                 // method
553                 //
554                 public bool IsCaptured (LocalInfo local)
555                 {
556                         return capture_context.IsCaptured (local);
557                 }
558
559                 public bool IsParameterCaptured (string name)
560                 {
561                         if (capture_context != null)
562                                 return capture_context.IsParameterCaptured (name);
563                         return false;
564                 }
565                 
566                 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
567                 {
568                         if (capture_context != null)
569                                 capture_context.EmitAnonymousHelperClasses (this);
570                         b.EmitMeta (this);
571
572                         if (HasReturnLabel)
573                                 ReturnLabel = ig.DefineLabel ();
574                 }
575
576                 //
577                 // Here until we can fix the problem with Mono.CSharp.Switch, which
578                 // currently can not cope with ig == null during resolve (which must
579                 // be fixed for switch statements to work on anonymous methods).
580                 //
581                 public void EmitTopBlock (IMethodData md, ToplevelBlock block, InternalParameters ip)
582                 {
583                         if (block == null)
584                                 return;
585                         
586                         bool unreachable;
587                         
588                         if (ResolveTopBlock (null, block, ip, md, out unreachable)){
589                                 EmitMeta (block, ip);
590
591                                 current_phase = Phase.Emitting;
592                                 EmitResolvedTopBlock (block, unreachable);
593                         }
594                 }
595
596                 bool resolved;
597
598                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
599                                              InternalParameters ip, IMethodData md, out bool unreachable)
600                 {
601                         current_phase = Phase.Resolving;
602                         
603                         unreachable = false;
604
605                         if (resolved)
606                                 return true;
607
608                         capture_context = block.CaptureContext;
609                         
610                         if (!Location.IsNull (loc))
611                                 CurrentFile = loc.File;
612
613 #if PRODUCTION
614                         try {
615 #endif
616                                 if (!block.ResolveMeta (this, ip))
617                                         return false;
618
619                                         bool old_do_flow_analysis = DoFlowAnalysis;
620                                         DoFlowAnalysis = true;
621
622                                         if (anonymous_method_host != null)
623                                                 current_flow_branching = FlowBranching.CreateBranching (
624                                                         anonymous_method_host.CurrentBranching,
625                                                         FlowBranching.BranchingType.Block, block, loc);
626                                         else 
627                                                 current_flow_branching = block.TopLevelBranching;
628
629                                         if (!block.Resolve (this)) {
630                                                 current_flow_branching = null;
631                                                 DoFlowAnalysis = old_do_flow_analysis;
632                                                 return false;
633                                         }
634
635                                         FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
636                                         current_flow_branching = null;
637                                         
638                                         DoFlowAnalysis = old_do_flow_analysis;
639
640                                         if (reachability.AlwaysReturns ||
641                                             reachability.AlwaysThrows ||
642                                             reachability.IsUnreachable)
643                                                 unreachable = true;
644 #if PRODUCTION
645                         } catch (Exception e) {
646                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
647                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
648                                         
649                                         if (CurrentBlock != null){
650                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
651                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
652                                         }
653                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
654                                         throw;
655                         }
656 #endif
657
658                         if (ReturnType != null && !unreachable) {
659                                 if (CurrentAnonymousMethod == null) {
660                                         Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
661                                         return false;
662                                 } else if (!CurrentAnonymousMethod.IsIterator) {
663                                         Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
664                                                 CurrentAnonymousMethod.GetSignatureForError ());
665                                         return false;
666                                 }
667                         }
668
669                         block.CompleteContexts ();
670                         resolved = true;
671                         return true;
672                 }
673
674                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
675                 {
676                         if (block != null)
677                                 block.Emit (this);
678                         
679                         if (HasReturnLabel)
680                                 ig.MarkLabel (ReturnLabel);
681                         
682                         if (return_value != null){
683                                 ig.Emit (OpCodes.Ldloc, return_value);
684                                 ig.Emit (OpCodes.Ret);
685                         } else {
686                                 //
687                                 // If `HasReturnLabel' is set, then we already emitted a
688                                 // jump to the end of the method, so we must emit a `ret'
689                                 // there.
690                                 //
691                                 // Unfortunately, System.Reflection.Emit automatically emits
692                                 // a leave to the end of a finally block.  This is a problem
693                                 // if no code is following the try/finally block since we may
694                                 // jump to a point after the end of the method.
695                                 // As a workaround, we're always creating a return label in
696                                 // this case.
697                                 //
698
699                                 bool in_iterator = (CurrentAnonymousMethod != null) &&
700                                         CurrentAnonymousMethod.IsIterator && InIterator;
701
702                                 if ((block != null) && block.IsDestructor) {
703                                         // Nothing to do; S.R.E automatically emits a leave.
704                                 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
705                                         if (ReturnType != null)
706                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
707                                         ig.Emit (OpCodes.Ret);
708                                 }
709                         }
710
711                         //
712                         // Close pending helper classes if we are the toplevel
713                         //
714                         if (capture_context != null && capture_context.ParentToplevel == null)
715                                 capture_context.CloseAnonymousHelperClasses ();
716                 }
717
718                 /// <summary>
719                 ///   This is called immediately before emitting an IL opcode to tell the symbol
720                 ///   writer to which source line this opcode belongs.
721                 /// </summary>
722                 public void Mark (Location loc, bool check_file)
723                 {
724                         if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
725                                 return;
726
727                         if (check_file && (CurrentFile != loc.File))
728                                 return;
729
730                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
731                 }
732
733                 public void DefineLocalVariable (string name, LocalBuilder builder)
734                 {
735                         if (CodeGen.SymbolWriter == null)
736                                 return;
737
738                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
739                 }
740
741                 public void BeginScope ()
742                 {
743                         ig.BeginScope();
744
745                         if (CodeGen.SymbolWriter != null)
746                                 CodeGen.SymbolWriter.OpenScope(ig);
747                 }
748
749                 public void EndScope ()
750                 {
751                         ig.EndScope();
752
753                         if (CodeGen.SymbolWriter != null)
754                                 CodeGen.SymbolWriter.CloseScope(ig);
755                 }
756
757                 /// <summary>
758                 ///   Returns a temporary storage for a variable of type t as 
759                 ///   a local variable in the current body.
760                 /// </summary>
761                 public LocalBuilder GetTemporaryLocal (Type t)
762                 {
763                         LocalBuilder location = null;
764                         
765                         if (temporary_storage != null){
766                                 object o = temporary_storage [t];
767                                 if (o != null){
768                                         if (o is ArrayList){
769                                                 ArrayList al = (ArrayList) o;
770                                                 
771                                                 for (int i = 0; i < al.Count; i++){
772                                                         if (al [i] != null){
773                                                                 location = (LocalBuilder) al [i];
774                                                                 al [i] = null;
775                                                                 break;
776                                                         }
777                                                 }
778                                         } else
779                                                 location = (LocalBuilder) o;
780                                         if (location != null)
781                                                 return location;
782                                 }
783                         }
784                         
785                         return ig.DeclareLocal (t);
786                 }
787
788                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
789                 {
790                         if (temporary_storage == null){
791                                 temporary_storage = new Hashtable ();
792                                 temporary_storage [t] = b;
793                                 return;
794                         }
795                         object o = temporary_storage [t];
796                         if (o == null){
797                                 temporary_storage [t] = b;
798                                 return;
799                         }
800                         if (o is ArrayList){
801                                 ArrayList al = (ArrayList) o;
802                                 for (int i = 0; i < al.Count; i++){
803                                         if (al [i] == null){
804                                                 al [i] = b;
805                                                 return;
806                                         }
807                                 }
808                                 al.Add (b);
809                                 return;
810                         }
811                         ArrayList replacement = new ArrayList ();
812                         replacement.Add (o);
813                         temporary_storage.Remove (t);
814                         temporary_storage [t] = replacement;
815                 }
816
817                 /// <summary>
818                 ///   Current loop begin and end labels.
819                 /// </summary>
820                 public Label LoopBegin, LoopEnd;
821
822                 /// <summary>
823                 ///   Default target in a switch statement.   Only valid if
824                 ///   InSwitch is true
825                 /// </summary>
826                 public Label DefaultTarget;
827
828                 /// <summary>
829                 ///   If this is non-null, points to the current switch statement
830                 /// </summary>
831                 public Switch Switch;
832
833                 /// <summary>
834                 ///   ReturnValue creates on demand the LocalBuilder for the
835                 ///   return value from the function.  By default this is not
836                 ///   used.  This is only required when returns are found inside
837                 ///   Try or Catch statements.
838                 ///
839                 ///   This method is typically invoked from the Emit phase, so
840                 ///   we allow the creation of a return label if it was not
841                 ///   requested during the resolution phase.   Could be cleaned
842                 ///   up, but it would replicate a lot of logic in the Emit phase
843                 ///   of the code that uses it.
844                 /// </summary>
845                 public LocalBuilder TemporaryReturn ()
846                 {
847                         if (return_value == null){
848                                 return_value = ig.DeclareLocal (ReturnType);
849                                 if (!HasReturnLabel){
850                                         ReturnLabel = ig.DefineLabel ();
851                                         HasReturnLabel = true;
852                                 }
853                         }
854
855                         return return_value;
856                 }
857
858                 /// <summary>
859                 ///   This method is used during the Resolution phase to flag the
860                 ///   need to define the ReturnLabel
861                 /// </summary>
862                 public void NeedReturnLabel ()
863                 {
864                         if (current_phase != Phase.Resolving){
865                                 //
866                                 // The reason is that the `ReturnLabel' is declared between
867                                 // resolution and emission
868                                 // 
869                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
870                         }
871                         
872                         if (!InIterator && !HasReturnLabel) 
873                                 HasReturnLabel = true;
874                 }
875
876                 //
877                 // Emits the proper object to address fields on a remapped
878                 // variable/parameter to field in anonymous-method/iterator proxy classes.
879                 //
880                 public void EmitThis ()
881                 {
882                         ig.Emit (OpCodes.Ldarg_0);
883                         if (capture_context != null && CurrentAnonymousMethod != null){
884                                 ScopeInfo si = CurrentAnonymousMethod.Scope;
885                                 while (si != null){
886                                         if (si.ParentLink != null)
887                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
888                                         if (si.THIS != null){
889                                                 ig.Emit (OpCodes.Ldfld, si.THIS);
890                                                 break;
891                                         }
892                                         si = si.ParentScope;
893                                 }
894                         } 
895                 }
896
897                 //
898                 // Emits the code necessary to load the instance required
899                 // to access the captured LocalInfo
900                 //
901                 public void EmitCapturedVariableInstance (LocalInfo li)
902                 {
903                         if (capture_context == null)
904                                 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
905                         
906                         capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
907                 }
908
909                 public void EmitParameter (string name)
910                 {
911                         capture_context.EmitParameter (this, name);
912                 }
913
914                 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
915                 {
916                         capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
917                 }
918
919                 public void EmitAddressOfParameter (string name)
920                 {
921                         capture_context.EmitAddressOfParameter (this, name);
922                 }
923                 
924                 public Expression GetThis (Location loc)
925                 {
926                         This my_this;
927                         if (CurrentBlock != null)
928                                 my_this = new This (CurrentBlock, loc);
929                         else
930                                 my_this = new This (loc);
931
932                         if (!my_this.ResolveBase (this))
933                                 my_this = null;
934
935                         return my_this;
936                 }
937         }
938
939
940         public abstract class CommonAssemblyModulClass: Attributable {
941                 protected CommonAssemblyModulClass ():
942                         base (null)
943                 {
944                 }
945
946                 public void AddAttributes (ArrayList attrs)
947                 {
948                         if (OptAttributes == null) {
949                                 OptAttributes = new Attributes (attrs);
950                                 return;
951                         }
952                         OptAttributes.AddAttributes (attrs);
953                 }
954
955                 public virtual void Emit (TypeContainer tc) 
956                 {
957                         if (OptAttributes == null)
958                                 return;
959
960                         EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
961                         OptAttributes.Emit (ec, this);
962                 }
963                 
964                 protected Attribute ResolveAttribute (Type a_type)
965                 {
966                         if (OptAttributes == null)
967                                 return null;
968
969                         // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
970                         if (!OptAttributes.CheckTargets (this))
971                                 return null;
972
973                         EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
974                         Attribute a = OptAttributes.Search (a_type, temp_ec);
975                         if (a != null) {
976                                 a.Resolve (temp_ec);
977                         }
978                         return a;
979                 }
980         }
981                 
982         public class AssemblyClass: CommonAssemblyModulClass {
983                 // TODO: make it private and move all builder based methods here
984                 public AssemblyBuilder Builder;
985                 bool is_cls_compliant;
986                 public Attribute ClsCompliantAttribute;
987
988                 ListDictionary declarative_security;
989
990                 // Module is here just because of error messages
991                 static string[] attribute_targets = new string [] { "assembly", "module" };
992
993                 public AssemblyClass (): base ()
994                 {
995                         is_cls_compliant = false;
996                 }
997
998                 public bool IsClsCompliant {
999                         get {
1000                                 return is_cls_compliant;
1001                         }
1002                 }
1003
1004                 public override AttributeTargets AttributeTargets {
1005                         get {
1006                                 return AttributeTargets.Assembly;
1007                         }
1008                 }
1009
1010                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1011                 {
1012                         return is_cls_compliant;
1013                 }
1014
1015                 public void ResolveClsCompliance ()
1016                 {
1017                         ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1018                         if (ClsCompliantAttribute == null)
1019                                 return;
1020
1021                         is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1022                 }
1023
1024                 // fix bug #56621
1025                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1026                 {
1027                         try {
1028                                 // check for possible ECMA key
1029                                 if (strongNameBlob.Length == 16) {
1030                                         // will be rejected if not "the" ECMA key
1031                                         an.SetPublicKey (strongNameBlob);
1032                                 }
1033                                 else {
1034                                         // take it, with or without, a private key
1035                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1036                                         // and make sure we only feed the public part to Sys.Ref
1037                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1038                                         
1039                                         // AssemblyName.SetPublicKey requires an additional header
1040                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1041
1042                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1043                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1044                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1045                                         an.SetPublicKey (encodedPublicKey);
1046                                 }
1047                         }
1048                         catch (Exception) {
1049                                 Error_AssemblySigning ("The speficied file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1050                                 Environment.Exit (1);
1051                         }
1052                 }
1053
1054                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1055                 public AssemblyName GetAssemblyName (string name, string output) 
1056                 {
1057                         if (OptAttributes != null) {
1058                                 foreach (Attribute a in OptAttributes.Attrs) {
1059                                         // cannot rely on any resolve-based members before you call Resolve
1060                                         if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1061                                                 continue;
1062
1063                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1064                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
1065                                         //       are loaded yet.
1066                                         switch (a.Name) {
1067                                                 case "AssemblyKeyFile":
1068                                                 case "AssemblyKeyFileAttribute":
1069                                                 case "System.Reflection.AssemblyKeyFileAttribute":
1070                                                         if (RootContext.StrongNameKeyFile != null) {
1071                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1072                                                                 Report.Warning (1616, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1073                                     "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1074                                                         }
1075                                                         else {
1076                                                                 string value = a.GetString ();
1077                                                                 if (value != String.Empty)
1078                                                                         RootContext.StrongNameKeyFile = value;
1079                                                         }
1080                                                         break;
1081                                                 case "AssemblyKeyName":
1082                                                 case "AssemblyKeyNameAttribute":
1083                                                 case "System.Reflection.AssemblyKeyNameAttribute":
1084                                                         if (RootContext.StrongNameKeyContainer != null) {
1085                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1086                                                                 Report.Warning (1616, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1087                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1088                                                         }
1089                                                         else {
1090                                                                 string value = a.GetString ();
1091                                                                 if (value != String.Empty)
1092                                                                         RootContext.StrongNameKeyContainer = value;
1093                                                         }
1094                                                         break;
1095                                                 case "AssemblyDelaySign":
1096                                                 case "AssemblyDelaySignAttribute":
1097                                                 case "System.Reflection.AssemblyDelaySignAttribute":
1098                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1099                                                         break;
1100                                         }
1101                                 }
1102                         }
1103
1104                         AssemblyName an = new AssemblyName ();
1105                         an.Name = Path.GetFileNameWithoutExtension (name);
1106
1107                         // note: delay doesn't apply when using a key container
1108                         if (RootContext.StrongNameKeyContainer != null) {
1109                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1110                                 return an;
1111                         }
1112
1113                         // strongname is optional
1114                         if (RootContext.StrongNameKeyFile == null)
1115                                 return an;
1116
1117                         string AssemblyDir = Path.GetDirectoryName (output);
1118
1119                         // the StrongName key file may be relative to (a) the compiled
1120                         // file or (b) to the output assembly. See bugzilla #55320
1121                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1122
1123                         // (a) relative to the compiled file
1124                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1125                         bool exist = File.Exists (filename);
1126                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1127                                 // (b) relative to the outputed assembly
1128                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1129                                 exist = File.Exists (filename);
1130                         }
1131
1132                         if (exist) {
1133                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1134                                         byte[] snkeypair = new byte [fs.Length];
1135                                         fs.Read (snkeypair, 0, snkeypair.Length);
1136
1137                                         if (RootContext.StrongNameDelaySign) {
1138                                                 // delayed signing - DO NOT include private key
1139                                                 SetPublicKey (an, snkeypair);
1140                                         }
1141                                         else {
1142                                                 // no delay so we make sure we have the private key
1143                                                 try {
1144                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1145                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1146                                                 }
1147                                                 catch (CryptographicException) {
1148                                                         if (snkeypair.Length == 16) {
1149                                                                 // error # is different for ECMA key
1150                                                                 Report.Error (1606, "Could not sign the assembly. " + 
1151                                                                         "ECMA key can only be used to delay-sign assemblies");
1152                                                         }
1153                                                         else {
1154                                                                 Error_AssemblySigning ("The speficied file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1155                                                         }
1156                                                         return null;
1157                                                 }
1158                                         }
1159                                 }
1160                         }
1161                         else {
1162                                 Error_AssemblySigning ("The speficied file `" + RootContext.StrongNameKeyFile + "' does not exist");
1163                                 return null;
1164                         }
1165                         return an;
1166                 }
1167
1168                 void Error_AssemblySigning (string text)
1169                 {
1170                         Report.Error (1548, "Error during assembly signing. " + text);
1171                 }
1172
1173                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1174                 {
1175                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1176                                 if (declarative_security == null)
1177                                         declarative_security = new ListDictionary ();
1178
1179                                 a.ExtractSecurityPermissionSet (declarative_security);
1180                                 return;
1181                         }
1182
1183                         Builder.SetCustomAttribute (customBuilder);
1184                 }
1185
1186                 public override void Emit (TypeContainer tc)
1187                 {
1188                         base.Emit (tc);
1189
1190                         if (declarative_security != null) {
1191
1192                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1193                                 object builder_instance = Builder;
1194
1195                                 try {
1196                                         // Microsoft runtime hacking
1197                                         if (add_permission == null) {
1198                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1199                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1200
1201                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1202                                                 builder_instance = fi.GetValue (Builder);
1203                                         }
1204
1205                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1206                                                                                                   declarative_security [SecurityAction.RequestOptional],
1207                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1208                                         add_permission.Invoke (builder_instance, args);
1209                                 }
1210                                 catch {
1211                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1212                                 }
1213                         }
1214                 }
1215
1216                 public override string[] ValidAttributeTargets {
1217                         get {
1218                                 return attribute_targets;
1219                         }
1220                 }
1221         }
1222
1223         public class ModuleClass: CommonAssemblyModulClass {
1224                 // TODO: make it private and move all builder based methods here
1225                 public ModuleBuilder Builder;
1226                 bool m_module_is_unsafe;
1227
1228                 public CharSet DefaultCharSet = CharSet.Ansi;
1229                 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1230
1231                 static string[] attribute_targets = new string [] { "module" };
1232
1233                 public ModuleClass (bool is_unsafe)
1234                 {
1235                         m_module_is_unsafe = is_unsafe;
1236                 }
1237
1238                 public override AttributeTargets AttributeTargets {
1239                         get {
1240                                 return AttributeTargets.Module;
1241                         }
1242                 }
1243
1244                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1245                 {
1246                         return CodeGen.Assembly.IsClsCompliant;
1247                 }
1248
1249                 public override void Emit (TypeContainer tc) 
1250                 {
1251                         base.Emit (tc);
1252
1253                         if (!m_module_is_unsafe)
1254                                 return;
1255
1256                         if (TypeManager.unverifiable_code_ctor == null) {
1257                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1258                                 return;
1259                         }
1260                                 
1261                         Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1262                 }
1263                 
1264                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1265                 {
1266                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
1267                                 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1268                                         Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1269                                 }
1270                                 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1271                                         Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1272                                         Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1273                                         return;
1274                                 }
1275                         }
1276
1277                         Builder.SetCustomAttribute (customBuilder);
1278                 }
1279
1280                 /// <summary>
1281                 /// It is called very early therefore can resolve only predefined attributes
1282                 /// </summary>
1283                 public void ResolveAttributes ()
1284                 {
1285 #if NET_2_0
1286                         Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1287                         if (a != null) {
1288                                 DefaultCharSet = a.GetCharSetValue ();
1289                                 switch (DefaultCharSet) {
1290                                         case CharSet.Ansi:
1291                                         case CharSet.None:
1292                                                 break;
1293                                         case CharSet.Auto:
1294                                                 DefaultCharSetType = TypeAttributes.AutoClass;
1295                                                 break;
1296                                         case CharSet.Unicode:
1297                                                 DefaultCharSetType = TypeAttributes.UnicodeClass;
1298                                                 break;
1299                                         default:
1300                                                 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1301                                                 break;
1302                                 }
1303                         }
1304 #endif
1305                 }
1306
1307                 public override string[] ValidAttributeTargets {
1308                         get {
1309                                 return attribute_targets;
1310                         }
1311                 }
1312         }
1313 }