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 TypeBuilder impl_details_class;
63 public static int WarningLevel = 2;
71 interface_resolve_order = new ArrayList ();
72 type_container_resolve_order = new ArrayList ();
75 static public Tree Tree {
81 static public string MainClass;
83 public static void RegisterOrder (Interface iface)
85 interface_resolve_order.Add (iface);
88 public static void RegisterOrder (TypeContainer tc)
90 type_container_resolve_order.Add (tc);
93 public static void RegisterAttribute (TypeContainer tc)
95 if (attribute_types == null)
96 attribute_types = new ArrayList ();
98 attribute_types.Add (tc);
102 // The default compiler checked state
104 static public bool Checked = false;
107 // Whether to allow Unsafe code
109 static public bool Unsafe = false;
111 static string MakeFQN (string nsn, string name)
113 string prefix = (nsn == "" ? "" : nsn + ".");
115 return prefix + name;
119 // This function is used to resolve the hierarchy tree.
120 // It processes interfaces, structs and classes in that order.
122 // It creates the TypeBuilder's as it processes the user defined
125 static public void ResolveTree ()
128 // Process the attribute types separately and before anything else
130 if (attribute_types != null)
131 foreach (TypeContainer tc in attribute_types)
135 // Interfaces are processed next, as classes and
136 // structs might inherit from an object or implement
137 // a set of interfaces, we need to be able to tell
138 // them appart by just using the TypeManager.
140 TypeContainer root = Tree.Types;
142 ArrayList ifaces = root.Interfaces;
144 foreach (Interface i in ifaces)
149 foreach (TypeContainer tc in root.Types)
152 if (root.Delegates != null)
153 foreach (Delegate d in root.Delegates)
156 if (root.Enums != null)
157 foreach (Enum e in root.Enums)
162 static void Error_TypeConflict (string name, Location loc)
165 520, loc, "`" + name + "' conflicts with a predefined type");
168 static void Error_TypeConflict (string name)
171 520, "`" + name + "' conflicts with a predefined type");
175 // Resolves a single class during the corlib bootstrap process
177 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
179 object o = root.GetDefinition (name);
181 Report.Error (518, "The predefined type `" + name + "' is not defined");
187 DeclSpace d = (DeclSpace) o;
189 Error_TypeConflict (name, d.Location);
191 Error_TypeConflict (name);
196 return ((DeclSpace) o).DefineType ();
200 // Resolves a struct during the corlib bootstrap process
202 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
204 object o = root.GetDefinition (name);
206 Report.Error (518, "The predefined type `" + name + "' is not defined");
212 DeclSpace d = (DeclSpace) o;
214 Error_TypeConflict (name, d.Location);
216 Error_TypeConflict (name);
221 ((DeclSpace) o).DefineType ();
225 // Resolves a struct during the corlib bootstrap process
227 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
229 object o = root.GetDefinition (name);
231 Report.Error (518, "The predefined type `" + name + "' is not defined");
235 if (!(o is Interface)){
237 DeclSpace d = (DeclSpace) o;
239 Error_TypeConflict (name, d.Location);
241 Error_TypeConflict (name);
246 ((DeclSpace) o).DefineType ();
250 // Resolves a delegate during the corlib bootstrap process
252 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
254 object o = root.GetDefinition (name);
256 Report.Error (518, "The predefined type `" + name + "' is not defined");
257 Environment.Exit (0);
260 if (!(o is Delegate)){
261 Error_TypeConflict (name);
265 ((DeclSpace) o).DefineType ();
270 /// Resolves the core types in the compiler when compiling with --nostdlib
272 static public void ResolveCore ()
274 TypeContainer root = Tree.Types;
276 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
277 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
278 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
280 string [] interfaces_first_stage = {
281 "System.IComparable", "System.ICloneable",
282 "System.IConvertible",
284 "System.Collections.IEnumerable",
285 "System.Collections.ICollection",
286 "System.Collections.IEnumerator",
287 "System.Collections.IList",
288 "System.IAsyncResult",
289 "System.IDisposable",
291 "System.Runtime.Serialization.ISerializable",
293 "System.Reflection.IReflect",
294 "System.Reflection.ICustomAttributeProvider"
297 foreach (string iname in interfaces_first_stage)
298 BootstrapCorlib_ResolveInterface (root, iname);
301 // These are the base value types
303 string [] structs_first_stage = {
304 "System.Byte", "System.SByte",
305 "System.Int16", "System.UInt16",
306 "System.Int32", "System.UInt32",
307 "System.Int64", "System.UInt64",
310 foreach (string cname in structs_first_stage)
311 BootstrapCorlib_ResolveStruct (root, cname);
314 // Now, we can load the enumerations, after this point,
317 TypeManager.InitEnumUnderlyingTypes ();
319 string [] structs_second_stage = {
320 "System.Single", "System.Double",
321 "System.Char", "System.Boolean",
322 "System.Decimal", "System.Void",
323 "System.RuntimeFieldHandle",
324 "System.RuntimeTypeHandle",
328 foreach (string cname in structs_second_stage)
329 BootstrapCorlib_ResolveStruct (root, cname);
332 // These are classes that depends on the core interfaces
334 string [] classes_second_stage = {
335 "System.Reflection.MemberInfo",
340 // These are not really important in the order, but they
341 // are used by the compiler later on (typemanager/CoreLookupType-d)
343 "System.Runtime.CompilerServices.RuntimeHelpers",
344 "System.Reflection.DefaultMemberAttribute",
345 "System.Threading.Monitor",
347 "System.AttributeUsageAttribute",
348 "System.Runtime.InteropServices.DllImportAttribute",
349 "System.Runtime.CompilerServices.MethodImplAttribute",
350 "System.Runtime.InteropServices.MarshalAsAttribute",
351 "System.Diagnostics.ConditionalAttribute",
352 "System.ObsoleteAttribute",
353 "System.ParamArrayAttribute",
354 "System.Security.UnverifiableCodeAttribute",
355 "System.Runtime.CompilerServices.IndexerNameAttribute",
356 "System.Runtime.InteropServices.InAttribute"
359 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
360 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
361 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
362 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
363 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
364 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
366 foreach (string cname in classes_second_stage)
367 BootstrapCorlib_ResolveClass (root, cname);
369 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
373 // Closes all open types
377 // We usually use TypeBuilder types. When we are done
378 // creating the type (which will happen after we have added
379 // methods, fields, etc) we need to "Define" them before we
380 // can save the Assembly
382 static public void CloseTypes ()
384 TypeContainer root = Tree.Types;
386 ArrayList ifaces = root.Interfaces;
388 if (root.Enums != null)
389 foreach (Enum en in root.Enums)
392 if (attribute_types != null)
393 foreach (TypeContainer tc in attribute_types)
396 foreach (Interface iface in interface_resolve_order)
400 // We do this in two passes, first we close the structs,
401 // then the classes, because it seems the code needs it this
402 // way. If this is really what is going on, we should probably
403 // make sure that we define the structs in order as well.
405 foreach (TypeContainer tc in type_container_resolve_order){
406 if (tc is Struct && tc.Parent == tree.Types){
411 foreach (TypeContainer tc in type_container_resolve_order){
412 if (!(tc is Struct && tc.Parent == tree.Types))
416 if (root.Delegates != null)
417 foreach (Delegate d in root.Delegates)
422 // If we have a <PrivateImplementationDetails> class, close it
424 if (impl_details_class != null){
425 impl_details_class.CreateType ();
430 // This idea is from Felix Arrese-Igor
432 // Returns : the implicit parent of a composite namespace string
433 // eg. Implicit parent of A.B is A
435 static public string ImplicitParent (string ns)
437 int i = ns.LastIndexOf (".");
441 return ns.Substring (0, i);
444 static Type NamespaceLookup (Namespace curr_ns, string name, Location loc)
449 // Try in the current namespace and all its implicit parents
451 for (string ns = curr_ns.Name; ns != null; ns = ImplicitParent (ns)) {
452 t = TypeManager.LookupType (MakeFQN (ns, name));
458 // It's possible that name already is fully qualified. So we do
459 // a simple direct lookup without adding any namespace names
461 t = TypeManager.LookupType (name);
466 // Try the aliases in the current namespace
468 string alias = curr_ns.LookupAlias (name);
471 t = TypeManager.LookupType (alias);
475 t = TypeManager.LookupType (MakeFQN (alias, name));
480 for (Namespace ns = curr_ns; ns != null; ns = ns.Parent) {
482 // Look in the namespace ns
484 t = TypeManager.LookupType (MakeFQN (ns.Name, name));
489 // Then try with the using clauses
491 ArrayList using_list = ns.UsingTable;
493 if (using_list == null)
497 foreach (Namespace.UsingEntry ue in using_list) {
498 match = TypeManager.LookupType (MakeFQN (ue.Name, name));
501 DeclSpace.Error_AmbiguousTypeReference (loc, name, t, match);
515 string a = ns.LookupAlias (name);
517 t = TypeManager.LookupType (a);
521 t = TypeManager.LookupType (MakeFQN (a, name));
531 // Public function used to locate types, this can only
532 // be used after the ResolveTree function has been invoked.
534 // Returns: Type or null if they type can not be found.
536 // Come to think of it, this should be a DeclSpace
538 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
542 if (ds.Cache.Contains (name)){
543 t = (Type) ds.Cache [name];
548 // For the case the type we are looking for is nested within this one
549 // or is in any base class
551 DeclSpace containing_ds = ds;
552 while (containing_ds != null){
553 Type current_type = containing_ds.TypeBuilder;
555 while (current_type != null) {
559 t = TypeManager.LookupType (current_type.FullName + "." + name);
565 current_type = current_type.BaseType;
568 containing_ds = containing_ds.Parent;
571 t = NamespaceLookup (ds.Namespace, name, loc);
579 Report.Error (246, loc, "Cannot find type `"+name+"'");
585 // This is the silent version of LookupType, you can use this
586 // to `probe' for a type
588 static public Type LookupType (TypeContainer tc, string name, Location loc)
590 return LookupType (tc, name, true, loc);
593 static public bool IsNamespace (string name)
597 if (tree.Namespaces != null){
598 ns = (Namespace) tree.Namespaces [name];
607 static void Report1530 (Location loc)
609 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
612 static public void PopulateCoreType (TypeContainer root, string name)
614 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
616 ds.DefineMembers (root);
620 static public void BootCorlib_PopulateCoreTypes ()
622 TypeContainer root = tree.Types;
624 PopulateCoreType (root, "System.Object");
625 PopulateCoreType (root, "System.ValueType");
626 PopulateCoreType (root, "System.Attribute");
630 // Populates the structs and classes with fields and methods
633 // This is invoked after all interfaces, structs and classes
634 // have been defined through `ResolveTree'
635 static public void PopulateTypes ()
637 TypeContainer root = Tree.Types;
639 if (attribute_types != null)
640 foreach (TypeContainer tc in attribute_types)
641 tc.DefineMembers (root);
643 if (interface_resolve_order != null){
644 foreach (Interface iface in interface_resolve_order)
645 if ((iface.ModFlags & Modifiers.NEW) == 0)
646 iface.DefineMembers (root);
648 Report1530 (iface.Location);
652 if (type_container_resolve_order != null){
653 if (RootContext.StdLib){
654 foreach (TypeContainer tc in type_container_resolve_order) {
655 if ((tc.ModFlags & Modifiers.NEW) == 0)
656 tc.DefineMembers (root);
658 Report1530 (tc.Location);
661 foreach (TypeContainer tc in type_container_resolve_order) {
662 // When compiling corlib, these types have already been
663 // populated from BootCorlib_PopulateCoreTypes ().
664 if (((tc.Name == "System.Object") ||
665 (tc.Name == "System.Attribute") ||
666 (tc.Name == "System.ValueType")))
669 if ((tc.ModFlags & Modifiers.NEW) == 0)
670 tc.DefineMembers (root);
672 Report1530 (tc.Location);
677 ArrayList delegates = root.Delegates;
678 if (delegates != null){
679 foreach (Delegate d in delegates)
680 if ((d.ModFlags & Modifiers.NEW) == 0)
681 d.DefineMembers (root);
683 Report1530 (d.Location);
686 ArrayList enums = root.Enums;
688 foreach (Enum en in enums)
689 if ((en.ModFlags & Modifiers.NEW) == 0)
690 en.DefineMembers (root);
692 Report1530 (en.Location);
696 static public void DefineTypes ()
698 TypeContainer root = Tree.Types;
700 if (attribute_types != null)
701 foreach (TypeContainer tc in attribute_types)
704 if (interface_resolve_order != null){
705 foreach (Interface iface in interface_resolve_order)
706 if ((iface.ModFlags & Modifiers.NEW) == 0)
711 if (type_container_resolve_order != null){
712 foreach (TypeContainer tc in type_container_resolve_order) {
713 // When compiling corlib, these types have already been
714 // populated from BootCorlib_PopulateCoreTypes ().
715 if (!RootContext.StdLib &&
716 ((tc.Name == "System.Object") ||
717 (tc.Name == "System.Attribute") ||
718 (tc.Name == "System.ValueType")))
721 if ((tc.ModFlags & Modifiers.NEW) == 0)
726 ArrayList delegates = root.Delegates;
727 if (delegates != null){
728 foreach (Delegate d in delegates)
729 if ((d.ModFlags & Modifiers.NEW) == 0)
733 ArrayList enums = root.Enums;
735 foreach (Enum en in enums)
736 if ((en.ModFlags & Modifiers.NEW) == 0)
741 static public void EmitCode ()
744 // Because of the strange way in which we do things, global
745 // attributes must be processed first.
747 if (global_attributes.Count > 0){
748 AssemblyBuilder ab = CodeGen.AssemblyBuilder;
749 TypeContainer dummy = new TypeContainer (null, "", new Location (-1));
750 EmitContext temp_ec = new EmitContext (
751 dummy, Mono.CSharp.Location.Null, null, null, 0, false);
753 foreach (DictionaryEntry de in global_attributes){
754 Namespace ns = (Namespace) de.Key;
755 Attributes attrs = (Attributes) de.Value;
757 dummy.Namespace = ns;
758 Attribute.ApplyAttributes (temp_ec, ab, ab, attrs);
762 if (attribute_types != null)
763 foreach (TypeContainer tc in attribute_types)
766 if (type_container_resolve_order != null) {
767 foreach (TypeContainer tc in type_container_resolve_order)
770 foreach (TypeContainer tc in type_container_resolve_order)
775 if (TypeManager.unverifiable_code_ctor == null) {
776 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
780 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor,
782 CodeGen.ModuleBuilder.SetCustomAttribute (cb);
787 // Public Field, used to track which method is the public entry
790 static public MethodInfo EntryPoint;
793 // Track the location of the entry point.
795 static public Location EntryPointLocation;
798 // These are used to generate unique names on the structs and fields.
800 static int field_count;
803 // Makes an initialized struct, returns the field builder that
804 // references the data. Thanks go to Sergey Chaban for researching
805 // how to do this. And coming up with a shorter mechanism than I
806 // was able to figure out.
808 // This works but makes an implicit public struct $ArrayType$SIZE and
809 // makes the fields point to it. We could get more control if we did
812 // 1. DefineNestedType on the impl_details_class with our struct.
814 // 2. Define the field on the impl_details_class
816 static public FieldBuilder MakeStaticData (byte [] data)
819 int size = data.Length;
821 if (impl_details_class == null)
822 impl_details_class = CodeGen.ModuleBuilder.DefineType (
823 "<PrivateImplementationDetails>", TypeAttributes.NotPublic, TypeManager.object_type);
825 fb = impl_details_class.DefineInitializedData (
826 "$$field-" + (field_count++), data,
827 FieldAttributes.Static | FieldAttributes.Assembly);
833 // Adds a global attribute that was declared in `container',
834 // the attribute is in `attr', and it was defined at `loc'
836 static public void AddGlobalAttributeSection (TypeContainer container, AttributeSection attr)
838 Namespace ns = container.Namespace;
839 Attributes a = (Attributes) global_attributes [ns];
842 global_attributes [ns] = new Attributes (attr);
844 a.AddAttributeSection (attr);