2005-05-31 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / mcs / rootcontext.cs
1 //
2 // rootcontext.cs: keeps track of our tree representation, and assemblies loaded.
3 //
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 //         Ravi Pratap     (ravi@ximian.com)
6 //
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 Tree tree;
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 = ".exe";
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                         tree = new Tree ();
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                         Version = LanguageVersion.Default;
117                         Documentation = null;
118                         impl_details_class = null;
119                 }
120                 
121                 public static bool NeedsEntryPoint {
122                         get {
123                                 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
124                         }
125                 }
126
127                 static public Tree Tree {
128                         get {
129                                 return tree;
130                         }
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                         TypeContainer root = Tree.Types;
164
165                         ArrayList ifaces = root.Interfaces;
166                         if (ifaces != null){
167                                 foreach (TypeContainer i in ifaces) 
168                                         i.DefineType ();
169                         }
170
171                         foreach (TypeContainer tc in root.Types)
172                                 tc.DefineType ();
173
174                         if (root.Delegates != null)
175                                 foreach (Delegate d in root.Delegates) 
176                                         d.DefineType ();
177
178                         if (root.Enums != null)
179                                 foreach (Enum e in root.Enums)
180                                         e.DefineType ();
181                 }
182
183                 static void Error_TypeConflict (string name, Location loc)
184                 {
185                         Report.Error (
186                                 520, loc, "`" + name + "' conflicts with a predefined type");
187                 }
188
189                 static void Error_TypeConflict (string name)
190                 {
191                         Report.Error (
192                                 520, "`" + name + "' conflicts with a predefined type");
193                 }
194
195                 //
196                 // Resolves a single class during the corlib bootstrap process
197                 //
198                 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
199                 {
200                         object o = root.GetDefinition (name);
201                         if (o == null){
202                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
203                                 return null;
204                         }
205
206                         if (!(o is Class)){
207                                 if (o is DeclSpace){
208                                         DeclSpace d = (DeclSpace) o;
209
210                                         Error_TypeConflict (name, d.Location);
211                                 } else
212                                         Error_TypeConflict (name);
213
214                                 return null;
215                         }
216
217                         return ((DeclSpace) o).DefineType ();
218                 }
219
220                 //
221                 // Resolves a struct during the corlib bootstrap process
222                 //
223                 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
224                 {
225                         object o = root.GetDefinition (name);
226                         if (o == null){
227                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
228                                 return;
229                         }
230
231                         if (!(o is Struct)){
232                                 if (o is DeclSpace){
233                                         DeclSpace d = (DeclSpace) o;
234
235                                         Error_TypeConflict (name, d.Location);
236                                 } else
237                                         Error_TypeConflict (name);
238
239                                 return;
240                         }
241
242                         ((DeclSpace) o).DefineType ();
243                 }
244
245                 //
246                 // Resolves a struct during the corlib bootstrap process
247                 //
248                 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
249                 {
250                         object o = root.GetDefinition (name);
251                         if (o == null){
252                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
253                                 return;
254                         }
255
256                         if (!(o is Interface)){
257                                 if (o is DeclSpace){
258                                         DeclSpace d = (DeclSpace) o;
259
260                                         Error_TypeConflict (name, d.Location);
261                                 } else
262                                         Error_TypeConflict (name);
263
264                                 return;
265                         }
266
267                         ((DeclSpace) o).DefineType ();
268                 }
269
270                 //
271                 // Resolves a delegate during the corlib bootstrap process
272                 //
273                 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
274                 {
275                         object o = root.GetDefinition (name);
276                         if (o == null){
277                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
278                                 return;
279                         }
280
281                         if (!(o is Delegate)){
282                                 Error_TypeConflict (name);
283                                 return;
284                         }
285
286                         ((DeclSpace) o).DefineType ();
287                 }
288                 
289
290                 /// <summary>
291                 ///    Resolves the core types in the compiler when compiling with --nostdlib
292                 /// </summary>
293                 static public void ResolveCore ()
294                 {
295                         TypeContainer root = Tree.Types;
296
297                         TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
298                         TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
299                         TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
300                         TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
301                         
302                         string [] interfaces_first_stage = {
303                                 "System.IComparable", "System.ICloneable",
304                                 "System.IConvertible",
305                                 
306                                 "System.Collections.IEnumerable",
307                                 "System.Collections.ICollection",
308                                 "System.Collections.IEnumerator",
309                                 "System.Collections.IList", 
310                                 "System.IAsyncResult",
311                                 "System.IDisposable",
312                                 
313                                 "System.Runtime.Serialization.ISerializable",
314
315                                 "System.Reflection.IReflect",
316                                 "System.Reflection.ICustomAttributeProvider"
317                         };
318
319                         foreach (string iname in interfaces_first_stage)
320                                 BootstrapCorlib_ResolveInterface (root, iname);
321
322                         //
323                         // These are the base value types
324                         //
325                         string [] structs_first_stage = {
326                                 "System.Byte",    "System.SByte",
327                                 "System.Int16",   "System.UInt16",
328                                 "System.Int32",   "System.UInt32",
329                                 "System.Int64",   "System.UInt64",
330                         };
331
332                         foreach (string cname in structs_first_stage)
333                                 BootstrapCorlib_ResolveStruct (root, cname);
334
335                         //
336                         // Now, we can load the enumerations, after this point,
337                         // we can use enums.
338                         //
339                         TypeManager.InitEnumUnderlyingTypes ();
340
341                         string [] structs_second_stage = {
342                                 "System.Single",  "System.Double",
343                                 "System.Char",    "System.Boolean",
344                                 "System.Decimal", "System.Void",
345                                 "System.RuntimeFieldHandle",
346                                 "System.RuntimeArgumentHandle",
347                                 "System.RuntimeTypeHandle",
348                                 "System.IntPtr",
349                                 "System.TypedReference",
350                                 "System.ArgIterator"
351                         };
352                         
353                         foreach (string cname in structs_second_stage)
354                                 BootstrapCorlib_ResolveStruct (root, cname);
355                         
356                         //
357                         // These are classes that depends on the core interfaces
358                         //
359                         string [] classes_second_stage = {
360                                 "System.Enum",
361                                 "System.String",
362                                 "System.Array",
363                                 "System.Reflection.MemberInfo",
364                                 "System.Type",
365                                 "System.Exception",
366
367                                 //
368                                 // These are not really important in the order, but they
369                                 // are used by the compiler later on (typemanager/CoreLookupType-d)
370                                 //
371                                 "System.Runtime.CompilerServices.RuntimeHelpers",
372                                 "System.Reflection.DefaultMemberAttribute",
373                                 "System.Threading.Monitor",
374                                 
375                                 "System.AttributeUsageAttribute",
376                                 "System.Runtime.InteropServices.DllImportAttribute",
377                                 "System.Runtime.CompilerServices.MethodImplAttribute",
378                                 "System.Runtime.InteropServices.MarshalAsAttribute",
379                                 "System.Diagnostics.ConditionalAttribute",
380                                 "System.ObsoleteAttribute",
381                                 "System.ParamArrayAttribute",
382                                 "System.CLSCompliantAttribute",
383                                 "System.Security.UnverifiableCodeAttribute",
384                                 "System.Security.Permissions.SecurityAttribute",
385                                 "System.Runtime.CompilerServices.DecimalConstantAttribute",
386                                 "System.Runtime.InteropServices.InAttribute",
387                                 "System.Runtime.InteropServices.OutAttribute",
388                                 "System.Runtime.InteropServices.StructLayoutAttribute",
389                                 "System.Runtime.InteropServices.FieldOffsetAttribute",
390                                 "System.InvalidOperationException",
391                                 "System.NotSupportedException",
392                                 "System.MarshalByRefObject",
393                                 "System.Security.CodeAccessPermission",
394                                 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
395                                 "System.Runtime.InteropServices.GuidAttribute"
396                         };
397
398                         foreach (string cname in classes_second_stage)
399                                 BootstrapCorlib_ResolveClass (root, cname);
400
401                         BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
402
403                         // These will be defined indirectly during the previous ResolveDelegate.
404                         // However make sure the rest of the checks happen.
405                         string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
406                         foreach (string cname in delegate_types)
407                                 BootstrapCorlib_ResolveClass (root, cname);
408                 }
409                         
410                 // <summary>
411                 //   Closes all open types
412                 // </summary>
413                 //
414                 // <remarks>
415                 //   We usually use TypeBuilder types.  When we are done
416                 //   creating the type (which will happen after we have added
417                 //   methods, fields, etc) we need to "Define" them before we
418                 //   can save the Assembly
419                 // </remarks>
420                 static public void CloseTypes ()
421                 {
422                         TypeContainer root = Tree.Types;
423                         
424                         if (root.Enums != null)
425                                 foreach (Enum en in root.Enums)
426                                         en.CloseType ();
427
428                         //
429                         // We do this in two passes, first we close the structs,
430                         // then the classes, because it seems the code needs it this
431                         // way.  If this is really what is going on, we should probably
432                         // make sure that we define the structs in order as well.
433                         //
434                         foreach (TypeContainer tc in type_container_resolve_order){
435                                 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
436                                         tc.CloseType ();
437                                 }
438                         }
439
440                         foreach (TypeContainer tc in type_container_resolve_order){
441                                 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
442                                         tc.CloseType ();                                        
443                         }
444                         
445                         if (root.Delegates != null)
446                                 foreach (Delegate d in root.Delegates)
447                                         d.CloseType ();
448
449
450                         //
451                         // If we have a <PrivateImplementationDetails> class, close it
452                         //
453                         if (helper_classes != null){
454                                 foreach (TypeBuilder type_builder in helper_classes) {
455 #if NET_2_0
456                                         type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
457 #endif
458                                         type_builder.CreateType ();
459                                 }
460                         }
461                         
462                         type_container_resolve_order = null;
463                         helper_classes = null;
464                         //tree = null;
465                         TypeManager.CleanUp ();
466                 }
467
468                 /// <summary>
469                 ///   Used to register classes that need to be closed after all the
470                 ///   user defined classes
471                 /// </summary>
472                 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
473                 {
474                         if (helper_classes == null)
475                                 helper_classes = new ArrayList ();
476
477                         helper_classes.Add (helper_class);
478                 }
479                 
480                 static void Report1530 (Location loc)
481                 {
482                         Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
483                 }
484                 
485                 static public void PopulateCoreType (TypeContainer root, string name)
486                 {
487                         DeclSpace ds = (DeclSpace) root.GetDefinition (name);
488
489                         ds.DefineMembers (root);
490                         ds.Define ();
491                 }
492                 
493                 static public void BootCorlib_PopulateCoreTypes ()
494                 {
495                         TypeContainer root = tree.Types;
496
497                         PopulateCoreType (root, "System.Object");
498                         PopulateCoreType (root, "System.ValueType");
499                         PopulateCoreType (root, "System.Attribute");
500                         PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
501                 }
502                 
503                 // <summary>
504                 //   Populates the structs and classes with fields and methods
505                 // </summary>
506                 //
507                 // This is invoked after all interfaces, structs and classes
508                 // have been defined through `ResolveTree' 
509                 static public void PopulateTypes ()
510                 {
511                         TypeContainer root = Tree.Types;
512
513                         if (type_container_resolve_order != null){
514                                 if (RootContext.StdLib){
515                                         foreach (TypeContainer tc in type_container_resolve_order)
516                                                 tc.DefineMembers (root);
517                                 } else {
518                                         foreach (TypeContainer tc in type_container_resolve_order) {
519                                                 // When compiling corlib, these types have already been
520                                                 // populated from BootCorlib_PopulateCoreTypes ().
521                                                 if (((tc.Name == "System.Object") ||
522                                                         (tc.Name == "System.Attribute") ||
523                                                         (tc.Name == "System.ValueType") ||
524                                                         (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
525                                                 continue;
526
527                                                 tc.DefineMembers (root);
528                                         }
529                                 } 
530                         }
531
532                         ArrayList delegates = root.Delegates;
533                         if (delegates != null){
534                                 foreach (Delegate d in delegates)
535                                         if ((d.ModFlags & Modifiers.NEW) == 0)
536                                                 d.DefineMembers (root);
537                                         else
538                                                 Report1530 (d.Location);
539                         }
540
541                         ArrayList enums = root.Enums;
542                         if (enums != null){
543                                 foreach (Enum en in enums)
544                                         if ((en.ModFlags & Modifiers.NEW) == 0)
545                                                 en.DefineMembers (root);
546                                         else
547                                                 Report1530 (en.Location);
548                         }
549
550                         //
551                         // Check for cycles in the struct layout
552                         //
553                         if (type_container_resolve_order != null){
554                                 Hashtable seen = new Hashtable ();
555                                 foreach (TypeContainer tc in type_container_resolve_order)
556                                         TypeManager.CheckStructCycles (tc, seen);
557                         }
558                 }
559
560                 //
561                 // A generic hook delegate
562                 //
563                 public delegate void Hook ();
564
565                 //
566                 // A hook invoked when the code has been generated.
567                 //
568                 public static event Hook EmitCodeHook;
569
570                 //
571                 // DefineTypes is used to fill in the members of each type.
572                 //
573                 static public void DefineTypes ()
574                 {
575                         TypeContainer root = Tree.Types;
576
577                         if (type_container_resolve_order != null){
578                                 foreach (TypeContainer tc in type_container_resolve_order) {
579                                         // When compiling corlib, these types have already been
580                                         // populated from BootCorlib_PopulateCoreTypes ().
581                                         if (!RootContext.StdLib &&
582                                             ((tc.Name == "System.Object") ||
583                                              (tc.Name == "System.Attribute") ||
584                                              (tc.Name == "System.ValueType") ||
585                                              (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
586                                                 continue;
587
588                                         if ((tc.ModFlags & Modifiers.NEW) == 0)
589                                                 tc.Define ();
590                                 }
591                         }
592
593                         ArrayList delegates = root.Delegates;
594                         if (delegates != null){
595                                 foreach (Delegate d in delegates)
596                                         if ((d.ModFlags & Modifiers.NEW) == 0)
597                                                 d.Define ();
598                         }
599
600                         ArrayList enums = root.Enums;
601                         if (enums != null){
602                                 foreach (Enum en in enums)
603                                         if ((en.ModFlags & Modifiers.NEW) == 0)
604                                                 en.Define ();
605                         }
606                 }
607
608                 static public void EmitCode ()
609                 {
610                         if (Tree.Types.Enums != null) {
611                                 foreach (Enum e in Tree.Types.Enums)
612                                         e.Emit ();
613                         }
614
615                         if (type_container_resolve_order != null) {
616                                 foreach (TypeContainer tc in type_container_resolve_order)
617                                         tc.EmitType ();
618
619                                 if (Report.Errors > 0)
620                                         return;
621
622                                 foreach (TypeContainer tc in type_container_resolve_order)
623                                         tc.VerifyMembers ();
624                         }
625                         
626                         if (Tree.Types.Delegates != null) {
627                                 foreach (Delegate d in Tree.Types.Delegates)
628                                         d.Emit ();
629                         }                       
630                         //
631                         // Run any hooks after all the types have been defined.
632                         // This is used to create nested auxiliary classes for example
633                         //
634
635                         if (EmitCodeHook != null)
636                                 EmitCodeHook ();
637
638                         CodeGen.Assembly.Emit (Tree.Types);
639                         CodeGen.Module.Emit (Tree.Types);
640                 }
641                 
642                 //
643                 // Public Field, used to track which method is the public entry
644                 // point.
645                 //
646                 static public MethodInfo EntryPoint;
647
648                 //
649                 // Track the location of the entry point.
650                 //
651                 static public Location EntryPointLocation;
652
653                 //
654                 // These are used to generate unique names on the structs and fields.
655                 //
656                 static int field_count;
657                 
658                 //
659                 // Makes an initialized struct, returns the field builder that
660                 // references the data.  Thanks go to Sergey Chaban for researching
661                 // how to do this.  And coming up with a shorter mechanism than I
662                 // was able to figure out.
663                 //
664                 // This works but makes an implicit public struct $ArrayType$SIZE and
665                 // makes the fields point to it.  We could get more control if we did
666                 // use instead:
667                 //
668                 // 1. DefineNestedType on the impl_details_class with our struct.
669                 //
670                 // 2. Define the field on the impl_details_class
671                 //
672                 static public FieldBuilder MakeStaticData (byte [] data)
673                 {
674                         FieldBuilder fb;
675                         
676                         if (impl_details_class == null){
677                                 impl_details_class = CodeGen.Module.Builder.DefineType (
678                                         "<PrivateImplementationDetails>",
679                                         TypeAttributes.NotPublic,
680                                         TypeManager.object_type);
681                                 
682                                 RegisterCompilerGeneratedType (impl_details_class);
683                         }
684
685                         fb = impl_details_class.DefineInitializedData (
686                                 "$$field-" + (field_count++), data,
687                                 FieldAttributes.Static | FieldAttributes.Assembly);
688                         
689                         return fb;
690                 }
691         }
692 }
693               
694