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
32 static RootTypes root;
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;
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;
59 // Holds a reference to the Private Implementation Details
62 static ArrayList helper_classes;
64 static TypeBuilder impl_details_class;
66 public static int WarningLevel;
68 public static Target Target;
69 public static string TargetExt;
71 public static bool VerifyClsCompliance = true;
74 /// Holds /optimize option
76 public static bool Optimize = true;
78 public static LanguageVersion Version;
81 // We keep strongname related info here because
82 // it's also used as complier options from CSC 8.x
84 public static string StrongNameKeyFile;
85 public static string StrongNameKeyContainer;
86 public static bool StrongNameDelaySign;
88 public static bool BrokenCircularDeps;
90 // If set, enable XML documentation generation
92 public static Documentation Documentation;
94 static public string MainClass;
104 public static void Reset ()
106 root = new RootTypes ();
107 type_container_resolve_order = new ArrayList ();
113 StrongNameKeyFile = null;
114 StrongNameKeyContainer = null;
115 StrongNameDelaySign = false;
119 Version = LanguageVersion.Default;
120 Documentation = null;
121 impl_details_class = null;
122 helper_classes = null;
125 public static bool NeedsEntryPoint {
126 get { return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe; }
129 static public RootTypes ToplevelTypes {
133 public static void RegisterOrder (TypeContainer tc)
135 type_container_resolve_order.Add (tc);
139 // The default compiler checked state
141 static public bool Checked;
144 // Whether to allow Unsafe code
146 static public bool Unsafe;
149 // This function is used to resolve the hierarchy tree.
150 // It processes interfaces, structs and classes in that order.
152 // It creates the TypeBuilder's as it processes the user defined
155 static public void ResolveTree ()
158 // Interfaces are processed next, as classes and
159 // structs might inherit from an object or implement
160 // a set of interfaces, we need to be able to tell
161 // them appart by just using the TypeManager.
163 ArrayList ifaces = root.Interfaces;
165 foreach (TypeContainer i in ifaces)
169 foreach (TypeContainer tc in root.Types)
172 if (root.Delegates != null)
173 foreach (Delegate d in root.Delegates)
176 if (root.Enums != null)
177 foreach (Enum e in root.Enums)
181 static void Error_TypeConflict (string name, Location loc)
184 520, loc, "`" + name + "' conflicts with a predefined type");
187 static void Error_TypeConflict (string name)
190 520, "`" + name + "' conflicts with a predefined type");
194 // Resolves a single class during the corlib bootstrap process
196 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
198 object o = root.GetDefinition (name);
200 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
206 DeclSpace d = (DeclSpace) o;
208 Error_TypeConflict (name, d.Location);
210 Error_TypeConflict (name);
215 return ((DeclSpace) o).DefineType ();
219 // Resolves a struct during the corlib bootstrap process
221 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
223 object o = root.GetDefinition (name);
225 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
231 DeclSpace d = (DeclSpace) o;
233 Error_TypeConflict (name, d.Location);
235 Error_TypeConflict (name);
240 ((DeclSpace) o).DefineType ();
244 // Resolves a struct during the corlib bootstrap process
246 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
248 object o = root.GetDefinition (name);
250 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
254 if (!(o is Interface)){
256 DeclSpace d = (DeclSpace) o;
258 Error_TypeConflict (name, d.Location);
260 Error_TypeConflict (name);
265 ((DeclSpace) o).DefineType ();
269 // Resolves a delegate during the corlib bootstrap process
271 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
273 object o = root.GetDefinition (name);
275 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
279 if (!(o is Delegate)){
280 Error_TypeConflict (name);
284 ((DeclSpace) o).DefineType ();
289 /// Resolves the core types in the compiler when compiling with --nostdlib
291 static public void ResolveCore ()
293 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
294 TypeManager.system_object_expr.Type = TypeManager.object_type;
295 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
296 TypeManager.system_valuetype_expr.Type = TypeManager.value_type;
297 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
298 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
300 string [] interfaces_first_stage = {
301 "System.IComparable", "System.ICloneable",
302 "System.IConvertible",
304 "System.Collections.IEnumerable",
305 "System.Collections.ICollection",
306 "System.Collections.IEnumerator",
307 "System.Collections.IList",
308 "System.IAsyncResult",
309 "System.IDisposable",
311 "System.Runtime.Serialization.ISerializable",
312 "System.Runtime.InteropServices._Exception",
314 "System.Reflection.IReflect",
315 "System.Reflection.ICustomAttributeProvider",
320 "System.Collections.Generic.IEnumerator`1",
321 "System.Collections.Generic.IEnumerable`1"
324 foreach (string iname in interfaces_first_stage)
325 BootstrapCorlib_ResolveInterface (root, iname);
328 // These are the base value types
330 string [] structs_first_stage = {
331 "System.Byte", "System.SByte",
332 "System.Int16", "System.UInt16",
333 "System.Int32", "System.UInt32",
334 "System.Int64", "System.UInt64",
337 foreach (string cname in structs_first_stage)
338 BootstrapCorlib_ResolveStruct (root, cname);
341 // Now, we can load the enumerations, after this point,
344 TypeManager.InitEnumUnderlyingTypes ();
346 string [] structs_second_stage = {
347 "System.Single", "System.Double",
348 "System.Char", "System.Boolean",
349 "System.Decimal", "System.Void",
350 "System.RuntimeFieldHandle",
351 "System.RuntimeArgumentHandle",
352 "System.RuntimeTypeHandle",
354 "System.TypedReference",
358 foreach (string cname in structs_second_stage)
359 BootstrapCorlib_ResolveStruct (root, cname);
362 // These are classes that depends on the core interfaces
364 string [] classes_second_stage = {
368 "System.Reflection.MemberInfo",
374 // These are not really important in the order, but they
375 // are used by the compiler later on (typemanager/CoreLookupType-d)
377 "System.Runtime.CompilerServices.RuntimeHelpers",
378 "System.Reflection.DefaultMemberAttribute",
379 "System.Threading.Monitor",
381 "System.AttributeUsageAttribute",
382 "System.Runtime.InteropServices.DllImportAttribute",
383 "System.Runtime.CompilerServices.MethodImplAttribute",
384 "System.Runtime.InteropServices.MarshalAsAttribute",
385 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
386 "System.Runtime.CompilerServices.FixedBufferAttribute",
387 "System.Diagnostics.ConditionalAttribute",
388 "System.ObsoleteAttribute",
389 "System.ParamArrayAttribute",
390 "System.CLSCompliantAttribute",
391 "System.Security.UnverifiableCodeAttribute",
392 "System.Security.Permissions.SecurityAttribute",
393 "System.Runtime.CompilerServices.DecimalConstantAttribute",
394 "System.Runtime.InteropServices.InAttribute",
395 "System.Runtime.InteropServices.OutAttribute",
396 "System.Runtime.InteropServices.StructLayoutAttribute",
397 "System.Runtime.InteropServices.FieldOffsetAttribute",
398 "System.Runtime.InteropServices.DefaultCharSetAttribute",
399 "System.InvalidOperationException",
400 "System.NotSupportedException",
401 "System.MarshalByRefObject",
402 "System.Security.CodeAccessPermission",
403 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
404 "System.Runtime.InteropServices.GuidAttribute",
405 "System.Reflection.AssemblyCultureAttribute"
408 foreach (string cname in classes_second_stage)
409 BootstrapCorlib_ResolveClass (root, cname);
411 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
413 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
415 // These will be defined indirectly during the previous ResolveDelegate.
416 // However make sure the rest of the checks happen.
417 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
418 foreach (string cname in delegate_types)
419 BootstrapCorlib_ResolveClass (root, cname);
423 // Closes all open types
427 // We usually use TypeBuilder types. When we are done
428 // creating the type (which will happen after we have added
429 // methods, fields, etc) we need to "Define" them before we
430 // can save the Assembly
432 static public void CloseTypes ()
434 if (root.Enums != null)
435 foreach (Enum en in root.Enums)
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 == root){
450 foreach (TypeContainer tc in type_container_resolve_order){
451 if (!(tc.Kind == Kind.Struct && tc.Parent == root))
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.SetCustomAttribute (TypeManager.compiler_generated_attr);
466 type_builder.CreateType ();
470 type_container_resolve_order = null;
471 helper_classes = null;
473 TypeManager.CleanUp ();
477 /// Used to register classes that need to be closed after all the
478 /// user defined classes
480 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
482 if (helper_classes == null)
483 helper_classes = new ArrayList ();
485 helper_classes.Add (helper_class);
488 static public void PopulateCoreType (TypeContainer root, string name)
490 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
496 static public void BootCorlib_PopulateCoreTypes ()
498 PopulateCoreType (root, "System.Object");
499 PopulateCoreType (root, "System.ValueType");
500 PopulateCoreType (root, "System.Attribute");
501 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
505 // Populates the structs and classes with fields and methods
508 // This is invoked after all interfaces, structs and classes
509 // have been defined through `ResolveTree'
510 static public void PopulateTypes ()
512 if (type_container_resolve_order != null){
513 foreach (TypeContainer tc in type_container_resolve_order)
515 foreach (TypeContainer tc in type_container_resolve_order)
519 ArrayList delegates = root.Delegates;
520 if (delegates != null){
521 foreach (Delegate d in delegates)
525 ArrayList enums = root.Enums;
527 foreach (Enum en in enums)
532 // Check for cycles in the struct layout
534 if (type_container_resolve_order != null){
535 Hashtable seen = new Hashtable ();
536 foreach (TypeContainer tc in type_container_resolve_order)
537 TypeManager.CheckStructCycles (tc, seen);
542 // A generic hook delegate
544 public delegate void Hook ();
547 // A hook invoked when the code has been generated.
549 public static event Hook EmitCodeHook;
552 // DefineTypes is used to fill in the members of each type.
554 static public void DefineTypes ()
556 ArrayList delegates = root.Delegates;
557 if (delegates != null){
558 foreach (Delegate d in delegates)
562 if (type_container_resolve_order != null){
563 foreach (TypeContainer tc in type_container_resolve_order) {
564 // When compiling corlib, these types have already been
565 // populated from BootCorlib_PopulateCoreTypes ().
566 if (!RootContext.StdLib &&
567 ((tc.Name == "System.Object") ||
568 (tc.Name == "System.Attribute") ||
569 (tc.Name == "System.ValueType") ||
570 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
577 ArrayList enums = root.Enums;
579 foreach (Enum en in enums)
584 static public void EmitCode ()
586 if (root.Enums != null) {
587 foreach (Enum e in root.Enums)
591 if (type_container_resolve_order != null) {
592 foreach (TypeContainer tc in type_container_resolve_order)
595 if (Report.Errors > 0)
598 foreach (TypeContainer tc in type_container_resolve_order)
602 if (root.Delegates != null) {
603 foreach (Delegate d in root.Delegates)
607 // Run any hooks after all the types have been defined.
608 // This is used to create nested auxiliary classes for example
611 if (EmitCodeHook != null)
614 CodeGen.Assembly.Emit (root);
615 CodeGen.Module.Emit (root);
619 // Public Field, used to track which method is the public entry
622 static public MethodInfo EntryPoint;
625 // Track the location of the entry point.
627 static public Location EntryPointLocation;
630 // These are used to generate unique names on the structs and fields.
632 static int field_count;
635 // Makes an initialized struct, returns the field builder that
636 // references the data. Thanks go to Sergey Chaban for researching
637 // how to do this. And coming up with a shorter mechanism than I
638 // was able to figure out.
640 // This works but makes an implicit public struct $ArrayType$SIZE and
641 // makes the fields point to it. We could get more control if we did
644 // 1. DefineNestedType on the impl_details_class with our struct.
646 // 2. Define the field on the impl_details_class
648 static public FieldBuilder MakeStaticData (byte [] data)
652 if (impl_details_class == null){
653 impl_details_class = CodeGen.Module.Builder.DefineType (
654 "<PrivateImplementationDetails>",
655 TypeAttributes.NotPublic,
656 TypeManager.object_type);
658 RegisterCompilerGeneratedType (impl_details_class);
661 fb = impl_details_class.DefineInitializedData (
662 "$$field-" + (field_count++), data,
663 FieldAttributes.Static | FieldAttributes.Assembly);
668 public static void CheckUnsafeOption (Location loc)
671 Report.Error (227, loc,
672 "Unsafe code requires the `unsafe' command line option to be specified");