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
29 public class RootContext {
32 // Contains the parsed tree
34 static RootTypes root;
37 // This hashtable contains all of the #definitions across the source code
38 // it is used by the ConditionalAttribute handler.
40 public static Hashtable AllDefines = new Hashtable ();
43 // Whether we are being linked against the standard libraries.
44 // This is only used to tell whether `System.Object' should
45 // have a base class or not.
47 public static bool StdLib;
50 // This keeps track of the order in which classes were defined
51 // so that we can poulate them in that order.
53 // Order is important, because we need to be able to tell, by
54 // examining the list of methods of the base class, which ones are virtual
55 // or abstract as well as the parent names (to implement new,
58 static ArrayList type_container_resolve_order;
61 // Holds a reference to the Private Implementation Details
64 static ArrayList helper_classes;
66 static TypeBuilder impl_details_class;
68 public static int WarningLevel;
70 public static Target Target;
71 public static string TargetExt;
73 public static bool VerifyClsCompliance = true;
76 /// Holds /optimize option
78 public static bool Optimize = true;
80 public static LanguageVersion Version;
83 // We keep strongname related info here because
84 // it's also used as complier options from CSC 8.x
86 public static string StrongNameKeyFile;
87 public static string StrongNameKeyContainer;
88 public static bool StrongNameDelaySign;
91 // If set, enable XML documentation generation
93 public static Documentation Documentation;
95 static public string MainClass;
100 static RootContext ()
105 public static void Reset ()
107 root = new RootTypes ();
108 type_container_resolve_order = new ArrayList ();
114 StrongNameKeyFile = null;
115 StrongNameKeyContainer = null;
116 StrongNameDelaySign = false;
120 Version = LanguageVersion.Default;
121 Documentation = null;
122 impl_details_class = null;
123 helper_classes = null;
126 public static bool NeedsEntryPoint {
127 get { return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe; }
130 static public RootTypes ToplevelTypes {
134 public static void RegisterOrder (TypeContainer tc)
136 type_container_resolve_order.Add (tc);
140 // The default compiler checked state
142 static public bool Checked;
145 // Whether to allow Unsafe code
147 static public bool Unsafe;
150 // This function is used to resolve the hierarchy tree.
151 // It processes interfaces, structs and classes in that order.
153 // It creates the TypeBuilder's as it processes the user defined
156 static public void ResolveTree ()
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 foreach (TypeContainer tc in root.Types)
167 foreach (TypeContainer tc in root.Types)
170 if (root.Delegates != null)
171 foreach (Delegate d in root.Delegates)
175 delegate bool VerifyBootstrapType (Type t);
177 static Type BootstrapCorlib_ResolveType (TypeContainer root, string name, VerifyBootstrapType typeVerifier)
179 TypeLookupExpression tle = new TypeLookupExpression (name);
180 Report.DisableErrors ();
181 TypeExpr te = tle.ResolveAsTypeTerminal (root, false);
182 Report.EnableErrors ();
184 Report.Error (518, "The predefined type `{0}' is not defined or imported", name);
189 if (!typeVerifier (t)) {
190 MemberCore mc = root.GetDefinition (name);
191 Location loc = Location.Null;
193 name = mc.GetSignatureForError ();
197 Report.Error (520, loc, "The predefined type `{0}' is not declared correctly", name);
201 AttributeTester.RegisterNonObsoleteType (t);
205 // Resolves a single class during the corlib bootstrap process
207 static Type BootstrapCorlib_ResolveClass (TypeContainer root, string name)
209 return BootstrapCorlib_ResolveType (root, name, IsClass);
212 static bool IsClass (Type t)
214 DeclSpace ds = TypeManager.LookupDeclSpace (t);
221 // Resolves a struct during the corlib bootstrap process
223 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
225 BootstrapCorlib_ResolveType (root, name, IsStruct);
228 static bool IsStruct (Type t)
230 DeclSpace ds = TypeManager.LookupDeclSpace (t);
234 return TypeManager.IsSubclassOf (t, TypeManager.value_type);
238 // Resolves an interface during the corlib bootstrap process
240 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
242 BootstrapCorlib_ResolveType (root, name, IsInterface);
245 static bool IsInterface (Type t)
247 return t.IsInterface;
251 // Resolves a delegate during the corlib bootstrap process
253 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
255 BootstrapCorlib_ResolveType (root, name, IsDelegate);
258 static bool IsDelegate (Type t)
260 return TypeManager.IsDelegateType (t);
264 /// Resolves the core types in the compiler when compiling with --nostdlib
266 static public void ResolveCore ()
268 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
269 TypeManager.system_object_expr.Type = TypeManager.object_type;
270 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
271 TypeManager.system_valuetype_expr.Type = TypeManager.value_type;
274 // The core attributes
276 BootstrapCorlib_ResolveInterface (root, "System.Runtime.InteropServices._Attribute");
277 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
278 TypeManager.obsolete_attribute_type = BootstrapCorlib_ResolveClass (root, "System.ObsoleteAttribute");
279 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
281 string [] interfaces_first_stage = {
282 "System.IComparable", "System.ICloneable",
283 "System.IConvertible",
285 "System.Collections.IEnumerable",
286 "System.Collections.ICollection",
287 "System.Collections.IEnumerator",
288 "System.Collections.IList",
289 "System.IAsyncResult",
290 "System.IDisposable",
292 "System.Runtime.Serialization.ISerializable",
294 "System.Reflection.IReflect",
295 "System.Reflection.ICustomAttributeProvider",
297 "System.Runtime.InteropServices._Exception",
302 "System.Collections.Generic.IEnumerator`1",
303 "System.Collections.Generic.IEnumerable`1"
307 foreach (string iname in interfaces_first_stage)
308 BootstrapCorlib_ResolveInterface (root, iname);
311 // These are the base value types
313 string [] structs_first_stage = {
314 "System.Byte", "System.SByte",
315 "System.Int16", "System.UInt16",
316 "System.Int32", "System.UInt32",
317 "System.Int64", "System.UInt64",
320 foreach (string cname in structs_first_stage)
321 BootstrapCorlib_ResolveStruct (root, cname);
324 // Now, we can load the enumerations, after this point,
327 TypeManager.InitEnumUnderlyingTypes ();
329 string [] structs_second_stage = {
330 "System.Single", "System.Double",
331 "System.Char", "System.Boolean",
332 "System.Decimal", "System.Void",
333 "System.RuntimeFieldHandle",
334 "System.RuntimeArgumentHandle",
335 "System.RuntimeTypeHandle",
337 "System.TypedReference",
341 foreach (string cname in structs_second_stage)
342 BootstrapCorlib_ResolveStruct (root, cname);
345 // These are classes that depends on the core interfaces
347 string [] classes_second_stage = {
351 "System.Reflection.MemberInfo",
359 // These are not really important in the order, but they
360 // are used by the compiler later on (typemanager/CoreLookupType-d)
362 "System.Runtime.CompilerServices.RuntimeHelpers",
363 "System.Reflection.DefaultMemberAttribute",
364 "System.Threading.Monitor",
365 "System.Threading.Interlocked",
367 "System.AttributeUsageAttribute",
368 "System.Runtime.InteropServices.DllImportAttribute",
369 "System.Runtime.CompilerServices.MethodImplAttribute",
370 "System.Runtime.InteropServices.MarshalAsAttribute",
372 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
373 "System.Runtime.CompilerServices.FixedBufferAttribute",
375 "System.Diagnostics.ConditionalAttribute",
376 "System.ParamArrayAttribute",
377 "System.CLSCompliantAttribute",
378 "System.Security.UnverifiableCodeAttribute",
379 "System.Security.Permissions.SecurityAttribute",
380 "System.Runtime.CompilerServices.DecimalConstantAttribute",
381 "System.Runtime.InteropServices.InAttribute",
382 "System.Runtime.InteropServices.OutAttribute",
383 "System.Runtime.InteropServices.StructLayoutAttribute",
384 "System.Runtime.InteropServices.FieldOffsetAttribute",
386 "System.Runtime.InteropServices.DefaultCharSetAttribute",
388 "System.InvalidOperationException",
389 "System.NotSupportedException",
390 "System.MarshalByRefObject",
391 "System.Security.CodeAccessPermission",
392 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
393 "System.Runtime.InteropServices.GuidAttribute",
394 "System.Reflection.AssemblyCultureAttribute"
397 foreach (string cname in classes_second_stage)
398 BootstrapCorlib_ResolveClass (root, cname);
400 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
402 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
403 BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
405 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
409 // Closes all open types
413 // We usually use TypeBuilder types. When we are done
414 // creating the type (which will happen after we have added
415 // methods, fields, etc) we need to "Define" them before we
416 // can save the Assembly
418 static public void CloseTypes ()
421 // We do this in two passes, first we close the structs,
422 // then the classes, because it seems the code needs it this
423 // way. If this is really what is going on, we should probably
424 // make sure that we define the structs in order as well.
426 foreach (TypeContainer tc in type_container_resolve_order){
427 if (tc.Kind == Kind.Struct && tc.Parent == root){
432 foreach (TypeContainer tc in type_container_resolve_order){
433 if (!(tc.Kind == Kind.Struct && tc.Parent == root))
437 if (root.Delegates != null)
438 foreach (Delegate d in root.Delegates)
443 // If we have a <PrivateImplementationDetails> class, close it
445 if (helper_classes != null){
446 foreach (TypeBuilder type_builder in helper_classes) {
448 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
450 type_builder.CreateType ();
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 RegisterCompilerGeneratedType (TypeBuilder helper_class)
466 if (helper_classes == null)
467 helper_classes = new ArrayList ();
469 helper_classes.Add (helper_class);
472 static public void PopulateCoreType (TypeContainer root, string name)
474 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
475 // Core type was imported
483 static public void BootCorlib_PopulateCoreTypes ()
485 PopulateCoreType (root, "System.Object");
486 PopulateCoreType (root, "System.ValueType");
487 PopulateCoreType (root, "System.Attribute");
488 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
492 // Populates the structs and classes with fields and methods
495 // This is invoked after all interfaces, structs and classes
496 // have been defined through `ResolveTree'
497 static public void PopulateTypes ()
500 if (type_container_resolve_order != null){
501 foreach (TypeContainer tc in type_container_resolve_order)
503 foreach (TypeContainer tc in type_container_resolve_order)
507 ArrayList delegates = root.Delegates;
508 if (delegates != null){
509 foreach (Delegate d in delegates)
514 // Check for cycles in the struct layout
516 if (type_container_resolve_order != null){
517 Hashtable seen = new Hashtable ();
518 foreach (TypeContainer tc in type_container_resolve_order)
519 TypeManager.CheckStructCycles (tc, seen);
524 // A generic hook delegate
526 public delegate void Hook ();
529 // A hook invoked when the code has been generated.
531 public static event Hook EmitCodeHook;
534 // DefineTypes is used to fill in the members of each type.
536 static public void DefineTypes ()
538 ArrayList delegates = root.Delegates;
539 if (delegates != null){
540 foreach (Delegate d in delegates)
544 if (type_container_resolve_order != null){
545 foreach (TypeContainer tc in type_container_resolve_order) {
546 // When compiling corlib, these types have already been
547 // populated from BootCorlib_PopulateCoreTypes ().
548 if (!RootContext.StdLib &&
549 ((tc.Name == "System.Object") ||
550 (tc.Name == "System.Attribute") ||
551 (tc.Name == "System.ValueType") ||
552 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
560 static public void EmitCode ()
562 if (type_container_resolve_order != null) {
563 foreach (TypeContainer tc in type_container_resolve_order)
566 if (Report.Errors > 0)
569 foreach (TypeContainer tc in type_container_resolve_order)
573 if (root.Delegates != null) {
574 foreach (Delegate d in root.Delegates)
578 // Run any hooks after all the types have been defined.
579 // This is used to create nested auxiliary classes for example
582 if (EmitCodeHook != null)
585 CodeGen.Assembly.Emit (root);
586 CodeGen.Module.Emit (root);
590 // Public Field, used to track which method is the public entry
593 static public MethodInfo EntryPoint;
596 // Track the location of the entry point.
598 static public Location EntryPointLocation;
601 // These are used to generate unique names on the structs and fields.
603 static int field_count;
606 // Makes an initialized struct, returns the field builder that
607 // references the data. Thanks go to Sergey Chaban for researching
608 // how to do this. And coming up with a shorter mechanism than I
609 // was able to figure out.
611 // This works but makes an implicit public struct $ArrayType$SIZE and
612 // makes the fields point to it. We could get more control if we did
615 // 1. DefineNestedType on the impl_details_class with our struct.
617 // 2. Define the field on the impl_details_class
619 static public FieldBuilder MakeStaticData (byte [] data)
623 if (impl_details_class == null){
624 impl_details_class = CodeGen.Module.Builder.DefineType (
625 "<PrivateImplementationDetails>",
626 TypeAttributes.NotPublic,
627 TypeManager.object_type);
629 RegisterCompilerGeneratedType (impl_details_class);
632 fb = impl_details_class.DefineInitializedData (
633 "$$field-" + (field_count++), data,
634 FieldAttributes.Static | FieldAttributes.Assembly);
639 public static void CheckUnsafeOption (Location loc)
642 Report.Error (227, loc,
643 "Unsafe code requires the `unsafe' command line option to be specified");