2005-07-05 Atsushi Enomoto <atsushi@ximian.com>
[mono.git] / mcs / mcs / rootcontext.cs
1 //
2 // rootcontext.cs: keeps track of our tree representation, and assemblies loaded.
3 //
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 //         Ravi Pratap     (ravi@ximian.com)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
11
12 using System;
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
17
18 namespace Mono.CSharp {
19
20         public enum LanguageVersion
21         {
22                 Default = 0,
23                 ISO_1   = 1
24         }
25
26         public class RootContext {
27
28                 //
29                 // Contains the parsed tree
30                 //
31                 static Tree tree;
32
33                 //
34                 // This hashtable contains all of the #definitions across the source code
35                 // it is used by the ConditionalAttribute handler.
36                 //
37                 public static Hashtable AllDefines = new Hashtable ();
38                 
39                 //
40                 // Whether we are being linked against the standard libraries.
41                 // This is only used to tell whether `System.Object' should
42                 // have a base class or not.
43                 //
44                 public static bool StdLib;
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");
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");
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");
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");
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.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
300                         TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
301                         TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
302                         
303                         string [] interfaces_first_stage = {
304                                 "System.IComparable", "System.ICloneable",
305                                 "System.IConvertible",
306                                 
307                                 "System.Collections.IEnumerable",
308                                 "System.Collections.ICollection",
309                                 "System.Collections.IEnumerator",
310                                 "System.Collections.IList", 
311                                 "System.IAsyncResult",
312                                 "System.IDisposable",
313                                 
314                                 "System.Runtime.Serialization.ISerializable",
315
316                                 "System.Reflection.IReflect",
317                                 "System.Reflection.ICustomAttributeProvider"
318                         };
319
320                         foreach (string iname in interfaces_first_stage)
321                                 BootstrapCorlib_ResolveInterface (root, iname);
322
323                         //
324                         // These are the base value types
325                         //
326                         string [] structs_first_stage = {
327                                 "System.Byte",    "System.SByte",
328                                 "System.Int16",   "System.UInt16",
329                                 "System.Int32",   "System.UInt32",
330                                 "System.Int64",   "System.UInt64",
331                         };
332
333                         foreach (string cname in structs_first_stage)
334                                 BootstrapCorlib_ResolveStruct (root, cname);
335
336                         //
337                         // Now, we can load the enumerations, after this point,
338                         // we can use enums.
339                         //
340                         TypeManager.InitEnumUnderlyingTypes ();
341
342                         string [] structs_second_stage = {
343                                 "System.Single",  "System.Double",
344                                 "System.Char",    "System.Boolean",
345                                 "System.Decimal", "System.Void",
346                                 "System.RuntimeFieldHandle",
347                                 "System.RuntimeArgumentHandle",
348                                 "System.RuntimeTypeHandle",
349                                 "System.IntPtr",
350                                 "System.TypedReference",
351                                 "System.ArgIterator"
352                         };
353                         
354                         foreach (string cname in structs_second_stage)
355                                 BootstrapCorlib_ResolveStruct (root, cname);
356                         
357                         //
358                         // These are classes that depends on the core interfaces
359                         //
360                         string [] classes_second_stage = {
361                                 "System.Enum",
362                                 "System.String",
363                                 "System.Array",
364                                 "System.Reflection.MemberInfo",
365                                 "System.Type",
366                                 "System.Exception",
367
368                                 //
369                                 // These are not really important in the order, but they
370                                 // are used by the compiler later on (typemanager/CoreLookupType-d)
371                                 //
372                                 "System.Runtime.CompilerServices.RuntimeHelpers",
373                                 "System.Reflection.DefaultMemberAttribute",
374                                 "System.Threading.Monitor",
375                                 
376                                 "System.AttributeUsageAttribute",
377                                 "System.Runtime.InteropServices.DllImportAttribute",
378                                 "System.Runtime.CompilerServices.MethodImplAttribute",
379                                 "System.Runtime.InteropServices.MarshalAsAttribute",
380                                 "System.Diagnostics.ConditionalAttribute",
381                                 "System.ObsoleteAttribute",
382                                 "System.ParamArrayAttribute",
383                                 "System.CLSCompliantAttribute",
384                                 "System.Security.UnverifiableCodeAttribute",
385                                 "System.Security.Permissions.SecurityAttribute",
386                                 "System.Runtime.CompilerServices.DecimalConstantAttribute",
387                                 "System.Runtime.InteropServices.InAttribute",
388                                 "System.Runtime.InteropServices.OutAttribute",
389                                 "System.Runtime.InteropServices.StructLayoutAttribute",
390                                 "System.Runtime.InteropServices.FieldOffsetAttribute",
391                                 "System.InvalidOperationException",
392                                 "System.NotSupportedException",
393                                 "System.MarshalByRefObject",
394                                 "System.Security.CodeAccessPermission",
395                                 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
396                                 "System.Runtime.InteropServices.GuidAttribute"
397                         };
398
399                         foreach (string cname in classes_second_stage)
400                                 BootstrapCorlib_ResolveClass (root, cname);
401
402                         BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
403
404                         // These will be defined indirectly during the previous ResolveDelegate.
405                         // However make sure the rest of the checks happen.
406                         string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
407                         foreach (string cname in delegate_types)
408                                 BootstrapCorlib_ResolveClass (root, cname);
409                 }
410                         
411                 // <summary>
412                 //   Closes all open types
413                 // </summary>
414                 //
415                 // <remarks>
416                 //   We usually use TypeBuilder types.  When we are done
417                 //   creating the type (which will happen after we have added
418                 //   methods, fields, etc) we need to "Define" them before we
419                 //   can save the Assembly
420                 // </remarks>
421                 static public void CloseTypes ()
422                 {
423                         TypeContainer root = Tree.Types;
424                         
425                         if (root.Enums != null)
426                                 foreach (Enum en in root.Enums)
427                                         en.CloseType ();
428
429                         //
430                         // We do this in two passes, first we close the structs,
431                         // then the classes, because it seems the code needs it this
432                         // way.  If this is really what is going on, we should probably
433                         // make sure that we define the structs in order as well.
434                         //
435                         foreach (TypeContainer tc in type_container_resolve_order){
436                                 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
437                                         tc.CloseType ();
438                                 }
439                         }
440
441                         foreach (TypeContainer tc in type_container_resolve_order){
442                                 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
443                                         tc.CloseType ();                                        
444                         }
445                         
446                         if (root.Delegates != null)
447                                 foreach (Delegate d in root.Delegates)
448                                         d.CloseType ();
449
450
451                         //
452                         // If we have a <PrivateImplementationDetails> class, close it
453                         //
454                         if (helper_classes != null){
455                                 foreach (TypeBuilder type_builder in helper_classes) {
456 #if NET_2_0
457                                         type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
458 #endif
459                                         type_builder.CreateType ();
460                                 }
461                         }
462                         
463                         type_container_resolve_order = null;
464                         helper_classes = null;
465                         //tree = null;
466                         TypeManager.CleanUp ();
467                 }
468
469                 /// <summary>
470                 ///   Used to register classes that need to be closed after all the
471                 ///   user defined classes
472                 /// </summary>
473                 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
474                 {
475                         if (helper_classes == null)
476                                 helper_classes = new ArrayList ();
477
478                         helper_classes.Add (helper_class);
479                 }
480                 
481                 static void Report1530 (Location loc)
482                 {
483                         Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
484                 }
485                 
486                 static public void PopulateCoreType (TypeContainer root, string name)
487                 {
488                         DeclSpace ds = (DeclSpace) root.GetDefinition (name);
489
490                         ds.DefineMembers (root);
491                         ds.Define ();
492                 }
493                 
494                 static public void BootCorlib_PopulateCoreTypes ()
495                 {
496                         TypeContainer root = tree.Types;
497
498                         PopulateCoreType (root, "System.Object");
499                         PopulateCoreType (root, "System.ValueType");
500                         PopulateCoreType (root, "System.Attribute");
501                         PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
502                 }
503                 
504                 // <summary>
505                 //   Populates the structs and classes with fields and methods
506                 // </summary>
507                 //
508                 // This is invoked after all interfaces, structs and classes
509                 // have been defined through `ResolveTree' 
510                 static public void PopulateTypes ()
511                 {
512                         TypeContainer root = Tree.Types;
513
514                         if (type_container_resolve_order != null){
515                                 if (RootContext.StdLib){
516                                         foreach (TypeContainer tc in type_container_resolve_order)
517                                                 tc.DefineMembers (root);
518                                 } else {
519                                         foreach (TypeContainer tc in type_container_resolve_order) {
520                                                 // When compiling corlib, these types have already been
521                                                 // populated from BootCorlib_PopulateCoreTypes ().
522                                                 if (((tc.Name == "System.Object") ||
523                                                         (tc.Name == "System.Attribute") ||
524                                                         (tc.Name == "System.ValueType") ||
525                                                         (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
526                                                 continue;
527
528                                                 tc.DefineMembers (root);
529                                         }
530                                 } 
531                         }
532
533                         ArrayList delegates = root.Delegates;
534                         if (delegates != null){
535                                 foreach (Delegate d in delegates)
536                                         if ((d.ModFlags & Modifiers.NEW) == 0)
537                                                 d.DefineMembers (root);
538                                         else
539                                                 Report1530 (d.Location);
540                         }
541
542                         ArrayList enums = root.Enums;
543                         if (enums != null){
544                                 foreach (Enum en in enums)
545                                         if ((en.ModFlags & Modifiers.NEW) == 0)
546                                                 en.DefineMembers (root);
547                                         else
548                                                 Report1530 (en.Location);
549                         }
550
551                         //
552                         // Check for cycles in the struct layout
553                         //
554                         if (type_container_resolve_order != null){
555                                 Hashtable seen = new Hashtable ();
556                                 foreach (TypeContainer tc in type_container_resolve_order)
557                                         TypeManager.CheckStructCycles (tc, seen);
558                         }
559                 }
560
561                 //
562                 // A generic hook delegate
563                 //
564                 public delegate void Hook ();
565
566                 //
567                 // A hook invoked when the code has been generated.
568                 //
569                 public static event Hook EmitCodeHook;
570
571                 //
572                 // DefineTypes is used to fill in the members of each type.
573                 //
574                 static public void DefineTypes ()
575                 {
576                         TypeContainer root = Tree.Types;
577
578                         ArrayList delegates = root.Delegates;
579                         if (delegates != null){
580                                 foreach (Delegate d in delegates)
581                                         if ((d.ModFlags & Modifiers.NEW) == 0)
582                                                 d.Define ();
583                         }
584
585                         if (type_container_resolve_order != null){
586                                 foreach (TypeContainer tc in type_container_resolve_order) {
587                                         // When compiling corlib, these types have already been
588                                         // populated from BootCorlib_PopulateCoreTypes ().
589                                         if (!RootContext.StdLib &&
590                                             ((tc.Name == "System.Object") ||
591                                              (tc.Name == "System.Attribute") ||
592                                              (tc.Name == "System.ValueType") ||
593                                              (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
594                                                 continue;
595
596                                         if ((tc.ModFlags & Modifiers.NEW) == 0)
597                                                 tc.Define ();
598                                 }
599                         }
600
601                         ArrayList enums = root.Enums;
602                         if (enums != null){
603                                 foreach (Enum en in enums)
604                                         if ((en.ModFlags & Modifiers.NEW) == 0)
605                                                 en.Define ();
606                         }
607                 }
608
609                 static public void EmitCode ()
610                 {
611                         if (Tree.Types.Enums != null) {
612                                 foreach (Enum e in Tree.Types.Enums)
613                                         e.Emit ();
614                         }
615
616                         if (type_container_resolve_order != null) {
617                                 foreach (TypeContainer tc in type_container_resolve_order)
618                                         tc.EmitType ();
619
620                                 if (Report.Errors > 0)
621                                         return;
622
623                                 foreach (TypeContainer tc in type_container_resolve_order)
624                                         tc.VerifyMembers ();
625                         }
626                         
627                         if (Tree.Types.Delegates != null) {
628                                 foreach (Delegate d in Tree.Types.Delegates)
629                                         d.Emit ();
630                         }                       
631                         //
632                         // Run any hooks after all the types have been defined.
633                         // This is used to create nested auxiliary classes for example
634                         //
635
636                         if (EmitCodeHook != null)
637                                 EmitCodeHook ();
638
639                         CodeGen.Assembly.Emit (Tree.Types);
640                         CodeGen.Module.Emit (Tree.Types);
641                 }
642                 
643                 //
644                 // Public Field, used to track which method is the public entry
645                 // point.
646                 //
647                 static public MethodInfo EntryPoint;
648
649                 //
650                 // Track the location of the entry point.
651                 //
652                 static public Location EntryPointLocation;
653
654                 //
655                 // These are used to generate unique names on the structs and fields.
656                 //
657                 static int field_count;
658                 
659                 //
660                 // Makes an initialized struct, returns the field builder that
661                 // references the data.  Thanks go to Sergey Chaban for researching
662                 // how to do this.  And coming up with a shorter mechanism than I
663                 // was able to figure out.
664                 //
665                 // This works but makes an implicit public struct $ArrayType$SIZE and
666                 // makes the fields point to it.  We could get more control if we did
667                 // use instead:
668                 //
669                 // 1. DefineNestedType on the impl_details_class with our struct.
670                 //
671                 // 2. Define the field on the impl_details_class
672                 //
673                 static public FieldBuilder MakeStaticData (byte [] data)
674                 {
675                         FieldBuilder fb;
676                         
677                         if (impl_details_class == null){
678                                 impl_details_class = CodeGen.Module.Builder.DefineType (
679                                         "<PrivateImplementationDetails>",
680                                         TypeAttributes.NotPublic,
681                                         TypeManager.object_type);
682                                 
683                                 RegisterCompilerGeneratedType (impl_details_class);
684                         }
685
686                         fb = impl_details_class.DefineInitializedData (
687                                 "$$field-" + (field_count++), data,
688                                 FieldAttributes.Static | FieldAttributes.Assembly);
689                         
690                         return fb;
691                 }
692         }
693 }
694               
695