**** Merged r39979-r40298 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                 static ArrayList attribute_types;
58
59                 //
60                 // Holds a reference to the Private Implementation Details
61                 // class.
62                 //
63                 static ArrayList helper_classes;
64                 
65                 static TypeBuilder impl_details_class;
66
67                 public static int WarningLevel = 3;
68
69                 public static Target Target = Target.Exe;
70                 public static string TargetExt = ".exe";
71
72                 public static bool VerifyClsCompliance = true;
73
74                 public static LanguageVersion Version = LanguageVersion.Default;
75
76                 //
77                 // We keep strongname related info here because
78                 // it's also used as complier options from CSC 8.x
79                 //
80                 public static string StrongNameKeyFile;
81                 public static string StrongNameKeyContainer;
82                 public static bool StrongNameDelaySign = false;
83
84                 //
85                 // If set, enable XML documentation generation
86                 //
87                 public static Documentation Documentation;
88
89                 //
90                 // Constructor
91                 //
92                 static RootContext ()
93                 {
94                         tree = new Tree ();
95                         type_container_resolve_order = new ArrayList ();
96                 }
97
98                 public static bool NeedsEntryPoint {
99                         get {
100                                 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
101                         }
102                 }
103
104                 static public Tree Tree {
105                         get {
106                                 return tree;
107                         }
108                 }
109
110                 static public string MainClass;
111                 
112                 public static void RegisterOrder (TypeContainer tc)
113                 {
114                         type_container_resolve_order.Add (tc);
115                 }
116
117                 public static void RegisterAttribute (TypeContainer tc)
118                 {
119                         if (attribute_types == null)
120                                 attribute_types = new ArrayList ();
121                         
122                         attribute_types.Add (tc);
123                 }
124                 
125                 // 
126                 // The default compiler checked state
127                 //
128                 static public bool Checked = false;
129
130                 //
131                 // Whether to allow Unsafe code
132                 //
133                 static public bool Unsafe = false;
134                 
135                 static string MakeFQN (string nsn, string name)
136                 {
137                         if (nsn == "")
138                                 return name;
139                         return String.Concat (nsn, ".", name);
140                 }
141
142                 // <remarks>
143                 //   This function is used to resolve the hierarchy tree.
144                 //   It processes interfaces, structs and classes in that order.
145                 //
146                 //   It creates the TypeBuilder's as it processes the user defined
147                 //   types.  
148                 // </remarks>
149                 static public void ResolveTree ()
150                 {
151                         //
152                         // Process the attribute types separately and before anything else
153                         //
154                         if (attribute_types != null)
155                                 foreach (TypeContainer tc in attribute_types)
156                                         tc.DefineType ();
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 (Interface 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                                 Environment.Exit (1);
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                         
302                         string [] interfaces_first_stage = {
303                                 "System.IComparable", "System.ICloneable",
304                                 "System.IConvertible",
305                                 
306                                 "System.Collections.IEnumerable",
307                                 "System.Collections.ICollection",
308                                 "System.Collections.IEnumerator",
309                                 "System.Collections.IList", 
310                                 "System.IAsyncResult",
311                                 "System.IDisposable",
312                                 
313                                 "System.Runtime.Serialization.ISerializable",
314                                 "System.Runtime.InteropServices._Exception",
315
316                                 "System.Reflection.IReflect",
317                                 "System.Reflection.ICustomAttributeProvider",
318
319                                 //
320                                 // Generic types
321                                 //
322                                 "System.Collections.Generic.IEnumerator`1",
323                                 "System.Collections.Generic.IEnumerable`1",
324                         };
325
326                         foreach (string iname in interfaces_first_stage)
327                                 BootstrapCorlib_ResolveInterface (root, iname);
328
329                         //
330                         // These are the base value types
331                         //
332                         string [] structs_first_stage = {
333                                 "System.Byte",    "System.SByte",
334                                 "System.Int16",   "System.UInt16",
335                                 "System.Int32",   "System.UInt32",
336                                 "System.Int64",   "System.UInt64",
337                         };
338
339                         foreach (string cname in structs_first_stage)
340                                 BootstrapCorlib_ResolveStruct (root, cname);
341
342                         //
343                         // Now, we can load the enumerations, after this point,
344                         // we can use enums.
345                         //
346                         TypeManager.InitEnumUnderlyingTypes ();
347
348                         string [] structs_second_stage = {
349                                 "System.Single",  "System.Double",
350                                 "System.Char",    "System.Boolean",
351                                 "System.Decimal", "System.Void",
352                                 "System.RuntimeFieldHandle",
353                                 "System.RuntimeArgumentHandle",
354                                 "System.RuntimeTypeHandle",
355                                 "System.IntPtr",
356                                 "System.TypedReference",
357                                 "System.ArgIterator"
358                         };
359                         
360                         foreach (string cname in structs_second_stage)
361                                 BootstrapCorlib_ResolveStruct (root, cname);
362                         
363                         //
364                         // These are classes that depends on the core interfaces
365                         //
366                         string [] classes_second_stage = {
367                                 "System.Enum",
368                                 "System.String",
369                                 "System.Array",
370                                 "System.Reflection.MemberInfo",
371                                 "System.Type",
372                                 "System.Exception",
373                                 "System.Activator",
374
375                                 //
376                                 // These are not really important in the order, but they
377                                 // are used by the compiler later on (typemanager/CoreLookupType-d)
378                                 //
379                                 "System.Runtime.CompilerServices.RuntimeHelpers",
380                                 "System.Reflection.DefaultMemberAttribute",
381                                 "System.Threading.Monitor",
382                                 
383                                 "System.AttributeUsageAttribute",
384                                 "System.Runtime.InteropServices.DllImportAttribute",
385                                 "System.Runtime.CompilerServices.MethodImplAttribute",
386                                 "System.Runtime.InteropServices.MarshalAsAttribute",
387                                 "System.Runtime.CompilerServices.NewConstraintAttribute",
388                                 "System.Diagnostics.ConditionalAttribute",
389                                 "System.ObsoleteAttribute",
390                                 "System.ParamArrayAttribute",
391                                 "System.CLSCompliantAttribute",
392                                 "System.Security.UnverifiableCodeAttribute",
393                                 "System.Security.Permissions.SecurityAttribute",
394                                 "System.Runtime.CompilerServices.IndexerNameAttribute",
395                                 "System.Runtime.CompilerServices.DecimalConstantAttribute",
396                                 "System.Runtime.InteropServices.InAttribute",
397                                 "System.Runtime.InteropServices.OutAttribute",
398                                 "System.Runtime.InteropServices.StructLayoutAttribute",
399                                 "System.Runtime.InteropServices.FieldOffsetAttribute",
400                                 "System.InvalidOperationException",
401                                 "System.NotSupportedException",
402                                 "System.MarshalByRefObject",
403                                 "System.Security.CodeAccessPermission"
404                         };
405
406                         foreach (string cname in classes_second_stage)
407                                 BootstrapCorlib_ResolveClass (root, cname);
408
409                         BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
410
411                         BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
412
413                         // These will be defined indirectly during the previous ResolveDelegate.
414                         // However make sure the rest of the checks happen.
415                         string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
416                         foreach (string cname in delegate_types)
417                                 BootstrapCorlib_ResolveClass (root, cname);
418                 }
419                         
420                 // <summary>
421                 //   Closes all open types
422                 // </summary>
423                 //
424                 // <remarks>
425                 //   We usually use TypeBuilder types.  When we are done
426                 //   creating the type (which will happen after we have added
427                 //   methods, fields, etc) we need to "Define" them before we
428                 //   can save the Assembly
429                 // </remarks>
430                 static public void CloseTypes ()
431                 {
432                         TypeContainer root = Tree.Types;
433                         
434                         if (root.Enums != null)
435                                 foreach (Enum en in root.Enums)
436                                         en.CloseType ();
437
438                         if (attribute_types != null)
439                                 foreach (TypeContainer tc in attribute_types)
440                                         tc.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.CreateType ();
470                         }
471                         
472                         attribute_types = null;
473                         type_container_resolve_order = null;
474                         helper_classes = null;
475                         //tree = null;
476                         TypeManager.CleanUp ();
477                 }
478
479                 /// <summary>
480                 ///   Used to register classes that need to be closed after all the
481                 ///   user defined classes
482                 /// </summary>
483                 public static void RegisterHelperClass (TypeBuilder helper_class)
484                 {
485                         if (helper_classes == null)
486                                 helper_classes = new ArrayList ();
487                         helper_classes.Add (helper_class);
488                 }
489                 
490                 static void Report1530 (Location loc)
491                 {
492                         Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
493                 }
494                 
495                 static public void PopulateCoreType (TypeContainer root, string name)
496                 {
497                         DeclSpace ds = (DeclSpace) root.GetDefinition (name);
498
499                         ds.DefineMembers (root);
500                         ds.Define ();
501                 }
502                 
503                 static public void BootCorlib_PopulateCoreTypes ()
504                 {
505                         TypeContainer root = tree.Types;
506
507                         PopulateCoreType (root, "System.Object");
508                         PopulateCoreType (root, "System.ValueType");
509                         PopulateCoreType (root, "System.Attribute");
510                 }
511                 
512                 // <summary>
513                 //   Populates the structs and classes with fields and methods
514                 // </summary>
515                 //
516                 // This is invoked after all interfaces, structs and classes
517                 // have been defined through `ResolveTree' 
518                 static public void PopulateTypes ()
519                 {
520                         TypeContainer root = Tree.Types;
521
522                         if (attribute_types != null)
523                                 foreach (TypeContainer tc in attribute_types)
524                                         tc.DefineMembers (root);
525
526                         if (type_container_resolve_order != null){
527                                 if (RootContext.StdLib){
528                                         foreach (TypeContainer tc in type_container_resolve_order)
529                                                 tc.DefineMembers (root);
530                                 } else {
531                                         foreach (TypeContainer tc in type_container_resolve_order) {
532                                                 // When compiling corlib, these types have already been
533                                                 // populated from BootCorlib_PopulateCoreTypes ().
534                                                 if (((tc.Name == "System.Object") ||
535                                                      (tc.Name == "System.Attribute") ||
536                                                      (tc.Name == "System.ValueType")))
537                                                 continue;
538
539                                                 tc.DefineMembers (root);
540                                         }
541                                 } 
542                         }
543
544                         ArrayList delegates = root.Delegates;
545                         if (delegates != null){
546                                 foreach (Delegate d in delegates)
547                                         if ((d.ModFlags & Modifiers.NEW) == 0)
548                                                 d.DefineMembers (root);
549                                         else
550                                                 Report1530 (d.Location);
551                         }
552
553                         ArrayList enums = root.Enums;
554                         if (enums != null){
555                                 foreach (Enum en in enums)
556                                         if ((en.ModFlags & Modifiers.NEW) == 0)
557                                                 en.DefineMembers (root);
558                                         else
559                                                 Report1530 (en.Location);
560                         }
561
562                         //
563                         // Check for cycles in the struct layout
564                         //
565                         if (type_container_resolve_order != null){
566                                 Hashtable seen = new Hashtable ();
567                                 foreach (TypeContainer tc in type_container_resolve_order)
568                                         TypeManager.CheckStructCycles (tc, seen);
569                         }
570                 }
571
572                 //
573                 // A generic hook delegate
574                 //
575                 public delegate void Hook ();
576
577                 //
578                 // A hook invoked when the code has been generated.
579                 //
580                 public static event Hook EmitCodeHook;
581
582                 //
583                 // DefineTypes is used to fill in the members of each type.
584                 //
585                 static public void DefineTypes ()
586                 {
587                         TypeContainer root = Tree.Types;
588
589                         if (attribute_types != null)
590                                 foreach (TypeContainer tc in attribute_types)
591                                         tc.Define ();
592
593                         if (type_container_resolve_order != null){
594                                 foreach (TypeContainer tc in type_container_resolve_order) {
595                                         // When compiling corlib, these types have already been
596                                         // populated from BootCorlib_PopulateCoreTypes ().
597                                         if (!RootContext.StdLib &&
598                                             ((tc.Name == "System.Object") ||
599                                              (tc.Name == "System.Attribute") ||
600                                              (tc.Name == "System.ValueType")))
601                                                 continue;
602
603                                         if ((tc.ModFlags & Modifiers.NEW) == 0)
604                                                 tc.Define ();
605                                 }
606                         }
607
608                         ArrayList delegates = root.Delegates;
609                         if (delegates != null){
610                                 foreach (Delegate d in delegates)
611                                         if ((d.ModFlags & Modifiers.NEW) == 0)
612                                                 d.Define ();
613                         }
614
615                         ArrayList enums = root.Enums;
616                         if (enums != null){
617                                 foreach (Enum en in enums)
618                                         if ((en.ModFlags & Modifiers.NEW) == 0)
619                                                 en.Define ();
620                         }
621                 }
622
623                 static public void EmitCode ()
624                 {
625                         if (attribute_types != null)
626                                 foreach (TypeContainer tc in attribute_types)
627                                         tc.EmitType ();
628
629                         CodeGen.Assembly.Emit (Tree.Types);
630                         CodeGen.Module.Emit (Tree.Types);
631                         
632                         if (Tree.Types.Enums != null) {
633                                 foreach (Enum e in Tree.Types.Enums)
634                                         e.Emit ();
635                         }
636
637                         if (type_container_resolve_order != null) {
638                                 foreach (TypeContainer tc in type_container_resolve_order)
639                                         tc.EmitType ();
640                         }
641                         
642                         if (Tree.Types.Delegates != null) {
643                                 foreach (Delegate d in Tree.Types.Delegates)
644                                         d.Emit ();
645                         }                       
646                         //
647                         // Run any hooks after all the types have been defined.
648                         // This is used to create nested auxiliary classes for example
649                         //
650
651                         if (EmitCodeHook != null)
652                                 EmitCodeHook ();
653                 }
654                 
655                 //
656                 // Public Field, used to track which method is the public entry
657                 // point.
658                 //
659                 static public MethodInfo EntryPoint;
660
661                 //
662                 // Track the location of the entry point.
663                 //
664                 static public Location EntryPointLocation;
665
666                 //
667                 // These are used to generate unique names on the structs and fields.
668                 //
669                 static int field_count;
670                 
671                 //
672                 // Makes an initialized struct, returns the field builder that
673                 // references the data.  Thanks go to Sergey Chaban for researching
674                 // how to do this.  And coming up with a shorter mechanism than I
675                 // was able to figure out.
676                 //
677                 // This works but makes an implicit public struct $ArrayType$SIZE and
678                 // makes the fields point to it.  We could get more control if we did
679                 // use instead:
680                 //
681                 // 1. DefineNestedType on the impl_details_class with our struct.
682                 //
683                 // 2. Define the field on the impl_details_class
684                 //
685                 static public FieldBuilder MakeStaticData (byte [] data)
686                 {
687                         FieldBuilder fb;
688                         
689                         if (impl_details_class == null){
690                                 impl_details_class = CodeGen.Module.Builder.DefineType (
691                                         "<PrivateImplementationDetails>",
692                                         TypeAttributes.NotPublic,
693                                         TypeManager.object_type);
694                                 
695                                 RegisterHelperClass (impl_details_class);
696                         }
697
698                         fb = impl_details_class.DefineInitializedData (
699                                 "$$field-" + (field_count++), data,
700                                 FieldAttributes.Static | FieldAttributes.Assembly);
701                         
702                         return fb;
703                 }
704         }
705 }
706               
707