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 (DeclSpace ds, string name, Location loc)
467 // Try in the current namespace and all its implicit parents
469 for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
470 object result = ns.Lookup (ds, name, loc);
475 return (Type) result;
484 // Public function used to locate types, this can only
485 // be used after the ResolveTree function has been invoked.
487 // Returns: Type or null if they type can not be found.
489 // Come to think of it, this should be a DeclSpace
491 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
495 if (ds.Cache.Contains (name)){
496 t = (Type) ds.Cache [name];
501 // For the case the type we are looking for is nested within this one
502 // or is in any base class
504 DeclSpace containing_ds = ds;
505 while (containing_ds != null){
506 Type current_type = containing_ds.TypeBuilder;
508 while (current_type != null) {
512 t = TypeManager.LookupType (current_type.FullName + "." + name);
518 current_type = current_type.BaseType;
521 containing_ds = containing_ds.Parent;
524 t = NamespaceLookup (ds, name, loc);
532 Report.Error (246, loc, "Cannot find type `"+name+"'");
538 // This is the silent version of LookupType, you can use this
539 // to `probe' for a type
541 static public Type LookupType (TypeContainer tc, string name, Location loc)
543 return LookupType (tc, name, true, loc);
546 static public bool IsNamespace (string name)
550 if (tree.Namespaces != null){
551 ns = (Namespace) tree.Namespaces [name];
560 static void Report1530 (Location loc)
562 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
565 static public void PopulateCoreType (TypeContainer root, string name)
567 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
569 ds.DefineMembers (root);
573 static public void BootCorlib_PopulateCoreTypes ()
575 TypeContainer root = tree.Types;
577 PopulateCoreType (root, "System.Object");
578 PopulateCoreType (root, "System.ValueType");
579 PopulateCoreType (root, "System.Attribute");
583 // Populates the structs and classes with fields and methods
586 // This is invoked after all interfaces, structs and classes
587 // have been defined through `ResolveTree'
588 static public void PopulateTypes ()
590 TypeContainer root = Tree.Types;
592 if (attribute_types != null)
593 foreach (TypeContainer tc in attribute_types)
594 tc.DefineMembers (root);
596 if (interface_resolve_order != null){
597 foreach (Interface iface in interface_resolve_order)
598 if ((iface.ModFlags & Modifiers.NEW) == 0)
599 iface.DefineMembers (root);
601 Report1530 (iface.Location);
605 if (type_container_resolve_order != null){
606 if (RootContext.StdLib){
607 foreach (TypeContainer tc in type_container_resolve_order)
608 tc.DefineMembers (root);
610 foreach (TypeContainer tc in type_container_resolve_order) {
611 // When compiling corlib, these types have already been
612 // populated from BootCorlib_PopulateCoreTypes ().
613 if (((tc.Name == "System.Object") ||
614 (tc.Name == "System.Attribute") ||
615 (tc.Name == "System.ValueType")))
618 tc.DefineMembers (root);
623 ArrayList delegates = root.Delegates;
624 if (delegates != null){
625 foreach (Delegate d in delegates)
626 if ((d.ModFlags & Modifiers.NEW) == 0)
627 d.DefineMembers (root);
629 Report1530 (d.Location);
632 ArrayList enums = root.Enums;
634 foreach (Enum en in enums)
635 if ((en.ModFlags & Modifiers.NEW) == 0)
636 en.DefineMembers (root);
638 Report1530 (en.Location);
643 // A generic hook delegate
645 public delegate void Hook ();
648 // A hook invoked when the code has been generated.
650 public static event Hook EmitCodeHook;
653 // DefineTypes is used to fill in the members of each type.
655 static public void DefineTypes ()
657 TypeContainer root = Tree.Types;
659 if (attribute_types != null)
660 foreach (TypeContainer tc in attribute_types)
663 if (interface_resolve_order != null){
664 foreach (Interface iface in interface_resolve_order)
665 if ((iface.ModFlags & Modifiers.NEW) == 0)
670 if (type_container_resolve_order != null){
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 (!RootContext.StdLib &&
675 ((tc.Name == "System.Object") ||
676 (tc.Name == "System.Attribute") ||
677 (tc.Name == "System.ValueType")))
680 if ((tc.ModFlags & Modifiers.NEW) == 0)
685 ArrayList delegates = root.Delegates;
686 if (delegates != null){
687 foreach (Delegate d in delegates)
688 if ((d.ModFlags & Modifiers.NEW) == 0)
692 ArrayList enums = root.Enums;
694 foreach (Enum en in enums)
695 if ((en.ModFlags & Modifiers.NEW) == 0)
700 static public void EmitCode ()
703 // Because of the strange way in which we do things, global
704 // attributes must be processed first.
706 if (global_attributes.Count > 0){
707 AssemblyBuilder ab = CodeGen.AssemblyBuilder;
708 TypeContainer dummy = new TypeContainer (null, null, "", new Location (-1));
709 EmitContext temp_ec = new EmitContext (
710 dummy, Mono.CSharp.Location.Null, null, null, 0, false);
712 foreach (DictionaryEntry de in global_attributes){
713 NamespaceEntry ns = (NamespaceEntry) de.Key;
714 Attributes attrs = (Attributes) de.Value;
716 dummy.NamespaceEntry = ns;
717 Attribute.ApplyAttributes (temp_ec, ab, ab, attrs);
721 if (attribute_types != null)
722 foreach (TypeContainer tc in attribute_types)
725 if (interface_resolve_order != null){
726 foreach (Interface iface in interface_resolve_order)
727 iface.Emit (Tree.Types);
730 if (type_container_resolve_order != null) {
731 foreach (TypeContainer tc in type_container_resolve_order)
734 foreach (TypeContainer tc in type_container_resolve_order)
739 // Run any hooks after all the types have been defined.
740 // This is used to create nested auxiliary classes for example
743 if (EmitCodeHook != null)
748 if (TypeManager.unverifiable_code_ctor == null) {
749 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
753 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor,
755 CodeGen.ModuleBuilder.SetCustomAttribute (cb);
760 // Public Field, used to track which method is the public entry
763 static public MethodInfo EntryPoint;
766 // Track the location of the entry point.
768 static public Location EntryPointLocation;
771 // These are used to generate unique names on the structs and fields.
773 static int field_count;
776 // Makes an initialized struct, returns the field builder that
777 // references the data. Thanks go to Sergey Chaban for researching
778 // how to do this. And coming up with a shorter mechanism than I
779 // was able to figure out.
781 // This works but makes an implicit public struct $ArrayType$SIZE and
782 // makes the fields point to it. We could get more control if we did
785 // 1. DefineNestedType on the impl_details_class with our struct.
787 // 2. Define the field on the impl_details_class
789 static public FieldBuilder MakeStaticData (byte [] data)
792 int size = data.Length;
794 if (impl_details_class == null){
795 impl_details_class = CodeGen.ModuleBuilder.DefineType (
796 "<PrivateImplementationDetails>",
797 TypeAttributes.NotPublic,
798 TypeManager.object_type);
800 RegisterHelperClass (impl_details_class);
803 fb = impl_details_class.DefineInitializedData (
804 "$$field-" + (field_count++), data,
805 FieldAttributes.Static | FieldAttributes.Assembly);
811 // Adds a global attribute that was declared in `container',
812 // the attribute is in `attr', and it was defined at `loc'
814 static public void AddGlobalAttributeSection (TypeContainer container, AttributeSection attr)
816 NamespaceEntry ns = container.NamespaceEntry;
817 Attributes a = (Attributes) global_attributes [ns];
820 global_attributes [ns] = new Attributes (attr);
822 a.AddAttributeSection (attr);