2005-12-27 Atsushi Enomoto <atsushi@ximian.com>
[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                 public static bool BrokenCircularDeps;
89                 //
90                 // If set, enable XML documentation generation
91                 //
92                 public static Documentation Documentation;
93
94                 static public string MainClass;
95
96                 //
97                 // Constructor
98                 //
99                 static RootContext ()
100                 {
101                         Reset ();
102                 }
103
104                 public static void Reset ()
105                 {
106                         tree = new Tree ();
107                         type_container_resolve_order = new ArrayList ();
108                         EntryPoint = null;
109                         WarningLevel = 3;
110                         Checked = false;
111                         Unsafe = false;
112                         StdLib = true;
113                         StrongNameKeyFile = null;
114                         StrongNameKeyContainer = null;
115                         StrongNameDelaySign = false;
116                         MainClass = null;
117                         Target = Target.Exe;
118                         TargetExt = ".exe";
119                         Version = LanguageVersion.Default;
120                         Documentation = null;
121                         impl_details_class = null;
122                 }
123
124                 public static bool NeedsEntryPoint {
125                         get {
126                                 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
127                         }
128                 }
129
130                 static public Tree Tree {
131                         get {
132                                 return tree;
133                         }
134                 }
135
136                 public static void RegisterOrder (TypeContainer tc)
137                 {
138                         type_container_resolve_order.Add (tc);
139                 }
140                 
141                 // 
142                 // The default compiler checked state
143                 //
144                 static public bool Checked;
145
146                 //
147                 // Whether to allow Unsafe code
148                 //
149                 static public bool Unsafe;
150                 
151                 // <remarks>
152                 //   This function is used to resolve the hierarchy tree.
153                 //   It processes interfaces, structs and classes in that order.
154                 //
155                 //   It creates the TypeBuilder's as it processes the user defined
156                 //   types.  
157                 // </remarks>
158                 static public void ResolveTree ()
159                 {
160                         //
161                         // Interfaces are processed next, as classes and
162                         // structs might inherit from an object or implement
163                         // a set of interfaces, we need to be able to tell
164                         // them appart by just using the TypeManager.
165                         //
166                         TypeContainer root = Tree.Types;
167
168                         ArrayList ifaces = root.Interfaces;
169                         if (ifaces != null){
170                                 foreach (TypeContainer i in ifaces) 
171                                         i.DefineType ();
172                         }
173
174                         foreach (TypeContainer tc in root.Types)
175                                 tc.DefineType ();
176
177                         if (root.Delegates != null)
178                                 foreach (Delegate d in root.Delegates) 
179                                         d.DefineType ();
180
181                         if (root.Enums != null)
182                                 foreach (Enum e in root.Enums)
183                                         e.DefineType ();
184                 }
185
186                 static void Error_TypeConflict (string name, Location loc)
187                 {
188                         Report.Error (
189                                 520, loc, "`" + name + "' conflicts with a predefined type");
190                 }
191
192                 static void Error_TypeConflict (string name)
193                 {
194                         Report.Error (
195                                 520, "`" + name + "' conflicts with a predefined type");
196                 }
197
198                 //
199                 // Resolves a single class during the corlib bootstrap process
200                 //
201                 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
202                 {
203                         object o = root.GetDefinition (name);
204                         if (o == null){
205                                 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
206                                 return null;
207                         }
208
209                         if (!(o is Class)){
210                                 if (o is DeclSpace){
211                                         DeclSpace d = (DeclSpace) o;
212
213                                         Error_TypeConflict (name, d.Location);
214                                 } else
215                                         Error_TypeConflict (name);
216
217                                 return null;
218                         }
219
220                         return ((DeclSpace) o).DefineType ();
221                 }
222
223                 //
224                 // Resolves a struct during the corlib bootstrap process
225                 //
226                 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
227                 {
228                         object o = root.GetDefinition (name);
229                         if (o == null){
230                                 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
231                                 return;
232                         }
233
234                         if (!(o is Struct)){
235                                 if (o is DeclSpace){
236                                         DeclSpace d = (DeclSpace) o;
237
238                                         Error_TypeConflict (name, d.Location);
239                                 } else
240                                         Error_TypeConflict (name);
241
242                                 return;
243                         }
244
245                         ((DeclSpace) o).DefineType ();
246                 }
247
248                 //
249                 // Resolves a struct during the corlib bootstrap process
250                 //
251                 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
252                 {
253                         object o = root.GetDefinition (name);
254                         if (o == null){
255                                 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
256                                 return;
257                         }
258
259                         if (!(o is Interface)){
260                                 if (o is DeclSpace){
261                                         DeclSpace d = (DeclSpace) o;
262
263                                         Error_TypeConflict (name, d.Location);
264                                 } else
265                                         Error_TypeConflict (name);
266
267                                 return;
268                         }
269
270                         ((DeclSpace) o).DefineType ();
271                 }
272
273                 //
274                 // Resolves a delegate during the corlib bootstrap process
275                 //
276                 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
277                 {
278                         object o = root.GetDefinition (name);
279                         if (o == null){
280                                 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
281                                 return;
282                         }
283
284                         if (!(o is Delegate)){
285                                 Error_TypeConflict (name);
286                                 return;
287                         }
288
289                         ((DeclSpace) o).DefineType ();
290                 }
291                 
292
293                 /// <summary>
294                 ///    Resolves the core types in the compiler when compiling with --nostdlib
295                 /// </summary>
296                 static public void ResolveCore ()
297                 {
298                         TypeContainer root = Tree.Types;
299
300                         TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
301                         TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
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                                 "System.Runtime.InteropServices._Exception",
318
319                                 "System.Reflection.IReflect",
320                                 "System.Reflection.ICustomAttributeProvider",
321
322                                 //
323                                 // Generic types
324                                 //
325                                 "System.Collections.Generic.IEnumerator`1",
326                                 "System.Collections.Generic.IEnumerable`1",
327                                 "System.INullableValue"
328                         };
329
330                         foreach (string iname in interfaces_first_stage)
331                                 BootstrapCorlib_ResolveInterface (root, iname);
332
333                         //
334                         // These are the base value types
335                         //
336                         string [] structs_first_stage = {
337                                 "System.Byte",    "System.SByte",
338                                 "System.Int16",   "System.UInt16",
339                                 "System.Int32",   "System.UInt32",
340                                 "System.Int64",   "System.UInt64",
341                         };
342
343                         foreach (string cname in structs_first_stage)
344                                 BootstrapCorlib_ResolveStruct (root, cname);
345
346                         //
347                         // Now, we can load the enumerations, after this point,
348                         // we can use enums.
349                         //
350                         TypeManager.InitEnumUnderlyingTypes ();
351
352                         string [] structs_second_stage = {
353                                 "System.Single",  "System.Double",
354                                 "System.Char",    "System.Boolean",
355                                 "System.Decimal", "System.Void",
356                                 "System.RuntimeFieldHandle",
357                                 "System.RuntimeArgumentHandle",
358                                 "System.RuntimeTypeHandle",
359                                 "System.IntPtr",
360                                 "System.TypedReference",
361                                 "System.ArgIterator"
362                         };
363                         
364                         foreach (string cname in structs_second_stage)
365                                 BootstrapCorlib_ResolveStruct (root, cname);
366                         
367                         //
368                         // These are classes that depends on the core interfaces
369                         //
370                         string [] classes_second_stage = {
371                                 "System.Enum",
372                                 "System.String",
373                                 "System.Array",
374                                 "System.Reflection.MemberInfo",
375                                 "System.Type",
376                                 "System.Exception",
377                                 "System.Activator",
378
379                                 //
380                                 // These are not really important in the order, but they
381                                 // are used by the compiler later on (typemanager/CoreLookupType-d)
382                                 //
383                                 "System.Runtime.CompilerServices.RuntimeHelpers",
384                                 "System.Reflection.DefaultMemberAttribute",
385                                 "System.Threading.Monitor",
386                                 
387                                 "System.AttributeUsageAttribute",
388                                 "System.Runtime.InteropServices.DllImportAttribute",
389                                 "System.Runtime.CompilerServices.MethodImplAttribute",
390                                 "System.Runtime.InteropServices.MarshalAsAttribute",
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 ();
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                                 foreach (TypeContainer tc in type_container_resolve_order)
528                                         tc.DefineMembers ();
529                         }
530
531                         ArrayList delegates = root.Delegates;
532                         if (delegates != null){
533                                 foreach (Delegate d in delegates)
534                                         d.DefineMembers ();
535                         }
536
537                         ArrayList enums = root.Enums;
538                         if (enums != null){
539                                 foreach (Enum en in enums)
540                                         en.DefineMembers ();
541                         }
542
543                         //
544                         // Check for cycles in the struct layout
545                         //
546                         if (type_container_resolve_order != null){
547                                 Hashtable seen = new Hashtable ();
548                                 foreach (TypeContainer tc in type_container_resolve_order)
549                                         TypeManager.CheckStructCycles (tc, seen);
550                         }
551                 }
552
553                 //
554                 // A generic hook delegate
555                 //
556                 public delegate void Hook ();
557
558                 //
559                 // A hook invoked when the code has been generated.
560                 //
561                 public static event Hook EmitCodeHook;
562
563                 //
564                 // DefineTypes is used to fill in the members of each type.
565                 //
566                 static public void DefineTypes ()
567                 {
568                         TypeContainer root = Tree.Types;
569
570                         ArrayList delegates = root.Delegates;
571                         if (delegates != null){
572                                 foreach (Delegate d in delegates)
573                                         d.Define ();
574                         }
575
576                         if (type_container_resolve_order != null){
577                                 foreach (TypeContainer tc in type_container_resolve_order) {
578                                         // When compiling corlib, these types have already been
579                                         // populated from BootCorlib_PopulateCoreTypes ().
580                                         if (!RootContext.StdLib &&
581                                             ((tc.Name == "System.Object") ||
582                                              (tc.Name == "System.Attribute") ||
583                                              (tc.Name == "System.ValueType") ||
584                                              (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
585                                                 continue;
586
587                                         tc.Define ();
588                                 }
589                         }
590
591                         ArrayList enums = root.Enums;
592                         if (enums != null){
593                                 foreach (Enum en in enums)
594                                         en.Define ();
595                         }
596                 }
597
598                 static public void EmitCode ()
599                 {
600                         if (Tree.Types.Enums != null) {
601                                 foreach (Enum e in Tree.Types.Enums)
602                                         e.Emit ();
603                         }
604
605                         if (type_container_resolve_order != null) {
606                                 foreach (TypeContainer tc in type_container_resolve_order)
607                                         tc.EmitType ();
608
609                                 if (Report.Errors > 0)
610                                         return;
611
612                                 foreach (TypeContainer tc in type_container_resolve_order)
613                                         tc.VerifyMembers ();
614                         }
615                         
616                         if (Tree.Types.Delegates != null) {
617                                 foreach (Delegate d in Tree.Types.Delegates)
618                                         d.Emit ();
619                         }                       
620                         //
621                         // Run any hooks after all the types have been defined.
622                         // This is used to create nested auxiliary classes for example
623                         //
624
625                         if (EmitCodeHook != null)
626                                 EmitCodeHook ();
627
628                         CodeGen.Assembly.Emit (Tree.Types);
629                         CodeGen.Module.Emit (Tree.Types);
630                 }
631                 
632                 //
633                 // Public Field, used to track which method is the public entry
634                 // point.
635                 //
636                 static public MethodInfo EntryPoint;
637
638                 //
639                 // Track the location of the entry point.
640                 //
641                 static public Location EntryPointLocation;
642
643                 //
644                 // These are used to generate unique names on the structs and fields.
645                 //
646                 static int field_count;
647                 
648                 //
649                 // Makes an initialized struct, returns the field builder that
650                 // references the data.  Thanks go to Sergey Chaban for researching
651                 // how to do this.  And coming up with a shorter mechanism than I
652                 // was able to figure out.
653                 //
654                 // This works but makes an implicit public struct $ArrayType$SIZE and
655                 // makes the fields point to it.  We could get more control if we did
656                 // use instead:
657                 //
658                 // 1. DefineNestedType on the impl_details_class with our struct.
659                 //
660                 // 2. Define the field on the impl_details_class
661                 //
662                 static public FieldBuilder MakeStaticData (byte [] data)
663                 {
664                         FieldBuilder fb;
665                         
666                         if (impl_details_class == null){
667                                 impl_details_class = CodeGen.Module.Builder.DefineType (
668                                         "<PrivateImplementationDetails>",
669                                         TypeAttributes.NotPublic,
670                                         TypeManager.object_type);
671                                 
672                                 RegisterCompilerGeneratedType (impl_details_class);
673                         }
674
675                         fb = impl_details_class.DefineInitializedData (
676                                 "$$field-" + (field_count++), data,
677                                 FieldAttributes.Static | FieldAttributes.Assembly);
678                         
679                         return fb;
680                 }
681
682                 public static void CheckUnsafeOption (Location loc)
683                 {
684                         if (!Unsafe) {
685                                 Report.Error (227, loc, 
686                                         "Unsafe code requires the `unsafe' command line option to be specified");
687                         }
688                 }
689         }
690 }
691               
692