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 // Whether we are being linked against the standard libraries.
34 // This is only used to tell whether `System.Object' should
35 // have a parent or not.
37 public static bool StdLib = true;
40 // This keeps track of the order in which classes were defined
41 // so that we can poulate them in that order.
43 // Order is important, because we need to be able to tell by
44 // examining the parent's list of methods which ones are virtual
45 // or abstract as well as the parent names (to implement new,
48 static ArrayList type_container_resolve_order;
49 static ArrayList interface_resolve_order;
50 static ArrayList attribute_types;
53 // Holds a reference to the Private Implementation Details
56 static ArrayList helper_classes;
58 static TypeBuilder impl_details_class;
60 public static int WarningLevel = 2;
62 public static Target Target = Target.Exe;
63 public static string TargetExt = ".exe";
66 // If set, enable C# version 2 features
68 public static bool V2 = true;
75 interface_resolve_order = new ArrayList ();
76 type_container_resolve_order = new ArrayList ();
79 public static bool NeedsEntryPoint {
81 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
85 static public Tree Tree {
91 static public string MainClass;
93 public static void RegisterOrder (Interface iface)
95 interface_resolve_order.Add (iface);
98 public static void RegisterOrder (TypeContainer tc)
100 type_container_resolve_order.Add (tc);
103 public static void RegisterAttribute (TypeContainer tc)
105 if (attribute_types == null)
106 attribute_types = new ArrayList ();
108 attribute_types.Add (tc);
112 // The default compiler checked state
114 static public bool Checked = false;
117 // Whether to allow Unsafe code
119 static public bool Unsafe = false;
121 static string MakeFQN (string nsn, string name)
125 return String.Concat (nsn, ".", name);
129 // This function is used to resolve the hierarchy tree.
130 // It processes interfaces, structs and classes in that order.
132 // It creates the TypeBuilder's as it processes the user defined
135 static public void ResolveTree ()
138 // Process the attribute types separately and before anything else
140 if (attribute_types != null)
141 foreach (TypeContainer tc in attribute_types)
145 // Interfaces are processed next, as classes and
146 // structs might inherit from an object or implement
147 // a set of interfaces, we need to be able to tell
148 // them appart by just using the TypeManager.
150 TypeContainer root = Tree.Types;
152 ArrayList ifaces = root.Interfaces;
154 foreach (Interface i in ifaces)
158 foreach (TypeContainer tc in root.Types)
161 if (root.Delegates != null)
162 foreach (Delegate d in root.Delegates)
165 if (root.Enums != null)
166 foreach (Enum e in root.Enums)
170 static void Error_TypeConflict (string name, Location loc)
173 520, loc, "`" + name + "' conflicts with a predefined type");
176 static void Error_TypeConflict (string name)
179 520, "`" + name + "' conflicts with a predefined type");
183 // Resolves a single class during the corlib bootstrap process
185 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
187 object o = root.GetDefinition (name);
189 Report.Error (518, "The predefined type `" + name + "' is not defined");
195 DeclSpace d = (DeclSpace) o;
197 Error_TypeConflict (name, d.Location);
199 Error_TypeConflict (name);
204 return ((DeclSpace) o).DefineType ();
208 // Resolves a struct during the corlib bootstrap process
210 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
212 object o = root.GetDefinition (name);
214 Report.Error (518, "The predefined type `" + name + "' is not defined");
220 DeclSpace d = (DeclSpace) o;
222 Error_TypeConflict (name, d.Location);
224 Error_TypeConflict (name);
229 ((DeclSpace) o).DefineType ();
233 // Resolves a struct during the corlib bootstrap process
235 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
237 object o = root.GetDefinition (name);
239 Report.Error (518, "The predefined type `" + name + "' is not defined");
243 if (!(o is Interface)){
245 DeclSpace d = (DeclSpace) o;
247 Error_TypeConflict (name, d.Location);
249 Error_TypeConflict (name);
254 ((DeclSpace) o).DefineType ();
258 // Resolves a delegate during the corlib bootstrap process
260 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
262 object o = root.GetDefinition (name);
264 Report.Error (518, "The predefined type `" + name + "' is not defined");
265 Environment.Exit (0);
268 if (!(o is Delegate)){
269 Error_TypeConflict (name);
273 ((DeclSpace) o).DefineType ();
278 /// Resolves the core types in the compiler when compiling with --nostdlib
280 static public void ResolveCore ()
282 TypeContainer root = Tree.Types;
284 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
285 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
286 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
288 string [] interfaces_first_stage = {
289 "System.IComparable", "System.ICloneable",
290 "System.IConvertible",
292 "System.Collections.IEnumerable",
293 "System.Collections.ICollection",
294 "System.Collections.IEnumerator",
295 "System.Collections.IList",
296 "System.IAsyncResult",
297 "System.IDisposable",
299 "System.Runtime.Serialization.ISerializable",
301 "System.Reflection.IReflect",
302 "System.Reflection.ICustomAttributeProvider"
305 foreach (string iname in interfaces_first_stage)
306 BootstrapCorlib_ResolveInterface (root, iname);
309 // These are the base value types
311 string [] structs_first_stage = {
312 "System.Byte", "System.SByte",
313 "System.Int16", "System.UInt16",
314 "System.Int32", "System.UInt32",
315 "System.Int64", "System.UInt64",
318 foreach (string cname in structs_first_stage)
319 BootstrapCorlib_ResolveStruct (root, cname);
322 // Now, we can load the enumerations, after this point,
325 TypeManager.InitEnumUnderlyingTypes ();
327 string [] structs_second_stage = {
328 "System.Single", "System.Double",
329 "System.Char", "System.Boolean",
330 "System.Decimal", "System.Void",
331 "System.RuntimeFieldHandle",
332 "System.RuntimeTypeHandle",
336 foreach (string cname in structs_second_stage)
337 BootstrapCorlib_ResolveStruct (root, cname);
340 // These are classes that depends on the core interfaces
342 string [] classes_second_stage = {
343 "System.Reflection.MemberInfo",
348 // These are not really important in the order, but they
349 // are used by the compiler later on (typemanager/CoreLookupType-d)
351 "System.Runtime.CompilerServices.RuntimeHelpers",
352 "System.Reflection.DefaultMemberAttribute",
353 "System.Threading.Monitor",
355 "System.AttributeUsageAttribute",
356 "System.Runtime.InteropServices.DllImportAttribute",
357 "System.Runtime.CompilerServices.MethodImplAttribute",
358 "System.Runtime.InteropServices.MarshalAsAttribute",
359 "System.Runtime.CompilerServices.NewConstraintAttribute",
360 "System.Diagnostics.ConditionalAttribute",
361 "System.ObsoleteAttribute",
362 "System.ParamArrayAttribute",
363 "System.Security.UnverifiableCodeAttribute",
364 "System.Runtime.CompilerServices.IndexerNameAttribute",
365 "System.Runtime.InteropServices.InAttribute",
366 "System.InvalidOperationException"
370 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
371 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
372 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
373 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
374 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
375 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
377 foreach (string cname in classes_second_stage)
378 BootstrapCorlib_ResolveClass (root, cname);
380 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
384 // Closes all open types
388 // We usually use TypeBuilder types. When we are done
389 // creating the type (which will happen after we have added
390 // methods, fields, etc) we need to "Define" them before we
391 // can save the Assembly
393 static public void CloseTypes ()
395 TypeContainer root = Tree.Types;
397 if (root.Enums != null)
398 foreach (Enum en in root.Enums)
401 if (attribute_types != null)
402 foreach (TypeContainer tc in attribute_types)
405 foreach (Interface iface in interface_resolve_order)
409 // We do this in two passes, first we close the structs,
410 // then the classes, because it seems the code needs it this
411 // way. If this is really what is going on, we should probably
412 // make sure that we define the structs in order as well.
414 foreach (TypeContainer tc in type_container_resolve_order){
415 if (tc is Struct && tc.Parent == tree.Types){
420 foreach (TypeContainer tc in type_container_resolve_order){
421 if (!(tc is Struct && tc.Parent == tree.Types))
425 if (root.Delegates != null)
426 foreach (Delegate d in root.Delegates)
431 // If we have a <PrivateImplementationDetails> class, close it
433 if (helper_classes != null){
434 foreach (TypeBuilder type_builder in helper_classes)
435 type_builder.CreateType ();
438 attribute_types = null;
439 interface_resolve_order = null;
440 type_container_resolve_order = null;
441 helper_classes = null;
443 TypeManager.CleanUp ();
447 /// Used to register classes that need to be closed after all the
448 /// user defined classes
450 public static void RegisterHelperClass (TypeBuilder helper_class)
452 if (helper_classes == null)
453 helper_classes = new ArrayList ();
454 helper_classes.Add (helper_class);
458 // This idea is from Felix Arrese-Igor
460 // Returns : the implicit parent of a composite namespace string
461 // eg. Implicit parent of A.B is A
463 static public string ImplicitParent (string ns)
465 int i = ns.LastIndexOf ('.');
469 return ns.Substring (0, i);
472 static Type NamespaceLookup (DeclSpace ds, string name,
473 int num_type_args, Location loc)
476 // Try in the current namespace and all its implicit parents
478 for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
479 object result = ns.Lookup (ds, name, loc);
483 Type t = result as Type;
485 if (TypeManager.CheckGeneric (t, num_type_args))
497 static public Type LookupType (DeclSpace ds, string name, bool silent,
500 return LookupType (ds, name, silent, 0, loc);
504 // Public function used to locate types, this can only
505 // be used after the ResolveTree function has been invoked.
507 // Returns: Type or null if they type can not be found.
509 // Come to think of it, this should be a DeclSpace
511 static public Type LookupType (DeclSpace ds, string name, bool silent,
512 int num_type_params, Location loc)
516 if (ds.Cache.Contains (name)){
517 t = (Type) ds.Cache [name];
522 // For the case the type we are looking for is nested within this one
523 // or is in any base class
525 DeclSpace containing_ds = ds;
526 while (containing_ds != null){
527 Type current_type = containing_ds.TypeBuilder;
529 while (current_type != null) {
533 t = TypeManager.LookupType (current_type.FullName + "." + name);
539 current_type = current_type.BaseType;
542 containing_ds = containing_ds.Parent;
545 t = NamespaceLookup (ds, name, num_type_params, loc);
553 Report.Error (246, loc, "Cannot find type `"+name+"'");
559 // This is the silent version of LookupType, you can use this
560 // to `probe' for a type
562 static public Type LookupType (TypeContainer tc, string name, Location loc)
564 return LookupType (tc, name, true, loc);
567 static public bool IsNamespace (string name)
571 if (tree.Namespaces != null){
572 ns = (Namespace) tree.Namespaces [name];
581 static void Report1530 (Location loc)
583 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
586 static public void PopulateCoreType (TypeContainer root, string name)
588 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
590 ds.DefineMembers (root);
594 static public void BootCorlib_PopulateCoreTypes ()
596 TypeContainer root = tree.Types;
598 PopulateCoreType (root, "System.Object");
599 PopulateCoreType (root, "System.ValueType");
600 PopulateCoreType (root, "System.Attribute");
604 // Populates the structs and classes with fields and methods
607 // This is invoked after all interfaces, structs and classes
608 // have been defined through `ResolveTree'
609 static public void PopulateTypes ()
611 TypeContainer root = Tree.Types;
613 if (attribute_types != null)
614 foreach (TypeContainer tc in attribute_types)
615 tc.DefineMembers (root);
617 if (interface_resolve_order != null){
618 foreach (Interface iface in interface_resolve_order)
619 if ((iface.ModFlags & Modifiers.NEW) == 0)
620 iface.DefineMembers (root);
622 Report1530 (iface.Location);
626 if (type_container_resolve_order != null){
627 if (RootContext.StdLib){
628 foreach (TypeContainer tc in type_container_resolve_order)
629 tc.DefineMembers (root);
631 foreach (TypeContainer tc in type_container_resolve_order) {
632 // When compiling corlib, these types have already been
633 // populated from BootCorlib_PopulateCoreTypes ().
634 if (((tc.Name == "System.Object") ||
635 (tc.Name == "System.Attribute") ||
636 (tc.Name == "System.ValueType")))
639 tc.DefineMembers (root);
644 ArrayList delegates = root.Delegates;
645 if (delegates != null){
646 foreach (Delegate d in delegates)
647 if ((d.ModFlags & Modifiers.NEW) == 0)
648 d.DefineMembers (root);
650 Report1530 (d.Location);
653 ArrayList enums = root.Enums;
655 foreach (Enum en in enums)
656 if ((en.ModFlags & Modifiers.NEW) == 0)
657 en.DefineMembers (root);
659 Report1530 (en.Location);
664 // A generic hook delegate
666 public delegate void Hook ();
669 // A hook invoked when the code has been generated.
671 public static event Hook EmitCodeHook;
674 // DefineTypes is used to fill in the members of each type.
676 static public void DefineTypes ()
678 TypeContainer root = Tree.Types;
680 if (attribute_types != null)
681 foreach (TypeContainer tc in attribute_types)
684 if (interface_resolve_order != null){
685 foreach (Interface iface in interface_resolve_order)
686 if ((iface.ModFlags & Modifiers.NEW) == 0)
691 if (type_container_resolve_order != null){
692 foreach (TypeContainer tc in type_container_resolve_order) {
693 // When compiling corlib, these types have already been
694 // populated from BootCorlib_PopulateCoreTypes ().
695 if (!RootContext.StdLib &&
696 ((tc.Name == "System.Object") ||
697 (tc.Name == "System.Attribute") ||
698 (tc.Name == "System.ValueType")))
701 if ((tc.ModFlags & Modifiers.NEW) == 0)
706 ArrayList delegates = root.Delegates;
707 if (delegates != null){
708 foreach (Delegate d in delegates)
709 if ((d.ModFlags & Modifiers.NEW) == 0)
713 ArrayList enums = root.Enums;
715 foreach (Enum en in enums)
716 if ((en.ModFlags & Modifiers.NEW) == 0)
721 static public void EmitCode ()
724 // Because of the strange way in which we do things, global
725 // attributes must be processed first.
727 CodeGen.Assembly.Emit ();
728 CodeGen.Module.Emit ();
730 if (attribute_types != null)
731 foreach (TypeContainer tc in attribute_types)
734 if (interface_resolve_order != null){
735 foreach (Interface iface in interface_resolve_order)
739 if (type_container_resolve_order != null) {
740 foreach (TypeContainer tc in type_container_resolve_order)
743 foreach (TypeContainer tc in type_container_resolve_order)
748 // Run any hooks after all the types have been defined.
749 // This is used to create nested auxiliary classes for example
752 if (EmitCodeHook != null)
757 // Public Field, used to track which method is the public entry
760 static public MethodInfo EntryPoint;
763 // Track the location of the entry point.
765 static public Location EntryPointLocation;
768 // These are used to generate unique names on the structs and fields.
770 static int field_count;
773 // Makes an initialized struct, returns the field builder that
774 // references the data. Thanks go to Sergey Chaban for researching
775 // how to do this. And coming up with a shorter mechanism than I
776 // was able to figure out.
778 // This works but makes an implicit public struct $ArrayType$SIZE and
779 // makes the fields point to it. We could get more control if we did
782 // 1. DefineNestedType on the impl_details_class with our struct.
784 // 2. Define the field on the impl_details_class
786 static public FieldBuilder MakeStaticData (byte [] data)
790 if (impl_details_class == null){
791 impl_details_class = CodeGen.Module.Builder.DefineType (
792 "<PrivateImplementationDetails>",
793 TypeAttributes.NotPublic,
794 TypeManager.object_type);
796 RegisterHelperClass (impl_details_class);
799 fb = impl_details_class.DefineInitializedData (
800 "$$field-" + (field_count++), data,
801 FieldAttributes.Static | FieldAttributes.Assembly);