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 attribute_types;
52 // Holds a reference to the Private Implementation Details
55 static ArrayList helper_classes;
57 static TypeBuilder impl_details_class;
59 public static int WarningLevel = 2;
61 public static Target Target = Target.Exe;
62 public static string TargetExt = ".exe";
64 public static bool VerifyClsCompliance = true;
67 // If set, enable C# version 2 features
69 public static bool V2 = true;
72 // We keep strongname related info here because
73 // it's also used as complier options from CSC 8.x
75 public static string StrongNameKeyFile;
76 public static string StrongNameKeyContainer;
77 public static bool StrongNameDelaySign = false;
85 type_container_resolve_order = new ArrayList ();
88 public static bool NeedsEntryPoint {
90 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
94 static public Tree Tree {
100 static public string MainClass;
102 public static void RegisterOrder (TypeContainer tc)
104 type_container_resolve_order.Add (tc);
107 public static void RegisterAttribute (TypeContainer tc)
109 if (attribute_types == null)
110 attribute_types = new ArrayList ();
112 attribute_types.Add (tc);
116 // The default compiler checked state
118 static public bool Checked = false;
121 // Whether to allow Unsafe code
123 static public bool Unsafe = false;
125 static string MakeFQN (string nsn, string name)
129 return String.Concat (nsn, ".", name);
133 // This function is used to resolve the hierarchy tree.
134 // It processes interfaces, structs and classes in that order.
136 // It creates the TypeBuilder's as it processes the user defined
139 static public void ResolveTree ()
142 // Process the attribute types separately and before anything else
144 if (attribute_types != null)
145 foreach (TypeContainer tc in attribute_types)
149 // Interfaces are processed next, as classes and
150 // structs might inherit from an object or implement
151 // a set of interfaces, we need to be able to tell
152 // them appart by just using the TypeManager.
154 TypeContainer root = Tree.Types;
156 ArrayList ifaces = root.Interfaces;
158 foreach (Interface i in ifaces)
162 foreach (TypeContainer tc in root.Types)
165 if (root.Delegates != null)
166 foreach (Delegate d in root.Delegates)
169 if (root.Enums != null)
170 foreach (Enum e in root.Enums)
174 static void Error_TypeConflict (string name, Location loc)
177 520, loc, "`" + name + "' conflicts with a predefined type");
180 static void Error_TypeConflict (string name)
183 520, "`" + name + "' conflicts with a predefined type");
187 // Resolves a single class during the corlib bootstrap process
189 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
191 object o = root.GetDefinition (name);
193 Report.Error (518, "The predefined type `" + name + "' is not defined");
199 DeclSpace d = (DeclSpace) o;
201 Error_TypeConflict (name, d.Location);
203 Error_TypeConflict (name);
208 return ((DeclSpace) o).DefineType ();
212 // Resolves a struct during the corlib bootstrap process
214 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
216 object o = root.GetDefinition (name);
218 Report.Error (518, "The predefined type `" + name + "' is not defined");
224 DeclSpace d = (DeclSpace) o;
226 Error_TypeConflict (name, d.Location);
228 Error_TypeConflict (name);
233 ((DeclSpace) o).DefineType ();
237 // Resolves a struct during the corlib bootstrap process
239 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
241 object o = root.GetDefinition (name);
243 Report.Error (518, "The predefined type `" + name + "' is not defined");
247 if (!(o is Interface)){
249 DeclSpace d = (DeclSpace) o;
251 Error_TypeConflict (name, d.Location);
253 Error_TypeConflict (name);
258 ((DeclSpace) o).DefineType ();
262 // Resolves a delegate during the corlib bootstrap process
264 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
266 object o = root.GetDefinition (name);
268 Report.Error (518, "The predefined type `" + name + "' is not defined");
269 Environment.Exit (1);
272 if (!(o is Delegate)){
273 Error_TypeConflict (name);
277 ((DeclSpace) o).DefineType ();
282 /// Resolves the core types in the compiler when compiling with --nostdlib
284 static public void ResolveCore ()
286 TypeContainer root = Tree.Types;
288 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
289 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
290 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
292 string [] interfaces_first_stage = {
293 "System.IComparable", "System.ICloneable",
294 "System.IConvertible",
296 "System.Collections.IEnumerable",
297 "System.Collections.ICollection",
298 "System.Collections.IEnumerator",
299 "System.Collections.IList",
300 "System.IAsyncResult",
301 "System.IDisposable",
303 "System.Runtime.Serialization.ISerializable",
305 "System.Reflection.IReflect",
306 "System.Reflection.ICustomAttributeProvider",
311 "System.Collections.Generic.IEnumerator`1",
312 "System.Collections.Generic.IEnumerable`1"
315 foreach (string iname in interfaces_first_stage)
316 BootstrapCorlib_ResolveInterface (root, iname);
319 // These are the base value types
321 string [] structs_first_stage = {
322 "System.Byte", "System.SByte",
323 "System.Int16", "System.UInt16",
324 "System.Int32", "System.UInt32",
325 "System.Int64", "System.UInt64",
328 foreach (string cname in structs_first_stage)
329 BootstrapCorlib_ResolveStruct (root, cname);
332 // Now, we can load the enumerations, after this point,
335 TypeManager.InitEnumUnderlyingTypes ();
337 string [] structs_second_stage = {
338 "System.Single", "System.Double",
339 "System.Char", "System.Boolean",
340 "System.Decimal", "System.Void",
341 "System.RuntimeFieldHandle",
342 "System.RuntimeArgumentHandle",
343 "System.RuntimeTypeHandle",
345 "System.TypedReference",
349 foreach (string cname in structs_second_stage)
350 BootstrapCorlib_ResolveStruct (root, cname);
353 // These are classes that depends on the core interfaces
355 string [] classes_second_stage = {
356 "System.Reflection.MemberInfo",
362 // These are not really important in the order, but they
363 // are used by the compiler later on (typemanager/CoreLookupType-d)
365 "System.Runtime.CompilerServices.RuntimeHelpers",
366 "System.Reflection.DefaultMemberAttribute",
367 "System.Threading.Monitor",
369 "System.AttributeUsageAttribute",
370 "System.Runtime.InteropServices.DllImportAttribute",
371 "System.Runtime.CompilerServices.MethodImplAttribute",
372 "System.Runtime.InteropServices.MarshalAsAttribute",
373 "System.Runtime.CompilerServices.NewConstraintAttribute",
374 "System.Diagnostics.ConditionalAttribute",
375 "System.ObsoleteAttribute",
376 "System.ParamArrayAttribute",
377 "System.CLSCompliantAttribute",
378 "System.Security.UnverifiableCodeAttribute",
379 "System.Runtime.CompilerServices.IndexerNameAttribute",
380 "System.Runtime.InteropServices.InAttribute",
381 "System.Runtime.InteropServices.StructLayoutAttribute",
382 "System.Runtime.InteropServices.FieldOffsetAttribute",
383 "System.InvalidOperationException",
384 "System.NotSupportedException",
385 "System.MarshalByRefObject"
388 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
389 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
390 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
391 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
392 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
393 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
395 foreach (string cname in classes_second_stage)
396 BootstrapCorlib_ResolveClass (root, cname);
398 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
402 // Closes all open types
406 // We usually use TypeBuilder types. When we are done
407 // creating the type (which will happen after we have added
408 // methods, fields, etc) we need to "Define" them before we
409 // can save the Assembly
411 static public void CloseTypes ()
413 TypeContainer root = Tree.Types;
415 if (root.Enums != null)
416 foreach (Enum en in root.Enums)
419 if (attribute_types != null)
420 foreach (TypeContainer tc in attribute_types)
424 // We do this in two passes, first we close the structs,
425 // then the classes, because it seems the code needs it this
426 // way. If this is really what is going on, we should probably
427 // make sure that we define the structs in order as well.
429 foreach (TypeContainer tc in type_container_resolve_order){
430 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
435 foreach (TypeContainer tc in type_container_resolve_order){
436 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
440 if (root.Delegates != null)
441 foreach (Delegate d in root.Delegates)
446 // If we have a <PrivateImplementationDetails> class, close it
448 if (helper_classes != null){
449 foreach (TypeBuilder type_builder in helper_classes)
450 type_builder.CreateType ();
453 attribute_types = null;
454 type_container_resolve_order = null;
455 helper_classes = null;
457 TypeManager.CleanUp ();
461 /// Used to register classes that need to be closed after all the
462 /// user defined classes
464 public static void RegisterHelperClass (TypeBuilder helper_class)
466 if (helper_classes == null)
467 helper_classes = new ArrayList ();
468 helper_classes.Add (helper_class);
472 // This idea is from Felix Arrese-Igor
474 // Returns : the implicit parent of a composite namespace string
475 // eg. Implicit parent of A.B is A
477 static public string ImplicitParent (string ns)
479 int i = ns.LastIndexOf ('.');
483 return ns.Substring (0, i);
486 static TypeExpr NamespaceLookup (DeclSpace ds, string name,
487 int num_type_args, bool silent, Location loc)
490 // Try in the current namespace and all its implicit parents
492 for (NamespaceEntry ns = ds.NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
493 IAlias result = ns.Lookup (ds, name, num_type_args, silent, loc);
507 static public TypeExpr LookupType (DeclSpace ds, string name, bool silent,
510 return LookupType (ds, name, silent, 0, loc);
514 // Public function used to locate types, this can only
515 // be used after the ResolveTree function has been invoked.
517 // Returns: Type or null if they type can not be found.
519 // Come to think of it, this should be a DeclSpace
521 static public TypeExpr LookupType (DeclSpace ds, string name, bool silent,
522 int num_type_params, Location loc)
526 if (ds.Cache.Contains (name)){
527 t = (TypeExpr) ds.Cache [name];
532 // For the case the type we are looking for is nested within this one
533 // or is in any base class
535 DeclSpace containing_ds = ds;
536 while (containing_ds != null){
537 Type current_type = containing_ds.TypeBuilder;
539 while (current_type != null) {
543 Type type = TypeManager.LookupType (current_type.FullName + "." + name);
545 t = new TypeExpression (type, loc);
550 current_type = current_type.BaseType;
553 containing_ds = containing_ds.Parent;
556 t = NamespaceLookup (ds, name, num_type_params, silent, loc);
564 Report.Error (246, loc, "Cannot find type `"+name+"'");
570 // This is the silent version of LookupType, you can use this
571 // to `probe' for a type
573 static public TypeExpr LookupType (TypeContainer tc, string name, Location loc)
575 return LookupType (tc, name, true, loc);
578 static void Report1530 (Location loc)
580 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
583 static public void PopulateCoreType (TypeContainer root, string name)
585 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
587 ds.DefineMembers (root);
591 static public void BootCorlib_PopulateCoreTypes ()
593 TypeContainer root = tree.Types;
595 PopulateCoreType (root, "System.Object");
596 PopulateCoreType (root, "System.ValueType");
597 PopulateCoreType (root, "System.Attribute");
601 // Populates the structs and classes with fields and methods
604 // This is invoked after all interfaces, structs and classes
605 // have been defined through `ResolveTree'
606 static public void PopulateTypes ()
608 TypeContainer root = Tree.Types;
610 if (attribute_types != null)
611 foreach (TypeContainer tc in attribute_types)
612 tc.DefineMembers (root);
614 if (type_container_resolve_order != null){
615 if (RootContext.StdLib){
616 foreach (TypeContainer tc in type_container_resolve_order)
617 tc.DefineMembers (root);
619 foreach (TypeContainer tc in type_container_resolve_order) {
620 // When compiling corlib, these types have already been
621 // populated from BootCorlib_PopulateCoreTypes ().
622 if (((tc.Name == "System.Object") ||
623 (tc.Name == "System.Attribute") ||
624 (tc.Name == "System.ValueType")))
627 tc.DefineMembers (root);
632 ArrayList delegates = root.Delegates;
633 if (delegates != null){
634 foreach (Delegate d in delegates)
635 if ((d.ModFlags & Modifiers.NEW) == 0)
636 d.DefineMembers (root);
638 Report1530 (d.Location);
641 ArrayList enums = root.Enums;
643 foreach (Enum en in enums)
644 if ((en.ModFlags & Modifiers.NEW) == 0)
645 en.DefineMembers (root);
647 Report1530 (en.Location);
651 // Check for cycles in the struct layout
653 if (type_container_resolve_order != null){
654 Hashtable seen = new Hashtable ();
655 foreach (TypeContainer tc in type_container_resolve_order)
656 TypeManager.CheckStructCycles (tc, seen);
661 // A generic hook delegate
663 public delegate void Hook ();
666 // A hook invoked when the code has been generated.
668 public static event Hook EmitCodeHook;
671 // DefineTypes is used to fill in the members of each type.
673 static public void DefineTypes ()
675 TypeContainer root = Tree.Types;
677 if (attribute_types != null)
678 foreach (TypeContainer tc in attribute_types)
681 if (type_container_resolve_order != null){
682 foreach (TypeContainer tc in type_container_resolve_order) {
683 // When compiling corlib, these types have already been
684 // populated from BootCorlib_PopulateCoreTypes ().
685 if (!RootContext.StdLib &&
686 ((tc.Name == "System.Object") ||
687 (tc.Name == "System.Attribute") ||
688 (tc.Name == "System.ValueType")))
691 if ((tc.ModFlags & Modifiers.NEW) == 0)
696 ArrayList delegates = root.Delegates;
697 if (delegates != null){
698 foreach (Delegate d in delegates)
699 if ((d.ModFlags & Modifiers.NEW) == 0)
703 ArrayList enums = root.Enums;
705 foreach (Enum en in enums)
706 if ((en.ModFlags & Modifiers.NEW) == 0)
711 static public void EmitCode ()
713 if (attribute_types != null)
714 foreach (TypeContainer tc in attribute_types)
717 CodeGen.Assembly.Emit (Tree.Types);
718 CodeGen.Module.Emit (Tree.Types);
720 if (Tree.Types.Enums != null) {
721 foreach (Enum e in Tree.Types.Enums)
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)
733 if (Tree.Types.Delegates != null) {
734 foreach (Delegate d in Tree.Types.Delegates)
738 // Run any hooks after all the types have been defined.
739 // This is used to create nested auxiliary classes for example
742 if (EmitCodeHook != null)
747 // Public Field, used to track which method is the public entry
750 static public MethodInfo EntryPoint;
753 // Track the location of the entry point.
755 static public Location EntryPointLocation;
758 // These are used to generate unique names on the structs and fields.
760 static int field_count;
763 // Makes an initialized struct, returns the field builder that
764 // references the data. Thanks go to Sergey Chaban for researching
765 // how to do this. And coming up with a shorter mechanism than I
766 // was able to figure out.
768 // This works but makes an implicit public struct $ArrayType$SIZE and
769 // makes the fields point to it. We could get more control if we did
772 // 1. DefineNestedType on the impl_details_class with our struct.
774 // 2. Define the field on the impl_details_class
776 static public FieldBuilder MakeStaticData (byte [] data)
780 if (impl_details_class == null){
781 impl_details_class = CodeGen.Module.Builder.DefineType (
782 "<PrivateImplementationDetails>",
783 TypeAttributes.NotPublic,
784 TypeManager.object_type);
786 RegisterHelperClass (impl_details_class);
789 fb = impl_details_class.DefineInitializedData (
790 "$$field-" + (field_count++), data,
791 FieldAttributes.Static | FieldAttributes.Assembly);