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;
120 public static bool NeedsEntryPoint {
122 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
126 static public Tree Tree {
132 public static void RegisterOrder (TypeContainer tc)
134 type_container_resolve_order.Add (tc);
138 // The default compiler checked state
140 static public bool Checked;
143 // Whether to allow Unsafe code
145 static public bool Unsafe;
148 // This function is used to resolve the hierarchy tree.
149 // It processes interfaces, structs and classes in that order.
151 // It creates the TypeBuilder's as it processes the user defined
154 static public void ResolveTree ()
157 // Interfaces are processed next, as classes and
158 // structs might inherit from an object or implement
159 // a set of interfaces, we need to be able to tell
160 // them appart by just using the TypeManager.
162 TypeContainer root = Tree.Types;
164 ArrayList ifaces = root.Interfaces;
166 foreach (Interface i in ifaces)
170 foreach (TypeContainer tc in root.Types)
173 if (root.Delegates != null)
174 foreach (Delegate d in root.Delegates)
177 if (root.Enums != null)
178 foreach (Enum e in root.Enums)
182 static void Error_TypeConflict (string name, Location loc)
185 520, loc, "`" + name + "' conflicts with a predefined type");
188 static void Error_TypeConflict (string name)
191 520, "`" + name + "' conflicts with a predefined type");
195 // Resolves a single class during the corlib bootstrap process
197 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
199 object o = root.GetDefinition (name);
201 Report.Error (518, "The predefined type `" + name + "' is not defined");
207 DeclSpace d = (DeclSpace) o;
209 Error_TypeConflict (name, d.Location);
211 Error_TypeConflict (name);
216 return ((DeclSpace) o).DefineType ();
220 // Resolves a struct during the corlib bootstrap process
222 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
224 object o = root.GetDefinition (name);
226 Report.Error (518, "The predefined type `" + name + "' is not defined");
232 DeclSpace d = (DeclSpace) o;
234 Error_TypeConflict (name, d.Location);
236 Error_TypeConflict (name);
241 ((DeclSpace) o).DefineType ();
245 // Resolves a struct during the corlib bootstrap process
247 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
249 object o = root.GetDefinition (name);
251 Report.Error (518, "The predefined type `" + name + "' is not defined");
255 if (!(o is Interface)){
257 DeclSpace d = (DeclSpace) o;
259 Error_TypeConflict (name, d.Location);
261 Error_TypeConflict (name);
266 ((DeclSpace) o).DefineType ();
270 // Resolves a delegate during the corlib bootstrap process
272 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
274 object o = root.GetDefinition (name);
276 Report.Error (518, "The predefined type `" + name + "' is not defined");
280 if (!(o is Delegate)){
281 Error_TypeConflict (name);
285 ((DeclSpace) o).DefineType ();
290 /// Resolves the core types in the compiler when compiling with --nostdlib
292 static public void ResolveCore ()
294 TypeContainer root = Tree.Types;
296 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
297 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
298 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
299 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
301 string [] interfaces_first_stage = {
302 "System.IComparable", "System.ICloneable",
303 "System.IConvertible",
305 "System.Collections.IEnumerable",
306 "System.Collections.ICollection",
307 "System.Collections.IEnumerator",
308 "System.Collections.IList",
309 "System.IAsyncResult",
310 "System.IDisposable",
312 "System.Runtime.Serialization.ISerializable",
314 "System.Reflection.IReflect",
315 "System.Reflection.ICustomAttributeProvider"
318 foreach (string iname in interfaces_first_stage)
319 BootstrapCorlib_ResolveInterface (root, iname);
322 // These are the base value types
324 string [] structs_first_stage = {
325 "System.Byte", "System.SByte",
326 "System.Int16", "System.UInt16",
327 "System.Int32", "System.UInt32",
328 "System.Int64", "System.UInt64",
331 foreach (string cname in structs_first_stage)
332 BootstrapCorlib_ResolveStruct (root, cname);
335 // Now, we can load the enumerations, after this point,
338 TypeManager.InitEnumUnderlyingTypes ();
340 string [] structs_second_stage = {
341 "System.Single", "System.Double",
342 "System.Char", "System.Boolean",
343 "System.Decimal", "System.Void",
344 "System.RuntimeFieldHandle",
345 "System.RuntimeArgumentHandle",
346 "System.RuntimeTypeHandle",
348 "System.TypedReference",
352 foreach (string cname in structs_second_stage)
353 BootstrapCorlib_ResolveStruct (root, cname);
356 // These are classes that depends on the core interfaces
358 string [] classes_second_stage = {
362 "System.Reflection.MemberInfo",
367 // These are not really important in the order, but they
368 // are used by the compiler later on (typemanager/CoreLookupType-d)
370 "System.Runtime.CompilerServices.RuntimeHelpers",
371 "System.Reflection.DefaultMemberAttribute",
372 "System.Threading.Monitor",
374 "System.AttributeUsageAttribute",
375 "System.Runtime.InteropServices.DllImportAttribute",
376 "System.Runtime.CompilerServices.MethodImplAttribute",
377 "System.Runtime.InteropServices.MarshalAsAttribute",
378 "System.Diagnostics.ConditionalAttribute",
379 "System.ObsoleteAttribute",
380 "System.ParamArrayAttribute",
381 "System.CLSCompliantAttribute",
382 "System.Security.UnverifiableCodeAttribute",
383 "System.Security.Permissions.SecurityAttribute",
384 "System.Runtime.CompilerServices.DecimalConstantAttribute",
385 "System.Runtime.InteropServices.InAttribute",
386 "System.Runtime.InteropServices.OutAttribute",
387 "System.Runtime.InteropServices.StructLayoutAttribute",
388 "System.Runtime.InteropServices.FieldOffsetAttribute",
389 "System.InvalidOperationException",
390 "System.NotSupportedException",
391 "System.MarshalByRefObject",
392 "System.Security.CodeAccessPermission"
395 foreach (string cname in classes_second_stage)
396 BootstrapCorlib_ResolveClass (root, cname);
398 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
400 // These will be defined indirectly during the previous ResolveDelegate.
401 // However make sure the rest of the checks happen.
402 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
403 foreach (string cname in delegate_types)
404 BootstrapCorlib_ResolveClass (root, cname);
408 // Closes all open types
412 // We usually use TypeBuilder types. When we are done
413 // creating the type (which will happen after we have added
414 // methods, fields, etc) we need to "Define" them before we
415 // can save the Assembly
417 static public void CloseTypes ()
419 TypeContainer root = Tree.Types;
421 if (root.Enums != null)
422 foreach (Enum en in root.Enums)
426 // We do this in two passes, first we close the structs,
427 // then the classes, because it seems the code needs it this
428 // way. If this is really what is going on, we should probably
429 // make sure that we define the structs in order as well.
431 foreach (TypeContainer tc in type_container_resolve_order){
432 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
437 foreach (TypeContainer tc in type_container_resolve_order){
438 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
442 if (root.Delegates != null)
443 foreach (Delegate d in root.Delegates)
448 // If we have a <PrivateImplementationDetails> class, close it
450 if (helper_classes != null){
451 foreach (TypeBuilder type_builder in helper_classes) {
453 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
455 type_builder.CreateType ();
459 type_container_resolve_order = null;
460 helper_classes = null;
462 TypeManager.CleanUp ();
466 /// Used to register classes that need to be closed after all the
467 /// user defined classes
469 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
471 if (helper_classes == null)
472 helper_classes = new ArrayList ();
474 helper_classes.Add (helper_class);
477 static void Report1530 (Location loc)
479 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
482 static public void PopulateCoreType (TypeContainer root, string name)
484 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
486 ds.DefineMembers (root);
490 static public void BootCorlib_PopulateCoreTypes ()
492 TypeContainer root = tree.Types;
494 PopulateCoreType (root, "System.Object");
495 PopulateCoreType (root, "System.ValueType");
496 PopulateCoreType (root, "System.Attribute");
497 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
501 // Populates the structs and classes with fields and methods
504 // This is invoked after all interfaces, structs and classes
505 // have been defined through `ResolveTree'
506 static public void PopulateTypes ()
508 TypeContainer root = Tree.Types;
510 if (type_container_resolve_order != null){
511 if (RootContext.StdLib){
512 foreach (TypeContainer tc in type_container_resolve_order)
513 tc.DefineMembers (root);
515 foreach (TypeContainer tc in type_container_resolve_order) {
516 // When compiling corlib, these types have already been
517 // populated from BootCorlib_PopulateCoreTypes ().
518 if (((tc.Name == "System.Object") ||
519 (tc.Name == "System.Attribute") ||
520 (tc.Name == "System.ValueType") ||
521 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
524 tc.DefineMembers (root);
529 ArrayList delegates = root.Delegates;
530 if (delegates != null){
531 foreach (Delegate d in delegates)
532 if ((d.ModFlags & Modifiers.NEW) == 0)
533 d.DefineMembers (root);
535 Report1530 (d.Location);
538 ArrayList enums = root.Enums;
540 foreach (Enum en in enums)
541 if ((en.ModFlags & Modifiers.NEW) == 0)
542 en.DefineMembers (root);
544 Report1530 (en.Location);
548 // Check for cycles in the struct layout
550 if (type_container_resolve_order != null){
551 Hashtable seen = new Hashtable ();
552 foreach (TypeContainer tc in type_container_resolve_order)
553 TypeManager.CheckStructCycles (tc, seen);
558 // A generic hook delegate
560 public delegate void Hook ();
563 // A hook invoked when the code has been generated.
565 public static event Hook EmitCodeHook;
568 // DefineTypes is used to fill in the members of each type.
570 static public void DefineTypes ()
572 TypeContainer root = Tree.Types;
574 if (type_container_resolve_order != null){
575 foreach (TypeContainer tc in type_container_resolve_order) {
576 // When compiling corlib, these types have already been
577 // populated from BootCorlib_PopulateCoreTypes ().
578 if (!RootContext.StdLib &&
579 ((tc.Name == "System.Object") ||
580 (tc.Name == "System.Attribute") ||
581 (tc.Name == "System.ValueType") ||
582 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
585 if ((tc.ModFlags & Modifiers.NEW) == 0)
590 ArrayList delegates = root.Delegates;
591 if (delegates != null){
592 foreach (Delegate d in delegates)
593 if ((d.ModFlags & Modifiers.NEW) == 0)
597 ArrayList enums = root.Enums;
599 foreach (Enum en in enums)
600 if ((en.ModFlags & Modifiers.NEW) == 0)
605 static public void EmitCode ()
607 if (Tree.Types.Enums != null) {
608 foreach (Enum e in Tree.Types.Enums)
612 if (type_container_resolve_order != null) {
613 foreach (TypeContainer tc in type_container_resolve_order)
617 if (Tree.Types.Delegates != null) {
618 foreach (Delegate d in Tree.Types.Delegates)
622 // Run any hooks after all the types have been defined.
623 // This is used to create nested auxiliary classes for example
626 if (EmitCodeHook != null)
629 CodeGen.Assembly.Emit (Tree.Types);
630 CodeGen.Module.Emit (Tree.Types);
634 // Public Field, used to track which method is the public entry
637 static public MethodInfo EntryPoint;
640 // Track the location of the entry point.
642 static public Location EntryPointLocation;
645 // These are used to generate unique names on the structs and fields.
647 static int field_count;
650 // Makes an initialized struct, returns the field builder that
651 // references the data. Thanks go to Sergey Chaban for researching
652 // how to do this. And coming up with a shorter mechanism than I
653 // was able to figure out.
655 // This works but makes an implicit public struct $ArrayType$SIZE and
656 // makes the fields point to it. We could get more control if we did
659 // 1. DefineNestedType on the impl_details_class with our struct.
661 // 2. Define the field on the impl_details_class
663 static public FieldBuilder MakeStaticData (byte [] data)
667 if (impl_details_class == null){
668 impl_details_class = CodeGen.Module.Builder.DefineType (
669 "<PrivateImplementationDetails>",
670 TypeAttributes.NotPublic,
671 TypeManager.object_type);
673 RegisterCompilerGeneratedType (impl_details_class);
676 fb = impl_details_class.DefineInitializedData (
677 "$$field-" + (field_count++), data,
678 FieldAttributes.Static | FieldAttributes.Assembly);