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