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