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 = true;
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 = 3;
67 public static Target Target = Target.Exe;
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 = LanguageVersion.Default;
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 = false;
88 // If set, enable XML documentation generation
90 public static Documentation Documentation;
98 type_container_resolve_order = new ArrayList ();
101 public static bool NeedsEntryPoint {
103 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
107 static public Tree Tree {
113 static public string MainClass;
115 public static void RegisterOrder (TypeContainer tc)
117 type_container_resolve_order.Add (tc);
121 // The default compiler checked state
123 static public bool Checked = false;
126 // Whether to allow Unsafe code
128 static public bool Unsafe = false;
130 static string MakeFQN (string nsn, string name)
134 return String.Concat (nsn, ".", name);
138 // This function is used to resolve the hierarchy tree.
139 // It processes interfaces, structs and classes in that order.
141 // It creates the TypeBuilder's as it processes the user defined
144 static public void ResolveTree ()
147 // Interfaces are processed next, as classes and
148 // structs might inherit from an object or implement
149 // a set of interfaces, we need to be able to tell
150 // them appart by just using the TypeManager.
152 TypeContainer root = Tree.Types;
154 ArrayList ifaces = root.Interfaces;
156 foreach (Interface i in ifaces)
160 foreach (TypeContainer tc in root.Types)
163 if (root.Delegates != null)
164 foreach (Delegate d in root.Delegates)
167 if (root.Enums != null)
168 foreach (Enum e in root.Enums)
172 static void Error_TypeConflict (string name, Location loc)
175 520, loc, "`" + name + "' conflicts with a predefined type");
178 static void Error_TypeConflict (string name)
181 520, "`" + name + "' conflicts with a predefined type");
185 // Resolves a single class during the corlib bootstrap process
187 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
189 object o = root.GetDefinition (name);
191 Report.Error (518, "The predefined type `" + name + "' is not defined");
197 DeclSpace d = (DeclSpace) o;
199 Error_TypeConflict (name, d.Location);
201 Error_TypeConflict (name);
206 return ((DeclSpace) o).DefineType ();
210 // Resolves a struct during the corlib bootstrap process
212 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
214 object o = root.GetDefinition (name);
216 Report.Error (518, "The predefined type `" + name + "' is not defined");
222 DeclSpace d = (DeclSpace) o;
224 Error_TypeConflict (name, d.Location);
226 Error_TypeConflict (name);
231 ((DeclSpace) o).DefineType ();
235 // Resolves a struct during the corlib bootstrap process
237 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
239 object o = root.GetDefinition (name);
241 Report.Error (518, "The predefined type `" + name + "' is not defined");
245 if (!(o is Interface)){
247 DeclSpace d = (DeclSpace) o;
249 Error_TypeConflict (name, d.Location);
251 Error_TypeConflict (name);
256 ((DeclSpace) o).DefineType ();
260 // Resolves a delegate during the corlib bootstrap process
262 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
264 object o = root.GetDefinition (name);
266 Report.Error (518, "The predefined type `" + name + "' is not defined");
267 Environment.Exit (1);
270 if (!(o is Delegate)){
271 Error_TypeConflict (name);
275 ((DeclSpace) o).DefineType ();
280 /// Resolves the core types in the compiler when compiling with --nostdlib
282 static public void ResolveCore ()
284 TypeContainer root = Tree.Types;
286 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
287 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
288 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
289 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
291 string [] interfaces_first_stage = {
292 "System.IComparable", "System.ICloneable",
293 "System.IConvertible",
295 "System.Collections.IEnumerable",
296 "System.Collections.ICollection",
297 "System.Collections.IEnumerator",
298 "System.Collections.IList",
299 "System.IAsyncResult",
300 "System.IDisposable",
302 "System.Runtime.Serialization.ISerializable",
304 "System.Reflection.IReflect",
305 "System.Reflection.ICustomAttributeProvider"
308 foreach (string iname in interfaces_first_stage)
309 BootstrapCorlib_ResolveInterface (root, iname);
312 // These are the base value types
314 string [] structs_first_stage = {
315 "System.Byte", "System.SByte",
316 "System.Int16", "System.UInt16",
317 "System.Int32", "System.UInt32",
318 "System.Int64", "System.UInt64",
321 foreach (string cname in structs_first_stage)
322 BootstrapCorlib_ResolveStruct (root, cname);
325 // Now, we can load the enumerations, after this point,
328 TypeManager.InitEnumUnderlyingTypes ();
330 string [] structs_second_stage = {
331 "System.Single", "System.Double",
332 "System.Char", "System.Boolean",
333 "System.Decimal", "System.Void",
334 "System.RuntimeFieldHandle",
335 "System.RuntimeArgumentHandle",
336 "System.RuntimeTypeHandle",
338 "System.TypedReference",
342 foreach (string cname in structs_second_stage)
343 BootstrapCorlib_ResolveStruct (root, cname);
346 // These are classes that depends on the core interfaces
348 string [] classes_second_stage = {
352 "System.Reflection.MemberInfo",
357 // These are not really important in the order, but they
358 // are used by the compiler later on (typemanager/CoreLookupType-d)
360 "System.Runtime.CompilerServices.RuntimeHelpers",
361 "System.Reflection.DefaultMemberAttribute",
362 "System.Threading.Monitor",
364 "System.AttributeUsageAttribute",
365 "System.Runtime.InteropServices.DllImportAttribute",
366 "System.Runtime.CompilerServices.MethodImplAttribute",
367 "System.Runtime.InteropServices.MarshalAsAttribute",
368 "System.Diagnostics.ConditionalAttribute",
369 "System.ObsoleteAttribute",
370 "System.ParamArrayAttribute",
371 "System.CLSCompliantAttribute",
372 "System.Security.UnverifiableCodeAttribute",
373 "System.Security.Permissions.SecurityAttribute",
374 "System.Runtime.CompilerServices.DecimalConstantAttribute",
375 "System.Runtime.InteropServices.InAttribute",
376 "System.Runtime.InteropServices.OutAttribute",
377 "System.Runtime.InteropServices.StructLayoutAttribute",
378 "System.Runtime.InteropServices.FieldOffsetAttribute",
379 "System.InvalidOperationException",
380 "System.NotSupportedException",
381 "System.MarshalByRefObject",
382 "System.Security.CodeAccessPermission"
385 foreach (string cname in classes_second_stage)
386 BootstrapCorlib_ResolveClass (root, cname);
388 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
390 // These will be defined indirectly during the previous ResolveDelegate.
391 // However make sure the rest of the checks happen.
392 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
393 foreach (string cname in delegate_types)
394 BootstrapCorlib_ResolveClass (root, cname);
398 // Closes all open types
402 // We usually use TypeBuilder types. When we are done
403 // creating the type (which will happen after we have added
404 // methods, fields, etc) we need to "Define" them before we
405 // can save the Assembly
407 static public void CloseTypes ()
409 TypeContainer root = Tree.Types;
411 if (root.Enums != null)
412 foreach (Enum en in root.Enums)
416 // We do this in two passes, first we close the structs,
417 // then the classes, because it seems the code needs it this
418 // way. If this is really what is going on, we should probably
419 // make sure that we define the structs in order as well.
421 foreach (TypeContainer tc in type_container_resolve_order){
422 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
427 foreach (TypeContainer tc in type_container_resolve_order){
428 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
432 if (root.Delegates != null)
433 foreach (Delegate d in root.Delegates)
438 // If we have a <PrivateImplementationDetails> class, close it
440 if (helper_classes != null){
441 foreach (TypeBuilder type_builder in helper_classes) {
443 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
445 type_builder.CreateType ();
449 type_container_resolve_order = null;
450 helper_classes = null;
452 TypeManager.CleanUp ();
456 /// Used to register classes that need to be closed after all the
457 /// user defined classes
459 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
461 if (helper_classes == null)
462 helper_classes = new ArrayList ();
464 helper_classes.Add (helper_class);
467 static void Report1530 (Location loc)
469 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
472 static public void PopulateCoreType (TypeContainer root, string name)
474 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
476 ds.DefineMembers (root);
480 static public void BootCorlib_PopulateCoreTypes ()
482 TypeContainer root = tree.Types;
484 PopulateCoreType (root, "System.Object");
485 PopulateCoreType (root, "System.ValueType");
486 PopulateCoreType (root, "System.Attribute");
487 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
491 // Populates the structs and classes with fields and methods
494 // This is invoked after all interfaces, structs and classes
495 // have been defined through `ResolveTree'
496 static public void PopulateTypes ()
498 TypeContainer root = Tree.Types;
500 if (type_container_resolve_order != null){
501 if (RootContext.StdLib){
502 foreach (TypeContainer tc in type_container_resolve_order)
503 tc.DefineMembers (root);
505 foreach (TypeContainer tc in type_container_resolve_order) {
506 // When compiling corlib, these types have already been
507 // populated from BootCorlib_PopulateCoreTypes ().
508 if (((tc.Name == "System.Object") ||
509 (tc.Name == "System.Attribute") ||
510 (tc.Name == "System.ValueType") ||
511 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
514 tc.DefineMembers (root);
519 ArrayList delegates = root.Delegates;
520 if (delegates != null){
521 foreach (Delegate d in delegates)
522 if ((d.ModFlags & Modifiers.NEW) == 0)
523 d.DefineMembers (root);
525 Report1530 (d.Location);
528 ArrayList enums = root.Enums;
530 foreach (Enum en in enums)
531 if ((en.ModFlags & Modifiers.NEW) == 0)
532 en.DefineMembers (root);
534 Report1530 (en.Location);
538 // Check for cycles in the struct layout
540 if (type_container_resolve_order != null){
541 Hashtable seen = new Hashtable ();
542 foreach (TypeContainer tc in type_container_resolve_order)
543 TypeManager.CheckStructCycles (tc, seen);
548 // A generic hook delegate
550 public delegate void Hook ();
553 // A hook invoked when the code has been generated.
555 public static event Hook EmitCodeHook;
558 // DefineTypes is used to fill in the members of each type.
560 static public void DefineTypes ()
562 TypeContainer root = Tree.Types;
564 if (type_container_resolve_order != null){
565 foreach (TypeContainer tc in type_container_resolve_order) {
566 // When compiling corlib, these types have already been
567 // populated from BootCorlib_PopulateCoreTypes ().
568 if (!RootContext.StdLib &&
569 ((tc.Name == "System.Object") ||
570 (tc.Name == "System.Attribute") ||
571 (tc.Name == "System.ValueType") ||
572 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
575 if ((tc.ModFlags & Modifiers.NEW) == 0)
580 ArrayList delegates = root.Delegates;
581 if (delegates != null){
582 foreach (Delegate d in delegates)
583 if ((d.ModFlags & Modifiers.NEW) == 0)
587 ArrayList enums = root.Enums;
589 foreach (Enum en in enums)
590 if ((en.ModFlags & Modifiers.NEW) == 0)
595 static public void EmitCode ()
597 if (Tree.Types.Enums != null) {
598 foreach (Enum e in Tree.Types.Enums)
602 if (type_container_resolve_order != null) {
603 foreach (TypeContainer tc in type_container_resolve_order)
607 if (Tree.Types.Delegates != null) {
608 foreach (Delegate d in Tree.Types.Delegates)
612 // Run any hooks after all the types have been defined.
613 // This is used to create nested auxiliary classes for example
616 if (EmitCodeHook != null)
619 CodeGen.Assembly.Emit (Tree.Types);
620 CodeGen.Module.Emit (Tree.Types);
624 // Public Field, used to track which method is the public entry
627 static public MethodInfo EntryPoint;
630 // Track the location of the entry point.
632 static public Location EntryPointLocation;
635 // These are used to generate unique names on the structs and fields.
637 static int field_count;
640 // Makes an initialized struct, returns the field builder that
641 // references the data. Thanks go to Sergey Chaban for researching
642 // how to do this. And coming up with a shorter mechanism than I
643 // was able to figure out.
645 // This works but makes an implicit public struct $ArrayType$SIZE and
646 // makes the fields point to it. We could get more control if we did
649 // 1. DefineNestedType on the impl_details_class with our struct.
651 // 2. Define the field on the impl_details_class
653 static public FieldBuilder MakeStaticData (byte [] data)
657 if (impl_details_class == null){
658 impl_details_class = CodeGen.Module.Builder.DefineType (
659 "<PrivateImplementationDetails>",
660 TypeAttributes.NotPublic,
661 TypeManager.object_type);
663 RegisterCompilerGeneratedType (impl_details_class);
666 fb = impl_details_class.DefineInitializedData (
667 "$$field-" + (field_count++), data,
668 FieldAttributes.Static | FieldAttributes.Assembly);