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