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;
67 public static Target Target = Target.Exe;
68 public static string TargetExt = ".exe";
71 // If set, enable C# version 2 features
73 public static bool V2;
80 interface_resolve_order = new ArrayList ();
81 type_container_resolve_order = new ArrayList ();
84 public static bool NeedsEntryPoint {
86 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
90 static public Tree Tree {
96 static public string MainClass;
98 public static void RegisterOrder (Interface iface)
100 interface_resolve_order.Add (iface);
103 public static void RegisterOrder (TypeContainer tc)
105 type_container_resolve_order.Add (tc);
108 public static void RegisterAttribute (TypeContainer tc)
110 if (attribute_types == null)
111 attribute_types = new ArrayList ();
113 attribute_types.Add (tc);
117 // The default compiler checked state
119 static public bool Checked = false;
122 // Whether to allow Unsafe code
124 static public bool Unsafe = false;
126 static string MakeFQN (string nsn, string name)
130 return String.Concat (nsn, ".", name);
134 // This function is used to resolve the hierarchy tree.
135 // It processes interfaces, structs and classes in that order.
137 // It creates the TypeBuilder's as it processes the user defined
140 static public void ResolveTree ()
143 // Process the attribute types separately and before anything else
145 if (attribute_types != null)
146 foreach (TypeContainer tc in attribute_types)
150 // Interfaces are processed next, as classes and
151 // structs might inherit from an object or implement
152 // a set of interfaces, we need to be able to tell
153 // them appart by just using the TypeManager.
155 TypeContainer root = Tree.Types;
157 ArrayList ifaces = root.Interfaces;
159 foreach (Interface i in ifaces)
163 foreach (TypeContainer tc in root.Types)
166 if (root.Delegates != null)
167 foreach (Delegate d in root.Delegates)
170 if (root.Enums != null)
171 foreach (Enum e in root.Enums)
175 static void Error_TypeConflict (string name, Location loc)
178 520, loc, "`" + name + "' conflicts with a predefined type");
181 static void Error_TypeConflict (string name)
184 520, "`" + name + "' conflicts with a predefined type");
188 // Resolves a single class during the corlib bootstrap process
190 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
192 object o = root.GetDefinition (name);
194 Report.Error (518, "The predefined type `" + name + "' is not defined");
200 DeclSpace d = (DeclSpace) o;
202 Error_TypeConflict (name, d.Location);
204 Error_TypeConflict (name);
209 return ((DeclSpace) o).DefineType ();
213 // Resolves a struct during the corlib bootstrap process
215 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
217 object o = root.GetDefinition (name);
219 Report.Error (518, "The predefined type `" + name + "' is not defined");
225 DeclSpace d = (DeclSpace) o;
227 Error_TypeConflict (name, d.Location);
229 Error_TypeConflict (name);
234 ((DeclSpace) o).DefineType ();
238 // Resolves a struct during the corlib bootstrap process
240 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
242 object o = root.GetDefinition (name);
244 Report.Error (518, "The predefined type `" + name + "' is not defined");
248 if (!(o is Interface)){
250 DeclSpace d = (DeclSpace) o;
252 Error_TypeConflict (name, d.Location);
254 Error_TypeConflict (name);
259 ((DeclSpace) o).DefineType ();
263 // Resolves a delegate during the corlib bootstrap process
265 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
267 object o = root.GetDefinition (name);
269 Report.Error (518, "The predefined type `" + name + "' is not defined");
270 Environment.Exit (0);
273 if (!(o is Delegate)){
274 Error_TypeConflict (name);
278 ((DeclSpace) o).DefineType ();
283 /// Resolves the core types in the compiler when compiling with --nostdlib
285 static public void ResolveCore ()
287 TypeContainer root = Tree.Types;
289 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
290 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
291 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
293 string [] interfaces_first_stage = {
294 "System.IComparable", "System.ICloneable",
295 "System.IConvertible",
297 "System.Collections.IEnumerable",
298 "System.Collections.ICollection",
299 "System.Collections.IEnumerator",
300 "System.Collections.IList",
301 "System.IAsyncResult",
302 "System.IDisposable",
304 "System.Runtime.Serialization.ISerializable",
306 "System.Reflection.IReflect",
307 "System.Reflection.ICustomAttributeProvider"
310 foreach (string iname in interfaces_first_stage)
311 BootstrapCorlib_ResolveInterface (root, iname);
314 // These are the base value types
316 string [] structs_first_stage = {
317 "System.Byte", "System.SByte",
318 "System.Int16", "System.UInt16",
319 "System.Int32", "System.UInt32",
320 "System.Int64", "System.UInt64",
323 foreach (string cname in structs_first_stage)
324 BootstrapCorlib_ResolveStruct (root, cname);
327 // Now, we can load the enumerations, after this point,
330 TypeManager.InitEnumUnderlyingTypes ();
332 string [] structs_second_stage = {
333 "System.Single", "System.Double",
334 "System.Char", "System.Boolean",
335 "System.Decimal", "System.Void",
336 "System.RuntimeFieldHandle",
337 "System.RuntimeTypeHandle",
341 foreach (string cname in structs_second_stage)
342 BootstrapCorlib_ResolveStruct (root, cname);
345 // These are classes that depends on the core interfaces
347 string [] classes_second_stage = {
348 "System.Reflection.MemberInfo",
353 // These are not really important in the order, but they
354 // are used by the compiler later on (typemanager/CoreLookupType-d)
356 "System.Runtime.CompilerServices.RuntimeHelpers",
357 "System.Reflection.DefaultMemberAttribute",
358 "System.Threading.Monitor",
360 "System.AttributeUsageAttribute",
361 "System.Runtime.InteropServices.DllImportAttribute",
362 "System.Runtime.CompilerServices.MethodImplAttribute",
363 "System.Runtime.InteropServices.MarshalAsAttribute",
364 "System.Diagnostics.ConditionalAttribute",
365 "System.ObsoleteAttribute",
366 "System.ParamArrayAttribute",
367 "System.Security.UnverifiableCodeAttribute",
368 "System.Runtime.CompilerServices.IndexerNameAttribute",
369 "System.Runtime.InteropServices.InAttribute",
370 "System.InvalidOperationException"
374 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
375 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
376 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
377 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
378 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
379 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
381 foreach (string cname in classes_second_stage)
382 BootstrapCorlib_ResolveClass (root, cname);
384 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
388 // Closes all open types
392 // We usually use TypeBuilder types. When we are done
393 // creating the type (which will happen after we have added
394 // methods, fields, etc) we need to "Define" them before we
395 // can save the Assembly
397 static public void CloseTypes ()
399 TypeContainer root = Tree.Types;
401 if (root.Enums != null)
402 foreach (Enum en in root.Enums)
405 if (attribute_types != null)
406 foreach (TypeContainer tc in attribute_types)
409 foreach (Interface iface in interface_resolve_order)
413 // We do this in two passes, first we close the structs,
414 // then the classes, because it seems the code needs it this
415 // way. If this is really what is going on, we should probably
416 // make sure that we define the structs in order as well.
418 foreach (TypeContainer tc in type_container_resolve_order){
419 if (tc is Struct && tc.Parent == tree.Types){
424 foreach (TypeContainer tc in type_container_resolve_order){
425 if (!(tc is Struct && tc.Parent == tree.Types))
429 if (root.Delegates != null)
430 foreach (Delegate d in root.Delegates)
435 // If we have a <PrivateImplementationDetails> class, close it
437 if (helper_classes != null){
438 foreach (TypeBuilder type_builder in helper_classes)
439 type_builder.CreateType ();
442 attribute_types = null;
443 interface_resolve_order = null;
444 type_container_resolve_order = null;
445 helper_classes = null;
447 TypeManager.CleanUp ();
451 /// Used to register classes that need to be closed after all the
452 /// user defined classes
454 public static void RegisterHelperClass (TypeBuilder helper_class)
456 if (helper_classes == null)
457 helper_classes = new ArrayList ();
458 helper_classes.Add (helper_class);
462 // This idea is from Felix Arrese-Igor
464 // Returns : the implicit parent of a composite namespace string
465 // eg. Implicit parent of A.B is A
467 static public string ImplicitParent (string ns)
469 int i = ns.LastIndexOf ('.');
473 return ns.Substring (0, i);
476 static Type NamespaceLookup (DeclSpace ds, string name, Location loc)
479 // Try in the current namespace and all its implicit parents
481 for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
482 object result = ns.Lookup (ds, name, loc);
487 return (Type) result;
496 // Public function used to locate types, this can only
497 // be used after the ResolveTree function has been invoked.
499 // Returns: Type or null if they type can not be found.
501 // Come to think of it, this should be a DeclSpace
503 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
507 if (ds.Cache.Contains (name)){
508 t = (Type) ds.Cache [name];
513 // For the case the type we are looking for is nested within this one
514 // or is in any base class
516 DeclSpace containing_ds = ds;
517 while (containing_ds != null){
518 Type current_type = containing_ds.TypeBuilder;
520 while (current_type != null) {
524 t = TypeManager.LookupType (current_type.FullName + "." + name);
530 current_type = current_type.BaseType;
533 containing_ds = containing_ds.Parent;
536 t = NamespaceLookup (ds, name, loc);
544 Report.Error (246, loc, "Cannot find type `"+name+"'");
550 // This is the silent version of LookupType, you can use this
551 // to `probe' for a type
553 static public Type LookupType (TypeContainer tc, string name, Location loc)
555 return LookupType (tc, name, true, loc);
558 static public bool IsNamespace (string name)
562 if (tree.Namespaces != null){
563 ns = (Namespace) tree.Namespaces [name];
572 static void Report1530 (Location loc)
574 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
577 static public void PopulateCoreType (TypeContainer root, string name)
579 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
581 ds.DefineMembers (root);
585 static public void BootCorlib_PopulateCoreTypes ()
587 TypeContainer root = tree.Types;
589 PopulateCoreType (root, "System.Object");
590 PopulateCoreType (root, "System.ValueType");
591 PopulateCoreType (root, "System.Attribute");
595 // Populates the structs and classes with fields and methods
598 // This is invoked after all interfaces, structs and classes
599 // have been defined through `ResolveTree'
600 static public void PopulateTypes ()
602 TypeContainer root = Tree.Types;
604 if (attribute_types != null)
605 foreach (TypeContainer tc in attribute_types)
606 tc.DefineMembers (root);
608 if (interface_resolve_order != null){
609 foreach (Interface iface in interface_resolve_order)
610 if ((iface.ModFlags & Modifiers.NEW) == 0)
611 iface.DefineMembers (root);
613 Report1530 (iface.Location);
617 if (type_container_resolve_order != null){
618 if (RootContext.StdLib){
619 foreach (TypeContainer tc in type_container_resolve_order)
620 tc.DefineMembers (root);
622 foreach (TypeContainer tc in type_container_resolve_order) {
623 // When compiling corlib, these types have already been
624 // populated from BootCorlib_PopulateCoreTypes ().
625 if (((tc.Name == "System.Object") ||
626 (tc.Name == "System.Attribute") ||
627 (tc.Name == "System.ValueType")))
630 tc.DefineMembers (root);
635 ArrayList delegates = root.Delegates;
636 if (delegates != null){
637 foreach (Delegate d in delegates)
638 if ((d.ModFlags & Modifiers.NEW) == 0)
639 d.DefineMembers (root);
641 Report1530 (d.Location);
644 ArrayList enums = root.Enums;
646 foreach (Enum en in enums)
647 if ((en.ModFlags & Modifiers.NEW) == 0)
648 en.DefineMembers (root);
650 Report1530 (en.Location);
655 // A generic hook delegate
657 public delegate void Hook ();
660 // A hook invoked when the code has been generated.
662 public static event Hook EmitCodeHook;
665 // DefineTypes is used to fill in the members of each type.
667 static public void DefineTypes ()
669 TypeContainer root = Tree.Types;
671 if (attribute_types != null)
672 foreach (TypeContainer tc in attribute_types)
675 if (interface_resolve_order != null){
676 foreach (Interface iface in interface_resolve_order)
677 if ((iface.ModFlags & Modifiers.NEW) == 0)
682 if (type_container_resolve_order != null){
683 foreach (TypeContainer tc in type_container_resolve_order) {
684 // When compiling corlib, these types have already been
685 // populated from BootCorlib_PopulateCoreTypes ().
686 if (!RootContext.StdLib &&
687 ((tc.Name == "System.Object") ||
688 (tc.Name == "System.Attribute") ||
689 (tc.Name == "System.ValueType")))
692 if ((tc.ModFlags & Modifiers.NEW) == 0)
697 ArrayList delegates = root.Delegates;
698 if (delegates != null){
699 foreach (Delegate d in delegates)
700 if ((d.ModFlags & Modifiers.NEW) == 0)
704 ArrayList enums = root.Enums;
706 foreach (Enum en in enums)
707 if ((en.ModFlags & Modifiers.NEW) == 0)
712 static public void EmitCode ()
715 // Because of the strange way in which we do things, global
716 // attributes must be processed first.
718 if (global_attributes.Count > 0){
719 AssemblyBuilder ab = CodeGen.AssemblyBuilder;
720 TypeContainer dummy = new TypeContainer (null, null, "", new Location (-1));
721 EmitContext temp_ec = new EmitContext (
722 dummy, Mono.CSharp.Location.Null, null, null, 0, false);
724 foreach (DictionaryEntry de in global_attributes){
725 NamespaceEntry ns = (NamespaceEntry) de.Key;
726 Attributes attrs = (Attributes) de.Value;
728 dummy.NamespaceEntry = ns;
729 Attribute.ApplyAttributes (temp_ec, ab, ab, attrs);
733 if (attribute_types != null)
734 foreach (TypeContainer tc in attribute_types)
737 if (interface_resolve_order != null){
738 foreach (Interface iface in interface_resolve_order)
739 iface.Emit (Tree.Types);
742 if (type_container_resolve_order != null) {
743 foreach (TypeContainer tc in type_container_resolve_order)
746 foreach (TypeContainer tc in type_container_resolve_order)
751 // Run any hooks after all the types have been defined.
752 // This is used to create nested auxiliary classes for example
755 if (EmitCodeHook != null)
760 if (TypeManager.unverifiable_code_ctor == null) {
761 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
765 CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor,
767 CodeGen.ModuleBuilder.SetCustomAttribute (cb);
772 // Public Field, used to track which method is the public entry
775 static public MethodInfo EntryPoint;
778 // Track the location of the entry point.
780 static public Location EntryPointLocation;
783 // These are used to generate unique names on the structs and fields.
785 static int field_count;
788 // Makes an initialized struct, returns the field builder that
789 // references the data. Thanks go to Sergey Chaban for researching
790 // how to do this. And coming up with a shorter mechanism than I
791 // was able to figure out.
793 // This works but makes an implicit public struct $ArrayType$SIZE and
794 // makes the fields point to it. We could get more control if we did
797 // 1. DefineNestedType on the impl_details_class with our struct.
799 // 2. Define the field on the impl_details_class
801 static public FieldBuilder MakeStaticData (byte [] data)
805 if (impl_details_class == null){
806 impl_details_class = CodeGen.ModuleBuilder.DefineType (
807 "<PrivateImplementationDetails>",
808 TypeAttributes.NotPublic,
809 TypeManager.object_type);
811 RegisterHelperClass (impl_details_class);
814 fb = impl_details_class.DefineInitializedData (
815 "$$field-" + (field_count++), data,
816 FieldAttributes.Static | FieldAttributes.Assembly);
822 // Adds a global attribute that was declared in `container',
823 // the attribute is in `attr', and it was defined at `loc'
825 static public void AddGlobalAttributeSection (TypeContainer container, AttributeSection attr)
827 NamespaceEntry ns = container.NamespaceEntry;
828 Attributes a = (Attributes) global_attributes [ns];
831 global_attributes [ns] = new Attributes (attr);
833 a.AddAttributeSection (attr);