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;
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;
118 Version = LanguageVersion.Default;
119 Documentation = null;
120 impl_details_class = null;
123 public static bool NeedsEntryPoint {
125 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
129 static public Tree Tree {
135 public static void RegisterOrder (TypeContainer tc)
137 type_container_resolve_order.Add (tc);
141 // The default compiler checked state
143 static public bool Checked;
146 // Whether to allow Unsafe code
148 static public bool Unsafe;
151 // This function is used to resolve the hierarchy tree.
152 // It processes interfaces, structs and classes in that order.
154 // It creates the TypeBuilder's as it processes the user defined
157 static public void ResolveTree ()
160 // Interfaces are processed next, as classes and
161 // structs might inherit from an object or implement
162 // a set of interfaces, we need to be able to tell
163 // them appart by just using the TypeManager.
165 TypeContainer root = Tree.Types;
167 ArrayList ifaces = root.Interfaces;
169 foreach (TypeContainer i in ifaces)
173 foreach (TypeContainer tc in root.Types)
176 if (root.Delegates != null)
177 foreach (Delegate d in root.Delegates)
180 if (root.Enums != null)
181 foreach (Enum e in root.Enums)
185 static void Error_TypeConflict (string name, Location loc)
188 520, loc, "`" + name + "' conflicts with a predefined type");
191 static void Error_TypeConflict (string name)
194 520, "`" + name + "' conflicts with a predefined type");
198 // Resolves a single class during the corlib bootstrap process
200 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
202 object o = root.GetDefinition (name);
204 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
210 DeclSpace d = (DeclSpace) o;
212 Error_TypeConflict (name, d.Location);
214 Error_TypeConflict (name);
219 return ((DeclSpace) o).DefineType ();
223 // Resolves a struct during the corlib bootstrap process
225 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
227 object o = root.GetDefinition (name);
229 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
235 DeclSpace d = (DeclSpace) o;
237 Error_TypeConflict (name, d.Location);
239 Error_TypeConflict (name);
244 ((DeclSpace) o).DefineType ();
248 // Resolves a struct during the corlib bootstrap process
250 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
252 object o = root.GetDefinition (name);
254 Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
258 if (!(o is Interface)){
260 DeclSpace d = (DeclSpace) o;
262 Error_TypeConflict (name, d.Location);
264 Error_TypeConflict (name);
269 ((DeclSpace) o).DefineType ();
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 TypeContainer root = Tree.Types;
299 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
300 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
301 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
302 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
304 string [] interfaces_first_stage = {
305 "System.IComparable", "System.ICloneable",
306 "System.IConvertible",
308 "System.Collections.IEnumerable",
309 "System.Collections.ICollection",
310 "System.Collections.IEnumerator",
311 "System.Collections.IList",
312 "System.IAsyncResult",
313 "System.IDisposable",
315 "System.Runtime.Serialization.ISerializable",
316 "System.Runtime.InteropServices._Exception",
318 "System.Reflection.IReflect",
319 "System.Reflection.ICustomAttributeProvider",
324 "System.Collections.Generic.IEnumerator`1",
325 "System.Collections.Generic.IEnumerable`1",
326 "System.INullableValue"
329 foreach (string iname in interfaces_first_stage)
330 BootstrapCorlib_ResolveInterface (root, iname);
333 // These are the base value types
335 string [] structs_first_stage = {
336 "System.Byte", "System.SByte",
337 "System.Int16", "System.UInt16",
338 "System.Int32", "System.UInt32",
339 "System.Int64", "System.UInt64",
342 foreach (string cname in structs_first_stage)
343 BootstrapCorlib_ResolveStruct (root, cname);
346 // Now, we can load the enumerations, after this point,
349 TypeManager.InitEnumUnderlyingTypes ();
351 string [] structs_second_stage = {
352 "System.Single", "System.Double",
353 "System.Char", "System.Boolean",
354 "System.Decimal", "System.Void",
355 "System.RuntimeFieldHandle",
356 "System.RuntimeArgumentHandle",
357 "System.RuntimeTypeHandle",
359 "System.TypedReference",
363 foreach (string cname in structs_second_stage)
364 BootstrapCorlib_ResolveStruct (root, cname);
367 // These are classes that depends on the core interfaces
369 string [] classes_second_stage = {
373 "System.Reflection.MemberInfo",
379 // These are not really important in the order, but they
380 // are used by the compiler later on (typemanager/CoreLookupType-d)
382 "System.Runtime.CompilerServices.RuntimeHelpers",
383 "System.Reflection.DefaultMemberAttribute",
384 "System.Threading.Monitor",
386 "System.AttributeUsageAttribute",
387 "System.Runtime.InteropServices.DllImportAttribute",
388 "System.Runtime.CompilerServices.MethodImplAttribute",
389 "System.Runtime.InteropServices.MarshalAsAttribute",
390 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
391 "System.Runtime.CompilerServices.FixedBufferAttribute",
392 "System.Diagnostics.ConditionalAttribute",
393 "System.ObsoleteAttribute",
394 "System.ParamArrayAttribute",
395 "System.CLSCompliantAttribute",
396 "System.Security.UnverifiableCodeAttribute",
397 "System.Security.Permissions.SecurityAttribute",
398 "System.Runtime.CompilerServices.DecimalConstantAttribute",
399 "System.Runtime.InteropServices.InAttribute",
400 "System.Runtime.InteropServices.OutAttribute",
401 "System.Runtime.InteropServices.StructLayoutAttribute",
402 "System.Runtime.InteropServices.FieldOffsetAttribute",
403 "System.Runtime.InteropServices.DefaultCharSetAttribute",
404 "System.InvalidOperationException",
405 "System.NotSupportedException",
406 "System.MarshalByRefObject",
407 "System.Security.CodeAccessPermission",
408 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
409 "System.Runtime.InteropServices.GuidAttribute",
410 "System.Reflection.AssemblyCultureAttribute"
413 foreach (string cname in classes_second_stage)
414 BootstrapCorlib_ResolveClass (root, cname);
416 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
418 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
420 // These will be defined indirectly during the previous ResolveDelegate.
421 // However make sure the rest of the checks happen.
422 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
423 foreach (string cname in delegate_types)
424 BootstrapCorlib_ResolveClass (root, cname);
428 // Closes all open types
432 // We usually use TypeBuilder types. When we are done
433 // creating the type (which will happen after we have added
434 // methods, fields, etc) we need to "Define" them before we
435 // can save the Assembly
437 static public void CloseTypes ()
439 TypeContainer root = Tree.Types;
441 if (root.Enums != null)
442 foreach (Enum en in root.Enums)
446 // We do this in two passes, first we close the structs,
447 // then the classes, because it seems the code needs it this
448 // way. If this is really what is going on, we should probably
449 // make sure that we define the structs in order as well.
451 foreach (TypeContainer tc in type_container_resolve_order){
452 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
457 foreach (TypeContainer tc in type_container_resolve_order){
458 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
462 if (root.Delegates != null)
463 foreach (Delegate d in root.Delegates)
468 // If we have a <PrivateImplementationDetails> class, close it
470 if (helper_classes != null){
471 foreach (TypeBuilder type_builder in helper_classes) {
472 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
473 type_builder.CreateType ();
477 type_container_resolve_order = null;
478 helper_classes = null;
480 TypeManager.CleanUp ();
484 /// Used to register classes that need to be closed after all the
485 /// user defined classes
487 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
489 if (helper_classes == null)
490 helper_classes = new ArrayList ();
492 helper_classes.Add (helper_class);
495 static public void PopulateCoreType (TypeContainer root, string name)
497 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
499 ds.DefineMembers (root);
503 static public void BootCorlib_PopulateCoreTypes ()
505 TypeContainer root = tree.Types;
507 PopulateCoreType (root, "System.Object");
508 PopulateCoreType (root, "System.ValueType");
509 PopulateCoreType (root, "System.Attribute");
510 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
514 // Populates the structs and classes with fields and methods
517 // This is invoked after all interfaces, structs and classes
518 // have been defined through `ResolveTree'
519 static public void PopulateTypes ()
521 TypeContainer root = Tree.Types;
523 if (type_container_resolve_order != null){
524 foreach (TypeContainer tc in type_container_resolve_order)
526 if (RootContext.StdLib){
527 foreach (TypeContainer tc in type_container_resolve_order)
528 tc.DefineMembers (root);
531 foreach (TypeContainer tc in type_container_resolve_order) {
532 // When compiling corlib, these types have already been
533 // populated from BootCorlib_PopulateCoreTypes ().
534 if (((tc.Name == "System.Object") ||
535 (tc.Name == "System.Attribute") ||
536 (tc.Name == "System.ValueType") ||
537 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
540 tc.DefineMembers (root);
545 ArrayList delegates = root.Delegates;
546 if (delegates != null){
547 foreach (Delegate d in delegates)
548 d.DefineMembers (root);
551 ArrayList enums = root.Enums;
553 foreach (Enum en in enums)
554 en.DefineMembers (root);
558 // Check for cycles in the struct layout
560 if (type_container_resolve_order != null){
561 Hashtable seen = new Hashtable ();
562 foreach (TypeContainer tc in type_container_resolve_order)
563 TypeManager.CheckStructCycles (tc, seen);
568 // A generic hook delegate
570 public delegate void Hook ();
573 // A hook invoked when the code has been generated.
575 public static event Hook EmitCodeHook;
578 // DefineTypes is used to fill in the members of each type.
580 static public void DefineTypes ()
582 TypeContainer root = Tree.Types;
584 ArrayList delegates = root.Delegates;
585 if (delegates != null){
586 foreach (Delegate d in delegates)
590 if (type_container_resolve_order != null){
591 foreach (TypeContainer tc in type_container_resolve_order) {
592 // When compiling corlib, these types have already been
593 // populated from BootCorlib_PopulateCoreTypes ().
594 if (!RootContext.StdLib &&
595 ((tc.Name == "System.Object") ||
596 (tc.Name == "System.Attribute") ||
597 (tc.Name == "System.ValueType") ||
598 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
605 ArrayList enums = root.Enums;
607 foreach (Enum en in enums)
612 static public void EmitCode ()
614 if (Tree.Types.Enums != null) {
615 foreach (Enum e in Tree.Types.Enums)
619 if (type_container_resolve_order != null) {
620 foreach (TypeContainer tc in type_container_resolve_order)
623 if (Report.Errors > 0)
626 foreach (TypeContainer tc in type_container_resolve_order)
630 if (Tree.Types.Delegates != null) {
631 foreach (Delegate d in Tree.Types.Delegates)
635 // Run any hooks after all the types have been defined.
636 // This is used to create nested auxiliary classes for example
639 if (EmitCodeHook != null)
642 CodeGen.Assembly.Emit (Tree.Types);
643 CodeGen.Module.Emit (Tree.Types);
647 // Public Field, used to track which method is the public entry
650 static public MethodInfo EntryPoint;
653 // Track the location of the entry point.
655 static public Location EntryPointLocation;
658 // These are used to generate unique names on the structs and fields.
660 static int field_count;
663 // Makes an initialized struct, returns the field builder that
664 // references the data. Thanks go to Sergey Chaban for researching
665 // how to do this. And coming up with a shorter mechanism than I
666 // was able to figure out.
668 // This works but makes an implicit public struct $ArrayType$SIZE and
669 // makes the fields point to it. We could get more control if we did
672 // 1. DefineNestedType on the impl_details_class with our struct.
674 // 2. Define the field on the impl_details_class
676 static public FieldBuilder MakeStaticData (byte [] data)
680 if (impl_details_class == null){
681 impl_details_class = CodeGen.Module.Builder.DefineType (
682 "<PrivateImplementationDetails>",
683 TypeAttributes.NotPublic,
684 TypeManager.object_type);
686 RegisterCompilerGeneratedType (impl_details_class);
689 fb = impl_details_class.DefineInitializedData (
690 "$$field-" + (field_count++), data,
691 FieldAttributes.Static | FieldAttributes.Assembly);
696 public static void CheckUnsafeOption (Location loc)
699 Report.Error (227, loc,
700 "Unsafe code requires the `unsafe' command line option to be specified");