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