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)
10 // (C) 2004 Novell, Inc
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
19 namespace Mono.CSharp {
21 public enum LanguageVersion
27 public class RootContext {
30 // Contains the parsed tree
35 // This hashtable contains all of the #definitions across the source code
36 // it is used by the ConditionalAttribute handler.
38 public static Hashtable AllDefines = new Hashtable ();
41 // Whether we are being linked against the standard libraries.
42 // This is only used to tell whether `System.Object' should
43 // have a base class or not.
45 public static bool StdLib = true;
48 // This keeps track of the order in which classes were defined
49 // so that we can poulate them in that order.
51 // Order is important, because we need to be able to tell, by
52 // examining the list of methods of the base class, which ones are virtual
53 // or abstract as well as the parent names (to implement new,
56 static ArrayList type_container_resolve_order;
57 static ArrayList attribute_types;
60 // Holds a reference to the Private Implementation Details
63 static ArrayList helper_classes;
65 static TypeBuilder impl_details_class;
67 public static int WarningLevel = 3;
69 public static Target Target = Target.Exe;
70 public static string TargetExt = ".exe";
72 public static bool VerifyClsCompliance = true;
74 public static LanguageVersion Version = LanguageVersion.Default;
77 // We keep strongname related info here because
78 // it's also used as complier options from CSC 8.x
80 public static string StrongNameKeyFile;
81 public static string StrongNameKeyContainer;
82 public static bool StrongNameDelaySign = false;
85 // If set, enable XML documentation generation
87 public static Documentation Documentation;
95 type_container_resolve_order = new ArrayList ();
98 public static bool NeedsEntryPoint {
100 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
104 static public Tree Tree {
110 static public string MainClass;
112 public static void RegisterOrder (TypeContainer tc)
114 type_container_resolve_order.Add (tc);
117 public static void RegisterAttribute (TypeContainer tc)
119 if (attribute_types == null)
120 attribute_types = new ArrayList ();
122 attribute_types.Add (tc);
126 // The default compiler checked state
128 static public bool Checked = false;
131 // Whether to allow Unsafe code
133 static public bool Unsafe = false;
135 static string MakeFQN (string nsn, string name)
139 return String.Concat (nsn, ".", name);
143 // This function is used to resolve the hierarchy tree.
144 // It processes interfaces, structs and classes in that order.
146 // It creates the TypeBuilder's as it processes the user defined
149 static public void ResolveTree ()
152 // Process the attribute types separately and before anything else
154 if (attribute_types != null)
155 foreach (TypeContainer tc in attribute_types)
159 // Interfaces are processed next, as classes and
160 // structs might inherit from an object or implement
161 // a set of interfaces, we need to be able to tell
162 // them appart by just using the TypeManager.
164 TypeContainer root = Tree.Types;
166 ArrayList ifaces = root.Interfaces;
168 foreach (Interface i in ifaces)
172 foreach (TypeContainer tc in root.Types)
175 if (root.Delegates != null)
176 foreach (Delegate d in root.Delegates)
179 if (root.Enums != null)
180 foreach (Enum e in root.Enums)
184 static void Error_TypeConflict (string name, Location loc)
187 520, loc, "`" + name + "' conflicts with a predefined type");
190 static void Error_TypeConflict (string name)
193 520, "`" + name + "' conflicts with a predefined type");
197 // Resolves a single class during the corlib bootstrap process
199 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
201 object o = root.GetDefinition (name);
203 Report.Error (518, "The predefined type `" + name + "' is not defined");
209 DeclSpace d = (DeclSpace) o;
211 Error_TypeConflict (name, d.Location);
213 Error_TypeConflict (name);
218 return ((DeclSpace) o).DefineType ();
222 // Resolves a struct during the corlib bootstrap process
224 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
226 object o = root.GetDefinition (name);
228 Report.Error (518, "The predefined type `" + name + "' is not defined");
234 DeclSpace d = (DeclSpace) o;
236 Error_TypeConflict (name, d.Location);
238 Error_TypeConflict (name);
243 ((DeclSpace) o).DefineType ();
247 // Resolves a struct during the corlib bootstrap process
249 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
251 object o = root.GetDefinition (name);
253 Report.Error (518, "The predefined type `" + name + "' is not defined");
257 if (!(o is Interface)){
259 DeclSpace d = (DeclSpace) o;
261 Error_TypeConflict (name, d.Location);
263 Error_TypeConflict (name);
268 ((DeclSpace) o).DefineType ();
272 // Resolves a delegate during the corlib bootstrap process
274 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
276 object o = root.GetDefinition (name);
278 Report.Error (518, "The predefined type `" + name + "' is not defined");
279 Environment.Exit (1);
282 if (!(o is Delegate)){
283 Error_TypeConflict (name);
287 ((DeclSpace) o).DefineType ();
292 /// Resolves the core types in the compiler when compiling with --nostdlib
294 static public void ResolveCore ()
296 TypeContainer root = Tree.Types;
298 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
299 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
300 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
302 string [] interfaces_first_stage = {
303 "System.IComparable", "System.ICloneable",
304 "System.IConvertible",
306 "System.Collections.IEnumerable",
307 "System.Collections.ICollection",
308 "System.Collections.IEnumerator",
309 "System.Collections.IList",
310 "System.IAsyncResult",
311 "System.IDisposable",
313 "System.Runtime.Serialization.ISerializable",
314 "System.Runtime.InteropServices._Exception",
316 "System.Reflection.IReflect",
317 "System.Reflection.ICustomAttributeProvider",
322 "System.Collections.Generic.IEnumerator`1",
323 "System.Collections.Generic.IEnumerable`1"
326 foreach (string iname in interfaces_first_stage)
327 BootstrapCorlib_ResolveInterface (root, iname);
330 // These are the base value types
332 string [] structs_first_stage = {
333 "System.Byte", "System.SByte",
334 "System.Int16", "System.UInt16",
335 "System.Int32", "System.UInt32",
336 "System.Int64", "System.UInt64",
339 foreach (string cname in structs_first_stage)
340 BootstrapCorlib_ResolveStruct (root, cname);
343 // Now, we can load the enumerations, after this point,
346 TypeManager.InitEnumUnderlyingTypes ();
348 string [] structs_second_stage = {
349 "System.Single", "System.Double",
350 "System.Char", "System.Boolean",
351 "System.Decimal", "System.Void",
352 "System.RuntimeFieldHandle",
353 "System.RuntimeArgumentHandle",
354 "System.RuntimeTypeHandle",
356 "System.TypedReference",
360 foreach (string cname in structs_second_stage)
361 BootstrapCorlib_ResolveStruct (root, cname);
364 // These are classes that depends on the core interfaces
366 string [] classes_second_stage = {
367 "System.Reflection.MemberInfo",
373 // These are not really important in the order, but they
374 // are used by the compiler later on (typemanager/CoreLookupType-d)
376 "System.Runtime.CompilerServices.RuntimeHelpers",
377 "System.Reflection.DefaultMemberAttribute",
378 "System.Threading.Monitor",
380 "System.AttributeUsageAttribute",
381 "System.Runtime.InteropServices.DllImportAttribute",
382 "System.Runtime.CompilerServices.MethodImplAttribute",
383 "System.Runtime.InteropServices.MarshalAsAttribute",
384 "System.Runtime.CompilerServices.NewConstraintAttribute",
385 "System.Diagnostics.ConditionalAttribute",
386 "System.ObsoleteAttribute",
387 "System.ParamArrayAttribute",
388 "System.CLSCompliantAttribute",
389 "System.Security.UnverifiableCodeAttribute",
390 "System.Security.Permissions.SecurityAttribute",
391 "System.Runtime.CompilerServices.IndexerNameAttribute",
392 "System.Runtime.CompilerServices.DecimalConstantAttribute",
393 "System.Runtime.InteropServices.InAttribute",
394 "System.Runtime.InteropServices.OutAttribute",
395 "System.Runtime.InteropServices.StructLayoutAttribute",
396 "System.Runtime.InteropServices.FieldOffsetAttribute",
397 "System.InvalidOperationException",
398 "System.NotSupportedException",
399 "System.MarshalByRefObject",
400 "System.Security.CodeAccessPermission"
403 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
404 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
405 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
406 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
407 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
408 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
410 foreach (string cname in classes_second_stage)
411 BootstrapCorlib_ResolveClass (root, cname);
413 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
417 // Closes all open types
421 // We usually use TypeBuilder types. When we are done
422 // creating the type (which will happen after we have added
423 // methods, fields, etc) we need to "Define" them before we
424 // can save the Assembly
426 static public void CloseTypes ()
428 TypeContainer root = Tree.Types;
430 if (root.Enums != null)
431 foreach (Enum en in root.Enums)
434 if (attribute_types != null)
435 foreach (TypeContainer tc in attribute_types)
439 // We do this in two passes, first we close the structs,
440 // then the classes, because it seems the code needs it this
441 // way. If this is really what is going on, we should probably
442 // make sure that we define the structs in order as well.
444 foreach (TypeContainer tc in type_container_resolve_order){
445 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
450 foreach (TypeContainer tc in type_container_resolve_order){
451 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
455 if (root.Delegates != null)
456 foreach (Delegate d in root.Delegates)
461 // If we have a <PrivateImplementationDetails> class, close it
463 if (helper_classes != null){
464 foreach (TypeBuilder type_builder in helper_classes)
465 type_builder.CreateType ();
468 attribute_types = null;
469 type_container_resolve_order = null;
470 helper_classes = null;
472 TypeManager.CleanUp ();
476 /// Used to register classes that need to be closed after all the
477 /// user defined classes
479 public static void RegisterHelperClass (TypeBuilder helper_class)
481 if (helper_classes == null)
482 helper_classes = new ArrayList ();
483 helper_classes.Add (helper_class);
486 static Type NamespaceLookup (DeclSpace ds, string name, int num_type_args, Location loc)
488 IAlias result = ds.NamespaceEntry.LookupNamespaceOrType (ds, name, loc);
495 TypeExpr texpr = result.ResolveAsType (ds.EmitContext);
502 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
504 return LookupType (ds, name, silent, 0, loc);
508 // Public function used to locate types, this can only
509 // be used after the ResolveTree function has been invoked.
511 // Returns: Type or null if they type can not be found.
513 // Come to think of it, this should be a DeclSpace
515 static public Type LookupType (DeclSpace ds, string name, bool silent,
516 int num_type_params, Location loc)
520 if (ds.Cache.Contains (name)){
521 t = (Type) ds.Cache [name];
526 // For the case the type we are looking for is nested within this one
527 // or is in any base class
529 DeclSpace containing_ds = ds;
530 while (containing_ds != null){
531 Type current_type = containing_ds.TypeBuilder;
533 while (current_type != null) {
537 Type type = TypeManager.LookupType (current_type.FullName + "." + name);
539 t = ds.ResolveNestedType (type, loc);
544 current_type = current_type.BaseType;
547 containing_ds = containing_ds.Parent;
550 t = NamespaceLookup (ds, name, num_type_params, loc);
551 if (!silent || t != null){
558 Report.Error (246, loc, "Cannot find type `"+name+"'");
564 // This is the silent version of LookupType, you can use this
565 // to `probe' for a type
567 static public Type LookupType (TypeContainer tc, string name, Location loc)
569 return LookupType (tc, name, true, loc);
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 (type_container_resolve_order != null){
609 if (RootContext.StdLib){
610 foreach (TypeContainer tc in type_container_resolve_order)
611 tc.DefineMembers (root);
613 foreach (TypeContainer tc in type_container_resolve_order) {
614 // When compiling corlib, these types have already been
615 // populated from BootCorlib_PopulateCoreTypes ().
616 if (((tc.Name == "System.Object") ||
617 (tc.Name == "System.Attribute") ||
618 (tc.Name == "System.ValueType")))
621 tc.DefineMembers (root);
626 ArrayList delegates = root.Delegates;
627 if (delegates != null){
628 foreach (Delegate d in delegates)
629 if ((d.ModFlags & Modifiers.NEW) == 0)
630 d.DefineMembers (root);
632 Report1530 (d.Location);
635 ArrayList enums = root.Enums;
637 foreach (Enum en in enums)
638 if ((en.ModFlags & Modifiers.NEW) == 0)
639 en.DefineMembers (root);
641 Report1530 (en.Location);
645 // Check for cycles in the struct layout
647 if (type_container_resolve_order != null){
648 Hashtable seen = new Hashtable ();
649 foreach (TypeContainer tc in type_container_resolve_order)
650 TypeManager.CheckStructCycles (tc, seen);
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 (type_container_resolve_order != null){
676 foreach (TypeContainer tc in type_container_resolve_order) {
677 // When compiling corlib, these types have already been
678 // populated from BootCorlib_PopulateCoreTypes ().
679 if (!RootContext.StdLib &&
680 ((tc.Name == "System.Object") ||
681 (tc.Name == "System.Attribute") ||
682 (tc.Name == "System.ValueType")))
685 if ((tc.ModFlags & Modifiers.NEW) == 0)
690 ArrayList delegates = root.Delegates;
691 if (delegates != null){
692 foreach (Delegate d in delegates)
693 if ((d.ModFlags & Modifiers.NEW) == 0)
697 ArrayList enums = root.Enums;
699 foreach (Enum en in enums)
700 if ((en.ModFlags & Modifiers.NEW) == 0)
705 static public void EmitCode ()
707 if (attribute_types != null)
708 foreach (TypeContainer tc in attribute_types)
711 CodeGen.Assembly.Emit (Tree.Types);
712 CodeGen.Module.Emit (Tree.Types);
714 if (Tree.Types.Enums != null) {
715 foreach (Enum e in Tree.Types.Enums)
719 if (type_container_resolve_order != null) {
720 foreach (TypeContainer tc in type_container_resolve_order)
724 if (Tree.Types.Delegates != null) {
725 foreach (Delegate d in Tree.Types.Delegates)
729 // Run any hooks after all the types have been defined.
730 // This is used to create nested auxiliary classes for example
733 if (EmitCodeHook != null)
738 // Public Field, used to track which method is the public entry
741 static public MethodInfo EntryPoint;
744 // Track the location of the entry point.
746 static public Location EntryPointLocation;
749 // These are used to generate unique names on the structs and fields.
751 static int field_count;
754 // Makes an initialized struct, returns the field builder that
755 // references the data. Thanks go to Sergey Chaban for researching
756 // how to do this. And coming up with a shorter mechanism than I
757 // was able to figure out.
759 // This works but makes an implicit public struct $ArrayType$SIZE and
760 // makes the fields point to it. We could get more control if we did
763 // 1. DefineNestedType on the impl_details_class with our struct.
765 // 2. Define the field on the impl_details_class
767 static public FieldBuilder MakeStaticData (byte [] data)
771 if (impl_details_class == null){
772 impl_details_class = CodeGen.Module.Builder.DefineType (
773 "<PrivateImplementationDetails>",
774 TypeAttributes.NotPublic,
775 TypeManager.object_type);
777 RegisterHelperClass (impl_details_class);
780 fb = impl_details_class.DefineInitializedData (
781 "$$field-" + (field_count++), data,
782 FieldAttributes.Static | FieldAttributes.Assembly);