2 // rootcontext.cs: keeps track of our tree representation, and assemblies loaded.
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 // Ravi Pratap (ravi@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
12 using System.Collections;
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 public class RootContext {
22 // Contains the parsed tree
27 // This hashtable contains all of the #definitions across the source code
28 // it is used by the ConditionalAttribute handler.
30 public static Hashtable AllDefines = new Hashtable ();
33 // Whether we are being linked against the standard libraries.
34 // This is only used to tell whether `System.Object' should
35 // have a parent or not.
37 public static bool StdLib = true;
40 // This keeps track of the order in which classes were defined
41 // so that we can poulate them in that order.
43 // Order is important, because we need to be able to tell by
44 // examining the parent's list of methods which ones are virtual
45 // or abstract as well as the parent names (to implement new,
48 static ArrayList type_container_resolve_order;
49 static ArrayList interface_resolve_order;
50 static ArrayList attribute_types;
53 // Holds a reference to the Private Implementation Details
56 static ArrayList helper_classes;
58 static TypeBuilder impl_details_class;
60 public static int WarningLevel = 2;
62 public static Target Target = Target.Exe;
63 public static string TargetExt = ".exe";
65 public static bool VerifyClsCompliance = true;
68 // If set, enable C# version 2 features
70 public static bool V2 = true;
73 // We keep strongname related info here because
74 // it's also used as complier options from CSC 8.x
76 public static string StrongNameKeyFile;
77 public static string StrongNameKeyContainer;
78 public static bool StrongNameDelaySign = false;
86 interface_resolve_order = new ArrayList ();
87 type_container_resolve_order = new ArrayList ();
90 public static bool NeedsEntryPoint {
92 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
96 static public Tree Tree {
102 static public string MainClass;
104 public static void RegisterOrder (Interface iface)
106 interface_resolve_order.Add (iface);
109 public static void RegisterOrder (TypeContainer tc)
111 type_container_resolve_order.Add (tc);
114 public static void RegisterAttribute (TypeContainer tc)
116 if (attribute_types == null)
117 attribute_types = new ArrayList ();
119 attribute_types.Add (tc);
123 // The default compiler checked state
125 static public bool Checked = false;
128 // Whether to allow Unsafe code
130 static public bool Unsafe = false;
132 static string MakeFQN (string nsn, string name)
136 return String.Concat (nsn, ".", name);
140 // This function is used to resolve the hierarchy tree.
141 // It processes interfaces, structs and classes in that order.
143 // It creates the TypeBuilder's as it processes the user defined
146 static public void ResolveTree ()
149 // Process the attribute types separately and before anything else
151 if (attribute_types != null)
152 foreach (TypeContainer tc in attribute_types)
156 // Interfaces are processed next, as classes and
157 // structs might inherit from an object or implement
158 // a set of interfaces, we need to be able to tell
159 // them appart by just using the TypeManager.
161 TypeContainer root = Tree.Types;
163 ArrayList ifaces = root.Interfaces;
165 foreach (Interface i in ifaces)
169 foreach (TypeContainer tc in root.Types)
172 if (root.Delegates != null)
173 foreach (Delegate d in root.Delegates)
176 if (root.Enums != null)
177 foreach (Enum e in root.Enums)
181 static void Error_TypeConflict (string name, Location loc)
184 520, loc, "`" + name + "' conflicts with a predefined type");
187 static void Error_TypeConflict (string name)
190 520, "`" + name + "' conflicts with a predefined type");
194 // Resolves a single class during the corlib bootstrap process
196 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
198 object o = root.GetDefinition (name);
200 Report.Error (518, "The predefined type `" + name + "' is not defined");
206 DeclSpace d = (DeclSpace) o;
208 Error_TypeConflict (name, d.Location);
210 Error_TypeConflict (name);
215 return ((DeclSpace) o).DefineType ();
219 // Resolves a struct during the corlib bootstrap process
221 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
223 object o = root.GetDefinition (name);
225 Report.Error (518, "The predefined type `" + name + "' is not defined");
231 DeclSpace d = (DeclSpace) o;
233 Error_TypeConflict (name, d.Location);
235 Error_TypeConflict (name);
240 ((DeclSpace) o).DefineType ();
244 // Resolves a struct during the corlib bootstrap process
246 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
248 object o = root.GetDefinition (name);
250 Report.Error (518, "The predefined type `" + name + "' is not defined");
254 if (!(o is Interface)){
256 DeclSpace d = (DeclSpace) o;
258 Error_TypeConflict (name, d.Location);
260 Error_TypeConflict (name);
265 ((DeclSpace) o).DefineType ();
269 // Resolves a delegate during the corlib bootstrap process
271 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
273 object o = root.GetDefinition (name);
275 Report.Error (518, "The predefined type `" + name + "' is not defined");
276 Environment.Exit (1);
279 if (!(o is Delegate)){
280 Error_TypeConflict (name);
284 ((DeclSpace) o).DefineType ();
289 /// Resolves the core types in the compiler when compiling with --nostdlib
291 static public void ResolveCore ()
293 TypeContainer root = Tree.Types;
295 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
296 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
297 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
299 string [] interfaces_first_stage = {
300 "System.IComparable", "System.ICloneable",
301 "System.IConvertible",
303 "System.Collections.IEnumerable",
304 "System.Collections.ICollection",
305 "System.Collections.IEnumerator",
306 "System.Collections.IList",
307 "System.IAsyncResult",
308 "System.IDisposable",
310 "System.Runtime.Serialization.ISerializable",
312 "System.Reflection.IReflect",
313 "System.Reflection.ICustomAttributeProvider"
316 foreach (string iname in interfaces_first_stage)
317 BootstrapCorlib_ResolveInterface (root, iname);
320 // These are the base value types
322 string [] structs_first_stage = {
323 "System.Byte", "System.SByte",
324 "System.Int16", "System.UInt16",
325 "System.Int32", "System.UInt32",
326 "System.Int64", "System.UInt64",
329 foreach (string cname in structs_first_stage)
330 BootstrapCorlib_ResolveStruct (root, cname);
333 // Now, we can load the enumerations, after this point,
336 TypeManager.InitEnumUnderlyingTypes ();
338 string [] structs_second_stage = {
339 "System.Single", "System.Double",
340 "System.Char", "System.Boolean",
341 "System.Decimal", "System.Void",
342 "System.RuntimeFieldHandle",
343 "System.RuntimeTypeHandle",
345 "System.TypedReference",
349 foreach (string cname in structs_second_stage)
350 BootstrapCorlib_ResolveStruct (root, cname);
353 // These are classes that depends on the core interfaces
355 string [] classes_second_stage = {
356 "System.Reflection.MemberInfo",
361 // These are not really important in the order, but they
362 // are used by the compiler later on (typemanager/CoreLookupType-d)
364 "System.Runtime.CompilerServices.RuntimeHelpers",
365 "System.Reflection.DefaultMemberAttribute",
366 "System.Threading.Monitor",
368 "System.AttributeUsageAttribute",
369 "System.Runtime.InteropServices.DllImportAttribute",
370 "System.Runtime.CompilerServices.MethodImplAttribute",
371 "System.Runtime.InteropServices.MarshalAsAttribute",
372 "System.Diagnostics.ConditionalAttribute",
373 "System.ObsoleteAttribute",
374 "System.ParamArrayAttribute",
375 "System.CLSCompliantAttribute",
376 "System.Security.UnverifiableCodeAttribute",
377 "System.Runtime.CompilerServices.IndexerNameAttribute",
378 "System.Runtime.InteropServices.InAttribute",
379 "System.Runtime.InteropServices.StructLayoutAttribute",
380 "System.Runtime.InteropServices.FieldOffsetAttribute",
381 "System.InvalidOperationException",
382 "System.MarshalByRefObject"
385 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
386 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
387 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
388 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
389 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
390 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
392 foreach (string cname in classes_second_stage)
393 BootstrapCorlib_ResolveClass (root, cname);
395 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
399 // Closes all open types
403 // We usually use TypeBuilder types. When we are done
404 // creating the type (which will happen after we have added
405 // methods, fields, etc) we need to "Define" them before we
406 // can save the Assembly
408 static public void CloseTypes ()
410 TypeContainer root = Tree.Types;
412 if (root.Enums != null)
413 foreach (Enum en in root.Enums)
416 if (attribute_types != null)
417 foreach (TypeContainer tc in attribute_types)
420 foreach (Interface iface in interface_resolve_order)
424 // We do this in two passes, first we close the structs,
425 // then the classes, because it seems the code needs it this
426 // way. If this is really what is going on, we should probably
427 // make sure that we define the structs in order as well.
429 foreach (TypeContainer tc in type_container_resolve_order){
430 if (tc is Struct && tc.Parent == tree.Types){
435 foreach (TypeContainer tc in type_container_resolve_order){
436 if (!(tc is Struct && tc.Parent == tree.Types))
440 if (root.Delegates != null)
441 foreach (Delegate d in root.Delegates)
446 // If we have a <PrivateImplementationDetails> class, close it
448 if (helper_classes != null){
449 foreach (TypeBuilder type_builder in helper_classes)
450 type_builder.CreateType ();
453 attribute_types = null;
454 interface_resolve_order = null;
455 type_container_resolve_order = null;
456 helper_classes = null;
458 TypeManager.CleanUp ();
462 /// Used to register classes that need to be closed after all the
463 /// user defined classes
465 public static void RegisterHelperClass (TypeBuilder helper_class)
467 if (helper_classes == null)
468 helper_classes = new ArrayList ();
469 helper_classes.Add (helper_class);
473 // This idea is from Felix Arrese-Igor
475 // Returns : the implicit parent of a composite namespace string
476 // eg. Implicit parent of A.B is A
478 static public string ImplicitParent (string ns)
480 int i = ns.LastIndexOf ('.');
484 return ns.Substring (0, i);
487 static Type NamespaceLookup (DeclSpace ds, string name, bool silent,
491 // Try in the current namespace and all its implicit parents
493 for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
494 object result = ns.Lookup (ds, name, silent, loc);
499 return (Type) result;
508 // Public function used to locate types, this can only
509 // be used after the ResolveTree function has been invoked.
511 // Returns: Type or null if they type can not be found.
513 // Come to think of it, this should be a DeclSpace
515 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
519 if (ds.Cache.Contains (name)) {
520 t = (Type) ds.Cache [name];
523 // For the case the type we are looking for is nested within this one
524 // or is in any base class
526 DeclSpace containing_ds = ds;
527 while (containing_ds != null){
529 // if the member cache has been created, lets use it.
530 // the member cache is MUCH faster.
531 if (containing_ds.MemberCache != null) {
532 t = containing_ds.MemberCache.FindNestedType (name);
534 containing_ds = containing_ds.Parent;
542 // no member cache. Do it the hard way -- reflection
543 Type current_type = containing_ds.TypeBuilder;
545 while (current_type != null &&
546 current_type != TypeManager.object_type) {
550 t = TypeManager.LookupType (current_type.FullName + "." + name);
556 current_type = current_type.BaseType;
559 containing_ds = containing_ds.Parent;
562 t = NamespaceLookup (ds, name, silent, loc);
567 if (t == null && !silent)
568 Report.Error (246, loc, "Cannot find type `"+name+"'");
574 // This is the silent version of LookupType, you can use this
575 // to `probe' for a type
577 static public Type LookupType (TypeContainer tc, string name, Location loc)
579 return LookupType (tc, name, true, loc);
582 static public bool IsNamespace (string name)
586 if (tree.Namespaces != null){
587 ns = (Namespace) tree.Namespaces [name];
596 static void Report1530 (Location loc)
598 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
601 static public void PopulateCoreType (TypeContainer root, string name)
603 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
605 ds.DefineMembers (root);
609 static public void BootCorlib_PopulateCoreTypes ()
611 TypeContainer root = tree.Types;
613 PopulateCoreType (root, "System.Object");
614 PopulateCoreType (root, "System.ValueType");
615 PopulateCoreType (root, "System.Attribute");
619 // Populates the structs and classes with fields and methods
622 // This is invoked after all interfaces, structs and classes
623 // have been defined through `ResolveTree'
624 static public void PopulateTypes ()
626 TypeContainer root = Tree.Types;
628 if (attribute_types != null)
629 foreach (TypeContainer tc in attribute_types)
630 tc.DefineMembers (root);
632 if (interface_resolve_order != null){
633 foreach (Interface iface in interface_resolve_order)
634 if ((iface.ModFlags & Modifiers.NEW) == 0)
635 iface.DefineMembers (root);
637 Report1530 (iface.Location);
641 if (type_container_resolve_order != null){
642 if (RootContext.StdLib){
643 foreach (TypeContainer tc in type_container_resolve_order)
644 tc.DefineMembers (root);
646 foreach (TypeContainer tc in type_container_resolve_order) {
647 // When compiling corlib, these types have already been
648 // populated from BootCorlib_PopulateCoreTypes ().
649 if (((tc.Name == "System.Object") ||
650 (tc.Name == "System.Attribute") ||
651 (tc.Name == "System.ValueType")))
654 tc.DefineMembers (root);
659 ArrayList delegates = root.Delegates;
660 if (delegates != null){
661 foreach (Delegate d in delegates)
662 if ((d.ModFlags & Modifiers.NEW) == 0)
663 d.DefineMembers (root);
665 Report1530 (d.Location);
668 ArrayList enums = root.Enums;
670 foreach (Enum en in enums)
671 if ((en.ModFlags & Modifiers.NEW) == 0)
672 en.DefineMembers (root);
674 Report1530 (en.Location);
678 // Check for cycles in the struct layout
680 if (type_container_resolve_order != null){
681 Hashtable seen = new Hashtable ();
682 foreach (TypeContainer tc in type_container_resolve_order)
683 TypeManager.CheckStructCycles (tc, seen);
688 // A generic hook delegate
690 public delegate void Hook ();
693 // A hook invoked when the code has been generated.
695 public static event Hook EmitCodeHook;
698 // DefineTypes is used to fill in the members of each type.
700 static public void DefineTypes ()
702 TypeContainer root = Tree.Types;
704 if (attribute_types != null)
705 foreach (TypeContainer tc in attribute_types)
708 if (interface_resolve_order != null){
709 foreach (Interface iface in interface_resolve_order)
710 if ((iface.ModFlags & Modifiers.NEW) == 0)
715 if (type_container_resolve_order != null){
716 foreach (TypeContainer tc in type_container_resolve_order) {
717 // When compiling corlib, these types have already been
718 // populated from BootCorlib_PopulateCoreTypes ().
719 if (!RootContext.StdLib &&
720 ((tc.Name == "System.Object") ||
721 (tc.Name == "System.Attribute") ||
722 (tc.Name == "System.ValueType")))
725 if ((tc.ModFlags & Modifiers.NEW) == 0)
730 ArrayList delegates = root.Delegates;
731 if (delegates != null){
732 foreach (Delegate d in delegates)
733 if ((d.ModFlags & Modifiers.NEW) == 0)
737 ArrayList enums = root.Enums;
739 foreach (Enum en in enums)
740 if ((en.ModFlags & Modifiers.NEW) == 0)
745 static public void EmitCode ()
747 if (attribute_types != null)
748 foreach (TypeContainer tc in attribute_types)
751 CodeGen.Assembly.Emit (Tree.Types);
752 CodeGen.Module.Emit (Tree.Types);
754 if (Tree.Types.Enums != null) {
755 foreach (Enum e in Tree.Types.Enums)
759 if (interface_resolve_order != null) {
760 foreach (Interface iface in interface_resolve_order)
761 iface.Emit (Tree.Types);
764 if (type_container_resolve_order != null) {
765 foreach (TypeContainer tc in type_container_resolve_order)
768 foreach (TypeContainer tc in type_container_resolve_order)
772 if (Tree.Types.Delegates != null) {
773 foreach (Delegate d in Tree.Types.Delegates)
777 // Run any hooks after all the types have been defined.
778 // This is used to create nested auxiliary classes for example
781 if (EmitCodeHook != null)
786 // Public Field, used to track which method is the public entry
789 static public MethodInfo EntryPoint;
792 // Track the location of the entry point.
794 static public Location EntryPointLocation;
797 // These are used to generate unique names on the structs and fields.
799 static int field_count;
802 // Makes an initialized struct, returns the field builder that
803 // references the data. Thanks go to Sergey Chaban for researching
804 // how to do this. And coming up with a shorter mechanism than I
805 // was able to figure out.
807 // This works but makes an implicit public struct $ArrayType$SIZE and
808 // makes the fields point to it. We could get more control if we did
811 // 1. DefineNestedType on the impl_details_class with our struct.
813 // 2. Define the field on the impl_details_class
815 static public FieldBuilder MakeStaticData (byte [] data)
819 if (impl_details_class == null){
820 impl_details_class = CodeGen.Module.Builder.DefineType (
821 "<PrivateImplementationDetails>",
822 TypeAttributes.NotPublic,
823 TypeManager.object_type);
825 RegisterHelperClass (impl_details_class);
828 fb = impl_details_class.DefineInitializedData (
829 "$$field-" + (field_count++), data,
830 FieldAttributes.Static | FieldAttributes.Assembly);