2007-10-17 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / mcs / rootcontext.cs
1 //
2 // rootcontext.cs: keeps track of our tree representation, and assemblies loaded.
3 //
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 //            Ravi Pratap  (ravi@ximian.com)
6 //            Marek Safar  (marek.safar@gmail.com)
7 //
8 //
9 // Licensed under the terms of the GNU GPL
10 //
11 // (C) 2001 Ximian, Inc (http://www.ximian.com)
12 // (C) 2004 Novell, Inc
13
14 using System;
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Diagnostics;
19
20 namespace Mono.CSharp {
21
22         public enum LanguageVersion
23         {
24                 ISO_1   = 1,
25                 ISO_2   = 2,
26                 LINQ    = 3,
27
28                 Default = ISO_2
29         }
30
31         public class RootContext {
32
33                 //
34                 // Contains the parsed tree
35                 //
36                 static RootTypes root;
37
38                 //
39                 // This hashtable contains all of the #definitions across the source code
40                 // it is used by the ConditionalAttribute handler.
41                 //
42                 public static Hashtable AllDefines = new Hashtable ();
43                 
44                 //
45                 // Whether we are being linked against the standard libraries.
46                 // This is only used to tell whether `System.Object' should
47                 // have a base class or not.
48                 //
49                 public static bool StdLib;
50
51                 //
52                 // This keeps track of the order in which classes were defined
53                 // so that we can poulate them in that order.
54                 //
55                 // Order is important, because we need to be able to tell, by
56                 // examining the list of methods of the base class, which ones are virtual
57                 // or abstract as well as the parent names (to implement new, 
58                 // override).
59                 //
60                 static ArrayList type_container_resolve_order;
61
62                 //
63                 // Holds a reference to the Private Implementation Details
64                 // class.
65                 //
66                 static ArrayList helper_classes;
67                 
68                 static TypeBuilder impl_details_class;
69
70                 public static Target Target;
71                 public static string TargetExt;
72
73                 public static bool VerifyClsCompliance = true;
74
75                 /// <summary>
76                 /// Holds /optimize option
77                 /// </summary>
78                 public static bool Optimize = true;
79
80                 public static LanguageVersion Version;
81
82                 //
83                 // We keep strongname related info here because
84                 // it's also used as complier options from CSC 8.x
85                 //
86                 public static string StrongNameKeyFile;
87                 public static string StrongNameKeyContainer;
88                 public static bool StrongNameDelaySign;
89
90                 //
91                 // If set, enable XML documentation generation
92                 //
93                 public static Documentation Documentation;
94
95                 static public string MainClass;
96
97                 //
98                 // Constructor
99                 //
100                 static RootContext ()
101                 {
102                         Reset ();
103                 }
104
105                 public static void Reset ()
106                 {
107                         root = new RootTypes ();
108                         type_container_resolve_order = new ArrayList ();
109                         EntryPoint = null;
110                         Report.WarningLevel = 3;
111                         Checked = false;
112                         Unsafe = false;
113                         StdLib = true;
114                         StrongNameKeyFile = null;
115                         StrongNameKeyContainer = null;
116                         StrongNameDelaySign = false;
117                         MainClass = null;
118                         Target = Target.Exe;
119                         TargetExt = ".exe";
120                         Version = LanguageVersion.Default;
121                         Documentation = null;
122                         impl_details_class = null;
123                         helper_classes = null;
124                 }
125
126                 public static bool NeedsEntryPoint {
127                         get { return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe; }
128                 }
129
130                 static public RootTypes ToplevelTypes {
131                         get { return root; }
132                 }
133
134                 public static void RegisterOrder (TypeContainer tc)
135                 {
136                         type_container_resolve_order.Add (tc);
137                 }
138                 
139                 // 
140                 // The default compiler checked state
141                 //
142                 static public bool Checked;
143
144                 //
145                 // Whether to allow Unsafe code
146                 //
147                 static public bool Unsafe;
148                 
149                 // <remarks>
150                 //   This function is used to resolve the hierarchy tree.
151                 //   It processes interfaces, structs and classes in that order.
152                 //
153                 //   It creates the TypeBuilder's as it processes the user defined
154                 //   types.  
155                 // </remarks>
156                 static public void ResolveTree ()
157                 {
158                         //
159                         // Interfaces are processed next, as classes and
160                         // structs might inherit from an object or implement
161                         // a set of interfaces, we need to be able to tell
162                         // them appart by just using the TypeManager.
163                         //
164                         foreach (TypeContainer tc in root.Types)
165                                 tc.CreateType ();
166
167                         foreach (TypeContainer tc in root.Types)
168                                 tc.DefineType ();
169
170                         if (root.Delegates != null)
171                                 foreach (Delegate d in root.Delegates) 
172                                         d.DefineType ();
173                 }
174
175                 delegate bool VerifyBootstrapType (Type t);
176
177                 static Type BootstrapCorlib_ResolveType (TypeContainer root, string name, VerifyBootstrapType typeVerifier)
178                 {
179                         TypeLookupExpression tle = new TypeLookupExpression (name);
180                         Report.DisableReporting ();
181                         TypeExpr te = tle.ResolveAsTypeTerminal (root, false);
182                         Report.EnableReporting ();
183                         if (te == null) {
184                                 Report.Error (518, "The predefined type `{0}' is not defined or imported", name);
185                                 return null;
186                         }
187
188                         Type t = te.Type;
189                         if (!typeVerifier (t)) {
190                                 MemberCore mc = root.GetDefinition (name);
191                                 Location loc = Location.Null;
192                                 if (mc != null) {
193                                         name = mc.GetSignatureForError ();
194                                         loc = mc.Location;
195                                 }
196
197                                 Report.Error (520, loc, "The predefined type `{0}' is not declared correctly", name);
198                                 return null;
199                         }
200
201                         AttributeTester.RegisterNonObsoleteType (t);
202                         return t;
203                 }
204                 //
205                 // Resolves a single class during the corlib bootstrap process
206                 //
207                 static Type BootstrapCorlib_ResolveClass (TypeContainer root, string name)
208                 {
209                         return BootstrapCorlib_ResolveType (root, name, IsClass);
210                 }
211
212                 static bool IsClass (Type t)
213                 {
214                         DeclSpace ds = TypeManager.LookupDeclSpace (t);
215                         if (ds != null)
216                                 return ds is Class;
217                         return t.IsClass;
218                 }
219
220                 //
221                 // Resolves a struct during the corlib bootstrap process
222                 //
223                 static Type BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
224                 {
225                         return BootstrapCorlib_ResolveType (root, name, IsStruct);
226                 }
227
228                 static bool IsStruct (Type t)
229                 {
230                         DeclSpace ds = TypeManager.LookupDeclSpace (t);
231                         if (ds != null)
232                                 return ds is Struct;
233                         
234                         return TypeManager.IsSubclassOf (t, TypeManager.value_type);                    
235                 }
236
237                 //
238                 // Resolves an interface during the corlib bootstrap process
239                 //
240                 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
241                 {
242                         BootstrapCorlib_ResolveType (root, name, IsInterface);
243                 }
244
245                 static bool IsInterface (Type t)
246                 {
247                         return t.IsInterface;
248                 }
249
250                 //
251                 // Resolves a delegate during the corlib bootstrap process
252                 //
253                 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
254                 {
255                         BootstrapCorlib_ResolveType (root, name, IsDelegate);
256                 }
257
258                 static bool IsDelegate (Type t)
259                 {
260                         return TypeManager.IsDelegateType (t);
261                 }
262
263                 /// <summary>
264                 ///    Resolves the core types in the compiler when compiling with --nostdlib
265                 /// </summary>
266                 static public void ResolveCore ()
267                 {
268                         TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
269                         TypeManager.system_object_expr.Type = TypeManager.object_type;
270                         TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
271                         TypeManager.system_valuetype_expr.Type = TypeManager.value_type;
272
273                         //
274                         // The core attributes
275                         //
276                         BootstrapCorlib_ResolveInterface (root, "System.Runtime.InteropServices._Attribute");
277                         TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
278                         TypeManager.obsolete_attribute_type = BootstrapCorlib_ResolveClass (root, "System.ObsoleteAttribute");
279                         TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
280                         
281                         string [] interfaces_first_stage = {
282                                 "System.IComparable", "System.ICloneable",
283                                 "System.IConvertible",
284                                 
285                                 "System.Collections.IEnumerable",
286                                 "System.Collections.ICollection",
287                                 "System.Collections.IEnumerator",
288                                 "System.Collections.IList", 
289                                 "System.IAsyncResult",
290                                 "System.IDisposable",
291                                 
292                                 "System.Runtime.Serialization.ISerializable",
293
294                                 "System.Reflection.IReflect",
295                                 "System.Reflection.ICustomAttributeProvider",
296 #if GMCS_SOURCE
297                                 "System.Runtime.InteropServices._Exception",
298
299                                 //
300                                 // Generic types
301                                 //
302                                 "System.Collections.Generic.IEnumerator`1",
303                                 "System.Collections.Generic.IEnumerable`1"
304 #endif
305                         };
306
307                         foreach (string iname in interfaces_first_stage)
308                                 BootstrapCorlib_ResolveInterface (root, iname);
309
310                         //
311                         // These are the base value types
312                         //
313                         string [] structs_first_stage = {
314                                 "System.Byte",    "System.SByte",
315                                 "System.Int16",   "System.UInt16",
316                                 "System.Int32",   "System.UInt32",
317                                 "System.Int64",   "System.UInt64",
318                         };
319                         
320                         foreach (string cname in structs_first_stage)
321                                 BootstrapCorlib_ResolveStruct (root, cname);
322
323                         //
324                         // Now, we can load the enumerations, after this point,
325                         // we can use enums.
326                         //
327                         TypeManager.InitEnumUnderlyingTypes ();
328
329                         string [] structs_second_stage = {
330                                 "System.Single",  "System.Double",
331                                 "System.Char",
332                                 "System.Decimal", "System.Void",
333                                 "System.RuntimeFieldHandle",
334                                 "System.RuntimeArgumentHandle",
335                                 "System.RuntimeTypeHandle",
336                                 "System.IntPtr",
337                                 "System.TypedReference",
338                                 "System.ArgIterator"
339                         };
340                         
341                         TypeManager.bool_type = BootstrapCorlib_ResolveStruct (root, "System.Boolean");
342                         
343                         foreach (string cname in structs_second_stage)
344                                 BootstrapCorlib_ResolveStruct (root, cname);
345                         
346                         //
347                         // These are classes that depends on the core interfaces
348                         //
349                         string [] classes_second_stage = {
350                                 "System.Enum",
351                                 "System.String",
352                                 "System.Array",
353                                 "System.Reflection.MemberInfo",
354                                 "System.Type",
355                                 "System.Exception",
356 #if GMCS_SOURCE
357                                 "System.Activator",
358 #endif
359
360                                 //
361                                 // These are not really important in the order, but they
362                                 // are used by the compiler later on (typemanager/CoreLookupType-d)
363                                 //
364                                 "System.Runtime.CompilerServices.RuntimeHelpers",
365                                 "System.Reflection.DefaultMemberAttribute",
366                                 "System.Threading.Monitor",
367                                 "System.Threading.Interlocked",
368                                 
369                                 "System.AttributeUsageAttribute",
370                                 "System.Runtime.InteropServices.DllImportAttribute",
371                                 "System.Runtime.CompilerServices.MethodImplAttribute",
372                                 "System.Runtime.InteropServices.MarshalAsAttribute",
373 #if GMCS_SOURCE
374                                 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
375                                 "System.Runtime.CompilerServices.FixedBufferAttribute",
376 #endif
377                                 "System.Diagnostics.ConditionalAttribute",
378                                 "System.ParamArrayAttribute",
379                                 "System.CLSCompliantAttribute",
380                                 "System.Security.UnverifiableCodeAttribute",
381                                 "System.Security.Permissions.SecurityAttribute",
382                                 "System.Runtime.CompilerServices.DecimalConstantAttribute",
383                                 "System.Runtime.InteropServices.InAttribute",
384                                 "System.Runtime.InteropServices.OutAttribute",
385                                 "System.Runtime.InteropServices.StructLayoutAttribute",
386                                 "System.Runtime.InteropServices.FieldOffsetAttribute",
387 #if GMCS_SOURCE
388                                 "System.Runtime.InteropServices.DefaultCharSetAttribute",
389 #endif
390                                 "System.InvalidOperationException",
391                                 "System.NotSupportedException",
392                                 "System.MarshalByRefObject",
393                                 "System.Security.CodeAccessPermission",
394                                 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
395                                 "System.Runtime.InteropServices.GuidAttribute",
396                                 "System.Reflection.AssemblyCultureAttribute"
397                         };
398
399                         foreach (string cname in classes_second_stage)
400                                 BootstrapCorlib_ResolveClass (root, cname);
401 #if GMCS_SOURCE
402                         BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
403 #endif
404                         TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
405                         BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
406
407                         BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
408                 }
409                         
410                 // <summary>
411                 //   Closes all open types
412                 // </summary>
413                 //
414                 // <remarks>
415                 //   We usually use TypeBuilder types.  When we are done
416                 //   creating the type (which will happen after we have added
417                 //   methods, fields, etc) we need to "Define" them before we
418                 //   can save the Assembly
419                 // </remarks>
420                 static public void CloseTypes ()
421                 {
422                         //
423                         // We do this in two passes, first we close the structs,
424                         // then the classes, because it seems the code needs it this
425                         // way.  If this is really what is going on, we should probably
426                         // make sure that we define the structs in order as well.
427                         //
428                         foreach (TypeContainer tc in type_container_resolve_order){
429                                 if (tc.Kind == Kind.Struct && tc.Parent == root){
430                                         tc.CloseType ();
431                                 }
432                         }
433
434                         foreach (TypeContainer tc in type_container_resolve_order){
435                                 if (!(tc.Kind == Kind.Struct && tc.Parent == root))
436                                         tc.CloseType ();                                        
437                         }
438                         
439                         if (root.Delegates != null)
440                                 foreach (Delegate d in root.Delegates)
441                                         d.CloseType ();
442
443
444                         //
445                         // If we have a <PrivateImplementationDetails> class, close it
446                         //
447                         if (helper_classes != null){
448                                 foreach (TypeBuilder type_builder in helper_classes) {
449 #if GMCS_SOURCE
450                                         type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
451 #endif
452                                         type_builder.CreateType ();
453                                 }
454                         }
455                         
456                         type_container_resolve_order = null;
457                         helper_classes = null;
458                         //root = null;
459                         TypeManager.CleanUp ();
460                 }
461
462                 /// <summary>
463                 ///   Used to register classes that need to be closed after all the
464                 ///   user defined classes
465                 /// </summary>
466                 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
467                 {
468                         if (helper_classes == null)
469                                 helper_classes = new ArrayList ();
470
471                         helper_classes.Add (helper_class);
472                 }
473                 
474                 static public void PopulateCoreType (TypeContainer root, string name)
475                 {
476                         DeclSpace ds = (DeclSpace) root.GetDefinition (name);
477                         // Core type was imported
478                         if (ds == null)
479                                 return;
480
481                         ds.DefineMembers ();
482                         ds.Define ();
483                 }
484                 
485                 static public void BootCorlib_PopulateCoreTypes ()
486                 {
487                         PopulateCoreType (root, "System.Object");
488                         PopulateCoreType (root, "System.ValueType");
489                         PopulateCoreType (root, "System.Attribute");
490                         PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
491                 }
492                 
493                 // <summary>
494                 //   Populates the structs and classes with fields and methods
495                 // </summary>
496                 //
497                 // This is invoked after all interfaces, structs and classes
498                 // have been defined through `ResolveTree' 
499                 static public void PopulateTypes ()
500                 {
501
502                         if (type_container_resolve_order != null){
503                                 foreach (TypeContainer tc in type_container_resolve_order)
504                                         tc.ResolveType ();
505                                 foreach (TypeContainer tc in type_container_resolve_order)
506                                         tc.DefineMembers ();
507                         }
508
509                         ArrayList delegates = root.Delegates;
510                         if (delegates != null){
511                                 foreach (Delegate d in delegates)
512                                         d.DefineMembers ();
513                         }
514
515                         //
516                         // Check for cycles in the struct layout
517                         //
518                         if (type_container_resolve_order != null){
519                                 Hashtable seen = new Hashtable ();
520                                 foreach (TypeContainer tc in type_container_resolve_order)
521                                         TypeManager.CheckStructCycles (tc, seen);
522                         }
523                 }
524
525                 //
526                 // A generic hook delegate
527                 //
528                 public delegate void Hook ();
529
530                 //
531                 // A hook invoked when the code has been generated.
532                 //
533                 public static event Hook EmitCodeHook;
534
535                 //
536                 // DefineTypes is used to fill in the members of each type.
537                 //
538                 static public void DefineTypes ()
539                 {
540                         ArrayList delegates = root.Delegates;
541                         if (delegates != null){
542                                 foreach (Delegate d in delegates)
543                                         d.Define ();
544                         }
545
546                         if (type_container_resolve_order != null){
547                                 foreach (TypeContainer tc in type_container_resolve_order) {
548                                         // When compiling corlib, these types have already been
549                                         // populated from BootCorlib_PopulateCoreTypes ().
550                                         if (!RootContext.StdLib &&
551                                             ((tc.Name == "System.Object") ||
552                                              (tc.Name == "System.Attribute") ||
553                                              (tc.Name == "System.ValueType") ||
554                                              (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
555                                                 continue;
556
557                                         tc.Define ();
558                                 }
559                         }
560                 }
561
562                 static public void EmitCode ()
563                 {
564                         if (type_container_resolve_order != null) {
565                                 foreach (TypeContainer tc in type_container_resolve_order)
566                                         tc.EmitType ();
567
568                                 if (Report.Errors > 0)
569                                         return;
570
571                                 foreach (TypeContainer tc in type_container_resolve_order)
572                                         tc.VerifyMembers ();
573                         }
574                         
575                         if (root.Delegates != null) {
576                                 foreach (Delegate d in root.Delegates)
577                                         d.Emit ();
578                         }                       
579                         //
580                         // Run any hooks after all the types have been defined.
581                         // This is used to create nested auxiliary classes for example
582                         //
583
584                         if (EmitCodeHook != null)
585                                 EmitCodeHook ();
586
587                         CodeGen.Assembly.Emit (root);
588                         CodeGen.Module.Emit (root);
589                 }
590                 
591                 //
592                 // Public Field, used to track which method is the public entry
593                 // point.
594                 //
595                 static public MethodInfo EntryPoint;
596
597                 //
598                 // Track the location of the entry point.
599                 //
600                 static public Location EntryPointLocation;
601
602                 //
603                 // These are used to generate unique names on the structs and fields.
604                 //
605                 static int field_count;
606                 
607                 //
608                 // Makes an initialized struct, returns the field builder that
609                 // references the data.  Thanks go to Sergey Chaban for researching
610                 // how to do this.  And coming up with a shorter mechanism than I
611                 // was able to figure out.
612                 //
613                 // This works but makes an implicit public struct $ArrayType$SIZE and
614                 // makes the fields point to it.  We could get more control if we did
615                 // use instead:
616                 //
617                 // 1. DefineNestedType on the impl_details_class with our struct.
618                 //
619                 // 2. Define the field on the impl_details_class
620                 //
621                 static public FieldBuilder MakeStaticData (byte [] data)
622                 {
623                         FieldBuilder fb;
624                         
625                         if (impl_details_class == null){
626                                 impl_details_class = CodeGen.Module.Builder.DefineType (
627                                         "<PrivateImplementationDetails>",
628                                         TypeAttributes.NotPublic,
629                                         TypeManager.object_type);
630                                 
631                                 RegisterCompilerGeneratedType (impl_details_class);
632                         }
633
634                         fb = impl_details_class.DefineInitializedData (
635                                 "$$field-" + (field_count++), data,
636                                 FieldAttributes.Static | FieldAttributes.Assembly);
637                         
638                         return fb;
639                 }
640
641                 public static void CheckUnsafeOption (Location loc)
642                 {
643                         if (!Unsafe) {
644                                 Report.Error (227, loc, 
645                                         "Unsafe code requires the `unsafe' command line option to be specified");
646                         }
647                 }
648         }
649 }
650               
651