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)
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)
495 foreach (string n in using_list) {
496 t = TypeManager.LookupType (MakeFQN (n, name));
504 string a = ns.LookupAlias (name);
506 t = TypeManager.LookupType (a);
510 t = TypeManager.LookupType (MakeFQN (a, name));
520 // Public function used to locate types, this can only
521 // be used after the ResolveTree function has been invoked.
523 // Returns: Type or null if they type can not be found.
525 // Come to think of it, this should be a DeclSpace
527 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
531 if (ds.Cache.Contains (name)){
532 t = (Type) ds.Cache [name];
537 // For the case the type we are looking for is nested within this one
538 // or is in any base class
540 DeclSpace containing_ds = ds;
541 while (containing_ds != null){
542 Type current_type = containing_ds.TypeBuilder;
544 while (current_type != null) {
548 t = TypeManager.LookupType (current_type.FullName + "+" + name);
554 current_type = current_type.BaseType;
557 containing_ds = containing_ds.Parent;
560 t = NamespaceLookup (ds.Namespace, name);
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);
608 static public void BootCorlib_PopulateCoreTypes ()
610 TypeContainer root = tree.Types;
612 PopulateCoreType (root, "System.Object");
613 PopulateCoreType (root, "System.ValueType");
614 PopulateCoreType (root, "System.Attribute");
618 // Populates the structs and classes with fields and methods
621 // This is invoked after all interfaces, structs and classes
622 // have been defined through `ResolveTree'
623 static public void PopulateTypes ()
625 TypeContainer root = Tree.Types;
627 if (attribute_types != null)
628 foreach (TypeContainer tc in attribute_types)
631 if (interface_resolve_order != null){
632 foreach (Interface iface in interface_resolve_order)
633 if ((iface.ModFlags & Modifiers.NEW) == 0)
636 Report1530 (iface.Location);
640 if (type_container_resolve_order != null){
641 foreach (TypeContainer tc in type_container_resolve_order) {
642 // When compiling corlib, these types have already been
643 // populated from BootCorlib_PopulateCoreTypes ().
644 if (!RootContext.StdLib &&
645 ((tc.Name == "System.Object") ||
646 (tc.Name == "System.Attribute") ||
647 (tc.Name == "System.ValueType")))
650 if ((tc.ModFlags & Modifiers.NEW) == 0)
653 Report1530 (tc.Location);
657 ArrayList delegates = root.Delegates;
658 if (delegates != null){
659 foreach (Delegate d in delegates)
660 if ((d.ModFlags & Modifiers.NEW) == 0)
663 Report1530 (d.Location);
666 ArrayList enums = root.Enums;
668 foreach (Enum en in enums)
669 if ((en.ModFlags & Modifiers.NEW) == 0)
672 Report1530 (en.Location);
676 static public void EmitCode ()
679 // Because of the strange way in which we do things, global
680 // attributes must be processed first.
682 if (global_attributes.Count > 0){
683 AssemblyBuilder ab = CodeGen.AssemblyBuilder;
684 TypeContainer dummy = new TypeContainer (null, "", new Location (-1));
685 EmitContext temp_ec = new EmitContext (
686 dummy, Mono.CSharp.Location.Null, null, null, 0, false);
688 foreach (DictionaryEntry de in global_attributes){
689 Namespace ns = (Namespace) de.Key;
690 Attributes attrs = (Attributes) de.Value;
692 dummy.Namespace = ns;
693 Attribute.ApplyAttributes (temp_ec, ab, ab, attrs, attrs.Location);
697 if (attribute_types != null)
698 foreach (TypeContainer tc in attribute_types)
701 if (type_container_resolve_order != null) {
702 foreach (TypeContainer tc in type_container_resolve_order)
705 foreach (TypeContainer tc in type_container_resolve_order)
710 if (TypeManager.unverifiable_code_ctor == null) {
711 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
715 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]);
716 CodeGen.ModuleBuilder.SetCustomAttribute (cb);
721 // Public Field, used to track which method is the public entry
724 static public MethodInfo EntryPoint;
727 // Track the location of the entry point.
729 static public Location EntryPointLocation;
732 // These are used to generate unique names on the structs and fields.
734 static int field_count;
737 // Makes an initialized struct, returns the field builder that
738 // references the data. Thanks go to Sergey Chaban for researching
739 // how to do this. And coming up with a shorter mechanism than I
740 // was able to figure out.
742 // This works but makes an implicit public struct $ArrayType$SIZE and
743 // makes the fields point to it. We could get more control if we did
746 // 1. DefineNestedType on the impl_details_class with our struct.
748 // 2. Define the field on the impl_details_class
750 static public FieldBuilder MakeStaticData (byte [] data)
753 int size = data.Length;
755 if (impl_details_class == null)
756 impl_details_class = CodeGen.ModuleBuilder.DefineType (
757 "<PrivateImplementationDetails>", TypeAttributes.NotPublic, TypeManager.object_type);
759 fb = impl_details_class.DefineInitializedData (
760 "$$field-" + (field_count++), data,
761 FieldAttributes.Static | FieldAttributes.Assembly);
767 // Adds a global attribute that was declared in `container',
768 // the attribute is in `attr', and it was defined at `loc'
770 static public void AddGlobalAttribute (TypeContainer container,
771 AttributeSection attr, Location loc)
773 Namespace ns = container.Namespace;
774 Attributes a = (Attributes) global_attributes [ns];
777 global_attributes [ns] = new Attributes (attr, loc);
779 a.AddAttribute (attr);