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
26 public class RootContext {
29 // Contains the parsed tree
34 // This hashtable contains all of the #definitions across the source code
35 // it is used by the ConditionalAttribute handler.
37 public static Hashtable AllDefines = new Hashtable ();
40 // Whether we are being linked against the standard libraries.
41 // This is only used to tell whether `System.Object' should
42 // have a base class or not.
44 public static bool StdLib;
47 // This keeps track of the order in which classes were defined
48 // so that we can poulate them in that order.
50 // Order is important, because we need to be able to tell, by
51 // examining the list of methods of the base class, which ones are virtual
52 // or abstract as well as the parent names (to implement new,
55 static ArrayList type_container_resolve_order;
58 // Holds a reference to the Private Implementation Details
61 static ArrayList helper_classes;
63 static TypeBuilder impl_details_class;
65 public static int WarningLevel;
67 public static Target Target;
68 public static string TargetExt = ".exe";
70 public static bool VerifyClsCompliance = true;
73 /// Holds /optimize option
75 public static bool Optimize = true;
77 public static LanguageVersion Version;
80 // We keep strongname related info here because
81 // it's also used as complier options from CSC 8.x
83 public static string StrongNameKeyFile;
84 public static string StrongNameKeyContainer;
85 public static bool StrongNameDelaySign;
88 // If set, enable XML documentation generation
90 public static Documentation Documentation;
92 static public string MainClass;
102 public static void Reset ()
105 type_container_resolve_order = new ArrayList ();
111 StrongNameKeyFile = null;
112 StrongNameKeyContainer = null;
113 StrongNameDelaySign = false;
116 Version = LanguageVersion.Default;
117 Documentation = null;
118 impl_details_class = null;
121 public static bool NeedsEntryPoint {
123 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
127 static public Tree Tree {
133 public static void RegisterOrder (TypeContainer tc)
135 type_container_resolve_order.Add (tc);
139 // The default compiler checked state
141 static public bool Checked;
144 // Whether to allow Unsafe code
146 static public bool Unsafe;
149 // This function is used to resolve the hierarchy tree.
150 // It processes interfaces, structs and classes in that order.
152 // It creates the TypeBuilder's as it processes the user defined
155 static public void ResolveTree ()
158 // Interfaces are processed next, as classes and
159 // structs might inherit from an object or implement
160 // a set of interfaces, we need to be able to tell
161 // them appart by just using the TypeManager.
163 TypeContainer root = Tree.Types;
165 ArrayList ifaces = root.Interfaces;
167 foreach (TypeContainer i in ifaces)
171 foreach (TypeContainer tc in root.Types)
174 if (root.Delegates != null)
175 foreach (Delegate d in root.Delegates)
178 if (root.Enums != null)
179 foreach (Enum e in root.Enums)
183 static void Error_TypeConflict (string name, Location loc)
186 520, loc, "`" + name + "' conflicts with a predefined type");
189 static void Error_TypeConflict (string name)
192 520, "`" + name + "' conflicts with a predefined type");
196 // Resolves a single class during the corlib bootstrap process
198 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
200 object o = root.GetDefinition (name);
202 Report.Error (518, "The predefined type `" + name + "' is not defined");
208 DeclSpace d = (DeclSpace) o;
210 Error_TypeConflict (name, d.Location);
212 Error_TypeConflict (name);
217 return ((DeclSpace) o).DefineType ();
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");
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");
256 if (!(o is Interface)){
258 DeclSpace d = (DeclSpace) o;
260 Error_TypeConflict (name, d.Location);
262 Error_TypeConflict (name);
267 ((DeclSpace) o).DefineType ();
271 // Resolves a delegate during the corlib bootstrap process
273 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
275 object o = root.GetDefinition (name);
277 Report.Error (518, "The predefined type `" + name + "' is not defined");
281 if (!(o is Delegate)){
282 Error_TypeConflict (name);
286 ((DeclSpace) o).DefineType ();
291 /// Resolves the core types in the compiler when compiling with --nostdlib
293 static public void ResolveCore ()
295 TypeContainer root = Tree.Types;
297 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
298 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
299 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
300 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
302 string [] interfaces_first_stage = {
303 "System.IComparable", "System.ICloneable",
304 "System.IConvertible",
306 "System.Collections.IEnumerable",
307 "System.Collections.ICollection",
308 "System.Collections.IEnumerator",
309 "System.Collections.IList",
310 "System.IAsyncResult",
311 "System.IDisposable",
313 "System.Runtime.Serialization.ISerializable",
315 "System.Reflection.IReflect",
316 "System.Reflection.ICustomAttributeProvider"
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",
343 "System.Char", "System.Boolean",
344 "System.Decimal", "System.Void",
345 "System.RuntimeFieldHandle",
346 "System.RuntimeArgumentHandle",
347 "System.RuntimeTypeHandle",
349 "System.TypedReference",
353 foreach (string cname in structs_second_stage)
354 BootstrapCorlib_ResolveStruct (root, cname);
357 // These are classes that depends on the core interfaces
359 string [] classes_second_stage = {
363 "System.Reflection.MemberInfo",
368 // These are not really important in the order, but they
369 // are used by the compiler later on (typemanager/CoreLookupType-d)
371 "System.Runtime.CompilerServices.RuntimeHelpers",
372 "System.Reflection.DefaultMemberAttribute",
373 "System.Threading.Monitor",
375 "System.AttributeUsageAttribute",
376 "System.Runtime.InteropServices.DllImportAttribute",
377 "System.Runtime.CompilerServices.MethodImplAttribute",
378 "System.Runtime.InteropServices.MarshalAsAttribute",
379 "System.Diagnostics.ConditionalAttribute",
380 "System.ObsoleteAttribute",
381 "System.ParamArrayAttribute",
382 "System.CLSCompliantAttribute",
383 "System.Security.UnverifiableCodeAttribute",
384 "System.Security.Permissions.SecurityAttribute",
385 "System.Runtime.CompilerServices.DecimalConstantAttribute",
386 "System.Runtime.InteropServices.InAttribute",
387 "System.Runtime.InteropServices.OutAttribute",
388 "System.Runtime.InteropServices.StructLayoutAttribute",
389 "System.Runtime.InteropServices.FieldOffsetAttribute",
390 "System.InvalidOperationException",
391 "System.NotSupportedException",
392 "System.MarshalByRefObject",
393 "System.Security.CodeAccessPermission",
394 "System.Runtime.CompilerServices.RequiredAttributeAttribute",
395 "System.Runtime.InteropServices.GuidAttribute"
398 foreach (string cname in classes_second_stage)
399 BootstrapCorlib_ResolveClass (root, cname);
401 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
403 // These will be defined indirectly during the previous ResolveDelegate.
404 // However make sure the rest of the checks happen.
405 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
406 foreach (string cname in delegate_types)
407 BootstrapCorlib_ResolveClass (root, cname);
411 // Closes all open types
415 // We usually use TypeBuilder types. When we are done
416 // creating the type (which will happen after we have added
417 // methods, fields, etc) we need to "Define" them before we
418 // can save the Assembly
420 static public void CloseTypes ()
422 TypeContainer root = Tree.Types;
424 if (root.Enums != null)
425 foreach (Enum en in root.Enums)
429 // We do this in two passes, first we close the structs,
430 // then the classes, because it seems the code needs it this
431 // way. If this is really what is going on, we should probably
432 // make sure that we define the structs in order as well.
434 foreach (TypeContainer tc in type_container_resolve_order){
435 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
440 foreach (TypeContainer tc in type_container_resolve_order){
441 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
445 if (root.Delegates != null)
446 foreach (Delegate d in root.Delegates)
451 // If we have a <PrivateImplementationDetails> class, close it
453 if (helper_classes != null){
454 foreach (TypeBuilder type_builder in helper_classes) {
456 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
458 type_builder.CreateType ();
462 type_container_resolve_order = null;
463 helper_classes = null;
465 TypeManager.CleanUp ();
469 /// Used to register classes that need to be closed after all the
470 /// user defined classes
472 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
474 if (helper_classes == null)
475 helper_classes = new ArrayList ();
477 helper_classes.Add (helper_class);
480 static void Report1530 (Location loc)
482 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
485 static public void PopulateCoreType (TypeContainer root, string name)
487 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
489 ds.DefineMembers (root);
493 static public void BootCorlib_PopulateCoreTypes ()
495 TypeContainer root = tree.Types;
497 PopulateCoreType (root, "System.Object");
498 PopulateCoreType (root, "System.ValueType");
499 PopulateCoreType (root, "System.Attribute");
500 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
504 // Populates the structs and classes with fields and methods
507 // This is invoked after all interfaces, structs and classes
508 // have been defined through `ResolveTree'
509 static public void PopulateTypes ()
511 TypeContainer root = Tree.Types;
513 if (type_container_resolve_order != null){
514 if (RootContext.StdLib){
515 foreach (TypeContainer tc in type_container_resolve_order)
516 tc.DefineMembers (root);
518 foreach (TypeContainer tc in type_container_resolve_order) {
519 // When compiling corlib, these types have already been
520 // populated from BootCorlib_PopulateCoreTypes ().
521 if (((tc.Name == "System.Object") ||
522 (tc.Name == "System.Attribute") ||
523 (tc.Name == "System.ValueType") ||
524 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
527 tc.DefineMembers (root);
532 ArrayList delegates = root.Delegates;
533 if (delegates != null){
534 foreach (Delegate d in delegates)
535 if ((d.ModFlags & Modifiers.NEW) == 0)
536 d.DefineMembers (root);
538 Report1530 (d.Location);
541 ArrayList enums = root.Enums;
543 foreach (Enum en in enums)
544 if ((en.ModFlags & Modifiers.NEW) == 0)
545 en.DefineMembers (root);
547 Report1530 (en.Location);
551 // Check for cycles in the struct layout
553 if (type_container_resolve_order != null){
554 Hashtable seen = new Hashtable ();
555 foreach (TypeContainer tc in type_container_resolve_order)
556 TypeManager.CheckStructCycles (tc, seen);
561 // A generic hook delegate
563 public delegate void Hook ();
566 // A hook invoked when the code has been generated.
568 public static event Hook EmitCodeHook;
571 // DefineTypes is used to fill in the members of each type.
573 static public void DefineTypes ()
575 TypeContainer root = Tree.Types;
577 if (type_container_resolve_order != null){
578 foreach (TypeContainer tc in type_container_resolve_order) {
579 // When compiling corlib, these types have already been
580 // populated from BootCorlib_PopulateCoreTypes ().
581 if (!RootContext.StdLib &&
582 ((tc.Name == "System.Object") ||
583 (tc.Name == "System.Attribute") ||
584 (tc.Name == "System.ValueType") ||
585 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
588 if ((tc.ModFlags & Modifiers.NEW) == 0)
593 ArrayList delegates = root.Delegates;
594 if (delegates != null){
595 foreach (Delegate d in delegates)
596 if ((d.ModFlags & Modifiers.NEW) == 0)
600 ArrayList enums = root.Enums;
602 foreach (Enum en in enums)
603 if ((en.ModFlags & Modifiers.NEW) == 0)
608 static public void EmitCode ()
610 if (Tree.Types.Enums != null) {
611 foreach (Enum e in Tree.Types.Enums)
615 if (type_container_resolve_order != null) {
616 foreach (TypeContainer tc in type_container_resolve_order)
619 if (Report.Errors > 0)
622 foreach (TypeContainer tc in type_container_resolve_order)
626 if (Tree.Types.Delegates != null) {
627 foreach (Delegate d in Tree.Types.Delegates)
631 // Run any hooks after all the types have been defined.
632 // This is used to create nested auxiliary classes for example
635 if (EmitCodeHook != null)
638 CodeGen.Assembly.Emit (Tree.Types);
639 CodeGen.Module.Emit (Tree.Types);
643 // Public Field, used to track which method is the public entry
646 static public MethodInfo EntryPoint;
649 // Track the location of the entry point.
651 static public Location EntryPointLocation;
654 // These are used to generate unique names on the structs and fields.
656 static int field_count;
659 // Makes an initialized struct, returns the field builder that
660 // references the data. Thanks go to Sergey Chaban for researching
661 // how to do this. And coming up with a shorter mechanism than I
662 // was able to figure out.
664 // This works but makes an implicit public struct $ArrayType$SIZE and
665 // makes the fields point to it. We could get more control if we did
668 // 1. DefineNestedType on the impl_details_class with our struct.
670 // 2. Define the field on the impl_details_class
672 static public FieldBuilder MakeStaticData (byte [] data)
676 if (impl_details_class == null){
677 impl_details_class = CodeGen.Module.Builder.DefineType (
678 "<PrivateImplementationDetails>",
679 TypeAttributes.NotPublic,
680 TypeManager.object_type);
682 RegisterCompilerGeneratedType (impl_details_class);
685 fb = impl_details_class.DefineInitializedData (
686 "$$field-" + (field_count++), data,
687 FieldAttributes.Static | FieldAttributes.Assembly);