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",
358 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
359 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
360 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
361 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
362 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
363 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
365 foreach (string cname in classes_second_stage)
366 BootstrapCorlib_ResolveClass (root, cname);
368 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
372 // Closes all open types
376 // We usually use TypeBuilder types. When we are done
377 // creating the type (which will happen after we have added
378 // methods, fields, etc) we need to "Define" them before we
379 // can save the Assembly
381 static public void CloseTypes ()
383 TypeContainer root = Tree.Types;
385 ArrayList ifaces = root.Interfaces;
387 if (root.Enums != null)
388 foreach (Enum en in root.Enums)
391 if (attribute_types != null)
392 foreach (TypeContainer tc in attribute_types)
395 foreach (Interface iface in interface_resolve_order)
399 // We do this in two passes, first we close the structs,
400 // then the classes, because it seems the code needs it this
401 // way. If this is really what is going on, we should probably
402 // make sure that we define the structs in order as well.
404 foreach (TypeContainer tc in type_container_resolve_order){
405 if (tc is Struct && tc.Parent == tree.Types){
410 foreach (TypeContainer tc in type_container_resolve_order){
411 if (!(tc is Struct && tc.Parent == tree.Types))
415 if (root.Delegates != null)
416 foreach (Delegate d in root.Delegates)
421 // If we have a <PrivateImplementationDetails> class, close it
423 if (impl_details_class != null){
424 impl_details_class.CreateType ();
429 // This idea is from Felix Arrese-Igor
431 // Returns : the implicit parent of a composite namespace string
432 // eg. Implicit parent of A.B is A
434 static public string ImplicitParent (string ns)
436 int i = ns.LastIndexOf (".");
440 return ns.Substring (0, i);
443 static Type NamespaceLookup (Namespace curr_ns, string name, Location loc)
448 // Try in the current namespace and all its implicit parents
450 for (string ns = curr_ns.Name; ns != null; ns = ImplicitParent (ns)) {
451 t = TypeManager.LookupType (MakeFQN (ns, name));
457 // It's possible that name already is fully qualified. So we do
458 // a simple direct lookup without adding any namespace names
460 t = TypeManager.LookupType (name);
465 // Try the aliases in the current namespace
467 string alias = curr_ns.LookupAlias (name);
470 t = TypeManager.LookupType (alias);
474 t = TypeManager.LookupType (MakeFQN (alias, name));
479 for (Namespace ns = curr_ns; ns != null; ns = ns.Parent) {
481 // Look in the namespace ns
483 t = TypeManager.LookupType (MakeFQN (ns.Name, name));
488 // Then try with the using clauses
490 ArrayList using_list = ns.UsingTable;
492 if (using_list == null)
496 foreach (Namespace.UsingEntry ue in using_list) {
497 match = TypeManager.LookupType (MakeFQN (ue.Name, name));
500 DeclSpace.Error_AmbiguousTypeReference (loc, name, t, match);
514 string a = ns.LookupAlias (name);
516 t = TypeManager.LookupType (a);
520 t = TypeManager.LookupType (MakeFQN (a, name));
530 // Public function used to locate types, this can only
531 // be used after the ResolveTree function has been invoked.
533 // Returns: Type or null if they type can not be found.
535 // Come to think of it, this should be a DeclSpace
537 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
541 if (ds.Cache.Contains (name)){
542 t = (Type) ds.Cache [name];
547 // For the case the type we are looking for is nested within this one
548 // or is in any base class
550 DeclSpace containing_ds = ds;
551 while (containing_ds != null){
552 Type current_type = containing_ds.TypeBuilder;
554 while (current_type != null) {
558 t = TypeManager.LookupType (current_type.FullName + "." + name);
564 current_type = current_type.BaseType;
567 containing_ds = containing_ds.Parent;
570 t = NamespaceLookup (ds.Namespace, name, loc);
578 Report.Error (246, loc, "Cannot find type `"+name+"'");
584 // This is the silent version of LookupType, you can use this
585 // to `probe' for a type
587 static public Type LookupType (TypeContainer tc, string name, Location loc)
589 return LookupType (tc, name, true, loc);
592 static public bool IsNamespace (string name)
596 if (tree.Namespaces != null){
597 ns = (Namespace) tree.Namespaces [name];
606 static void Report1530 (Location loc)
608 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
611 static public void PopulateCoreType (TypeContainer root, string name)
613 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
615 ds.DefineMembers (root);
619 static public void BootCorlib_PopulateCoreTypes ()
621 TypeContainer root = tree.Types;
623 PopulateCoreType (root, "System.Object");
624 PopulateCoreType (root, "System.ValueType");
625 PopulateCoreType (root, "System.Attribute");
629 // Populates the structs and classes with fields and methods
632 // This is invoked after all interfaces, structs and classes
633 // have been defined through `ResolveTree'
634 static public void PopulateTypes ()
636 TypeContainer root = Tree.Types;
638 if (attribute_types != null)
639 foreach (TypeContainer tc in attribute_types)
640 tc.DefineMembers (root);
642 if (interface_resolve_order != null){
643 foreach (Interface iface in interface_resolve_order)
644 if ((iface.ModFlags & Modifiers.NEW) == 0)
645 iface.DefineMembers (root);
647 Report1530 (iface.Location);
651 if (type_container_resolve_order != null){
652 foreach (TypeContainer tc in type_container_resolve_order) {
653 // When compiling corlib, these types have already been
654 // populated from BootCorlib_PopulateCoreTypes ().
655 if (!RootContext.StdLib &&
656 ((tc.Name == "System.Object") ||
657 (tc.Name == "System.Attribute") ||
658 (tc.Name == "System.ValueType")))
661 if ((tc.ModFlags & Modifiers.NEW) == 0)
662 tc.DefineMembers (root);
664 Report1530 (tc.Location);
668 ArrayList delegates = root.Delegates;
669 if (delegates != null){
670 foreach (Delegate d in delegates)
671 if ((d.ModFlags & Modifiers.NEW) == 0)
672 d.DefineMembers (root);
674 Report1530 (d.Location);
677 ArrayList enums = root.Enums;
679 foreach (Enum en in enums)
680 if ((en.ModFlags & Modifiers.NEW) == 0)
681 en.DefineMembers (root);
683 Report1530 (en.Location);
687 static public void DefineTypes ()
689 TypeContainer root = Tree.Types;
691 if (attribute_types != null)
692 foreach (TypeContainer tc in attribute_types)
695 if (interface_resolve_order != null){
696 foreach (Interface iface in interface_resolve_order)
697 if ((iface.ModFlags & Modifiers.NEW) == 0)
702 if (type_container_resolve_order != null){
703 foreach (TypeContainer tc in type_container_resolve_order) {
704 // When compiling corlib, these types have already been
705 // populated from BootCorlib_PopulateCoreTypes ().
706 if (!RootContext.StdLib &&
707 ((tc.Name == "System.Object") ||
708 (tc.Name == "System.Attribute") ||
709 (tc.Name == "System.ValueType")))
712 if ((tc.ModFlags & Modifiers.NEW) == 0)
717 ArrayList delegates = root.Delegates;
718 if (delegates != null){
719 foreach (Delegate d in delegates)
720 if ((d.ModFlags & Modifiers.NEW) == 0)
724 ArrayList enums = root.Enums;
726 foreach (Enum en in enums)
727 if ((en.ModFlags & Modifiers.NEW) == 0)
732 static public void EmitCode ()
735 // Because of the strange way in which we do things, global
736 // attributes must be processed first.
738 if (global_attributes.Count > 0){
739 AssemblyBuilder ab = CodeGen.AssemblyBuilder;
740 TypeContainer dummy = new TypeContainer (null, "", new Location (-1));
741 EmitContext temp_ec = new EmitContext (
742 dummy, Mono.CSharp.Location.Null, null, null, 0, false);
744 foreach (DictionaryEntry de in global_attributes){
745 Namespace ns = (Namespace) de.Key;
746 Attributes attrs = (Attributes) de.Value;
748 dummy.Namespace = ns;
749 Attribute.ApplyAttributes (temp_ec, ab, ab, attrs, attrs.Location);
753 if (attribute_types != null)
754 foreach (TypeContainer tc in attribute_types)
757 if (type_container_resolve_order != null) {
758 foreach (TypeContainer tc in type_container_resolve_order)
761 foreach (TypeContainer tc in type_container_resolve_order)
766 if (TypeManager.unverifiable_code_ctor == null) {
767 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
771 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]);
772 CodeGen.ModuleBuilder.SetCustomAttribute (cb);
777 // Public Field, used to track which method is the public entry
780 static public MethodInfo EntryPoint;
783 // Track the location of the entry point.
785 static public Location EntryPointLocation;
788 // These are used to generate unique names on the structs and fields.
790 static int field_count;
793 // Makes an initialized struct, returns the field builder that
794 // references the data. Thanks go to Sergey Chaban for researching
795 // how to do this. And coming up with a shorter mechanism than I
796 // was able to figure out.
798 // This works but makes an implicit public struct $ArrayType$SIZE and
799 // makes the fields point to it. We could get more control if we did
802 // 1. DefineNestedType on the impl_details_class with our struct.
804 // 2. Define the field on the impl_details_class
806 static public FieldBuilder MakeStaticData (byte [] data)
809 int size = data.Length;
811 if (impl_details_class == null)
812 impl_details_class = CodeGen.ModuleBuilder.DefineType (
813 "<PrivateImplementationDetails>", TypeAttributes.NotPublic, TypeManager.object_type);
815 fb = impl_details_class.DefineInitializedData (
816 "$$field-" + (field_count++), data,
817 FieldAttributes.Static | FieldAttributes.Assembly);
823 // Adds a global attribute that was declared in `container',
824 // the attribute is in `attr', and it was defined at `loc'
826 static public void AddGlobalAttribute (TypeContainer container,
827 AttributeSection attr, Location loc)
829 Namespace ns = container.Namespace;
830 Attributes a = (Attributes) global_attributes [ns];
833 global_attributes [ns] = new Attributes (attr, loc);
835 a.AddAttribute (attr);