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