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)
6 // Marek Safar (marek.safar@gmail.com)
9 // Licensed under the terms of the GNU GPL
11 // (C) 2001 Ximian, Inc (http://www.ximian.com)
12 // (C) 2004 Novell, Inc
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Diagnostics;
20 namespace Mono.CSharp {
22 public enum LanguageVersion
38 public class RootContext {
41 // Contains the parsed tree
43 static RootTypes root;
46 // This hashtable contains all of the #definitions across the source code
47 // it is used by the ConditionalAttribute handler.
49 public static Hashtable AllDefines = new Hashtable ();
52 // Whether we are being linked against the standard libraries.
53 // This is only used to tell whether `System.Object' should
54 // have a base class or not.
56 public static bool StdLib;
59 // This keeps track of the order in which classes were defined
60 // so that we can poulate them in that order.
62 // Order is important, because we need to be able to tell, by
63 // examining the list of methods of the base class, which ones are virtual
64 // or abstract as well as the parent names (to implement new,
67 static ArrayList type_container_resolve_order;
70 // Holds a reference to the Private Implementation Details
73 static ArrayList helper_classes;
75 static TypeBuilder impl_details_class;
77 public static Target Target;
78 public static string TargetExt;
80 public static bool VerifyClsCompliance = true;
83 /// Holds /optimize option
85 public static bool Optimize = true;
87 public static LanguageVersion Version;
90 // We keep strongname related info here because
91 // it's also used as complier options from CSC 8.x
93 public static string StrongNameKeyFile;
94 public static string StrongNameKeyContainer;
95 public static bool StrongNameDelaySign;
98 // If set, enable XML documentation generation
100 public static Documentation Documentation;
102 static public string MainClass;
107 static RootContext ()
112 public static void Reset ()
114 root = new RootTypes ();
115 type_container_resolve_order = new ArrayList ();
117 Report.WarningLevel = 3;
121 StrongNameKeyFile = null;
122 StrongNameKeyContainer = null;
123 StrongNameDelaySign = false;
127 Version = LanguageVersion.Default;
128 Documentation = null;
129 impl_details_class = null;
130 helper_classes = null;
133 public static bool NeedsEntryPoint {
134 get { return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe; }
137 static public RootTypes ToplevelTypes {
141 public static void RegisterOrder (TypeContainer tc)
143 type_container_resolve_order.Add (tc);
147 // The default compiler checked state
149 static public bool Checked;
152 // Whether to allow Unsafe code
154 static public bool Unsafe;
157 // This function is used to resolve the hierarchy tree.
158 // It processes interfaces, structs and classes in that order.
160 // It creates the TypeBuilder's as it processes the user defined
163 static public void ResolveTree ()
166 // Interfaces are processed next, as classes and
167 // structs might inherit from an object or implement
168 // a set of interfaces, we need to be able to tell
169 // them appart by just using the TypeManager.
171 foreach (TypeContainer tc in root.Types)
174 foreach (TypeContainer tc in root.Types)
177 if (root.Delegates != null)
178 foreach (Delegate d in root.Delegates)
182 delegate bool VerifyBootstrapType (Type t);
184 static Type BootstrapCorlib_ResolveType (TypeContainer root, string name, VerifyBootstrapType typeVerifier)
186 TypeLookupExpression tle = new TypeLookupExpression (name);
187 Report.DisableReporting ();
188 TypeExpr te = tle.ResolveAsTypeTerminal (root, false);
189 Report.EnableReporting ();
191 Report.Error (518, "The predefined type `{0}' is not defined or imported", name);
196 if (!typeVerifier (t)) {
197 MemberCore mc = root.GetDefinition (name);
198 Location loc = Location.Null;
200 name = mc.GetSignatureForError ();
204 Report.Error (520, loc, "The predefined type `{0}' is not declared correctly", name);
208 AttributeTester.RegisterNonObsoleteType (t);
212 // Resolves a single class during the corlib bootstrap process
214 static Type BootstrapCorlib_ResolveClass (TypeContainer root, string name)
216 return BootstrapCorlib_ResolveType (root, name, IsClass);
219 static bool IsClass (Type t)
221 DeclSpace ds = TypeManager.LookupDeclSpace (t);
228 // Resolves a struct during the corlib bootstrap process
230 static Type BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
232 return BootstrapCorlib_ResolveType (root, name, IsStruct);
235 static bool IsStruct (Type t)
237 DeclSpace ds = TypeManager.LookupDeclSpace (t);
241 return TypeManager.IsSubclassOf (t, TypeManager.value_type);
245 // Resolves an interface during the corlib bootstrap process
247 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
249 BootstrapCorlib_ResolveType (root, name, IsInterface);
252 static bool IsInterface (Type t)
254 return t.IsInterface;
258 // Resolves a delegate during the corlib bootstrap process
260 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
262 BootstrapCorlib_ResolveType (root, name, IsDelegate);
265 static bool IsDelegate (Type t)
267 return TypeManager.IsDelegateType (t);
271 /// Resolves the core types in the compiler when compiling with --nostdlib
273 static public void ResolveCore ()
275 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
276 TypeManager.system_object_expr.Type = TypeManager.object_type;
277 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
278 TypeManager.system_valuetype_expr.Type = TypeManager.value_type;
281 // The core attributes
283 BootstrapCorlib_ResolveInterface (root, "System.Runtime.InteropServices._Attribute");
284 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
285 TypeManager.obsolete_attribute_type = BootstrapCorlib_ResolveClass (root, "System.ObsoleteAttribute");
286 if (TypeManager.obsolete_attribute_type != null) {
287 Class c = TypeManager.LookupClass (TypeManager.obsolete_attribute_type);
291 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
293 string [] interfaces_first_stage = {
294 "System.IComparable", "System.ICloneable",
295 "System.IConvertible",
297 "System.Collections.IEnumerable",
298 "System.Collections.ICollection",
299 "System.Collections.IEnumerator",
300 "System.Collections.IList",
301 "System.IAsyncResult",
302 "System.IDisposable",
304 "System.Runtime.Serialization.ISerializable",
306 "System.Reflection.IReflect",
307 "System.Reflection.ICustomAttributeProvider",
309 "System.Runtime.InteropServices._Exception",
314 "System.Collections.Generic.IEnumerator`1",
315 "System.Collections.Generic.IEnumerable`1"
319 foreach (string iname in interfaces_first_stage)
320 BootstrapCorlib_ResolveInterface (root, iname);
323 // These are the base value types
325 string [] structs_first_stage = {
326 "System.Byte", "System.SByte",
327 "System.Int16", "System.UInt16",
328 "System.Int32", "System.UInt32",
329 "System.Int64", "System.UInt64",
332 foreach (string cname in structs_first_stage)
333 BootstrapCorlib_ResolveStruct (root, cname);
336 // Now, we can load the enumerations, after this point,
339 TypeManager.InitEnumUnderlyingTypes ();
341 string [] structs_second_stage = {
342 "System.Single", "System.Double",
344 "System.Decimal", "System.Void",
345 "System.RuntimeFieldHandle",
346 "System.RuntimeArgumentHandle",
347 "System.RuntimeTypeHandle",
349 "System.TypedReference",
353 TypeManager.bool_type = BootstrapCorlib_ResolveStruct (root, "System.Boolean");
355 foreach (string cname in structs_second_stage)
356 BootstrapCorlib_ResolveStruct (root, cname);
359 // These are classes that depends on the core interfaces
361 string [] classes_second_stage = {
365 "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",
379 "System.Threading.Interlocked",
381 "System.AttributeUsageAttribute",
382 "System.Runtime.InteropServices.DllImportAttribute",
383 "System.Runtime.CompilerServices.MethodImplAttribute",
384 "System.Runtime.InteropServices.MarshalAsAttribute",
386 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
387 "System.Runtime.CompilerServices.FixedBufferAttribute",
389 "System.Diagnostics.ConditionalAttribute",
390 "System.ParamArrayAttribute",
391 "System.CLSCompliantAttribute",
392 "System.Security.UnverifiableCodeAttribute",
393 "System.Security.Permissions.SecurityAttribute",
394 "System.Runtime.CompilerServices.DecimalConstantAttribute",
395 "System.Runtime.InteropServices.InAttribute",
396 "System.Runtime.InteropServices.OutAttribute",
397 "System.Runtime.InteropServices.StructLayoutAttribute",
398 "System.Runtime.InteropServices.FieldOffsetAttribute",
400 "System.Runtime.InteropServices.DefaultCharSetAttribute",
402 "System.InvalidOperationException",
403 "System.NotSupportedException",
404 "System.MarshalByRefObject",
405 "System.Security.CodeAccessPermission",
406 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
407 "System.Runtime.InteropServices.GuidAttribute",
408 "System.Reflection.AssemblyCultureAttribute"
411 foreach (string cname in classes_second_stage)
412 BootstrapCorlib_ResolveClass (root, cname);
414 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
416 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
417 BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
419 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
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 ()
435 // We do this in two passes, first we close the structs,
436 // then the classes, because it seems the code needs it this
437 // way. If this is really what is going on, we should probably
438 // make sure that we define the structs in order as well.
440 foreach (TypeContainer tc in type_container_resolve_order){
441 if (tc.Kind == Kind.Struct && tc.Parent == root){
446 foreach (TypeContainer tc in type_container_resolve_order){
447 if (!(tc.Kind == Kind.Struct && tc.Parent == root))
451 if (root.Delegates != null)
452 foreach (Delegate d in root.Delegates)
457 // If we have a <PrivateImplementationDetails> class, close it
459 if (helper_classes != null){
460 foreach (TypeBuilder type_builder in helper_classes) {
462 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
464 type_builder.CreateType ();
468 type_container_resolve_order = null;
469 helper_classes = null;
471 TypeManager.CleanUp ();
475 /// Used to register classes that need to be closed after all the
476 /// user defined classes
478 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
480 if (helper_classes == null)
481 helper_classes = new ArrayList ();
483 helper_classes.Add (helper_class);
486 static public void PopulateCoreType (TypeContainer root, string name)
488 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
489 // Core type was imported
497 static public void BootCorlib_PopulateCoreTypes ()
499 PopulateCoreType (root, "System.Object");
500 PopulateCoreType (root, "System.ValueType");
501 PopulateCoreType (root, "System.Attribute");
502 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
506 // Populates the structs and classes with fields and methods
509 // This is invoked after all interfaces, structs and classes
510 // have been defined through `ResolveTree'
511 static public void PopulateTypes ()
514 if (type_container_resolve_order != null){
515 foreach (TypeContainer tc in type_container_resolve_order)
517 foreach (TypeContainer tc in type_container_resolve_order)
521 ArrayList delegates = root.Delegates;
522 if (delegates != null){
523 foreach (Delegate d in delegates)
528 // Check for cycles in the struct layout
530 if (type_container_resolve_order != null){
531 Hashtable seen = new Hashtable ();
532 foreach (TypeContainer tc in type_container_resolve_order)
533 TypeManager.CheckStructCycles (tc, seen);
538 // A generic hook delegate
540 public delegate void Hook ();
543 // A hook invoked when the code has been generated.
545 public static event Hook EmitCodeHook;
548 // DefineTypes is used to fill in the members of each type.
550 static public void DefineTypes ()
552 ArrayList delegates = root.Delegates;
553 if (delegates != null){
554 foreach (Delegate d in delegates)
558 if (type_container_resolve_order != null){
559 foreach (TypeContainer tc in type_container_resolve_order) {
560 // When compiling corlib, these types have already been
561 // populated from BootCorlib_PopulateCoreTypes ().
562 if (!RootContext.StdLib &&
563 ((tc.Name == "System.Object") ||
564 (tc.Name == "System.Attribute") ||
565 (tc.Name == "System.ValueType") ||
566 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
574 static public void EmitCode ()
576 if (type_container_resolve_order != null) {
577 foreach (TypeContainer tc in type_container_resolve_order)
580 if (Report.Errors > 0)
583 foreach (TypeContainer tc in type_container_resolve_order)
587 if (root.Delegates != null) {
588 foreach (Delegate d in root.Delegates)
592 // Run any hooks after all the types have been defined.
593 // This is used to create nested auxiliary classes for example
596 if (EmitCodeHook != null)
599 CodeGen.Assembly.Emit (root);
600 CodeGen.Module.Emit (root);
604 // Public Field, used to track which method is the public entry
607 static public MethodInfo EntryPoint;
610 // Track the location of the entry point.
612 static public Location EntryPointLocation;
615 // These are used to generate unique names on the structs and fields.
617 static int field_count;
620 // Makes an initialized struct, returns the field builder that
621 // references the data. Thanks go to Sergey Chaban for researching
622 // how to do this. And coming up with a shorter mechanism than I
623 // was able to figure out.
625 // This works but makes an implicit public struct $ArrayType$SIZE and
626 // makes the fields point to it. We could get more control if we did
629 // 1. DefineNestedType on the impl_details_class with our struct.
631 // 2. Define the field on the impl_details_class
633 static public FieldBuilder MakeStaticData (byte [] data)
637 if (impl_details_class == null){
638 impl_details_class = CodeGen.Module.Builder.DefineType (
639 "<PrivateImplementationDetails>",
640 TypeAttributes.NotPublic,
641 TypeManager.object_type);
643 RegisterCompilerGeneratedType (impl_details_class);
646 fb = impl_details_class.DefineInitializedData (
647 "$$field-" + (field_count++), data,
648 FieldAttributes.Static | FieldAttributes.Assembly);
653 public static void CheckUnsafeOption (Location loc)
656 Report.Error (227, loc,
657 "Unsafe code requires the `unsafe' command line option to be specified");