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