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