2002-07-22 Peter Williams <peterw@ximian.com>
[mono.git] / mcs / mbas / codegen.cs
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.
8 //
9
10 using System;
11 using System.Collections;
12 using System.Reflection;
13 using System.Reflection.Emit;
14 using System.Diagnostics.SymbolStore;
15
16 namespace Mono.CSharp {
17
18         /// <summary>
19         ///    Code generator class.
20         /// </summary>
21         public class CodeGen {
22                 static AppDomain current_domain;
23                 public static AssemblyBuilder AssemblyBuilder;
24                 public static ModuleBuilder   ModuleBuilder;
25
26                 static public ISymbolWriter SymbolWriter;
27
28                 public static string Basename (string name)
29                 {
30                         int pos = name.LastIndexOf ("/");
31
32                         if (pos != -1)
33                                 return name.Substring (pos + 1);
34
35                         pos = name.LastIndexOf ("\\");
36                         if (pos != -1)
37                                 return name.Substring (pos + 1);
38
39                         return name;
40                 }
41
42                 public static string Dirname (string name)
43                 {
44                         int pos = name.LastIndexOf ("/");
45
46                         if (pos != -1)
47                                 return name.Substring (0, pos);
48
49                         pos = name.LastIndexOf ("\\");
50                         if (pos != -1)
51                                 return name.Substring (0, pos);
52
53                         return ".";
54                 }
55
56                 static string TrimExt (string name)
57                 {
58                         int pos = name.LastIndexOf (".");
59
60                         return name.Substring (0, pos);
61                 }
62
63                 static public string FileName;
64
65                 //
66                 // This routine initializes the Mono runtime SymbolWriter.
67                 //
68                 static void InitMonoSymbolWriter (string basename, string[] debug_args)
69                 {
70                         string symbol_output = basename + "-debug.s";
71
72                         Type itype = SymbolWriter.GetType ();
73                         if (itype == null)
74                                 return;
75
76                         Type[] arg_types = new Type [2];
77                         arg_types [0] = typeof (string);
78                         arg_types [1] = typeof (string[]);
79
80                         MethodInfo initialize = itype.GetMethod ("Initialize", arg_types);
81                         if (initialize == null)
82                                 return;
83
84                         object[] args = new object [2];
85                         args [0] = symbol_output;
86                         args [1] = debug_args;
87
88                         initialize.Invoke (SymbolWriter, args);
89                 }
90
91                 //
92                 // Initializes the symbol writer
93                 //
94                 static void InitializeSymbolWriter (string basename, string[] args)
95                 {
96                         SymbolWriter = ModuleBuilder.GetSymWriter ();
97
98                         //
99                         // If we got an ISymbolWriter instance, initialize it.
100                         //
101                         if (SymbolWriter == null)
102                                 return;
103                         
104                         //
105                         // Due to lacking documentation about the first argument of the
106                         // Initialize method, we cannot use Microsoft's default symbol
107                         // writer yet.
108                         //
109                         // If we're using the mono symbol writer, the SymbolWriter object
110                         // is of type MonoSymbolWriter - but that's defined in a dynamically
111                         // loaded DLL - that's why we're doing a comparision based on the type
112                         // name here instead of using `SymbolWriter is MonoSymbolWriter'.
113                         //
114                         Type sym_type = ((object) SymbolWriter).GetType ();
115                         
116                         switch (sym_type.Name){
117                         case "MonoSymbolWriter":
118                                 InitMonoSymbolWriter (basename, args);
119                                 break;
120
121                         default:
122                                 Report.Error (
123                                         -18, "Cannot generate debugging information on this platform");
124                                 break;
125                         }
126                 }
127
128                 //
129                 // Initializes the code generator variables
130                 //
131                 static public void Init (string name, string output, bool want_debugging_support,
132                                          string[] debug_args)
133                 {
134                         AssemblyName an;
135
136                         FileName = output;
137                         an = new AssemblyName ();
138                         an.Name = TrimExt (Basename (name));
139                         current_domain = AppDomain.CurrentDomain;
140                         AssemblyBuilder = current_domain.DefineDynamicAssembly (
141                                 an, AssemblyBuilderAccess.RunAndSave, Dirname (name));
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                         ModuleBuilder = AssemblyBuilder.DefineDynamicModule (
152                                 Basename (name), Basename (output), want_debugging_support);
153
154                         if (want_debugging_support)
155                                 InitializeSymbolWriter (an.Name, debug_args);
156                 }
157
158                 static public void Save (string name)
159                 {
160                         try {
161                                 AssemblyBuilder.Save (Basename (name));
162                         } catch (System.IO.IOException io){
163                                 Report.Error (16, "Coult not write to file `"+name+"', cause: " + io.Message);
164                         }
165                 }
166
167                 static public void SaveSymbols ()
168                 {
169                         if (SymbolWriter != null) {
170                                 // If we have a symbol writer, call its Close() method to write
171                                 // the symbol file to disk.
172                                 //
173                                 // When using Mono's default symbol writer, the Close() method must
174                                 // be called after the assembly has already been written to disk since
175                                 // it opens the assembly and reads its metadata.
176                                 SymbolWriter.Close ();
177                         }
178                 }
179         }
180
181         /// <summary>
182         ///   An Emit Context is created for each body of code (from methods,
183         ///   properties bodies, indexer bodies or constructor bodies)
184         /// </summary>
185         public class EmitContext {
186                 public DeclSpace DeclSpace;
187                 public TypeContainer TypeContainer;
188                 public ILGenerator   ig;
189
190                 /// <summary>
191                 ///   This variable tracks the `checked' state of the compilation,
192                 ///   it controls whether we should generate code that does overflow
193                 ///   checking, or if we generate code that ignores overflows.
194                 ///
195                 ///   The default setting comes from the command line option to generate
196                 ///   checked or unchecked code plus any source code changes using the
197                 ///   checked/unchecked statements or expressions.   Contrast this with
198                 ///   the ConstantCheckState flag.
199                 /// </summary>
200                 
201                 public bool CheckState;
202
203                 /// <summary>
204                 ///   The constant check state is always set to `true' and cant be changed
205                 ///   from the command line.  The source code can change this setting with
206                 ///   the `checked' and `unchecked' statements and expressions. 
207                 /// </summary>
208                 public bool ConstantCheckState;
209
210                 /// <summary>
211                 ///   Whether we are emitting code inside a static or instance method
212                 /// </summary>
213                 public bool IsStatic;
214
215                 /// <summary>
216                 ///   The value that is allowed to be returned or NULL if there is no
217                 ///   return type.
218                 /// </summary>
219                 public Type ReturnType;
220
221                 /// <summary>
222                 ///   Points to the Type (extracted from the TypeContainer) that
223                 ///   declares this body of code
224                 /// </summary>
225                 public Type ContainerType;
226                 
227                 /// <summary>
228                 ///   Whether this is generating code for a constructor
229                 /// </summary>
230                 public bool IsConstructor;
231                 
232                 /// <summary>
233                 ///   Keeps track of the Type to LocalBuilder temporary storage created
234                 ///   to store structures (used to compute the address of the structure
235                 ///   value on structure method invocations)
236                 /// </summary>
237                 public Hashtable temporary_storage;
238
239                 public Block CurrentBlock;
240
241                 /// <summary>
242                 ///   The location where we store the return value.
243                 /// </summary>
244                 LocalBuilder return_value;
245
246                 /// <summary>
247                 ///   The location where return has to jump to return the
248                 ///   value
249                 /// </summary>
250                 public Label ReturnLabel;
251
252                 /// <summary>
253                 ///   Whether we are in a Finally block
254                 /// </summary>
255                 public bool InFinally;
256
257                 /// <summary>
258                 ///   Whether we are in a Try block
259                 /// </summary>
260                 public bool InTry;
261
262                 /// <summary>
263                 ///   Whether we are in a Catch block
264                 /// </summary>
265                 public bool InCatch;
266
267                 /// <summary>
268                 ///  Whether we are inside an unsafe block
269                 /// </summary>
270                 public bool InUnsafe;
271
272                 /// <summary>
273                 ///   Whether we break from a loop or not
274                 /// </summary>
275                 public bool Breaks;
276                 
277                 /// <summary>
278                 ///   Location for this EmitContext
279                 /// </summary>
280                 public Location loc;
281
282                 /// <summary>
283                 ///   Used to "flag" the resolution process to only lookup types,
284                 ///   and nothing else.  This is an out-of-band communication
285                 ///   path to SimpleName from the cast operation.
286                 /// </summary>
287                 public bool OnlyLookupTypes;
288
289                 /// <summary>
290                 ///   Inside an enum definition, we do not resolve enumeration values
291                 ///   to their enumerations, but rather to the underlying type/value
292                 ///   This is so EnumVal + EnumValB can be evaluated.
293                 ///
294                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
295                 ///   we relax the rules
296                 /// </summary>
297                 public bool InEnumContext;
298                 
299                 public EmitContext (TypeContainer parent, DeclSpace ds, Location l, ILGenerator ig,
300                                     Type return_type, int code_flags, bool is_constructor)
301                 {
302                         this.ig = ig;
303
304                         TypeContainer = parent;
305                         DeclSpace = ds;
306                         CheckState = RootContext.Checked;
307                         ConstantCheckState = true;
308                         
309                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
310                         ReturnType = return_type;
311                         IsConstructor = is_constructor;
312                         CurrentBlock = null;
313                         ContainerType = parent.TypeBuilder;
314                         InUnsafe = ((parent.ModFlags | code_flags) & Modifiers.UNSAFE) != 0;
315                         OnlyLookupTypes = false;
316                         loc = l;
317                         
318                         if (ReturnType == TypeManager.void_type)
319                                 ReturnType = null;
320                 }
321
322                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
323                                     Type return_type, int code_flags, bool is_constructor)
324                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
325                 {
326                 }
327
328                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
329                                     Type return_type, int code_flags)
330                         : this (tc, tc, l, ig, return_type, code_flags, false)
331                 {
332                 }
333
334                 public void EmitTopBlock (Block block, Location loc)
335                 {
336                         bool has_ret = false;
337
338 //                      Console.WriteLine ("Emitting: " + loc);
339
340                         if (CodeGen.SymbolWriter != null)
341                                 Mark (loc);
342
343                         if (block != null){
344                                 int errors = Report.Errors;
345
346                                 block.EmitMeta (this, block);
347
348                                 if (Report.Errors == errors){
349                                         if (!block.Resolve (this))
350                                                 return;
351                                         
352                                         has_ret = block.Emit (this);
353
354                                         if (Report.Errors == errors){
355                                                 if (RootContext.WarningLevel >= 3)
356                                                         block.UsageWarning ();
357                                         }
358                                 }
359                         }
360
361                         if (ReturnType != null && !has_ret){
362                                 //
363                                 // FIXME: we need full flow analysis to implement this
364                                 // correctly and emit an error instead of a warning.
365                                 //
366                                 //
367                                 Report.Error (161, loc, "Not all code paths return a value");
368                                 return;
369                         }
370
371                         if (return_value != null){
372                                 ig.MarkLabel (ReturnLabel);
373                                 ig.Emit (OpCodes.Ldloc, return_value);
374                                 ig.Emit (OpCodes.Ret);
375                         } else {
376                                 if (!has_ret){
377                                         if (!InTry)
378                                                 ig.Emit (OpCodes.Ret);
379                                 }
380                         }
381                 }
382
383                 /// <summary>
384                 ///   This is called immediately before emitting an IL opcode to tell the symbol
385                 ///   writer to which source line this opcode belongs.
386                 /// </summary>
387                 public void Mark (Location loc)
388                 {
389                         if (!Location.IsNull (loc)) {
390                                 ISymbolDocumentWriter doc = loc.SymbolDocument;
391
392                                 if (doc != null)
393                                         ig.MarkSequencePoint (doc, loc.Row, 0,  loc.Row, 0);
394                         }               }
395
396
397                 /// <summary>
398                 ///   Returns a temporary storage for a variable of type t as 
399                 ///   a local variable in the current body.
400                 /// </summary>
401                 public LocalBuilder GetTemporaryStorage (Type t)
402                 {
403                         LocalBuilder location;
404                         
405                         if (temporary_storage != null){
406                                 location = (LocalBuilder) temporary_storage [t];
407                                 if (location != null)
408                                         return location;
409                         }
410                         
411                         location = ig.DeclareLocal (t);
412                         
413                         return location;
414                 }
415
416                 public void FreeTemporaryStorage (LocalBuilder b)
417                 {
418                         // Empty for now.
419                 }
420
421                 /// <summary>
422                 ///   Current loop begin and end labels.
423                 /// </summary>
424                 public Label LoopBegin, LoopEnd;
425
426                 /// <summary>
427                 ///   Whether we are inside a loop and break/continue are possible.
428                 /// </summary>
429                 public bool  InLoop;
430
431                 /// <summary>
432                 ///   Default target in a switch statement.   Only valid if
433                 ///   InSwitch is true
434                 /// </summary>
435                 public Label DefaultTarget;
436
437                 /// <summary>
438                 ///   If this is non-null, points to the current switch statement
439                 /// </summary>
440                 public Switch Switch;
441
442                 /// <summary>
443                 ///   ReturnValue creates on demand the LocalBuilder for the
444                 ///   return value from the function.  By default this is not
445                 ///   used.  This is only required when returns are found inside
446                 ///   Try or Catch statements.
447                 /// </summary>
448                 public LocalBuilder TemporaryReturn ()
449                 {
450                         if (return_value == null){
451                                 return_value = ig.DeclareLocal (ReturnType);
452                                 ReturnLabel = ig.DefineLabel ();
453                         }
454
455                         return return_value;
456                 }
457
458                 /// <summary>
459                 ///   A dynamic This that is shared by all variables in a emitcontext.
460                 ///   Created on demand.
461                 /// </summary>
462                 public Expression my_this;
463                 public Expression This {
464                         get {
465                                 if (my_this == null)
466                                         my_this = new This (loc).Resolve (this);
467
468                                 return my_this;
469                         }
470                 }
471         }
472 }