Oooops, typo.
[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 = 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
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 = 3;
67
68                 public static Target Target = Target.Exe;
69                 public static string TargetExt = ".exe";
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 = LanguageVersion.Default;
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 = false;
87
88                 //
89                 // If set, enable XML documentation generation
90                 //
91                 public static Documentation Documentation;
92
93                 //
94                 // Constructor
95                 //
96                 static RootContext ()
97                 {
98                         tree = new Tree ();
99                         type_container_resolve_order = new ArrayList ();
100                 }
101
102                 public static bool NeedsEntryPoint {
103                         get {
104                                 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
105                         }
106                 }
107
108                 static public Tree Tree {
109                         get {
110                                 return tree;
111                         }
112                 }
113
114                 static public string MainClass;
115                 
116                 public static void RegisterOrder (TypeContainer tc)
117                 {
118                         type_container_resolve_order.Add (tc);
119                 }
120                 
121                 // 
122                 // The default compiler checked state
123                 //
124                 static public bool Checked = false;
125
126                 //
127                 // Whether to allow Unsafe code
128                 //
129                 static public bool Unsafe = false;
130                 
131                 static string MakeFQN (string nsn, string name)
132                 {
133                         if (nsn == "")
134                                 return name;
135                         return String.Concat (nsn, ".", name);
136                 }
137
138                 // <remarks>
139                 //   This function is used to resolve the hierarchy tree.
140                 //   It processes interfaces, structs and classes in that order.
141                 //
142                 //   It creates the TypeBuilder's as it processes the user defined
143                 //   types.  
144                 // </remarks>
145                 static public void ResolveTree ()
146                 {
147                         //
148                         // Interfaces are processed next, as classes and
149                         // structs might inherit from an object or implement
150                         // a set of interfaces, we need to be able to tell
151                         // them appart by just using the TypeManager.
152                         //
153                         TypeContainer root = Tree.Types;
154
155                         ArrayList ifaces = root.Interfaces;
156                         if (ifaces != null){
157                                 foreach (Interface i in ifaces) 
158                                         i.DefineType ();
159                         }
160
161                         foreach (TypeContainer tc in root.Types)
162                                 tc.DefineType ();
163
164                         if (root.Delegates != null)
165                                 foreach (Delegate d in root.Delegates) 
166                                         d.DefineType ();
167
168                         if (root.Enums != null)
169                                 foreach (Enum e in root.Enums)
170                                         e.DefineType ();
171                 }
172
173                 static void Error_TypeConflict (string name, Location loc)
174                 {
175                         Report.Error (
176                                 520, loc, "`" + name + "' conflicts with a predefined type");
177                 }
178
179                 static void Error_TypeConflict (string name)
180                 {
181                         Report.Error (
182                                 520, "`" + name + "' conflicts with a predefined type");
183                 }
184
185                 //
186                 // Resolves a single class during the corlib bootstrap process
187                 //
188                 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
189                 {
190                         object o = root.GetDefinition (name);
191                         if (o == null){
192                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
193                                 return null;
194                         }
195
196                         if (!(o is Class)){
197                                 if (o is DeclSpace){
198                                         DeclSpace d = (DeclSpace) o;
199
200                                         Error_TypeConflict (name, d.Location);
201                                 } else
202                                         Error_TypeConflict (name);
203
204                                 return null;
205                         }
206
207                         return ((DeclSpace) o).DefineType ();
208                 }
209
210                 //
211                 // Resolves a struct during the corlib bootstrap process
212                 //
213                 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
214                 {
215                         object o = root.GetDefinition (name);
216                         if (o == null){
217                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
218                                 return;
219                         }
220
221                         if (!(o is Struct)){
222                                 if (o is DeclSpace){
223                                         DeclSpace d = (DeclSpace) o;
224
225                                         Error_TypeConflict (name, d.Location);
226                                 } else
227                                         Error_TypeConflict (name);
228
229                                 return;
230                         }
231
232                         ((DeclSpace) o).DefineType ();
233                 }
234
235                 //
236                 // Resolves a struct during the corlib bootstrap process
237                 //
238                 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
239                 {
240                         object o = root.GetDefinition (name);
241                         if (o == null){
242                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
243                                 return;
244                         }
245
246                         if (!(o is Interface)){
247                                 if (o is DeclSpace){
248                                         DeclSpace d = (DeclSpace) o;
249
250                                         Error_TypeConflict (name, d.Location);
251                                 } else
252                                         Error_TypeConflict (name);
253
254                                 return;
255                         }
256
257                         ((DeclSpace) o).DefineType ();
258                 }
259
260                 //
261                 // Resolves a delegate during the corlib bootstrap process
262                 //
263                 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
264                 {
265                         object o = root.GetDefinition (name);
266                         if (o == null){
267                                 Report.Error (518, "The predefined type `" + name + "' is not defined");
268                                 Environment.Exit (1);
269                         }
270
271                         if (!(o is Delegate)){
272                                 Error_TypeConflict (name);
273                                 return;
274                         }
275
276                         ((DeclSpace) o).DefineType ();
277                 }
278                 
279
280                 /// <summary>
281                 ///    Resolves the core types in the compiler when compiling with --nostdlib
282                 /// </summary>
283                 static public void ResolveCore ()
284                 {
285                         TypeContainer root = Tree.Types;
286
287                         TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
288                         TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
289                         TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
290                         TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
291                         
292                         string [] interfaces_first_stage = {
293                                 "System.IComparable", "System.ICloneable",
294                                 "System.IConvertible",
295                                 
296                                 "System.Collections.IEnumerable",
297                                 "System.Collections.ICollection",
298                                 "System.Collections.IEnumerator",
299                                 "System.Collections.IList", 
300                                 "System.IAsyncResult",
301                                 "System.IDisposable",
302                                 
303                                 "System.Runtime.Serialization.ISerializable",
304                                 "System.Runtime.InteropServices._Exception",
305
306                                 "System.Reflection.IReflect",
307                                 "System.Reflection.ICustomAttributeProvider",
308
309                                 //
310                                 // Generic types
311                                 //
312                                 "System.Collections.Generic.IEnumerator`1",
313                                 "System.Collections.Generic.IEnumerable`1",
314                         };
315
316                         foreach (string iname in interfaces_first_stage)
317                                 BootstrapCorlib_ResolveInterface (root, iname);
318
319                         //
320                         // These are the base value types
321                         //
322                         string [] structs_first_stage = {
323                                 "System.Byte",    "System.SByte",
324                                 "System.Int16",   "System.UInt16",
325                                 "System.Int32",   "System.UInt32",
326                                 "System.Int64",   "System.UInt64",
327                         };
328
329                         foreach (string cname in structs_first_stage)
330                                 BootstrapCorlib_ResolveStruct (root, cname);
331
332                         //
333                         // Now, we can load the enumerations, after this point,
334                         // we can use enums.
335                         //
336                         TypeManager.InitEnumUnderlyingTypes ();
337
338                         string [] structs_second_stage = {
339                                 "System.Single",  "System.Double",
340                                 "System.Char",    "System.Boolean",
341                                 "System.Decimal", "System.Void",
342                                 "System.RuntimeFieldHandle",
343                                 "System.RuntimeArgumentHandle",
344                                 "System.RuntimeTypeHandle",
345                                 "System.IntPtr",
346                                 "System.TypedReference",
347                                 "System.ArgIterator"
348                         };
349                         
350                         foreach (string cname in structs_second_stage)
351                                 BootstrapCorlib_ResolveStruct (root, cname);
352                         
353                         //
354                         // These are classes that depends on the core interfaces
355                         //
356                         string [] classes_second_stage = {
357                                 "System.Enum",
358                                 "System.String",
359                                 "System.Array",
360                                 "System.Reflection.MemberInfo",
361                                 "System.Type",
362                                 "System.Exception",
363                                 "System.Activator",
364
365                                 //
366                                 // These are not really important in the order, but they
367                                 // are used by the compiler later on (typemanager/CoreLookupType-d)
368                                 //
369                                 "System.Runtime.CompilerServices.RuntimeHelpers",
370                                 "System.Reflection.DefaultMemberAttribute",
371                                 "System.Threading.Monitor",
372                                 
373                                 "System.AttributeUsageAttribute",
374                                 "System.Runtime.InteropServices.DllImportAttribute",
375                                 "System.Runtime.CompilerServices.MethodImplAttribute",
376                                 "System.Runtime.InteropServices.MarshalAsAttribute",
377                                 "System.Runtime.CompilerServices.NewConstraintAttribute",
378                                 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
379                                 "System.Runtime.CompilerServices.FixedBufferAttribute",
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                         };
396
397                         foreach (string cname in classes_second_stage)
398                                 BootstrapCorlib_ResolveClass (root, cname);
399
400                         BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
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                         if (type_container_resolve_order != null){
579                                 foreach (TypeContainer tc in type_container_resolve_order) {
580                                         // When compiling corlib, these types have already been
581                                         // populated from BootCorlib_PopulateCoreTypes ().
582                                         if (!RootContext.StdLib &&
583                                             ((tc.Name == "System.Object") ||
584                                              (tc.Name == "System.Attribute") ||
585                                              (tc.Name == "System.ValueType") ||
586                                              (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
587                                                 continue;
588
589                                         if ((tc.ModFlags & Modifiers.NEW) == 0)
590                                                 tc.Define ();
591                                 }
592                         }
593
594                         ArrayList delegates = root.Delegates;
595                         if (delegates != null){
596                                 foreach (Delegate d in delegates)
597                                         if ((d.ModFlags & Modifiers.NEW) == 0)
598                                                 d.Define ();
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                         
621                         if (Tree.Types.Delegates != null) {
622                                 foreach (Delegate d in Tree.Types.Delegates)
623                                         d.Emit ();
624                         }                       
625                         //
626                         // Run any hooks after all the types have been defined.
627                         // This is used to create nested auxiliary classes for example
628                         //
629
630                         if (EmitCodeHook != null)
631                                 EmitCodeHook ();
632
633                         CodeGen.Assembly.Emit (Tree.Types);
634                         CodeGen.Module.Emit (Tree.Types);
635                 }
636                 
637                 //
638                 // Public Field, used to track which method is the public entry
639                 // point.
640                 //
641                 static public MethodInfo EntryPoint;
642
643                 //
644                 // Track the location of the entry point.
645                 //
646                 static public Location EntryPointLocation;
647
648                 //
649                 // These are used to generate unique names on the structs and fields.
650                 //
651                 static int field_count;
652                 
653                 //
654                 // Makes an initialized struct, returns the field builder that
655                 // references the data.  Thanks go to Sergey Chaban for researching
656                 // how to do this.  And coming up with a shorter mechanism than I
657                 // was able to figure out.
658                 //
659                 // This works but makes an implicit public struct $ArrayType$SIZE and
660                 // makes the fields point to it.  We could get more control if we did
661                 // use instead:
662                 //
663                 // 1. DefineNestedType on the impl_details_class with our struct.
664                 //
665                 // 2. Define the field on the impl_details_class
666                 //
667                 static public FieldBuilder MakeStaticData (byte [] data)
668                 {
669                         FieldBuilder fb;
670                         
671                         if (impl_details_class == null){
672                                 impl_details_class = CodeGen.Module.Builder.DefineType (
673                                         "<PrivateImplementationDetails>",
674                                         TypeAttributes.NotPublic,
675                                         TypeManager.object_type);
676                                 
677                                 RegisterCompilerGeneratedType (impl_details_class);
678                         }
679
680                         fb = impl_details_class.DefineInitializedData (
681                                 "$$field-" + (field_count++), data,
682                                 FieldAttributes.Static | FieldAttributes.Assembly);
683                         
684                         return fb;
685                 }
686         }
687 }
688               
689