**** Merged r41364 from MCS ****
[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                                         type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
457                                         type_builder.CreateType ();
458                                 }
459                         }
460                         
461                         type_container_resolve_order = null;
462                         helper_classes = null;
463                         //tree = null;
464                         TypeManager.CleanUp ();
465                 }
466
467                 /// <summary>
468                 ///   Used to register classes that need to be closed after all the
469                 ///   user defined classes
470                 /// </summary>
471                 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
472                 {
473                         if (helper_classes == null)
474                                 helper_classes = new ArrayList ();
475
476                         helper_classes.Add (helper_class);
477                 }
478                 
479                 static void Report1530 (Location loc)
480                 {
481                         Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
482                 }
483                 
484                 static public void PopulateCoreType (TypeContainer root, string name)
485                 {
486                         DeclSpace ds = (DeclSpace) root.GetDefinition (name);
487
488                         ds.DefineMembers (root);
489                         ds.Define ();
490                 }
491                 
492                 static public void BootCorlib_PopulateCoreTypes ()
493                 {
494                         TypeContainer root = tree.Types;
495
496                         PopulateCoreType (root, "System.Object");
497                         PopulateCoreType (root, "System.ValueType");
498                         PopulateCoreType (root, "System.Attribute");
499                         PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
500                 }
501                 
502                 // <summary>
503                 //   Populates the structs and classes with fields and methods
504                 // </summary>
505                 //
506                 // This is invoked after all interfaces, structs and classes
507                 // have been defined through `ResolveTree' 
508                 static public void PopulateTypes ()
509                 {
510                         TypeContainer root = Tree.Types;
511
512                         if (type_container_resolve_order != null){
513                                 if (RootContext.StdLib){
514                                         foreach (TypeContainer tc in type_container_resolve_order)
515                                                 tc.DefineMembers (root);
516                                 } else {
517                                         foreach (TypeContainer tc in type_container_resolve_order) {
518                                                 // When compiling corlib, these types have already been
519                                                 // populated from BootCorlib_PopulateCoreTypes ().
520                                                 if (((tc.Name == "System.Object") ||
521                                                         (tc.Name == "System.Attribute") ||
522                                                         (tc.Name == "System.ValueType") ||
523                                                         (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
524                                                 continue;
525
526                                                 tc.DefineMembers (root);
527                                         }
528                                 } 
529                         }
530
531                         ArrayList delegates = root.Delegates;
532                         if (delegates != null){
533                                 foreach (Delegate d in delegates)
534                                         if ((d.ModFlags & Modifiers.NEW) == 0)
535                                                 d.DefineMembers (root);
536                                         else
537                                                 Report1530 (d.Location);
538                         }
539
540                         ArrayList enums = root.Enums;
541                         if (enums != null){
542                                 foreach (Enum en in enums)
543                                         if ((en.ModFlags & Modifiers.NEW) == 0)
544                                                 en.DefineMembers (root);
545                                         else
546                                                 Report1530 (en.Location);
547                         }
548
549                         //
550                         // Check for cycles in the struct layout
551                         //
552                         if (type_container_resolve_order != null){
553                                 Hashtable seen = new Hashtable ();
554                                 foreach (TypeContainer tc in type_container_resolve_order)
555                                         TypeManager.CheckStructCycles (tc, seen);
556                         }
557                 }
558
559                 //
560                 // A generic hook delegate
561                 //
562                 public delegate void Hook ();
563
564                 //
565                 // A hook invoked when the code has been generated.
566                 //
567                 public static event Hook EmitCodeHook;
568
569                 //
570                 // DefineTypes is used to fill in the members of each type.
571                 //
572                 static public void DefineTypes ()
573                 {
574                         TypeContainer root = Tree.Types;
575
576                         if (type_container_resolve_order != null){
577                                 foreach (TypeContainer tc in type_container_resolve_order) {
578                                         // When compiling corlib, these types have already been
579                                         // populated from BootCorlib_PopulateCoreTypes ().
580                                         if (!RootContext.StdLib &&
581                                             ((tc.Name == "System.Object") ||
582                                              (tc.Name == "System.Attribute") ||
583                                              (tc.Name == "System.ValueType") ||
584                                              (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
585                                                 continue;
586
587                                         if ((tc.ModFlags & Modifiers.NEW) == 0)
588                                                 tc.Define ();
589                                 }
590                         }
591
592                         ArrayList delegates = root.Delegates;
593                         if (delegates != null){
594                                 foreach (Delegate d in delegates)
595                                         if ((d.ModFlags & Modifiers.NEW) == 0)
596                                                 d.Define ();
597                         }
598
599                         ArrayList enums = root.Enums;
600                         if (enums != null){
601                                 foreach (Enum en in enums)
602                                         if ((en.ModFlags & Modifiers.NEW) == 0)
603                                                 en.Define ();
604                         }
605                 }
606
607                 static public void EmitCode ()
608                 {
609                         if (Tree.Types.Enums != null) {
610                                 foreach (Enum e in Tree.Types.Enums)
611                                         e.Emit ();
612                         }
613
614                         if (type_container_resolve_order != null) {
615                                 foreach (TypeContainer tc in type_container_resolve_order)
616                                         tc.EmitType ();
617                         }
618                         
619                         if (Tree.Types.Delegates != null) {
620                                 foreach (Delegate d in Tree.Types.Delegates)
621                                         d.Emit ();
622                         }                       
623                         //
624                         // Run any hooks after all the types have been defined.
625                         // This is used to create nested auxiliary classes for example
626                         //
627
628                         if (EmitCodeHook != null)
629                                 EmitCodeHook ();
630
631                         CodeGen.Assembly.Emit (Tree.Types);
632                         CodeGen.Module.Emit (Tree.Types);
633                 }
634                 
635                 //
636                 // Public Field, used to track which method is the public entry
637                 // point.
638                 //
639                 static public MethodInfo EntryPoint;
640
641                 //
642                 // Track the location of the entry point.
643                 //
644                 static public Location EntryPointLocation;
645
646                 //
647                 // These are used to generate unique names on the structs and fields.
648                 //
649                 static int field_count;
650                 
651                 //
652                 // Makes an initialized struct, returns the field builder that
653                 // references the data.  Thanks go to Sergey Chaban for researching
654                 // how to do this.  And coming up with a shorter mechanism than I
655                 // was able to figure out.
656                 //
657                 // This works but makes an implicit public struct $ArrayType$SIZE and
658                 // makes the fields point to it.  We could get more control if we did
659                 // use instead:
660                 //
661                 // 1. DefineNestedType on the impl_details_class with our struct.
662                 //
663                 // 2. Define the field on the impl_details_class
664                 //
665                 static public FieldBuilder MakeStaticData (byte [] data)
666                 {
667                         FieldBuilder fb;
668                         
669                         if (impl_details_class == null){
670                                 impl_details_class = CodeGen.Module.Builder.DefineType (
671                                         "<PrivateImplementationDetails>",
672                                         TypeAttributes.NotPublic,
673                                         TypeManager.object_type);
674                                 
675                                 RegisterCompilerGeneratedType (impl_details_class);
676                         }
677
678                         fb = impl_details_class.DefineInitializedData (
679                                 "$$field-" + (field_count++), data,
680                                 FieldAttributes.Static | FieldAttributes.Assembly);
681                         
682                         return fb;
683                 }
684         }
685 }
686               
687