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;
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 = ".exe";
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 ()
106 type_container_resolve_order = new ArrayList ();
112 StrongNameKeyFile = null;
113 StrongNameKeyContainer = null;
114 StrongNameDelaySign = false;
117 Version = LanguageVersion.Default;
118 Documentation = null;
119 impl_details_class = null;
122 public static bool NeedsEntryPoint {
124 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
128 static public Tree Tree {
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 TypeContainer root = Tree.Types;
166 ArrayList ifaces = root.Interfaces;
168 foreach (TypeContainer 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");
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");
301 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
303 string [] interfaces_first_stage = {
304 "System.IComparable", "System.ICloneable",
305 "System.IConvertible",
307 "System.Collections.IEnumerable",
308 "System.Collections.ICollection",
309 "System.Collections.IEnumerator",
310 "System.Collections.IList",
311 "System.IAsyncResult",
312 "System.IDisposable",
314 "System.Runtime.Serialization.ISerializable",
315 "System.Runtime.InteropServices._Exception",
317 "System.Reflection.IReflect",
318 "System.Reflection.ICustomAttributeProvider",
323 "System.Collections.Generic.IEnumerator`1",
324 "System.Collections.Generic.IEnumerable`1",
327 foreach (string iname in interfaces_first_stage)
328 BootstrapCorlib_ResolveInterface (root, iname);
331 // These are the base value types
333 string [] structs_first_stage = {
334 "System.Byte", "System.SByte",
335 "System.Int16", "System.UInt16",
336 "System.Int32", "System.UInt32",
337 "System.Int64", "System.UInt64",
340 foreach (string cname in structs_first_stage)
341 BootstrapCorlib_ResolveStruct (root, cname);
344 // Now, we can load the enumerations, after this point,
347 TypeManager.InitEnumUnderlyingTypes ();
349 string [] structs_second_stage = {
350 "System.Single", "System.Double",
351 "System.Char", "System.Boolean",
352 "System.Decimal", "System.Void",
353 "System.RuntimeFieldHandle",
354 "System.RuntimeArgumentHandle",
355 "System.RuntimeTypeHandle",
357 "System.TypedReference",
361 foreach (string cname in structs_second_stage)
362 BootstrapCorlib_ResolveStruct (root, cname);
365 // These are classes that depends on the core interfaces
367 string [] classes_second_stage = {
371 "System.Reflection.MemberInfo",
377 // These are not really important in the order, but they
378 // are used by the compiler later on (typemanager/CoreLookupType-d)
380 "System.Runtime.CompilerServices.RuntimeHelpers",
381 "System.Reflection.DefaultMemberAttribute",
382 "System.Threading.Monitor",
384 "System.AttributeUsageAttribute",
385 "System.Runtime.InteropServices.DllImportAttribute",
386 "System.Runtime.CompilerServices.MethodImplAttribute",
387 "System.Runtime.InteropServices.MarshalAsAttribute",
388 "System.Runtime.CompilerServices.NewConstraintAttribute",
389 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
390 "System.Runtime.CompilerServices.FixedBufferAttribute",
391 "System.Diagnostics.ConditionalAttribute",
392 "System.ObsoleteAttribute",
393 "System.ParamArrayAttribute",
394 "System.CLSCompliantAttribute",
395 "System.Security.UnverifiableCodeAttribute",
396 "System.Security.Permissions.SecurityAttribute",
397 "System.Runtime.CompilerServices.DecimalConstantAttribute",
398 "System.Runtime.InteropServices.InAttribute",
399 "System.Runtime.InteropServices.OutAttribute",
400 "System.Runtime.InteropServices.StructLayoutAttribute",
401 "System.Runtime.InteropServices.FieldOffsetAttribute",
402 "System.Runtime.InteropServices.DefaultCharSetAttribute",
403 "System.InvalidOperationException",
404 "System.NotSupportedException",
405 "System.MarshalByRefObject",
406 "System.Security.CodeAccessPermission",
407 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
408 "System.Runtime.InteropServices.GuidAttribute"
411 foreach (string cname in classes_second_stage)
412 BootstrapCorlib_ResolveClass (root, cname);
414 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
416 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
418 // These will be defined indirectly during the previous ResolveDelegate.
419 // However make sure the rest of the checks happen.
420 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
421 foreach (string cname in delegate_types)
422 BootstrapCorlib_ResolveClass (root, cname);
426 // Closes all open types
430 // We usually use TypeBuilder types. When we are done
431 // creating the type (which will happen after we have added
432 // methods, fields, etc) we need to "Define" them before we
433 // can save the Assembly
435 static public void CloseTypes ()
437 TypeContainer root = Tree.Types;
439 if (root.Enums != null)
440 foreach (Enum en in root.Enums)
444 // We do this in two passes, first we close the structs,
445 // then the classes, because it seems the code needs it this
446 // way. If this is really what is going on, we should probably
447 // make sure that we define the structs in order as well.
449 foreach (TypeContainer tc in type_container_resolve_order){
450 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
455 foreach (TypeContainer tc in type_container_resolve_order){
456 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
460 if (root.Delegates != null)
461 foreach (Delegate d in root.Delegates)
466 // If we have a <PrivateImplementationDetails> class, close it
468 if (helper_classes != null){
469 foreach (TypeBuilder type_builder in helper_classes) {
470 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
471 type_builder.CreateType ();
475 type_container_resolve_order = null;
476 helper_classes = null;
478 TypeManager.CleanUp ();
482 /// Used to register classes that need to be closed after all the
483 /// user defined classes
485 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
487 if (helper_classes == null)
488 helper_classes = new ArrayList ();
490 helper_classes.Add (helper_class);
493 static void Report1530 (Location loc)
495 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
498 static public void PopulateCoreType (TypeContainer root, string name)
500 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
502 ds.DefineMembers (root);
506 static public void BootCorlib_PopulateCoreTypes ()
508 TypeContainer root = tree.Types;
510 PopulateCoreType (root, "System.Object");
511 PopulateCoreType (root, "System.ValueType");
512 PopulateCoreType (root, "System.Attribute");
513 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
517 // Populates the structs and classes with fields and methods
520 // This is invoked after all interfaces, structs and classes
521 // have been defined through `ResolveTree'
522 static public void PopulateTypes ()
524 TypeContainer root = Tree.Types;
526 if (type_container_resolve_order != null){
527 foreach (TypeContainer tc in type_container_resolve_order)
529 if (RootContext.StdLib){
530 foreach (TypeContainer tc in type_container_resolve_order)
531 tc.DefineMembers (root);
533 foreach (TypeContainer tc in type_container_resolve_order) {
534 // When compiling corlib, these types have already been
535 // populated from BootCorlib_PopulateCoreTypes ().
536 if (((tc.Name == "System.Object") ||
537 (tc.Name == "System.Attribute") ||
538 (tc.Name == "System.ValueType") ||
539 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
542 tc.DefineMembers (root);
547 ArrayList delegates = root.Delegates;
548 if (delegates != null){
549 foreach (Delegate d in delegates)
550 if ((d.ModFlags & Modifiers.NEW) == 0)
551 d.DefineMembers (root);
553 Report1530 (d.Location);
556 ArrayList enums = root.Enums;
558 foreach (Enum en in enums)
559 if ((en.ModFlags & Modifiers.NEW) == 0)
560 en.DefineMembers (root);
562 Report1530 (en.Location);
566 // Check for cycles in the struct layout
568 if (type_container_resolve_order != null){
569 Hashtable seen = new Hashtable ();
570 foreach (TypeContainer tc in type_container_resolve_order)
571 TypeManager.CheckStructCycles (tc, seen);
576 // A generic hook delegate
578 public delegate void Hook ();
581 // A hook invoked when the code has been generated.
583 public static event Hook EmitCodeHook;
586 // DefineTypes is used to fill in the members of each type.
588 static public void DefineTypes ()
590 TypeContainer root = Tree.Types;
592 if (type_container_resolve_order != null){
593 foreach (TypeContainer tc in type_container_resolve_order) {
594 // When compiling corlib, these types have already been
595 // populated from BootCorlib_PopulateCoreTypes ().
596 if (!RootContext.StdLib &&
597 ((tc.Name == "System.Object") ||
598 (tc.Name == "System.Attribute") ||
599 (tc.Name == "System.ValueType") ||
600 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
603 if ((tc.ModFlags & Modifiers.NEW) == 0)
608 ArrayList delegates = root.Delegates;
609 if (delegates != null){
610 foreach (Delegate d in delegates)
611 if ((d.ModFlags & Modifiers.NEW) == 0)
615 ArrayList enums = root.Enums;
617 foreach (Enum en in enums)
618 if ((en.ModFlags & Modifiers.NEW) == 0)
623 static public void EmitCode ()
625 if (Tree.Types.Enums != null) {
626 foreach (Enum e in Tree.Types.Enums)
630 if (type_container_resolve_order != null) {
631 foreach (TypeContainer tc in type_container_resolve_order)
634 if (Report.Errors > 0)
637 foreach (TypeContainer tc in type_container_resolve_order)
641 if (Tree.Types.Delegates != null) {
642 foreach (Delegate d in Tree.Types.Delegates)
646 // Run any hooks after all the types have been defined.
647 // This is used to create nested auxiliary classes for example
650 if (EmitCodeHook != null)
653 CodeGen.Assembly.Emit (Tree.Types);
654 CodeGen.Module.Emit (Tree.Types);
658 // Public Field, used to track which method is the public entry
661 static public MethodInfo EntryPoint;
664 // Track the location of the entry point.
666 static public Location EntryPointLocation;
669 // These are used to generate unique names on the structs and fields.
671 static int field_count;
674 // Makes an initialized struct, returns the field builder that
675 // references the data. Thanks go to Sergey Chaban for researching
676 // how to do this. And coming up with a shorter mechanism than I
677 // was able to figure out.
679 // This works but makes an implicit public struct $ArrayType$SIZE and
680 // makes the fields point to it. We could get more control if we did
683 // 1. DefineNestedType on the impl_details_class with our struct.
685 // 2. Define the field on the impl_details_class
687 static public FieldBuilder MakeStaticData (byte [] data)
691 if (impl_details_class == null){
692 impl_details_class = CodeGen.Module.Builder.DefineType (
693 "<PrivateImplementationDetails>",
694 TypeAttributes.NotPublic,
695 TypeManager.object_type);
697 RegisterCompilerGeneratedType (impl_details_class);
700 fb = impl_details_class.DefineInitializedData (
701 "$$field-" + (field_count++), data,
702 FieldAttributes.Static | FieldAttributes.Assembly);