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;
18 namespace Mono.CSharp {
20 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;
89 // If set, enable XML documentation generation
91 public static Documentation Documentation;
93 static public string MainClass;
103 public static void Reset ()
105 root = new RootTypes ();
106 type_container_resolve_order = new ArrayList ();
112 StrongNameKeyFile = null;
113 StrongNameKeyContainer = null;
114 StrongNameDelaySign = false;
118 Version = LanguageVersion.Default;
119 Documentation = null;
120 impl_details_class = null;
121 helper_classes = null;
124 public static bool NeedsEntryPoint {
125 get { return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe; }
128 static public RootTypes ToplevelTypes {
132 public static void RegisterOrder (TypeContainer tc)
134 type_container_resolve_order.Add (tc);
138 // The default compiler checked state
140 static public bool Checked;
143 // Whether to allow Unsafe code
145 static public bool Unsafe;
148 // This function is used to resolve the hierarchy tree.
149 // It processes interfaces, structs and classes in that order.
151 // It creates the TypeBuilder's as it processes the user defined
154 static public void ResolveTree ()
157 // Interfaces are processed next, as classes and
158 // structs might inherit from an object or implement
159 // a set of interfaces, we need to be able to tell
160 // them appart by just using the TypeManager.
162 ArrayList ifaces = root.Interfaces;
164 foreach (TypeContainer i in ifaces)
168 foreach (TypeContainer tc in root.Types)
171 if (root.Delegates != null)
172 foreach (Delegate d in root.Delegates)
175 if (root.Enums != null)
176 foreach (Enum e in root.Enums)
180 static void Error_TypeConflict (string name, Location loc)
183 520, loc, "`" + name + "' conflicts with a predefined type");
186 static void Error_TypeConflict (string name)
189 520, "`" + name + "' conflicts with a predefined type");
193 // Resolves a single class during the corlib bootstrap process
195 static Type BootstrapCorlib_ResolveClass (TypeContainer root, string name)
197 object o = root.GetDefinition (name);
199 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
205 DeclSpace d = (DeclSpace) o;
207 Error_TypeConflict (name, d.Location);
209 Error_TypeConflict (name);
214 Type t = ((DeclSpace) o).DefineType ();
216 AttributeTester.RegisterNonObsoleteType (t);
221 // Resolves a struct during the corlib bootstrap process
223 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
225 object o = root.GetDefinition (name);
227 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
233 DeclSpace d = (DeclSpace) o;
235 Error_TypeConflict (name, d.Location);
237 Error_TypeConflict (name);
242 ((DeclSpace) o).DefineType ();
246 // Resolves a struct during the corlib bootstrap process
248 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
250 object o = root.GetDefinition (name);
252 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
256 if (!(o is Interface)){
258 DeclSpace d = (DeclSpace) o;
260 Error_TypeConflict (name, d.Location);
262 Error_TypeConflict (name);
267 Type t = ((DeclSpace) o).DefineType ();
269 AttributeTester.RegisterNonObsoleteType (t);
273 // Resolves a delegate during the corlib bootstrap process
275 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
277 object o = root.GetDefinition (name);
279 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
283 if (!(o is Delegate)){
284 Error_TypeConflict (name);
288 ((DeclSpace) o).DefineType ();
293 /// Resolves the core types in the compiler when compiling with --nostdlib
295 static public void ResolveCore ()
297 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
298 TypeManager.system_object_expr.Type = TypeManager.object_type;
299 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
300 TypeManager.system_valuetype_expr.Type = TypeManager.value_type;
303 // The core attributes
305 BootstrapCorlib_ResolveInterface (root, "System.Runtime.InteropServices._Attribute");
306 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
307 TypeManager.obsolete_attribute_type = BootstrapCorlib_ResolveClass (root, "System.ObsoleteAttribute");
308 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
310 string [] interfaces_first_stage = {
311 "System.IComparable", "System.ICloneable",
312 "System.IConvertible",
314 "System.Collections.IEnumerable",
315 "System.Collections.ICollection",
316 "System.Collections.IEnumerator",
317 "System.Collections.IList",
318 "System.IAsyncResult",
319 "System.IDisposable",
321 "System.Runtime.Serialization.ISerializable",
323 "System.Reflection.IReflect",
324 "System.Reflection.ICustomAttributeProvider",
326 "System.Runtime.InteropServices._Exception",
331 "System.Collections.Generic.IEnumerator`1",
332 "System.Collections.Generic.IEnumerable`1"
336 foreach (string iname in interfaces_first_stage)
337 BootstrapCorlib_ResolveInterface (root, iname);
340 // These are the base value types
342 string [] structs_first_stage = {
343 "System.Byte", "System.SByte",
344 "System.Int16", "System.UInt16",
345 "System.Int32", "System.UInt32",
346 "System.Int64", "System.UInt64",
349 foreach (string cname in structs_first_stage)
350 BootstrapCorlib_ResolveStruct (root, cname);
353 // Now, we can load the enumerations, after this point,
356 TypeManager.InitEnumUnderlyingTypes ();
358 string [] structs_second_stage = {
359 "System.Single", "System.Double",
360 "System.Char", "System.Boolean",
361 "System.Decimal", "System.Void",
362 "System.RuntimeFieldHandle",
363 "System.RuntimeArgumentHandle",
364 "System.RuntimeTypeHandle",
366 "System.TypedReference",
370 foreach (string cname in structs_second_stage)
371 BootstrapCorlib_ResolveStruct (root, cname);
374 // These are classes that depends on the core interfaces
376 string [] classes_second_stage = {
380 "System.Reflection.MemberInfo",
388 // These are not really important in the order, but they
389 // are used by the compiler later on (typemanager/CoreLookupType-d)
391 "System.Runtime.CompilerServices.RuntimeHelpers",
392 "System.Reflection.DefaultMemberAttribute",
393 "System.Threading.Monitor",
394 "System.Threading.Interlocked",
396 "System.AttributeUsageAttribute",
397 "System.Runtime.InteropServices.DllImportAttribute",
398 "System.Runtime.CompilerServices.MethodImplAttribute",
399 "System.Runtime.InteropServices.MarshalAsAttribute",
401 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
402 "System.Runtime.CompilerServices.FixedBufferAttribute",
404 "System.Diagnostics.ConditionalAttribute",
405 "System.ParamArrayAttribute",
406 "System.CLSCompliantAttribute",
407 "System.Security.UnverifiableCodeAttribute",
408 "System.Security.Permissions.SecurityAttribute",
409 "System.Runtime.CompilerServices.DecimalConstantAttribute",
410 "System.Runtime.InteropServices.InAttribute",
411 "System.Runtime.InteropServices.OutAttribute",
412 "System.Runtime.InteropServices.StructLayoutAttribute",
413 "System.Runtime.InteropServices.FieldOffsetAttribute",
415 "System.Runtime.InteropServices.DefaultCharSetAttribute",
417 "System.InvalidOperationException",
418 "System.NotSupportedException",
419 "System.MarshalByRefObject",
420 "System.Security.CodeAccessPermission",
421 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
422 "System.Runtime.InteropServices.GuidAttribute",
423 "System.Reflection.AssemblyCultureAttribute"
426 foreach (string cname in classes_second_stage)
427 BootstrapCorlib_ResolveClass (root, cname);
429 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
431 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
433 // These will be defined indirectly during the previous ResolveDelegate.
434 // However make sure the rest of the checks happen.
435 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
436 foreach (string cname in delegate_types)
437 BootstrapCorlib_ResolveClass (root, cname);
441 // Closes all open types
445 // We usually use TypeBuilder types. When we are done
446 // creating the type (which will happen after we have added
447 // methods, fields, etc) we need to "Define" them before we
448 // can save the Assembly
450 static public void CloseTypes ()
452 if (root.Enums != null)
453 foreach (Enum en in root.Enums)
457 // We do this in two passes, first we close the structs,
458 // then the classes, because it seems the code needs it this
459 // way. If this is really what is going on, we should probably
460 // make sure that we define the structs in order as well.
462 foreach (TypeContainer tc in type_container_resolve_order){
463 if (tc.Kind == Kind.Struct && tc.Parent == root){
468 foreach (TypeContainer tc in type_container_resolve_order){
469 if (!(tc.Kind == Kind.Struct && tc.Parent == root))
473 if (root.Delegates != null)
474 foreach (Delegate d in root.Delegates)
479 // If we have a <PrivateImplementationDetails> class, close it
481 if (helper_classes != null){
482 foreach (TypeBuilder type_builder in helper_classes) {
484 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
486 type_builder.CreateType ();
490 type_container_resolve_order = null;
491 helper_classes = null;
493 TypeManager.CleanUp ();
497 /// Used to register classes that need to be closed after all the
498 /// user defined classes
500 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
502 if (helper_classes == null)
503 helper_classes = new ArrayList ();
505 helper_classes.Add (helper_class);
508 static public void PopulateCoreType (TypeContainer root, string name)
510 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
516 static public void BootCorlib_PopulateCoreTypes ()
518 PopulateCoreType (root, "System.Object");
519 PopulateCoreType (root, "System.ValueType");
520 PopulateCoreType (root, "System.Attribute");
521 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
525 // Populates the structs and classes with fields and methods
528 // This is invoked after all interfaces, structs and classes
529 // have been defined through `ResolveTree'
530 static public void PopulateTypes ()
533 if (type_container_resolve_order != null){
535 foreach (TypeContainer tc in type_container_resolve_order)
538 foreach (TypeContainer tc in type_container_resolve_order)
542 ArrayList delegates = root.Delegates;
543 if (delegates != null){
544 foreach (Delegate d in delegates)
548 ArrayList enums = root.Enums;
550 foreach (Enum en in enums)
555 // Check for cycles in the struct layout
557 if (type_container_resolve_order != null){
558 Hashtable seen = new Hashtable ();
559 foreach (TypeContainer tc in type_container_resolve_order)
560 TypeManager.CheckStructCycles (tc, seen);
565 // A generic hook delegate
567 public delegate void Hook ();
570 // A hook invoked when the code has been generated.
572 public static event Hook EmitCodeHook;
575 // DefineTypes is used to fill in the members of each type.
577 static public void DefineTypes ()
579 ArrayList delegates = root.Delegates;
580 if (delegates != null){
581 foreach (Delegate d in delegates)
585 if (type_container_resolve_order != null){
586 foreach (TypeContainer tc in type_container_resolve_order) {
587 // When compiling corlib, these types have already been
588 // populated from BootCorlib_PopulateCoreTypes ().
589 if (!RootContext.StdLib &&
590 ((tc.Name == "System.Object") ||
591 (tc.Name == "System.Attribute") ||
592 (tc.Name == "System.ValueType") ||
593 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
600 ArrayList enums = root.Enums;
602 foreach (Enum en in enums)
607 static public void EmitCode ()
609 if (root.Enums != null) {
610 foreach (Enum e in root.Enums)
614 if (type_container_resolve_order != null) {
615 foreach (TypeContainer tc in type_container_resolve_order)
618 if (Report.Errors > 0)
621 foreach (TypeContainer tc in type_container_resolve_order)
625 if (root.Delegates != null) {
626 foreach (Delegate d in root.Delegates)
630 // Run any hooks after all the types have been defined.
631 // This is used to create nested auxiliary classes for example
634 if (EmitCodeHook != null)
637 CodeGen.Assembly.Emit (root);
638 CodeGen.Module.Emit (root);
642 // Public Field, used to track which method is the public entry
645 static public MethodInfo EntryPoint;
648 // Track the location of the entry point.
650 static public Location EntryPointLocation;
653 // These are used to generate unique names on the structs and fields.
655 static int field_count;
658 // Makes an initialized struct, returns the field builder that
659 // references the data. Thanks go to Sergey Chaban for researching
660 // how to do this. And coming up with a shorter mechanism than I
661 // was able to figure out.
663 // This works but makes an implicit public struct $ArrayType$SIZE and
664 // makes the fields point to it. We could get more control if we did
667 // 1. DefineNestedType on the impl_details_class with our struct.
669 // 2. Define the field on the impl_details_class
671 static public FieldBuilder MakeStaticData (byte [] data)
675 if (impl_details_class == null){
676 impl_details_class = CodeGen.Module.Builder.DefineType (
677 "<PrivateImplementationDetails>",
678 TypeAttributes.NotPublic,
679 TypeManager.object_type);
681 RegisterCompilerGeneratedType (impl_details_class);
684 fb = impl_details_class.DefineInitializedData (
685 "$$field-" + (field_count++), data,
686 FieldAttributes.Static | FieldAttributes.Assembly);
691 public static void CheckUnsafeOption (Location loc)
694 Report.Error (227, loc,
695 "Unsafe code requires the `unsafe' command line option to be specified");