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