2006-04-27 Jonathan Chambers <jonathan.chambers@ansys.com>
[mcs.git] / gmcs / rootcontext.cs
blobf5ad0c98a628e98b442f466f84a483d464fe13c3
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
12 using System;
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
17 using System.Xml;
19 namespace Mono.CSharp {
21 public enum LanguageVersion
23 Default = 0,
24 ISO_1 = 1
27 public class RootContext {
30 // Contains the parsed tree
32 static Tree tree;
35 // This hashtable contains all of the #definitions across the source code
36 // it is used by the ConditionalAttribute handler.
38 public static Hashtable AllDefines = new Hashtable ();
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.
45 public static bool StdLib;
48 // This keeps track of the order in which classes were defined
49 // so that we can poulate them in that order.
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).
56 static ArrayList type_container_resolve_order;
59 // Holds a reference to the Private Implementation Details
60 // class.
62 static ArrayList helper_classes;
64 static TypeBuilder impl_details_class;
66 public static int WarningLevel;
68 public static Target Target;
69 public static string TargetExt;
71 public static bool VerifyClsCompliance = true;
73 /// <summary>
74 /// Holds /optimize option
75 /// </summary>
76 public static bool Optimize = true;
78 public static LanguageVersion Version;
81 // We keep strongname related info here because
82 // it's also used as complier options from CSC 8.x
84 public static string StrongNameKeyFile;
85 public static string StrongNameKeyContainer;
86 public static bool StrongNameDelaySign;
88 public static bool BrokenCircularDeps;
90 // If set, enable XML documentation generation
92 public static Documentation Documentation;
94 static public string MainClass;
97 // Constructor
99 static RootContext ()
101 Reset ();
104 public static void Reset ()
106 tree = new Tree ();
107 type_container_resolve_order = new ArrayList ();
108 EntryPoint = null;
109 WarningLevel = 3;
110 Checked = false;
111 Unsafe = false;
112 StdLib = true;
113 StrongNameKeyFile = null;
114 StrongNameKeyContainer = null;
115 StrongNameDelaySign = false;
116 MainClass = null;
117 Target = Target.Exe;
118 TargetExt = ".exe";
119 Version = LanguageVersion.Default;
120 Documentation = null;
121 impl_details_class = null;
124 public static bool NeedsEntryPoint {
125 get {
126 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
130 static public Tree Tree {
131 get {
132 return tree;
136 public static void RegisterOrder (TypeContainer tc)
138 type_container_resolve_order.Add (tc);
142 // The default compiler checked state
144 static public bool Checked;
147 // Whether to allow Unsafe code
149 static public bool Unsafe;
151 // <remarks>
152 // This function is used to resolve the hierarchy tree.
153 // It processes interfaces, structs and classes in that order.
155 // It creates the TypeBuilder's as it processes the user defined
156 // types.
157 // </remarks>
158 static public void ResolveTree ()
161 // Interfaces are processed next, as classes and
162 // structs might inherit from an object or implement
163 // a set of interfaces, we need to be able to tell
164 // them appart by just using the TypeManager.
166 TypeContainer root = Tree.Types;
168 ArrayList ifaces = root.Interfaces;
169 if (ifaces != null){
170 foreach (TypeContainer i in ifaces)
171 i.DefineType ();
174 foreach (TypeContainer tc in root.Types)
175 tc.DefineType ();
177 if (root.Delegates != null)
178 foreach (Delegate d in root.Delegates)
179 d.DefineType ();
181 if (root.Enums != null)
182 foreach (Enum e in root.Enums)
183 e.DefineType ();
186 static void Error_TypeConflict (string name, Location loc)
188 Report.Error (
189 520, loc, "`" + name + "' conflicts with a predefined type");
192 static void Error_TypeConflict (string name)
194 Report.Error (
195 520, "`" + name + "' conflicts with a predefined type");
199 // Resolves a single class during the corlib bootstrap process
201 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
203 object o = root.GetDefinition (name);
204 if (o == null){
205 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
206 return null;
209 if (!(o is Class)){
210 if (o is DeclSpace){
211 DeclSpace d = (DeclSpace) o;
213 Error_TypeConflict (name, d.Location);
214 } else
215 Error_TypeConflict (name);
217 return null;
220 return ((DeclSpace) o).DefineType ();
224 // Resolves a struct during the corlib bootstrap process
226 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
228 object o = root.GetDefinition (name);
229 if (o == null){
230 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
231 return;
234 if (!(o is Struct)){
235 if (o is DeclSpace){
236 DeclSpace d = (DeclSpace) o;
238 Error_TypeConflict (name, d.Location);
239 } else
240 Error_TypeConflict (name);
242 return;
245 ((DeclSpace) o).DefineType ();
249 // Resolves a struct during the corlib bootstrap process
251 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
253 object o = root.GetDefinition (name);
254 if (o == null){
255 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
256 return;
259 if (!(o is Interface)){
260 if (o is DeclSpace){
261 DeclSpace d = (DeclSpace) o;
263 Error_TypeConflict (name, d.Location);
264 } else
265 Error_TypeConflict (name);
267 return;
270 ((DeclSpace) o).DefineType ();
274 // Resolves a delegate during the corlib bootstrap process
276 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
278 object o = root.GetDefinition (name);
279 if (o == null){
280 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
281 return;
284 if (!(o is Delegate)){
285 Error_TypeConflict (name);
286 return;
289 ((DeclSpace) o).DefineType ();
293 /// <summary>
294 /// Resolves the core types in the compiler when compiling with --nostdlib
295 /// </summary>
296 static public void ResolveCore ()
298 TypeContainer root = Tree.Types;
300 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
301 TypeManager.system_object_expr.Type = TypeManager.object_type;
302 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
303 TypeManager.system_valuetype_expr.Type = TypeManager.value_type;
304 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
305 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
307 string [] interfaces_first_stage = {
308 "System.IComparable", "System.ICloneable",
309 "System.IConvertible",
311 "System.Collections.IEnumerable",
312 "System.Collections.ICollection",
313 "System.Collections.IEnumerator",
314 "System.Collections.IList",
315 "System.IAsyncResult",
316 "System.IDisposable",
318 "System.Runtime.Serialization.ISerializable",
319 "System.Runtime.InteropServices._Exception",
321 "System.Reflection.IReflect",
322 "System.Reflection.ICustomAttributeProvider",
325 // Generic types
327 "System.Collections.Generic.IEnumerator`1",
328 "System.Collections.Generic.IEnumerable`1"
331 foreach (string iname in interfaces_first_stage)
332 BootstrapCorlib_ResolveInterface (root, iname);
335 // These are the base value types
337 string [] structs_first_stage = {
338 "System.Byte", "System.SByte",
339 "System.Int16", "System.UInt16",
340 "System.Int32", "System.UInt32",
341 "System.Int64", "System.UInt64",
344 foreach (string cname in structs_first_stage)
345 BootstrapCorlib_ResolveStruct (root, cname);
348 // Now, we can load the enumerations, after this point,
349 // we can use enums.
351 TypeManager.InitEnumUnderlyingTypes ();
353 string [] structs_second_stage = {
354 "System.Single", "System.Double",
355 "System.Char", "System.Boolean",
356 "System.Decimal", "System.Void",
357 "System.RuntimeFieldHandle",
358 "System.RuntimeArgumentHandle",
359 "System.RuntimeTypeHandle",
360 "System.IntPtr",
361 "System.TypedReference",
362 "System.ArgIterator"
365 foreach (string cname in structs_second_stage)
366 BootstrapCorlib_ResolveStruct (root, cname);
369 // These are classes that depends on the core interfaces
371 string [] classes_second_stage = {
372 "System.Enum",
373 "System.String",
374 "System.Array",
375 "System.Reflection.MemberInfo",
376 "System.Type",
377 "System.Exception",
378 "System.Activator",
381 // These are not really important in the order, but they
382 // are used by the compiler later on (typemanager/CoreLookupType-d)
384 "System.Runtime.CompilerServices.RuntimeHelpers",
385 "System.Reflection.DefaultMemberAttribute",
386 "System.Threading.Monitor",
388 "System.AttributeUsageAttribute",
389 "System.Runtime.InteropServices.DllImportAttribute",
390 "System.Runtime.CompilerServices.MethodImplAttribute",
391 "System.Runtime.InteropServices.MarshalAsAttribute",
392 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
393 "System.Runtime.CompilerServices.FixedBufferAttribute",
394 "System.Diagnostics.ConditionalAttribute",
395 "System.ObsoleteAttribute",
396 "System.ParamArrayAttribute",
397 "System.CLSCompliantAttribute",
398 "System.Security.UnverifiableCodeAttribute",
399 "System.Security.Permissions.SecurityAttribute",
400 "System.Runtime.CompilerServices.DecimalConstantAttribute",
401 "System.Runtime.InteropServices.InAttribute",
402 "System.Runtime.InteropServices.OutAttribute",
403 "System.Runtime.InteropServices.StructLayoutAttribute",
404 "System.Runtime.InteropServices.FieldOffsetAttribute",
405 "System.Runtime.InteropServices.DefaultCharSetAttribute",
406 "System.InvalidOperationException",
407 "System.NotSupportedException",
408 "System.MarshalByRefObject",
409 "System.Security.CodeAccessPermission",
410 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
411 "System.Runtime.InteropServices.GuidAttribute",
412 "System.Reflection.AssemblyCultureAttribute"
415 foreach (string cname in classes_second_stage)
416 BootstrapCorlib_ResolveClass (root, cname);
418 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
420 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
422 // These will be defined indirectly during the previous ResolveDelegate.
423 // However make sure the rest of the checks happen.
424 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
425 foreach (string cname in delegate_types)
426 BootstrapCorlib_ResolveClass (root, cname);
429 // <summary>
430 // Closes all open types
431 // </summary>
433 // <remarks>
434 // We usually use TypeBuilder types. When we are done
435 // creating the type (which will happen after we have added
436 // methods, fields, etc) we need to "Define" them before we
437 // can save the Assembly
438 // </remarks>
439 static public void CloseTypes ()
441 TypeContainer root = Tree.Types;
443 if (root.Enums != null)
444 foreach (Enum en in root.Enums)
445 en.CloseType ();
448 // We do this in two passes, first we close the structs,
449 // then the classes, because it seems the code needs it this
450 // way. If this is really what is going on, we should probably
451 // make sure that we define the structs in order as well.
453 foreach (TypeContainer tc in type_container_resolve_order){
454 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
455 tc.CloseType ();
459 foreach (TypeContainer tc in type_container_resolve_order){
460 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
461 tc.CloseType ();
464 if (root.Delegates != null)
465 foreach (Delegate d in root.Delegates)
466 d.CloseType ();
470 // If we have a <PrivateImplementationDetails> class, close it
472 if (helper_classes != null){
473 foreach (TypeBuilder type_builder in helper_classes) {
474 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
475 type_builder.CreateType ();
479 type_container_resolve_order = null;
480 helper_classes = null;
481 //tree = null;
482 TypeManager.CleanUp ();
485 /// <summary>
486 /// Used to register classes that need to be closed after all the
487 /// user defined classes
488 /// </summary>
489 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
491 if (helper_classes == null)
492 helper_classes = new ArrayList ();
494 helper_classes.Add (helper_class);
497 static public void PopulateCoreType (TypeContainer root, string name)
499 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
501 ds.DefineMembers ();
502 ds.Define ();
505 static public void BootCorlib_PopulateCoreTypes ()
507 TypeContainer root = tree.Types;
509 PopulateCoreType (root, "System.Object");
510 PopulateCoreType (root, "System.ValueType");
511 PopulateCoreType (root, "System.Attribute");
512 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
515 // <summary>
516 // Populates the structs and classes with fields and methods
517 // </summary>
519 // This is invoked after all interfaces, structs and classes
520 // have been defined through `ResolveTree'
521 static public void PopulateTypes ()
523 TypeContainer root = Tree.Types;
525 if (type_container_resolve_order != null){
526 foreach (TypeContainer tc in type_container_resolve_order)
527 tc.ResolveType ();
528 foreach (TypeContainer tc in type_container_resolve_order)
529 tc.DefineMembers ();
532 ArrayList delegates = root.Delegates;
533 if (delegates != null){
534 foreach (Delegate d in delegates)
535 d.DefineMembers ();
538 ArrayList enums = root.Enums;
539 if (enums != null){
540 foreach (Enum en in enums)
541 en.DefineMembers ();
545 // Check for cycles in the struct layout
547 if (type_container_resolve_order != null){
548 Hashtable seen = new Hashtable ();
549 foreach (TypeContainer tc in type_container_resolve_order)
550 TypeManager.CheckStructCycles (tc, seen);
555 // A generic hook delegate
557 public delegate void Hook ();
560 // A hook invoked when the code has been generated.
562 public static event Hook EmitCodeHook;
565 // DefineTypes is used to fill in the members of each type.
567 static public void DefineTypes ()
569 TypeContainer root = Tree.Types;
571 ArrayList delegates = root.Delegates;
572 if (delegates != null){
573 foreach (Delegate d in delegates)
574 d.Define ();
577 if (type_container_resolve_order != null){
578 foreach (TypeContainer tc in type_container_resolve_order) {
579 // When compiling corlib, these types have already been
580 // populated from BootCorlib_PopulateCoreTypes ().
581 if (!RootContext.StdLib &&
582 ((tc.Name == "System.Object") ||
583 (tc.Name == "System.Attribute") ||
584 (tc.Name == "System.ValueType") ||
585 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
586 continue;
588 tc.Define ();
592 ArrayList enums = root.Enums;
593 if (enums != null){
594 foreach (Enum en in enums)
595 en.Define ();
599 static public void EmitCode ()
601 if (Tree.Types.Enums != null) {
602 foreach (Enum e in Tree.Types.Enums)
603 e.Emit ();
606 if (type_container_resolve_order != null) {
607 foreach (TypeContainer tc in type_container_resolve_order)
608 tc.EmitType ();
610 if (Report.Errors > 0)
611 return;
613 foreach (TypeContainer tc in type_container_resolve_order)
614 tc.VerifyMembers ();
617 if (Tree.Types.Delegates != null) {
618 foreach (Delegate d in Tree.Types.Delegates)
619 d.Emit ();
622 // Run any hooks after all the types have been defined.
623 // This is used to create nested auxiliary classes for example
626 if (EmitCodeHook != null)
627 EmitCodeHook ();
629 CodeGen.Assembly.Emit (Tree.Types);
630 CodeGen.Module.Emit (Tree.Types);
634 // Public Field, used to track which method is the public entry
635 // point.
637 static public MethodInfo EntryPoint;
640 // Track the location of the entry point.
642 static public Location EntryPointLocation;
645 // These are used to generate unique names on the structs and fields.
647 static int field_count;
650 // Makes an initialized struct, returns the field builder that
651 // references the data. Thanks go to Sergey Chaban for researching
652 // how to do this. And coming up with a shorter mechanism than I
653 // was able to figure out.
655 // This works but makes an implicit public struct $ArrayType$SIZE and
656 // makes the fields point to it. We could get more control if we did
657 // use instead:
659 // 1. DefineNestedType on the impl_details_class with our struct.
661 // 2. Define the field on the impl_details_class
663 static public FieldBuilder MakeStaticData (byte [] data)
665 FieldBuilder fb;
667 if (impl_details_class == null){
668 impl_details_class = CodeGen.Module.Builder.DefineType (
669 "<PrivateImplementationDetails>",
670 TypeAttributes.NotPublic,
671 TypeManager.object_type);
673 RegisterCompilerGeneratedType (impl_details_class);
676 fb = impl_details_class.DefineInitializedData (
677 "$$field-" + (field_count++), data,
678 FieldAttributes.Static | FieldAttributes.Assembly);
680 return fb;
683 public static void CheckUnsafeOption (Location loc)
685 if (!Unsafe) {
686 Report.Error (227, loc,
687 "Unsafe code requires the `unsafe' command line option to be specified");