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 // The list of global attributes (those that target the assembly)
35 static Hashtable global_attributes = new Hashtable ();
38 // Whether we are being linked against the standard libraries.
39 // This is only used to tell whether `System.Object' should
40 // have a parent or not.
42 public static bool StdLib = true;
45 // This keeps track of the order in which classes were defined
46 // so that we can poulate them in that order.
48 // Order is important, because we need to be able to tell by
49 // examining the parent's list of methods which ones are virtual
50 // or abstract as well as the parent names (to implement new,
53 static ArrayList type_container_resolve_order;
54 static ArrayList interface_resolve_order;
55 static ArrayList attribute_types;
58 // Holds a reference to the Private Implementation Details
61 static ArrayList helper_classes;
63 static TypeBuilder impl_details_class;
65 public static int WarningLevel = 2;
68 // If set, enable C# version 2 features
70 public static bool V2;
77 interface_resolve_order = new ArrayList ();
78 type_container_resolve_order = new ArrayList ();
81 static public Tree Tree {
87 static public string MainClass;
89 public static void RegisterOrder (Interface iface)
91 interface_resolve_order.Add (iface);
94 public static void RegisterOrder (TypeContainer tc)
96 type_container_resolve_order.Add (tc);
99 public static void RegisterAttribute (TypeContainer tc)
101 if (attribute_types == null)
102 attribute_types = new ArrayList ();
104 attribute_types.Add (tc);
108 // The default compiler checked state
110 static public bool Checked = false;
113 // Whether to allow Unsafe code
115 static public bool Unsafe = false;
117 static string MakeFQN (string nsn, string name)
121 return String.Concat (nsn, ".", name);
125 // This function is used to resolve the hierarchy tree.
126 // It processes interfaces, structs and classes in that order.
128 // It creates the TypeBuilder's as it processes the user defined
131 static public void ResolveTree ()
134 // Process the attribute types separately and before anything else
136 if (attribute_types != null)
137 foreach (TypeContainer tc in attribute_types)
141 // Interfaces are processed next, as classes and
142 // structs might inherit from an object or implement
143 // a set of interfaces, we need to be able to tell
144 // them appart by just using the TypeManager.
146 TypeContainer root = Tree.Types;
148 ArrayList ifaces = root.Interfaces;
150 foreach (Interface i in ifaces)
154 foreach (TypeContainer tc in root.Types)
157 if (root.Delegates != null)
158 foreach (Delegate d in root.Delegates)
161 if (root.Enums != null)
162 foreach (Enum e in root.Enums)
166 static void Error_TypeConflict (string name, Location loc)
169 520, loc, "`" + name + "' conflicts with a predefined type");
172 static void Error_TypeConflict (string name)
175 520, "`" + name + "' conflicts with a predefined type");
179 // Resolves a single class during the corlib bootstrap process
181 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
183 object o = root.GetDefinition (name);
185 Report.Error (518, "The predefined type `" + name + "' is not defined");
191 DeclSpace d = (DeclSpace) o;
193 Error_TypeConflict (name, d.Location);
195 Error_TypeConflict (name);
200 return ((DeclSpace) o).DefineType ();
204 // Resolves a struct during the corlib bootstrap process
206 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
208 object o = root.GetDefinition (name);
210 Report.Error (518, "The predefined type `" + name + "' is not defined");
216 DeclSpace d = (DeclSpace) o;
218 Error_TypeConflict (name, d.Location);
220 Error_TypeConflict (name);
225 ((DeclSpace) o).DefineType ();
229 // Resolves a struct during the corlib bootstrap process
231 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
233 object o = root.GetDefinition (name);
235 Report.Error (518, "The predefined type `" + name + "' is not defined");
239 if (!(o is Interface)){
241 DeclSpace d = (DeclSpace) o;
243 Error_TypeConflict (name, d.Location);
245 Error_TypeConflict (name);
250 ((DeclSpace) o).DefineType ();
254 // Resolves a delegate during the corlib bootstrap process
256 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
258 object o = root.GetDefinition (name);
260 Report.Error (518, "The predefined type `" + name + "' is not defined");
261 Environment.Exit (0);
264 if (!(o is Delegate)){
265 Error_TypeConflict (name);
269 ((DeclSpace) o).DefineType ();
274 /// Resolves the core types in the compiler when compiling with --nostdlib
276 static public void ResolveCore ()
278 TypeContainer root = Tree.Types;
280 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
281 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
282 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
284 string [] interfaces_first_stage = {
285 "System.IComparable", "System.ICloneable",
286 "System.IConvertible",
288 "System.Collections.IEnumerable",
289 "System.Collections.ICollection",
290 "System.Collections.IEnumerator",
291 "System.Collections.IList",
292 "System.IAsyncResult",
293 "System.IDisposable",
295 "System.Runtime.Serialization.ISerializable",
297 "System.Reflection.IReflect",
298 "System.Reflection.ICustomAttributeProvider"
301 foreach (string iname in interfaces_first_stage)
302 BootstrapCorlib_ResolveInterface (root, iname);
305 // These are the base value types
307 string [] structs_first_stage = {
308 "System.Byte", "System.SByte",
309 "System.Int16", "System.UInt16",
310 "System.Int32", "System.UInt32",
311 "System.Int64", "System.UInt64",
314 foreach (string cname in structs_first_stage)
315 BootstrapCorlib_ResolveStruct (root, cname);
318 // Now, we can load the enumerations, after this point,
321 TypeManager.InitEnumUnderlyingTypes ();
323 string [] structs_second_stage = {
324 "System.Single", "System.Double",
325 "System.Char", "System.Boolean",
326 "System.Decimal", "System.Void",
327 "System.RuntimeFieldHandle",
328 "System.RuntimeTypeHandle",
332 foreach (string cname in structs_second_stage)
333 BootstrapCorlib_ResolveStruct (root, cname);
336 // These are classes that depends on the core interfaces
338 string [] classes_second_stage = {
339 "System.Reflection.MemberInfo",
344 // These are not really important in the order, but they
345 // are used by the compiler later on (typemanager/CoreLookupType-d)
347 "System.Runtime.CompilerServices.RuntimeHelpers",
348 "System.Reflection.DefaultMemberAttribute",
349 "System.Threading.Monitor",
351 "System.AttributeUsageAttribute",
352 "System.Runtime.InteropServices.DllImportAttribute",
353 "System.Runtime.CompilerServices.MethodImplAttribute",
354 "System.Runtime.InteropServices.MarshalAsAttribute",
355 "System.Diagnostics.ConditionalAttribute",
356 "System.ObsoleteAttribute",
357 "System.ParamArrayAttribute",
358 "System.Security.UnverifiableCodeAttribute",
359 "System.Runtime.CompilerServices.IndexerNameAttribute",
360 "System.Runtime.InteropServices.InAttribute",
361 "System.InvalidOperationException"
365 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
366 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
367 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
368 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
369 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
370 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
372 foreach (string cname in classes_second_stage)
373 BootstrapCorlib_ResolveClass (root, cname);
375 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
379 // Closes all open types
383 // We usually use TypeBuilder types. When we are done
384 // creating the type (which will happen after we have added
385 // methods, fields, etc) we need to "Define" them before we
386 // can save the Assembly
388 static public void CloseTypes ()
390 TypeContainer root = Tree.Types;
392 ArrayList ifaces = root.Interfaces;
394 if (root.Enums != null)
395 foreach (Enum en in root.Enums)
398 if (attribute_types != null)
399 foreach (TypeContainer tc in attribute_types)
402 foreach (Interface iface in interface_resolve_order)
406 // We do this in two passes, first we close the structs,
407 // then the classes, because it seems the code needs it this
408 // way. If this is really what is going on, we should probably
409 // make sure that we define the structs in order as well.
411 foreach (TypeContainer tc in type_container_resolve_order){
412 if (tc is Struct && tc.Parent == tree.Types){
417 foreach (TypeContainer tc in type_container_resolve_order){
418 if (!(tc is Struct && tc.Parent == tree.Types))
422 if (root.Delegates != null)
423 foreach (Delegate d in root.Delegates)
428 // If we have a <PrivateImplementationDetails> class, close it
430 if (helper_classes != null){
431 foreach (TypeBuilder type_builder in helper_classes)
432 type_builder.CreateType ();
437 /// Used to register classes that need to be closed after all the
438 /// user defined classes
440 public static void RegisterHelperClass (TypeBuilder helper_class)
442 if (helper_classes == null)
443 helper_classes = new ArrayList ();
444 helper_classes.Add (helper_class);
448 // This idea is from Felix Arrese-Igor
450 // Returns : the implicit parent of a composite namespace string
451 // eg. Implicit parent of A.B is A
453 static public string ImplicitParent (string ns)
455 int i = ns.LastIndexOf (".");
459 return ns.Substring (0, i);
462 static Type NamespaceLookup (NamespaceEntry curr_ns, string name, Location loc)
467 // Try in the current namespace and all its implicit parents
469 for (string ns = curr_ns.Name; ns != null; ns = ImplicitParent (ns)) {
470 t = TypeManager.LookupType (MakeFQN (ns, name));
476 // It's possible that name already is fully qualified. So we do
477 // a simple direct lookup without adding any namespace names
479 t = TypeManager.LookupType (name);
484 // Try the aliases in the current namespace
486 string alias = curr_ns.LookupAlias (name);
489 t = TypeManager.LookupType (alias);
493 t = TypeManager.LookupType (MakeFQN (alias, name));
498 for (NamespaceEntry ns = curr_ns; ns != null; ns = ns.Parent) {
500 // Look in the namespace ns
502 t = TypeManager.LookupType (MakeFQN (ns.Name, name));
507 // Then try with the using clauses
510 foreach (Namespace using_ns in ns.GetUsingTable ()) {
511 string full_name = DeclSpace.MakeFQN (using_ns.Name, name);
512 match = TypeManager.LookupType (full_name);
515 DeclSpace.Error_AmbiguousTypeReference (loc, name, t, match);
529 string a = ns.LookupAlias (name);
531 t = TypeManager.LookupType (a);
535 t = TypeManager.LookupType (MakeFQN (a, name));
545 // Public function used to locate types, this can only
546 // be used after the ResolveTree function has been invoked.
548 // Returns: Type or null if they type can not be found.
550 // Come to think of it, this should be a DeclSpace
552 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
556 if (ds.Cache.Contains (name)){
557 t = (Type) ds.Cache [name];
562 // For the case the type we are looking for is nested within this one
563 // or is in any base class
565 DeclSpace containing_ds = ds;
566 while (containing_ds != null){
567 Type current_type = containing_ds.TypeBuilder;
569 while (current_type != null) {
573 t = TypeManager.LookupType (current_type.FullName + "." + name);
579 current_type = current_type.BaseType;
582 containing_ds = containing_ds.Parent;
585 t = NamespaceLookup (ds.Namespace, name, loc);
593 Report.Error (246, loc, "Cannot find type `"+name+"'");
599 // This is the silent version of LookupType, you can use this
600 // to `probe' for a type
602 static public Type LookupType (TypeContainer tc, string name, Location loc)
604 return LookupType (tc, name, true, loc);
607 static public bool IsNamespace (string name)
611 if (tree.Namespaces != null){
612 ns = (Namespace) tree.Namespaces [name];
621 static void Report1530 (Location loc)
623 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
626 static public void PopulateCoreType (TypeContainer root, string name)
628 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
630 ds.DefineMembers (root);
634 static public void BootCorlib_PopulateCoreTypes ()
636 TypeContainer root = tree.Types;
638 PopulateCoreType (root, "System.Object");
639 PopulateCoreType (root, "System.ValueType");
640 PopulateCoreType (root, "System.Attribute");
644 // Populates the structs and classes with fields and methods
647 // This is invoked after all interfaces, structs and classes
648 // have been defined through `ResolveTree'
649 static public void PopulateTypes ()
651 TypeContainer root = Tree.Types;
653 if (attribute_types != null)
654 foreach (TypeContainer tc in attribute_types)
655 tc.DefineMembers (root);
657 if (interface_resolve_order != null){
658 foreach (Interface iface in interface_resolve_order)
659 if ((iface.ModFlags & Modifiers.NEW) == 0)
660 iface.DefineMembers (root);
662 Report1530 (iface.Location);
666 if (type_container_resolve_order != null){
667 if (RootContext.StdLib){
668 foreach (TypeContainer tc in type_container_resolve_order)
669 tc.DefineMembers (root);
671 foreach (TypeContainer tc in type_container_resolve_order) {
672 // When compiling corlib, these types have already been
673 // populated from BootCorlib_PopulateCoreTypes ().
674 if (((tc.Name == "System.Object") ||
675 (tc.Name == "System.Attribute") ||
676 (tc.Name == "System.ValueType")))
679 tc.DefineMembers (root);
684 ArrayList delegates = root.Delegates;
685 if (delegates != null){
686 foreach (Delegate d in delegates)
687 if ((d.ModFlags & Modifiers.NEW) == 0)
688 d.DefineMembers (root);
690 Report1530 (d.Location);
693 ArrayList enums = root.Enums;
695 foreach (Enum en in enums)
696 if ((en.ModFlags & Modifiers.NEW) == 0)
697 en.DefineMembers (root);
699 Report1530 (en.Location);
704 // A generic hook delegate
706 public delegate void Hook ();
709 // A hook invoked when the code has been generated.
711 public static event Hook EmitCodeHook;
714 // DefineTypes is used to fill in the members of each type.
716 static public void DefineTypes ()
718 TypeContainer root = Tree.Types;
720 if (attribute_types != null)
721 foreach (TypeContainer tc in attribute_types)
724 if (interface_resolve_order != null){
725 foreach (Interface iface in interface_resolve_order)
726 if ((iface.ModFlags & Modifiers.NEW) == 0)
731 if (type_container_resolve_order != null){
732 foreach (TypeContainer tc in type_container_resolve_order) {
733 // When compiling corlib, these types have already been
734 // populated from BootCorlib_PopulateCoreTypes ().
735 if (!RootContext.StdLib &&
736 ((tc.Name == "System.Object") ||
737 (tc.Name == "System.Attribute") ||
738 (tc.Name == "System.ValueType")))
741 if ((tc.ModFlags & Modifiers.NEW) == 0)
746 ArrayList delegates = root.Delegates;
747 if (delegates != null){
748 foreach (Delegate d in delegates)
749 if ((d.ModFlags & Modifiers.NEW) == 0)
753 ArrayList enums = root.Enums;
755 foreach (Enum en in enums)
756 if ((en.ModFlags & Modifiers.NEW) == 0)
761 static public void EmitCode ()
764 // Because of the strange way in which we do things, global
765 // attributes must be processed first.
767 if (global_attributes.Count > 0){
768 AssemblyBuilder ab = CodeGen.AssemblyBuilder;
769 TypeContainer dummy = new TypeContainer (null, "", new Location (-1));
770 EmitContext temp_ec = new EmitContext (
771 dummy, Mono.CSharp.Location.Null, null, null, 0, false);
773 foreach (DictionaryEntry de in global_attributes){
774 NamespaceEntry ns = (NamespaceEntry) de.Key;
775 Attributes attrs = (Attributes) de.Value;
777 dummy.Namespace = ns;
778 Attribute.ApplyAttributes (temp_ec, ab, ab, attrs);
782 if (attribute_types != null)
783 foreach (TypeContainer tc in attribute_types)
786 if (type_container_resolve_order != null) {
787 foreach (TypeContainer tc in type_container_resolve_order)
790 foreach (TypeContainer tc in type_container_resolve_order)
795 // Run any hooks after all the types have been defined.
796 // This is used to create nested auxiliary classes for example
799 if (EmitCodeHook != null)
804 if (TypeManager.unverifiable_code_ctor == null) {
805 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
809 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor,
811 CodeGen.ModuleBuilder.SetCustomAttribute (cb);
816 // Public Field, used to track which method is the public entry
819 static public MethodInfo EntryPoint;
822 // Track the location of the entry point.
824 static public Location EntryPointLocation;
827 // These are used to generate unique names on the structs and fields.
829 static int field_count;
832 // Makes an initialized struct, returns the field builder that
833 // references the data. Thanks go to Sergey Chaban for researching
834 // how to do this. And coming up with a shorter mechanism than I
835 // was able to figure out.
837 // This works but makes an implicit public struct $ArrayType$SIZE and
838 // makes the fields point to it. We could get more control if we did
841 // 1. DefineNestedType on the impl_details_class with our struct.
843 // 2. Define the field on the impl_details_class
845 static public FieldBuilder MakeStaticData (byte [] data)
848 int size = data.Length;
850 if (impl_details_class == null){
851 impl_details_class = CodeGen.ModuleBuilder.DefineType (
852 "<PrivateImplementationDetails>", TypeAttributes.NotPublic, TypeManager.object_type);
853 RegisterHelperClass (impl_details_class);
856 fb = impl_details_class.DefineInitializedData (
857 "$$field-" + (field_count++), data,
858 FieldAttributes.Static | FieldAttributes.Assembly);
864 // Adds a global attribute that was declared in `container',
865 // the attribute is in `attr', and it was defined at `loc'
867 static public void AddGlobalAttributeSection (TypeContainer container, AttributeSection attr)
869 NamespaceEntry ns = container.Namespace;
870 Attributes a = (Attributes) global_attributes [ns];
873 global_attributes [ns] = new Attributes (attr);
875 a.AddAttributeSection (attr);