2005-02-14 Cesar Lopez Nataren <cnataren@novell.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 = true;
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                 static ArrayList attribute_types;
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 = 3;
67                 
68                 public static Target Target = Target.Exe;
69                 public static string TargetExt = ".exe";
70
71                 public static bool VerifyClsCompliance = true;
72
73                 public static LanguageVersion Version = LanguageVersion.Default;
74
75                 //
76                 // We keep strongname related info here because
77                 // it's also used as complier options from CSC 8.x
78                 //
79                 public static string StrongNameKeyFile;
80                 public static string StrongNameKeyContainer;
81                 public static bool StrongNameDelaySign = false;
82
83                 //
84                 // If set, enable XML documentation generation
85                 //
86                 public static Documentation Documentation;
87
88                 //
89                 // Constructor
90                 //
91                 static RootContext ()
92                 {
93                         tree = new Tree ();
94                         type_container_resolve_order = new ArrayList ();
95                 }
96                 
97                 public static bool NeedsEntryPoint {
98                         get {
99                                 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
100                         }
101                 }
102
103                 static public Tree Tree {
104                         get {
105                                 return tree;
106                         }
107                 }
108
109                 static public string MainClass;
110                 
111                 public static void RegisterOrder (TypeContainer tc)
112                 {
113                         type_container_resolve_order.Add (tc);
114                 }
115
116                 public static void RegisterAttribute (TypeContainer tc)
117                 {
118                         if (attribute_types == null)
119                                 attribute_types = new ArrayList ();
120                         
121                         attribute_types.Add (tc);
122                 }
123                 
124                 // 
125                 // The default compiler checked state
126                 //
127                 static public bool Checked = false;
128
129                 //
130                 // Whether to allow Unsafe code
131                 //
132                 static public bool Unsafe = false;
133                 
134                 static string MakeFQN (string nsn, string name)
135                 {
136                         if (nsn == "")
137                                 return name;
138                         return String.Concat (nsn, ".", name);
139                 }
140
141                 // <remarks>
142                 //   This function is used to resolve the hierarchy tree.
143                 //   It processes interfaces, structs and classes in that order.
144                 //
145                 //   It creates the TypeBuilder's as it processes the user defined
146                 //   types.  
147                 // </remarks>
148                 static public void ResolveTree ()
149                 {
150                         //
151                         // Process the attribute types separately and before anything else
152                         //
153                         if (attribute_types != null)
154                                 foreach (TypeContainer tc in attribute_types)
155                                         tc.DefineType ();
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 (Interface 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                                 Environment.Exit (1);
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                         
301                         string [] interfaces_first_stage = {
302                                 "System.IComparable", "System.ICloneable",
303                                 "System.IConvertible",
304                                 
305                                 "System.Collections.IEnumerable",
306                                 "System.Collections.ICollection",
307                                 "System.Collections.IEnumerator",
308                                 "System.Collections.IList", 
309                                 "System.IAsyncResult",
310                                 "System.IDisposable",
311                                 
312                                 "System.Runtime.Serialization.ISerializable",
313
314                                 "System.Reflection.IReflect",
315                                 "System.Reflection.ICustomAttributeProvider"
316                         };
317
318                         foreach (string iname in interfaces_first_stage)
319                                 BootstrapCorlib_ResolveInterface (root, iname);
320
321                         //
322                         // These are the base value types
323                         //
324                         string [] structs_first_stage = {
325                                 "System.Byte",    "System.SByte",
326                                 "System.Int16",   "System.UInt16",
327                                 "System.Int32",   "System.UInt32",
328                                 "System.Int64",   "System.UInt64",
329                         };
330
331                         foreach (string cname in structs_first_stage)
332                                 BootstrapCorlib_ResolveStruct (root, cname);
333
334                         //
335                         // Now, we can load the enumerations, after this point,
336                         // we can use enums.
337                         //
338                         TypeManager.InitEnumUnderlyingTypes ();
339
340                         string [] structs_second_stage = {
341                                 "System.Single",  "System.Double",
342                                 "System.Char",    "System.Boolean",
343                                 "System.Decimal", "System.Void",
344                                 "System.RuntimeFieldHandle",
345                                 "System.RuntimeArgumentHandle",
346                                 "System.RuntimeTypeHandle",
347                                 "System.IntPtr",
348                                 "System.TypedReference",
349                                 "System.ArgIterator"
350                         };
351                         
352                         foreach (string cname in structs_second_stage)
353                                 BootstrapCorlib_ResolveStruct (root, cname);
354                         
355                         //
356                         // These are classes that depends on the core interfaces
357                         //
358                         string [] classes_second_stage = {
359                                 "System.Enum",
360                                 "System.String",
361                                 "System.Array",
362                                 "System.Reflection.MemberInfo",
363                                 "System.Type",
364                                 "System.Exception",
365
366                                 //
367                                 // These are not really important in the order, but they
368                                 // are used by the compiler later on (typemanager/CoreLookupType-d)
369                                 //
370                                 "System.Runtime.CompilerServices.RuntimeHelpers",
371                                 "System.Reflection.DefaultMemberAttribute",
372                                 "System.Threading.Monitor",
373                                 
374                                 "System.AttributeUsageAttribute",
375                                 "System.Runtime.InteropServices.DllImportAttribute",
376                                 "System.Runtime.CompilerServices.MethodImplAttribute",
377                                 "System.Runtime.InteropServices.MarshalAsAttribute",
378                                 "System.Diagnostics.ConditionalAttribute",
379                                 "System.ObsoleteAttribute",
380                                 "System.ParamArrayAttribute",
381                                 "System.CLSCompliantAttribute",
382                                 "System.Security.UnverifiableCodeAttribute",
383                                 "System.Security.Permissions.SecurityAttribute",
384                                 "System.Runtime.CompilerServices.IndexerNameAttribute",
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                         };
395
396                         foreach (string cname in classes_second_stage)
397                                 BootstrapCorlib_ResolveClass (root, cname);
398
399                         BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
400
401                         // These will be defined indirectly during the previous ResolveDelegate.
402                         // However make sure the rest of the checks happen.
403                         string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
404                         foreach (string cname in delegate_types)
405                                 BootstrapCorlib_ResolveClass (root, cname);
406                 }
407                         
408                 // <summary>
409                 //   Closes all open types
410                 // </summary>
411                 //
412                 // <remarks>
413                 //   We usually use TypeBuilder types.  When we are done
414                 //   creating the type (which will happen after we have added
415                 //   methods, fields, etc) we need to "Define" them before we
416                 //   can save the Assembly
417                 // </remarks>
418                 static public void CloseTypes ()
419                 {
420                         TypeContainer root = Tree.Types;
421                         
422                         if (root.Enums != null)
423                                 foreach (Enum en in root.Enums)
424                                         en.CloseType ();
425
426                         if (attribute_types != null)
427                                 foreach (TypeContainer tc in attribute_types)
428                                         tc.CloseType ();
429                         
430                         //
431                         // We do this in two passes, first we close the structs,
432                         // then the classes, because it seems the code needs it this
433                         // way.  If this is really what is going on, we should probably
434                         // make sure that we define the structs in order as well.
435                         //
436                         foreach (TypeContainer tc in type_container_resolve_order){
437                                 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
438                                         tc.CloseType ();
439                                 }
440                         }
441
442                         foreach (TypeContainer tc in type_container_resolve_order){
443                                 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
444                                         tc.CloseType ();                                        
445                         }
446                         
447                         if (root.Delegates != null)
448                                 foreach (Delegate d in root.Delegates)
449                                         d.CloseType ();
450
451
452                         //
453                         // If we have a <PrivateImplementationDetails> class, close it
454                         //
455                         if (helper_classes != null){
456                                 foreach (TypeBuilder type_builder in helper_classes) {
457 #if NET_2_0
458                                         type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
459 #endif
460                                         type_builder.CreateType ();
461                                 }
462                         }
463                         
464                         attribute_types = null;
465                         type_container_resolve_order = null;
466                         helper_classes = null;
467                         //tree = null;
468                         TypeManager.CleanUp ();
469                 }
470
471                 /// <summary>
472                 ///   Used to register classes that need to be closed after all the
473                 ///   user defined classes
474                 /// </summary>
475                 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
476                 {
477                         if (helper_classes == null)
478                                 helper_classes = new ArrayList ();
479
480                         helper_classes.Add (helper_class);
481                 }
482                 
483                 static void Report1530 (Location loc)
484                 {
485                         Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
486                 }
487                 
488                 static public void PopulateCoreType (TypeContainer root, string name)
489                 {
490                         DeclSpace ds = (DeclSpace) root.GetDefinition (name);
491
492                         ds.DefineMembers (root);
493                         ds.Define ();
494                 }
495                 
496                 static public void BootCorlib_PopulateCoreTypes ()
497                 {
498                         TypeContainer root = tree.Types;
499
500                         PopulateCoreType (root, "System.Object");
501                         PopulateCoreType (root, "System.ValueType");
502                         PopulateCoreType (root, "System.Attribute");
503                 }
504                 
505                 // <summary>
506                 //   Populates the structs and classes with fields and methods
507                 // </summary>
508                 //
509                 // This is invoked after all interfaces, structs and classes
510                 // have been defined through `ResolveTree' 
511                 static public void PopulateTypes ()
512                 {
513                         TypeContainer root = Tree.Types;
514
515                         if (attribute_types != null)
516                                 foreach (TypeContainer tc in attribute_types)
517                                         tc.DefineMembers (root);
518                         
519                         if (type_container_resolve_order != null){
520                                 if (RootContext.StdLib){
521                                         foreach (TypeContainer tc in type_container_resolve_order)
522                                                 tc.DefineMembers (root);
523                                 } else {
524                                         foreach (TypeContainer tc in type_container_resolve_order) {
525                                                 // When compiling corlib, these types have already been
526                                                 // populated from BootCorlib_PopulateCoreTypes ().
527                                                 if (((tc.Name == "System.Object") ||
528                                                      (tc.Name == "System.Attribute") ||
529                                                      (tc.Name == "System.ValueType")))
530                                                 continue;
531
532                                                 tc.DefineMembers (root);
533                                         }
534                                 } 
535                         }
536
537                         ArrayList delegates = root.Delegates;
538                         if (delegates != null){
539                                 foreach (Delegate d in delegates)
540                                         if ((d.ModFlags & Modifiers.NEW) == 0)
541                                                 d.DefineMembers (root);
542                                         else
543                                                 Report1530 (d.Location);
544                         }
545
546                         ArrayList enums = root.Enums;
547                         if (enums != null){
548                                 foreach (Enum en in enums)
549                                         if ((en.ModFlags & Modifiers.NEW) == 0)
550                                                 en.DefineMembers (root);
551                                         else
552                                                 Report1530 (en.Location);
553                         }
554
555                         //
556                         // Check for cycles in the struct layout
557                         //
558                         if (type_container_resolve_order != null){
559                                 Hashtable seen = new Hashtable ();
560                                 foreach (TypeContainer tc in type_container_resolve_order)
561                                         TypeManager.CheckStructCycles (tc, seen);
562                         }
563                 }
564
565                 //
566                 // A generic hook delegate
567                 //
568                 public delegate void Hook ();
569
570                 //
571                 // A hook invoked when the code has been generated.
572                 //
573                 public static event Hook EmitCodeHook;
574
575                 //
576                 // DefineTypes is used to fill in the members of each type.
577                 //
578                 static public void DefineTypes ()
579                 {
580                         TypeContainer root = Tree.Types;
581
582                         if (attribute_types != null)
583                                 foreach (TypeContainer tc in attribute_types)
584                                         tc.Define ();
585                         
586                         if (type_container_resolve_order != null){
587                                 foreach (TypeContainer tc in type_container_resolve_order) {
588                                         // When compiling corlib, these types have already been
589                                         // populated from BootCorlib_PopulateCoreTypes ().
590                                         if (!RootContext.StdLib &&
591                                             ((tc.Name == "System.Object") ||
592                                              (tc.Name == "System.Attribute") ||
593                                              (tc.Name == "System.ValueType")))
594                                                 continue;
595
596                                         if ((tc.ModFlags & Modifiers.NEW) == 0)
597                                                 tc.Define ();
598                                 }
599                         }
600
601                         ArrayList delegates = root.Delegates;
602                         if (delegates != null){
603                                 foreach (Delegate d in delegates)
604                                         if ((d.ModFlags & Modifiers.NEW) == 0)
605                                                 d.Define ();
606                         }
607
608                         ArrayList enums = root.Enums;
609                         if (enums != null){
610                                 foreach (Enum en in enums)
611                                         if ((en.ModFlags & Modifiers.NEW) == 0)
612                                                 en.Define ();
613                         }
614                 }
615
616                 static public void EmitCode ()
617                 {
618                         if (attribute_types != null)
619                                 foreach (TypeContainer tc in attribute_types)
620                                         tc.EmitType ();
621
622                         CodeGen.Assembly.Emit (Tree.Types);
623                         CodeGen.Module.Emit (Tree.Types);
624                         
625                         if (Tree.Types.Enums != null) {
626                                 foreach (Enum e in Tree.Types.Enums)
627                                         e.Emit ();
628                         }
629
630                         if (type_container_resolve_order != null) {
631                                 foreach (TypeContainer tc in type_container_resolve_order)
632                                         tc.EmitType ();
633                         }
634                         
635                         if (Tree.Types.Delegates != null) {
636                                 foreach (Delegate d in Tree.Types.Delegates)
637                                         d.Emit ();
638                         }                       
639                         //
640                         // Run any hooks after all the types have been defined.
641                         // This is used to create nested auxiliary classes for example
642                         //
643
644                         if (EmitCodeHook != null)
645                                 EmitCodeHook ();
646                 }
647                 
648                 //
649                 // Public Field, used to track which method is the public entry
650                 // point.
651                 //
652                 static public MethodInfo EntryPoint;
653
654                 //
655                 // Track the location of the entry point.
656                 //
657                 static public Location EntryPointLocation;
658
659                 //
660                 // These are used to generate unique names on the structs and fields.
661                 //
662                 static int field_count;
663                 
664                 //
665                 // Makes an initialized struct, returns the field builder that
666                 // references the data.  Thanks go to Sergey Chaban for researching
667                 // how to do this.  And coming up with a shorter mechanism than I
668                 // was able to figure out.
669                 //
670                 // This works but makes an implicit public struct $ArrayType$SIZE and
671                 // makes the fields point to it.  We could get more control if we did
672                 // use instead:
673                 //
674                 // 1. DefineNestedType on the impl_details_class with our struct.
675                 //
676                 // 2. Define the field on the impl_details_class
677                 //
678                 static public FieldBuilder MakeStaticData (byte [] data)
679                 {
680                         FieldBuilder fb;
681                         
682                         if (impl_details_class == null){
683                                 impl_details_class = CodeGen.Module.Builder.DefineType (
684                                         "<PrivateImplementationDetails>",
685                                         TypeAttributes.NotPublic,
686                                         TypeManager.object_type);
687                                 
688                                 RegisterCompilerGeneratedType (impl_details_class);
689                         }
690
691                         fb = impl_details_class.DefineInitializedData (
692                                 "$$field-" + (field_count++), data,
693                                 FieldAttributes.Static | FieldAttributes.Assembly);
694                         
695                         return fb;
696                 }
697         }
698 }
699               
700