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