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;
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.Diagnostics.ConditionalAttribute",
360 "System.ObsoleteAttribute",
361 "System.ParamArrayAttribute",
362 "System.Security.UnverifiableCodeAttribute",
363 "System.Runtime.CompilerServices.IndexerNameAttribute",
364 "System.Runtime.InteropServices.InAttribute",
365 "System.InvalidOperationException"
369 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
370 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
371 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
372 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
373 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
374 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
376 foreach (string cname in classes_second_stage)
377 BootstrapCorlib_ResolveClass (root, cname);
379 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
383 // Closes all open types
387 // We usually use TypeBuilder types. When we are done
388 // creating the type (which will happen after we have added
389 // methods, fields, etc) we need to "Define" them before we
390 // can save the Assembly
392 static public void CloseTypes ()
394 TypeContainer root = Tree.Types;
396 if (root.Enums != null)
397 foreach (Enum en in root.Enums)
400 if (attribute_types != null)
401 foreach (TypeContainer tc in attribute_types)
404 foreach (Interface iface in interface_resolve_order)
408 // We do this in two passes, first we close the structs,
409 // then the classes, because it seems the code needs it this
410 // way. If this is really what is going on, we should probably
411 // make sure that we define the structs in order as well.
413 foreach (TypeContainer tc in type_container_resolve_order){
414 if (tc is Struct && tc.Parent == tree.Types){
419 foreach (TypeContainer tc in type_container_resolve_order){
420 if (!(tc is Struct && tc.Parent == tree.Types))
424 if (root.Delegates != null)
425 foreach (Delegate d in root.Delegates)
430 // If we have a <PrivateImplementationDetails> class, close it
432 if (helper_classes != null){
433 foreach (TypeBuilder type_builder in helper_classes)
434 type_builder.CreateType ();
437 attribute_types = null;
438 interface_resolve_order = null;
439 type_container_resolve_order = null;
440 helper_classes = null;
442 TypeManager.CleanUp ();
446 /// Used to register classes that need to be closed after all the
447 /// user defined classes
449 public static void RegisterHelperClass (TypeBuilder helper_class)
451 if (helper_classes == null)
452 helper_classes = new ArrayList ();
453 helper_classes.Add (helper_class);
457 // This idea is from Felix Arrese-Igor
459 // Returns : the implicit parent of a composite namespace string
460 // eg. Implicit parent of A.B is A
462 static public string ImplicitParent (string ns)
464 int i = ns.LastIndexOf ('.');
468 return ns.Substring (0, i);
471 static Type NamespaceLookup (DeclSpace ds, string name, Location loc)
474 // Try in the current namespace and all its implicit parents
476 for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
477 object result = ns.Lookup (ds, name, loc);
482 return (Type) result;
491 // Public function used to locate types, this can only
492 // be used after the ResolveTree function has been invoked.
494 // Returns: Type or null if they type can not be found.
496 // Come to think of it, this should be a DeclSpace
498 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
502 if (ds.Cache.Contains (name)){
503 t = (Type) ds.Cache [name];
508 // For the case the type we are looking for is nested within this one
509 // or is in any base class
511 DeclSpace containing_ds = ds;
512 while (containing_ds != null){
513 Type current_type = containing_ds.TypeBuilder;
515 while (current_type != null) {
519 t = TypeManager.LookupType (current_type.FullName + "." + name);
525 current_type = current_type.BaseType;
528 containing_ds = containing_ds.Parent;
531 t = NamespaceLookup (ds, name, loc);
539 Report.Error (246, loc, "Cannot find type `"+name+"'");
545 // This is the silent version of LookupType, you can use this
546 // to `probe' for a type
548 static public Type LookupType (TypeContainer tc, string name, Location loc)
550 return LookupType (tc, name, true, loc);
553 static public bool IsNamespace (string name)
557 if (tree.Namespaces != null){
558 ns = (Namespace) tree.Namespaces [name];
567 static void Report1530 (Location loc)
569 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
572 static public void PopulateCoreType (TypeContainer root, string name)
574 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
576 ds.DefineMembers (root);
580 static public void BootCorlib_PopulateCoreTypes ()
582 TypeContainer root = tree.Types;
584 PopulateCoreType (root, "System.Object");
585 PopulateCoreType (root, "System.ValueType");
586 PopulateCoreType (root, "System.Attribute");
590 // Populates the structs and classes with fields and methods
593 // This is invoked after all interfaces, structs and classes
594 // have been defined through `ResolveTree'
595 static public void PopulateTypes ()
597 TypeContainer root = Tree.Types;
599 if (attribute_types != null)
600 foreach (TypeContainer tc in attribute_types)
601 tc.DefineMembers (root);
603 if (interface_resolve_order != null){
604 foreach (Interface iface in interface_resolve_order)
605 if ((iface.ModFlags & Modifiers.NEW) == 0)
606 iface.DefineMembers (root);
608 Report1530 (iface.Location);
612 if (type_container_resolve_order != null){
613 if (RootContext.StdLib){
614 foreach (TypeContainer tc in type_container_resolve_order)
615 tc.DefineMembers (root);
617 foreach (TypeContainer tc in type_container_resolve_order) {
618 // When compiling corlib, these types have already been
619 // populated from BootCorlib_PopulateCoreTypes ().
620 if (((tc.Name == "System.Object") ||
621 (tc.Name == "System.Attribute") ||
622 (tc.Name == "System.ValueType")))
625 tc.DefineMembers (root);
630 ArrayList delegates = root.Delegates;
631 if (delegates != null){
632 foreach (Delegate d in delegates)
633 if ((d.ModFlags & Modifiers.NEW) == 0)
634 d.DefineMembers (root);
636 Report1530 (d.Location);
639 ArrayList enums = root.Enums;
641 foreach (Enum en in enums)
642 if ((en.ModFlags & Modifiers.NEW) == 0)
643 en.DefineMembers (root);
645 Report1530 (en.Location);
650 // A generic hook delegate
652 public delegate void Hook ();
655 // A hook invoked when the code has been generated.
657 public static event Hook EmitCodeHook;
660 // DefineTypes is used to fill in the members of each type.
662 static public void DefineTypes ()
664 TypeContainer root = Tree.Types;
666 if (attribute_types != null)
667 foreach (TypeContainer tc in attribute_types)
670 if (interface_resolve_order != null){
671 foreach (Interface iface in interface_resolve_order)
672 if ((iface.ModFlags & Modifiers.NEW) == 0)
677 if (type_container_resolve_order != null){
678 foreach (TypeContainer tc in type_container_resolve_order) {
679 // When compiling corlib, these types have already been
680 // populated from BootCorlib_PopulateCoreTypes ().
681 if (!RootContext.StdLib &&
682 ((tc.Name == "System.Object") ||
683 (tc.Name == "System.Attribute") ||
684 (tc.Name == "System.ValueType")))
687 if ((tc.ModFlags & Modifiers.NEW) == 0)
692 ArrayList delegates = root.Delegates;
693 if (delegates != null){
694 foreach (Delegate d in delegates)
695 if ((d.ModFlags & Modifiers.NEW) == 0)
699 ArrayList enums = root.Enums;
701 foreach (Enum en in enums)
702 if ((en.ModFlags & Modifiers.NEW) == 0)
707 static public void EmitCode ()
710 // Because of the strange way in which we do things, global
711 // attributes must be processed first.
713 CodeGen.Assembly.Emit ();
714 CodeGen.Module.Emit ();
716 if (attribute_types != null)
717 foreach (TypeContainer tc in attribute_types)
720 if (interface_resolve_order != null){
721 foreach (Interface iface in interface_resolve_order)
722 iface.Emit (Tree.Types);
725 if (type_container_resolve_order != null) {
726 foreach (TypeContainer tc in type_container_resolve_order)
729 foreach (TypeContainer tc in type_container_resolve_order)
734 // Run any hooks after all the types have been defined.
735 // This is used to create nested auxiliary classes for example
738 if (EmitCodeHook != null)
743 // Public Field, used to track which method is the public entry
746 static public MethodInfo EntryPoint;
749 // Track the location of the entry point.
751 static public Location EntryPointLocation;
754 // These are used to generate unique names on the structs and fields.
756 static int field_count;
759 // Makes an initialized struct, returns the field builder that
760 // references the data. Thanks go to Sergey Chaban for researching
761 // how to do this. And coming up with a shorter mechanism than I
762 // was able to figure out.
764 // This works but makes an implicit public struct $ArrayType$SIZE and
765 // makes the fields point to it. We could get more control if we did
768 // 1. DefineNestedType on the impl_details_class with our struct.
770 // 2. Define the field on the impl_details_class
772 static public FieldBuilder MakeStaticData (byte [] data)
776 if (impl_details_class == null){
777 impl_details_class = CodeGen.Module.Builder.DefineType (
778 "<PrivateImplementationDetails>",
779 TypeAttributes.NotPublic,
780 TypeManager.object_type);
782 RegisterHelperClass (impl_details_class);
785 fb = impl_details_class.DefineInitializedData (
786 "$$field-" + (field_count++), data,
787 FieldAttributes.Static | FieldAttributes.Assembly);