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 enum LanguageVersion
25 public class RootContext {
28 // Contains the parsed tree
33 // This hashtable contains all of the #definitions across the source code
34 // it is used by the ConditionalAttribute handler.
36 public static Hashtable AllDefines = new Hashtable ();
39 // Whether we are being linked against the standard libraries.
40 // This is only used to tell whether `System.Object' should
41 // have a parent or not.
43 public static bool StdLib = true;
46 // This keeps track of the order in which classes were defined
47 // so that we can poulate them in that order.
49 // Order is important, because we need to be able to tell by
50 // examining the parent's list of methods which ones are virtual
51 // or abstract as well as the parent names (to implement new,
54 static ArrayList type_container_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";
70 public static bool VerifyClsCompliance = true;
72 public static LanguageVersion Version = LanguageVersion.Default;
75 // We keep strongname related info here because
76 // it's also used as complier options from CSC 8.x
78 public static string StrongNameKeyFile;
79 public static string StrongNameKeyContainer;
80 public static bool StrongNameDelaySign = false;
88 type_container_resolve_order = new ArrayList ();
91 public static bool NeedsEntryPoint {
93 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
97 static public Tree Tree {
103 static public string MainClass;
105 public static void RegisterOrder (TypeContainer tc)
107 type_container_resolve_order.Add (tc);
110 public static void RegisterAttribute (TypeContainer tc)
112 if (attribute_types == null)
113 attribute_types = new ArrayList ();
115 attribute_types.Add (tc);
119 // The default compiler checked state
121 static public bool Checked = false;
124 // Whether to allow Unsafe code
126 static public bool Unsafe = false;
128 static string MakeFQN (string nsn, string name)
132 return String.Concat (nsn, ".", name);
136 // This function is used to resolve the hierarchy tree.
137 // It processes interfaces, structs and classes in that order.
139 // It creates the TypeBuilder's as it processes the user defined
142 static public void ResolveTree ()
145 // Process the attribute types separately and before anything else
147 if (attribute_types != null)
148 foreach (TypeContainer tc in attribute_types)
152 // Interfaces are processed next, as classes and
153 // structs might inherit from an object or implement
154 // a set of interfaces, we need to be able to tell
155 // them appart by just using the TypeManager.
157 TypeContainer root = Tree.Types;
159 ArrayList ifaces = root.Interfaces;
161 foreach (Interface i in ifaces)
165 foreach (TypeContainer tc in root.Types)
168 if (root.Delegates != null)
169 foreach (Delegate d in root.Delegates)
172 if (root.Enums != null)
173 foreach (Enum e in root.Enums)
177 static void Error_TypeConflict (string name, Location loc)
180 520, loc, "`" + name + "' conflicts with a predefined type");
183 static void Error_TypeConflict (string name)
186 520, "`" + name + "' conflicts with a predefined type");
190 // Resolves a single class during the corlib bootstrap process
192 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
194 object o = root.GetDefinition (name);
196 Report.Error (518, "The predefined type `" + name + "' is not defined");
202 DeclSpace d = (DeclSpace) o;
204 Error_TypeConflict (name, d.Location);
206 Error_TypeConflict (name);
211 return ((DeclSpace) o).DefineType ();
215 // Resolves a struct during the corlib bootstrap process
217 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
219 object o = root.GetDefinition (name);
221 Report.Error (518, "The predefined type `" + name + "' is not defined");
227 DeclSpace d = (DeclSpace) o;
229 Error_TypeConflict (name, d.Location);
231 Error_TypeConflict (name);
236 ((DeclSpace) o).DefineType ();
240 // Resolves a struct during the corlib bootstrap process
242 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
244 object o = root.GetDefinition (name);
246 Report.Error (518, "The predefined type `" + name + "' is not defined");
250 if (!(o is Interface)){
252 DeclSpace d = (DeclSpace) o;
254 Error_TypeConflict (name, d.Location);
256 Error_TypeConflict (name);
261 ((DeclSpace) o).DefineType ();
265 // Resolves a delegate during the corlib bootstrap process
267 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
269 object o = root.GetDefinition (name);
271 Report.Error (518, "The predefined type `" + name + "' is not defined");
272 Environment.Exit (1);
275 if (!(o is Delegate)){
276 Error_TypeConflict (name);
280 ((DeclSpace) o).DefineType ();
285 /// Resolves the core types in the compiler when compiling with --nostdlib
287 static public void ResolveCore ()
289 TypeContainer root = Tree.Types;
291 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
292 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
293 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
295 string [] interfaces_first_stage = {
296 "System.IComparable", "System.ICloneable",
297 "System.IConvertible",
299 "System.Collections.IEnumerable",
300 "System.Collections.ICollection",
301 "System.Collections.IEnumerator",
302 "System.Collections.IList",
303 "System.IAsyncResult",
304 "System.IDisposable",
306 "System.Runtime.Serialization.ISerializable",
308 "System.Reflection.IReflect",
309 "System.Reflection.ICustomAttributeProvider",
314 "System.Collections.Generic.IEnumerator`1",
315 "System.Collections.Generic.IEnumerable`1"
318 foreach (string iname in interfaces_first_stage)
319 BootstrapCorlib_ResolveInterface (root, iname);
322 // These are the base value types
324 string [] structs_first_stage = {
325 "System.Byte", "System.SByte",
326 "System.Int16", "System.UInt16",
327 "System.Int32", "System.UInt32",
328 "System.Int64", "System.UInt64",
331 foreach (string cname in structs_first_stage)
332 BootstrapCorlib_ResolveStruct (root, cname);
335 // Now, we can load the enumerations, after this point,
338 TypeManager.InitEnumUnderlyingTypes ();
340 string [] structs_second_stage = {
341 "System.Single", "System.Double",
342 "System.Char", "System.Boolean",
343 "System.Decimal", "System.Void",
344 "System.RuntimeFieldHandle",
345 "System.RuntimeArgumentHandle",
346 "System.RuntimeTypeHandle",
348 "System.TypedReference",
352 foreach (string cname in structs_second_stage)
353 BootstrapCorlib_ResolveStruct (root, cname);
356 // These are classes that depends on the core interfaces
358 string [] classes_second_stage = {
359 "System.Reflection.MemberInfo",
365 // These are not really important in the order, but they
366 // are used by the compiler later on (typemanager/CoreLookupType-d)
368 "System.Runtime.CompilerServices.RuntimeHelpers",
369 "System.Reflection.DefaultMemberAttribute",
370 "System.Threading.Monitor",
372 "System.AttributeUsageAttribute",
373 "System.Runtime.InteropServices.DllImportAttribute",
374 "System.Runtime.CompilerServices.MethodImplAttribute",
375 "System.Runtime.InteropServices.MarshalAsAttribute",
376 "System.Runtime.CompilerServices.NewConstraintAttribute",
377 "System.Diagnostics.ConditionalAttribute",
378 "System.ObsoleteAttribute",
379 "System.ParamArrayAttribute",
380 "System.CLSCompliantAttribute",
381 "System.Security.UnverifiableCodeAttribute",
382 "System.Security.Permissions.SecurityAttribute",
383 "System.Runtime.CompilerServices.IndexerNameAttribute",
384 "System.Runtime.InteropServices.InAttribute",
385 "System.Runtime.InteropServices.StructLayoutAttribute",
386 "System.Runtime.InteropServices.FieldOffsetAttribute",
387 "System.InvalidOperationException",
388 "System.NotSupportedException",
389 "System.MarshalByRefObject",
390 "System.Security.CodeAccessPermission"
393 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
394 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
395 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
396 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
397 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
398 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
400 foreach (string cname in classes_second_stage)
401 BootstrapCorlib_ResolveClass (root, cname);
403 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
407 // Closes all open types
411 // We usually use TypeBuilder types. When we are done
412 // creating the type (which will happen after we have added
413 // methods, fields, etc) we need to "Define" them before we
414 // can save the Assembly
416 static public void CloseTypes ()
418 TypeContainer root = Tree.Types;
420 if (root.Enums != null)
421 foreach (Enum en in root.Enums)
424 if (attribute_types != null)
425 foreach (TypeContainer tc in attribute_types)
429 // We do this in two passes, first we close the structs,
430 // then the classes, because it seems the code needs it this
431 // way. If this is really what is going on, we should probably
432 // make sure that we define the structs in order as well.
434 foreach (TypeContainer tc in type_container_resolve_order){
435 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
440 foreach (TypeContainer tc in type_container_resolve_order){
441 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
445 if (root.Delegates != null)
446 foreach (Delegate d in root.Delegates)
451 // If we have a <PrivateImplementationDetails> class, close it
453 if (helper_classes != null){
454 foreach (TypeBuilder type_builder in helper_classes)
455 type_builder.CreateType ();
458 attribute_types = null;
459 type_container_resolve_order = null;
460 helper_classes = null;
462 TypeManager.CleanUp ();
466 /// Used to register classes that need to be closed after all the
467 /// user defined classes
469 public static void RegisterHelperClass (TypeBuilder helper_class)
471 if (helper_classes == null)
472 helper_classes = new ArrayList ();
473 helper_classes.Add (helper_class);
477 // This idea is from Felix Arrese-Igor
479 // Returns : the implicit parent of a composite namespace string
480 // eg. Implicit parent of A.B is A
482 static public string ImplicitParent (string ns)
484 int i = ns.LastIndexOf ('.');
488 return ns.Substring (0, i);
491 static Type NamespaceLookup (DeclSpace ds, string name, int num_type_args, Location loc)
494 // Try in the current namespace and all its implicit parents
496 for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
497 IAlias result = ns.Lookup (ds, name, num_type_args, false, loc);
505 TypeExpr texpr = result.ResolveAsType (ds.EmitContext);
515 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
517 return LookupType (ds, name, silent, 0, loc);
521 // Public function used to locate types, this can only
522 // be used after the ResolveTree function has been invoked.
524 // Returns: Type or null if they type can not be found.
526 // Come to think of it, this should be a DeclSpace
528 static public Type LookupType (DeclSpace ds, string name, bool silent,
529 int num_type_params, Location loc)
533 if (ds.Cache.Contains (name)){
534 t = (Type) ds.Cache [name];
539 // For the case the type we are looking for is nested within this one
540 // or is in any base class
542 DeclSpace containing_ds = ds;
543 while (containing_ds != null){
544 Type current_type = containing_ds.TypeBuilder;
546 while (current_type != null) {
550 Type type = TypeManager.LookupType (current_type.FullName + "." + name);
552 t = ds.ResolveNestedType (type, loc);
557 current_type = current_type.BaseType;
560 containing_ds = containing_ds.Parent;
563 t = NamespaceLookup (ds, name, num_type_params, loc);
571 Report.Error (246, loc, "Cannot find type `"+name+"'");
577 // This is the silent version of LookupType, you can use this
578 // to `probe' for a type
580 static public Type LookupType (TypeContainer tc, string name, Location loc)
582 return LookupType (tc, name, true, loc);
585 static void Report1530 (Location loc)
587 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
590 static public void PopulateCoreType (TypeContainer root, string name)
592 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
594 ds.DefineMembers (root);
598 static public void BootCorlib_PopulateCoreTypes ()
600 TypeContainer root = tree.Types;
602 PopulateCoreType (root, "System.Object");
603 PopulateCoreType (root, "System.ValueType");
604 PopulateCoreType (root, "System.Attribute");
608 // Populates the structs and classes with fields and methods
611 // This is invoked after all interfaces, structs and classes
612 // have been defined through `ResolveTree'
613 static public void PopulateTypes ()
615 TypeContainer root = Tree.Types;
617 if (attribute_types != null)
618 foreach (TypeContainer tc in attribute_types)
619 tc.DefineMembers (root);
621 if (type_container_resolve_order != null){
622 if (RootContext.StdLib){
623 foreach (TypeContainer tc in type_container_resolve_order)
624 tc.DefineMembers (root);
626 foreach (TypeContainer tc in type_container_resolve_order) {
627 // When compiling corlib, these types have already been
628 // populated from BootCorlib_PopulateCoreTypes ().
629 if (((tc.Name == "System.Object") ||
630 (tc.Name == "System.Attribute") ||
631 (tc.Name == "System.ValueType")))
634 tc.DefineMembers (root);
639 ArrayList delegates = root.Delegates;
640 if (delegates != null){
641 foreach (Delegate d in delegates)
642 if ((d.ModFlags & Modifiers.NEW) == 0)
643 d.DefineMembers (root);
645 Report1530 (d.Location);
648 ArrayList enums = root.Enums;
650 foreach (Enum en in enums)
651 if ((en.ModFlags & Modifiers.NEW) == 0)
652 en.DefineMembers (root);
654 Report1530 (en.Location);
658 // Check for cycles in the struct layout
660 if (type_container_resolve_order != null){
661 Hashtable seen = new Hashtable ();
662 foreach (TypeContainer tc in type_container_resolve_order)
663 TypeManager.CheckStructCycles (tc, seen);
668 // A generic hook delegate
670 public delegate void Hook ();
673 // A hook invoked when the code has been generated.
675 public static event Hook EmitCodeHook;
678 // DefineTypes is used to fill in the members of each type.
680 static public void DefineTypes ()
682 TypeContainer root = Tree.Types;
684 if (attribute_types != null)
685 foreach (TypeContainer tc in attribute_types)
688 if (type_container_resolve_order != null){
689 foreach (TypeContainer tc in type_container_resolve_order) {
690 // When compiling corlib, these types have already been
691 // populated from BootCorlib_PopulateCoreTypes ().
692 if (!RootContext.StdLib &&
693 ((tc.Name == "System.Object") ||
694 (tc.Name == "System.Attribute") ||
695 (tc.Name == "System.ValueType")))
698 if ((tc.ModFlags & Modifiers.NEW) == 0)
703 ArrayList delegates = root.Delegates;
704 if (delegates != null){
705 foreach (Delegate d in delegates)
706 if ((d.ModFlags & Modifiers.NEW) == 0)
710 ArrayList enums = root.Enums;
712 foreach (Enum en in enums)
713 if ((en.ModFlags & Modifiers.NEW) == 0)
718 static public void EmitCode ()
720 if (attribute_types != null)
721 foreach (TypeContainer tc in attribute_types)
724 CodeGen.Assembly.Emit (Tree.Types);
725 CodeGen.Module.Emit (Tree.Types);
727 if (Tree.Types.Enums != null) {
728 foreach (Enum e in Tree.Types.Enums)
732 if (type_container_resolve_order != null) {
733 foreach (TypeContainer tc in type_container_resolve_order)
737 if (Tree.Types.Delegates != null) {
738 foreach (Delegate d in Tree.Types.Delegates)
742 // Run any hooks after all the types have been defined.
743 // This is used to create nested auxiliary classes for example
746 if (EmitCodeHook != null)
751 // Public Field, used to track which method is the public entry
754 static public MethodInfo EntryPoint;
757 // Track the location of the entry point.
759 static public Location EntryPointLocation;
762 // These are used to generate unique names on the structs and fields.
764 static int field_count;
767 // Makes an initialized struct, returns the field builder that
768 // references the data. Thanks go to Sergey Chaban for researching
769 // how to do this. And coming up with a shorter mechanism than I
770 // was able to figure out.
772 // This works but makes an implicit public struct $ArrayType$SIZE and
773 // makes the fields point to it. We could get more control if we did
776 // 1. DefineNestedType on the impl_details_class with our struct.
778 // 2. Define the field on the impl_details_class
780 static public FieldBuilder MakeStaticData (byte [] data)
784 if (impl_details_class == null){
785 impl_details_class = CodeGen.Module.Builder.DefineType (
786 "<PrivateImplementationDetails>",
787 TypeAttributes.NotPublic,
788 TypeManager.object_type);
790 RegisterHelperClass (impl_details_class);
793 fb = impl_details_class.DefineInitializedData (
794 "$$field-" + (field_count++), data,
795 FieldAttributes.Static | FieldAttributes.Assembly);