2005-03-16 Zoltan Varga <vargaz@freemail.hu>
[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                 }
119                 
120                 public static bool NeedsEntryPoint {
121                         get {
122                                 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
123                         }
124                 }
125
126                 static public Tree Tree {
127                         get {
128                                 return tree;
129                         }
130                 }
131
132                 public static void RegisterOrder (TypeContainer tc)
133                 {
134                         type_container_resolve_order.Add (tc);
135                 }
136                 
137                 // 
138                 // The default compiler checked state
139                 //
140                 static public bool Checked;
141
142                 //
143                 // Whether to allow Unsafe code
144                 //
145                 static public bool Unsafe;
146                 
147                 // <remarks>
148                 //   This function is used to resolve the hierarchy tree.
149                 //   It processes interfaces, structs and classes in that order.
150                 //
151                 //   It creates the TypeBuilder's as it processes the user defined
152                 //   types.  
153                 // </remarks>
154                 static public void ResolveTree ()
155                 {
156                         //
157                         // Interfaces are processed next, as classes and
158                         // structs might inherit from an object or implement
159                         // a set of interfaces, we need to be able to tell
160                         // them appart by just using the TypeManager.
161                         //
162                         TypeContainer root = Tree.Types;
163
164                         ArrayList ifaces = root.Interfaces;
165                         if (ifaces != null){
166                                 foreach (Interface i in ifaces) 
167                                         i.DefineType ();
168                         }
169
170                         foreach (TypeContainer tc in root.Types)
171                                 tc.DefineType ();
172
173                         if (root.Delegates != null)
174                                 foreach (Delegate d in root.Delegates) 
175                                         d.DefineType ();
176
177                         if (root.Enums != null)
178                                 foreach (Enum e in root.Enums)
179                                         e.DefineType ();
180                 }
181
182                 static void Error_TypeConflict (string name, Location loc)
183                 {
184                         Report.Error (
185                                 520, loc, "`" + name + "' conflicts with a predefined type");
186                 }
187
188                 static void Error_TypeConflict (string name)
189                 {
190                         Report.Error (
191                                 520, "`" + name + "' conflicts with a predefined type");
192                 }
193
194                 //
195                 // Resolves a single class during the corlib bootstrap process
196                 //
197                 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
198                 {
199                         object o = root.GetDefinition (name);
200                         if (o == null){
201                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
202                                 return null;
203                         }
204
205                         if (!(o is Class)){
206                                 if (o is DeclSpace){
207                                         DeclSpace d = (DeclSpace) o;
208
209                                         Error_TypeConflict (name, d.Location);
210                                 } else
211                                         Error_TypeConflict (name);
212
213                                 return null;
214                         }
215
216                         return ((DeclSpace) o).DefineType ();
217                 }
218
219                 //
220                 // Resolves a struct during the corlib bootstrap process
221                 //
222                 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
223                 {
224                         object o = root.GetDefinition (name);
225                         if (o == null){
226                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
227                                 return;
228                         }
229
230                         if (!(o is Struct)){
231                                 if (o is DeclSpace){
232                                         DeclSpace d = (DeclSpace) o;
233
234                                         Error_TypeConflict (name, d.Location);
235                                 } else
236                                         Error_TypeConflict (name);
237
238                                 return;
239                         }
240
241                         ((DeclSpace) o).DefineType ();
242                 }
243
244                 //
245                 // Resolves a struct during the corlib bootstrap process
246                 //
247                 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
248                 {
249                         object o = root.GetDefinition (name);
250                         if (o == null){
251                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
252                                 return;
253                         }
254
255                         if (!(o is Interface)){
256                                 if (o is DeclSpace){
257                                         DeclSpace d = (DeclSpace) o;
258
259                                         Error_TypeConflict (name, d.Location);
260                                 } else
261                                         Error_TypeConflict (name);
262
263                                 return;
264                         }
265
266                         ((DeclSpace) o).DefineType ();
267                 }
268
269                 //
270                 // Resolves a delegate during the corlib bootstrap process
271                 //
272                 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
273                 {
274                         object o = root.GetDefinition (name);
275                         if (o == null){
276                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
277                                 return;
278                         }
279
280                         if (!(o is Delegate)){
281                                 Error_TypeConflict (name);
282                                 return;
283                         }
284
285                         ((DeclSpace) o).DefineType ();
286                 }
287                 
288
289                 /// <summary>
290                 ///    Resolves the core types in the compiler when compiling with --nostdlib
291                 /// </summary>
292                 static public void ResolveCore ()
293                 {
294                         TypeContainer root = Tree.Types;
295
296                         TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
297                         TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
298                         TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
299                         TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
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.DecimalConstantAttribute",
385                                 "System.Runtime.InteropServices.InAttribute",
386                                 "System.Runtime.InteropServices.OutAttribute",
387                                 "System.Runtime.InteropServices.StructLayoutAttribute",
388                                 "System.Runtime.InteropServices.FieldOffsetAttribute",
389                                 "System.InvalidOperationException",
390                                 "System.NotSupportedException",
391                                 "System.MarshalByRefObject",
392                                 "System.Security.CodeAccessPermission"
393                         };
394
395                         foreach (string cname in classes_second_stage)
396                                 BootstrapCorlib_ResolveClass (root, cname);
397
398                         BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
399
400                         // These will be defined indirectly during the previous ResolveDelegate.
401                         // However make sure the rest of the checks happen.
402                         string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
403                         foreach (string cname in delegate_types)
404                                 BootstrapCorlib_ResolveClass (root, cname);
405                 }
406                         
407                 // <summary>
408                 //   Closes all open types
409                 // </summary>
410                 //
411                 // <remarks>
412                 //   We usually use TypeBuilder types.  When we are done
413                 //   creating the type (which will happen after we have added
414                 //   methods, fields, etc) we need to "Define" them before we
415                 //   can save the Assembly
416                 // </remarks>
417                 static public void CloseTypes ()
418                 {
419                         TypeContainer root = Tree.Types;
420                         
421                         if (root.Enums != null)
422                                 foreach (Enum en in root.Enums)
423                                         en.CloseType ();
424
425                         //
426                         // We do this in two passes, first we close the structs,
427                         // then the classes, because it seems the code needs it this
428                         // way.  If this is really what is going on, we should probably
429                         // make sure that we define the structs in order as well.
430                         //
431                         foreach (TypeContainer tc in type_container_resolve_order){
432                                 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
433                                         tc.CloseType ();
434                                 }
435                         }
436
437                         foreach (TypeContainer tc in type_container_resolve_order){
438                                 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
439                                         tc.CloseType ();                                        
440                         }
441                         
442                         if (root.Delegates != null)
443                                 foreach (Delegate d in root.Delegates)
444                                         d.CloseType ();
445
446
447                         //
448                         // If we have a <PrivateImplementationDetails> class, close it
449                         //
450                         if (helper_classes != null){
451                                 foreach (TypeBuilder type_builder in helper_classes) {
452 #if NET_2_0
453                                         type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
454 #endif
455                                         type_builder.CreateType ();
456                                 }
457                         }
458                         
459                         type_container_resolve_order = null;
460                         helper_classes = null;
461                         //tree = null;
462                         TypeManager.CleanUp ();
463                 }
464
465                 /// <summary>
466                 ///   Used to register classes that need to be closed after all the
467                 ///   user defined classes
468                 /// </summary>
469                 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
470                 {
471                         if (helper_classes == null)
472                                 helper_classes = new ArrayList ();
473
474                         helper_classes.Add (helper_class);
475                 }
476                 
477                 static void Report1530 (Location loc)
478                 {
479                         Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
480                 }
481                 
482                 static public void PopulateCoreType (TypeContainer root, string name)
483                 {
484                         DeclSpace ds = (DeclSpace) root.GetDefinition (name);
485
486                         ds.DefineMembers (root);
487                         ds.Define ();
488                 }
489                 
490                 static public void BootCorlib_PopulateCoreTypes ()
491                 {
492                         TypeContainer root = tree.Types;
493
494                         PopulateCoreType (root, "System.Object");
495                         PopulateCoreType (root, "System.ValueType");
496                         PopulateCoreType (root, "System.Attribute");
497                         PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
498                 }
499                 
500                 // <summary>
501                 //   Populates the structs and classes with fields and methods
502                 // </summary>
503                 //
504                 // This is invoked after all interfaces, structs and classes
505                 // have been defined through `ResolveTree' 
506                 static public void PopulateTypes ()
507                 {
508                         TypeContainer root = Tree.Types;
509
510                         if (type_container_resolve_order != null){
511                                 if (RootContext.StdLib){
512                                         foreach (TypeContainer tc in type_container_resolve_order)
513                                                 tc.DefineMembers (root);
514                                 } else {
515                                         foreach (TypeContainer tc in type_container_resolve_order) {
516                                                 // When compiling corlib, these types have already been
517                                                 // populated from BootCorlib_PopulateCoreTypes ().
518                                                 if (((tc.Name == "System.Object") ||
519                                                         (tc.Name == "System.Attribute") ||
520                                                         (tc.Name == "System.ValueType") ||
521                                                         (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
522                                                 continue;
523
524                                                 tc.DefineMembers (root);
525                                         }
526                                 } 
527                         }
528
529                         ArrayList delegates = root.Delegates;
530                         if (delegates != null){
531                                 foreach (Delegate d in delegates)
532                                         if ((d.ModFlags & Modifiers.NEW) == 0)
533                                                 d.DefineMembers (root);
534                                         else
535                                                 Report1530 (d.Location);
536                         }
537
538                         ArrayList enums = root.Enums;
539                         if (enums != null){
540                                 foreach (Enum en in enums)
541                                         if ((en.ModFlags & Modifiers.NEW) == 0)
542                                                 en.DefineMembers (root);
543                                         else
544                                                 Report1530 (en.Location);
545                         }
546
547                         //
548                         // Check for cycles in the struct layout
549                         //
550                         if (type_container_resolve_order != null){
551                                 Hashtable seen = new Hashtable ();
552                                 foreach (TypeContainer tc in type_container_resolve_order)
553                                         TypeManager.CheckStructCycles (tc, seen);
554                         }
555                 }
556
557                 //
558                 // A generic hook delegate
559                 //
560                 public delegate void Hook ();
561
562                 //
563                 // A hook invoked when the code has been generated.
564                 //
565                 public static event Hook EmitCodeHook;
566
567                 //
568                 // DefineTypes is used to fill in the members of each type.
569                 //
570                 static public void DefineTypes ()
571                 {
572                         TypeContainer root = Tree.Types;
573
574                         if (type_container_resolve_order != null){
575                                 foreach (TypeContainer tc in type_container_resolve_order) {
576                                         // When compiling corlib, these types have already been
577                                         // populated from BootCorlib_PopulateCoreTypes ().
578                                         if (!RootContext.StdLib &&
579                                             ((tc.Name == "System.Object") ||
580                                              (tc.Name == "System.Attribute") ||
581                                              (tc.Name == "System.ValueType") ||
582                                              (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
583                                                 continue;
584
585                                         if ((tc.ModFlags & Modifiers.NEW) == 0)
586                                                 tc.Define ();
587                                 }
588                         }
589
590                         ArrayList delegates = root.Delegates;
591                         if (delegates != null){
592                                 foreach (Delegate d in delegates)
593                                         if ((d.ModFlags & Modifiers.NEW) == 0)
594                                                 d.Define ();
595                         }
596
597                         ArrayList enums = root.Enums;
598                         if (enums != null){
599                                 foreach (Enum en in enums)
600                                         if ((en.ModFlags & Modifiers.NEW) == 0)
601                                                 en.Define ();
602                         }
603                 }
604
605                 static public void EmitCode ()
606                 {
607                         if (Tree.Types.Enums != null) {
608                                 foreach (Enum e in Tree.Types.Enums)
609                                         e.Emit ();
610                         }
611
612                         if (type_container_resolve_order != null) {
613                                 foreach (TypeContainer tc in type_container_resolve_order)
614                                         tc.EmitType ();
615                         }
616                         
617                         if (Tree.Types.Delegates != null) {
618                                 foreach (Delegate d in Tree.Types.Delegates)
619                                         d.Emit ();
620                         }                       
621                         //
622                         // Run any hooks after all the types have been defined.
623                         // This is used to create nested auxiliary classes for example
624                         //
625
626                         if (EmitCodeHook != null)
627                                 EmitCodeHook ();
628
629                         CodeGen.Assembly.Emit (Tree.Types);
630                         CodeGen.Module.Emit (Tree.Types);
631                 }
632                 
633                 //
634                 // Public Field, used to track which method is the public entry
635                 // point.
636                 //
637                 static public MethodInfo EntryPoint;
638
639                 //
640                 // Track the location of the entry point.
641                 //
642                 static public Location EntryPointLocation;
643
644                 //
645                 // These are used to generate unique names on the structs and fields.
646                 //
647                 static int field_count;
648                 
649                 //
650                 // Makes an initialized struct, returns the field builder that
651                 // references the data.  Thanks go to Sergey Chaban for researching
652                 // how to do this.  And coming up with a shorter mechanism than I
653                 // was able to figure out.
654                 //
655                 // This works but makes an implicit public struct $ArrayType$SIZE and
656                 // makes the fields point to it.  We could get more control if we did
657                 // use instead:
658                 //
659                 // 1. DefineNestedType on the impl_details_class with our struct.
660                 //
661                 // 2. Define the field on the impl_details_class
662                 //
663                 static public FieldBuilder MakeStaticData (byte [] data)
664                 {
665                         FieldBuilder fb;
666                         
667                         if (impl_details_class == null){
668                                 impl_details_class = CodeGen.Module.Builder.DefineType (
669                                         "<PrivateImplementationDetails>",
670                                         TypeAttributes.NotPublic,
671                                         TypeManager.object_type);
672                                 
673                                 RegisterCompilerGeneratedType (impl_details_class);
674                         }
675
676                         fb = impl_details_class.DefineInitializedData (
677                                 "$$field-" + (field_count++), data,
678                                 FieldAttributes.Static | FieldAttributes.Assembly);
679                         
680                         return fb;
681                 }
682         }
683 }
684               
685