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 = true;
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 = 3;
68 public static Target Target = Target.Exe;
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 = LanguageVersion.Default;
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 = false;
89 // If set, enable XML documentation generation
91 public static Documentation Documentation;
99 type_container_resolve_order = new ArrayList ();
102 public static bool NeedsEntryPoint {
104 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
108 static public Tree Tree {
114 static public string MainClass;
116 public static void RegisterOrder (TypeContainer tc)
118 type_container_resolve_order.Add (tc);
122 // The default compiler checked state
124 static public bool Checked = false;
127 // Whether to allow Unsafe code
129 static public bool Unsafe = false;
131 static string MakeFQN (string nsn, string name)
135 return String.Concat (nsn, ".", name);
139 // This function is used to resolve the hierarchy tree.
140 // It processes interfaces, structs and classes in that order.
142 // It creates the TypeBuilder's as it processes the user defined
145 static public void ResolveTree ()
148 // Interfaces are processed next, as classes and
149 // structs might inherit from an object or implement
150 // a set of interfaces, we need to be able to tell
151 // them appart by just using the TypeManager.
153 TypeContainer root = Tree.Types;
155 ArrayList ifaces = root.Interfaces;
157 foreach (Interface i in ifaces)
161 foreach (TypeContainer tc in root.Types)
164 if (root.Delegates != null)
165 foreach (Delegate d in root.Delegates)
168 if (root.Enums != null)
169 foreach (Enum e in root.Enums)
173 static void Error_TypeConflict (string name, Location loc)
176 520, loc, "`" + name + "' conflicts with a predefined type");
179 static void Error_TypeConflict (string name)
182 520, "`" + name + "' conflicts with a predefined type");
186 // Resolves a single class during the corlib bootstrap process
188 static TypeBuilder BootstrapCorlib_ResolveClass (TypeContainer root, string name)
190 object o = root.GetDefinition (name);
192 Report.Error (518, "The predefined type `" + name + "' is not defined");
198 DeclSpace d = (DeclSpace) o;
200 Error_TypeConflict (name, d.Location);
202 Error_TypeConflict (name);
207 return ((DeclSpace) o).DefineType ();
211 // Resolves a struct during the corlib bootstrap process
213 static void BootstrapCorlib_ResolveStruct (TypeContainer root, string name)
215 object o = root.GetDefinition (name);
217 Report.Error (518, "The predefined type `" + name + "' is not defined");
223 DeclSpace d = (DeclSpace) o;
225 Error_TypeConflict (name, d.Location);
227 Error_TypeConflict (name);
232 ((DeclSpace) o).DefineType ();
236 // Resolves a struct during the corlib bootstrap process
238 static void BootstrapCorlib_ResolveInterface (TypeContainer root, string name)
240 object o = root.GetDefinition (name);
242 Report.Error (518, "The predefined type `" + name + "' is not defined");
246 if (!(o is Interface)){
248 DeclSpace d = (DeclSpace) o;
250 Error_TypeConflict (name, d.Location);
252 Error_TypeConflict (name);
257 ((DeclSpace) o).DefineType ();
261 // Resolves a delegate during the corlib bootstrap process
263 static void BootstrapCorlib_ResolveDelegate (TypeContainer root, string name)
265 object o = root.GetDefinition (name);
267 Report.Error (518, "The predefined type `" + name + "' is not defined");
268 Environment.Exit (1);
271 if (!(o is Delegate)){
272 Error_TypeConflict (name);
276 ((DeclSpace) o).DefineType ();
281 /// Resolves the core types in the compiler when compiling with --nostdlib
283 static public void ResolveCore ()
285 TypeContainer root = Tree.Types;
287 TypeManager.object_type = BootstrapCorlib_ResolveClass (root, "System.Object");
288 TypeManager.value_type = BootstrapCorlib_ResolveClass (root, "System.ValueType");
289 TypeManager.attribute_type = BootstrapCorlib_ResolveClass (root, "System.Attribute");
290 TypeManager.indexer_name_type = BootstrapCorlib_ResolveClass (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
292 string [] interfaces_first_stage = {
293 "System.IComparable", "System.ICloneable",
294 "System.IConvertible",
296 "System.Collections.IEnumerable",
297 "System.Collections.ICollection",
298 "System.Collections.IEnumerator",
299 "System.Collections.IList",
300 "System.IAsyncResult",
301 "System.IDisposable",
303 "System.Runtime.Serialization.ISerializable",
304 "System.Runtime.InteropServices._Exception",
306 "System.Reflection.IReflect",
307 "System.Reflection.ICustomAttributeProvider",
312 "System.Collections.Generic.IEnumerator`1",
313 "System.Collections.Generic.IEnumerable`1",
316 foreach (string iname in interfaces_first_stage)
317 BootstrapCorlib_ResolveInterface (root, iname);
320 // These are the base value types
322 string [] structs_first_stage = {
323 "System.Byte", "System.SByte",
324 "System.Int16", "System.UInt16",
325 "System.Int32", "System.UInt32",
326 "System.Int64", "System.UInt64",
329 foreach (string cname in structs_first_stage)
330 BootstrapCorlib_ResolveStruct (root, cname);
333 // Now, we can load the enumerations, after this point,
336 TypeManager.InitEnumUnderlyingTypes ();
338 string [] structs_second_stage = {
339 "System.Single", "System.Double",
340 "System.Char", "System.Boolean",
341 "System.Decimal", "System.Void",
342 "System.RuntimeFieldHandle",
343 "System.RuntimeArgumentHandle",
344 "System.RuntimeTypeHandle",
346 "System.TypedReference",
350 foreach (string cname in structs_second_stage)
351 BootstrapCorlib_ResolveStruct (root, cname);
354 // These are classes that depends on the core interfaces
356 string [] classes_second_stage = {
360 "System.Reflection.MemberInfo",
366 // These are not really important in the order, but they
367 // are used by the compiler later on (typemanager/CoreLookupType-d)
369 "System.Runtime.CompilerServices.RuntimeHelpers",
370 "System.Reflection.DefaultMemberAttribute",
371 "System.Threading.Monitor",
373 "System.AttributeUsageAttribute",
374 "System.Runtime.InteropServices.DllImportAttribute",
375 "System.Runtime.CompilerServices.MethodImplAttribute",
376 "System.Runtime.InteropServices.MarshalAsAttribute",
377 "System.Runtime.CompilerServices.NewConstraintAttribute",
378 "System.Runtime.CompilerServices.CompilerGeneratedAttribute",
379 "System.Runtime.CompilerServices.FixedBufferAttribute",
380 "System.Diagnostics.ConditionalAttribute",
381 "System.ObsoleteAttribute",
382 "System.ParamArrayAttribute",
383 "System.CLSCompliantAttribute",
384 "System.Security.UnverifiableCodeAttribute",
385 "System.Security.Permissions.SecurityAttribute",
386 "System.Runtime.CompilerServices.DecimalConstantAttribute",
387 "System.Runtime.InteropServices.InAttribute",
388 "System.Runtime.InteropServices.OutAttribute",
389 "System.Runtime.InteropServices.StructLayoutAttribute",
390 "System.Runtime.InteropServices.FieldOffsetAttribute",
391 "System.InvalidOperationException",
392 "System.NotSupportedException",
393 "System.MarshalByRefObject",
394 "System.Security.CodeAccessPermission"
397 foreach (string cname in classes_second_stage)
398 BootstrapCorlib_ResolveClass (root, cname);
400 BootstrapCorlib_ResolveStruct (root, "System.Nullable`1");
402 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
404 // These will be defined indirectly during the previous ResolveDelegate.
405 // However make sure the rest of the checks happen.
406 string [] delegate_types = { "System.Delegate", "System.MulticastDelegate" };
407 foreach (string cname in delegate_types)
408 BootstrapCorlib_ResolveClass (root, cname);
412 // Closes all open types
416 // We usually use TypeBuilder types. When we are done
417 // creating the type (which will happen after we have added
418 // methods, fields, etc) we need to "Define" them before we
419 // can save the Assembly
421 static public void CloseTypes ()
423 TypeContainer root = Tree.Types;
425 if (root.Enums != null)
426 foreach (Enum en in root.Enums)
430 // We do this in two passes, first we close the structs,
431 // then the classes, because it seems the code needs it this
432 // way. If this is really what is going on, we should probably
433 // make sure that we define the structs in order as well.
435 foreach (TypeContainer tc in type_container_resolve_order){
436 if (tc.Kind == Kind.Struct && tc.Parent == tree.Types){
441 foreach (TypeContainer tc in type_container_resolve_order){
442 if (!(tc.Kind == Kind.Struct && tc.Parent == tree.Types))
446 if (root.Delegates != null)
447 foreach (Delegate d in root.Delegates)
452 // If we have a <PrivateImplementationDetails> class, close it
454 if (helper_classes != null){
455 foreach (TypeBuilder type_builder in helper_classes) {
456 type_builder.SetCustomAttribute (TypeManager.compiler_generated_attr);
457 type_builder.CreateType ();
461 type_container_resolve_order = null;
462 helper_classes = null;
464 TypeManager.CleanUp ();
468 /// Used to register classes that need to be closed after all the
469 /// user defined classes
471 public static void RegisterCompilerGeneratedType (TypeBuilder helper_class)
473 if (helper_classes == null)
474 helper_classes = new ArrayList ();
476 helper_classes.Add (helper_class);
479 static void Report1530 (Location loc)
481 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
484 static public void PopulateCoreType (TypeContainer root, string name)
486 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
488 ds.DefineMembers (root);
492 static public void BootCorlib_PopulateCoreTypes ()
494 TypeContainer root = tree.Types;
496 PopulateCoreType (root, "System.Object");
497 PopulateCoreType (root, "System.ValueType");
498 PopulateCoreType (root, "System.Attribute");
499 PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
503 // Populates the structs and classes with fields and methods
506 // This is invoked after all interfaces, structs and classes
507 // have been defined through `ResolveTree'
508 static public void PopulateTypes ()
510 TypeContainer root = Tree.Types;
512 if (type_container_resolve_order != null){
513 if (RootContext.StdLib){
514 foreach (TypeContainer tc in type_container_resolve_order)
515 tc.DefineMembers (root);
517 foreach (TypeContainer tc in type_container_resolve_order) {
518 // When compiling corlib, these types have already been
519 // populated from BootCorlib_PopulateCoreTypes ().
520 if (((tc.Name == "System.Object") ||
521 (tc.Name == "System.Attribute") ||
522 (tc.Name == "System.ValueType") ||
523 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
526 tc.DefineMembers (root);
531 ArrayList delegates = root.Delegates;
532 if (delegates != null){
533 foreach (Delegate d in delegates)
534 if ((d.ModFlags & Modifiers.NEW) == 0)
535 d.DefineMembers (root);
537 Report1530 (d.Location);
540 ArrayList enums = root.Enums;
542 foreach (Enum en in enums)
543 if ((en.ModFlags & Modifiers.NEW) == 0)
544 en.DefineMembers (root);
546 Report1530 (en.Location);
550 // Check for cycles in the struct layout
552 if (type_container_resolve_order != null){
553 Hashtable seen = new Hashtable ();
554 foreach (TypeContainer tc in type_container_resolve_order)
555 TypeManager.CheckStructCycles (tc, seen);
560 // A generic hook delegate
562 public delegate void Hook ();
565 // A hook invoked when the code has been generated.
567 public static event Hook EmitCodeHook;
570 // DefineTypes is used to fill in the members of each type.
572 static public void DefineTypes ()
574 TypeContainer root = Tree.Types;
576 if (type_container_resolve_order != null){
577 foreach (TypeContainer tc in type_container_resolve_order) {
578 // When compiling corlib, these types have already been
579 // populated from BootCorlib_PopulateCoreTypes ().
580 if (!RootContext.StdLib &&
581 ((tc.Name == "System.Object") ||
582 (tc.Name == "System.Attribute") ||
583 (tc.Name == "System.ValueType") ||
584 (tc.Name == "System.Runtime.CompilerServices.IndexerNameAttribute")))
587 if ((tc.ModFlags & Modifiers.NEW) == 0)
592 ArrayList delegates = root.Delegates;
593 if (delegates != null){
594 foreach (Delegate d in delegates)
595 if ((d.ModFlags & Modifiers.NEW) == 0)
599 ArrayList enums = root.Enums;
601 foreach (Enum en in enums)
602 if ((en.ModFlags & Modifiers.NEW) == 0)
607 static public void EmitCode ()
609 if (Tree.Types.Enums != null) {
610 foreach (Enum e in Tree.Types.Enums)
614 if (type_container_resolve_order != null) {
615 foreach (TypeContainer tc in type_container_resolve_order)
619 if (Tree.Types.Delegates != null) {
620 foreach (Delegate d in Tree.Types.Delegates)
624 // Run any hooks after all the types have been defined.
625 // This is used to create nested auxiliary classes for example
628 if (EmitCodeHook != null)
631 CodeGen.Assembly.Emit (Tree.Types);
632 CodeGen.Module.Emit (Tree.Types);
636 // Public Field, used to track which method is the public entry
639 static public MethodInfo EntryPoint;
642 // Track the location of the entry point.
644 static public Location EntryPointLocation;
647 // These are used to generate unique names on the structs and fields.
649 static int field_count;
652 // Makes an initialized struct, returns the field builder that
653 // references the data. Thanks go to Sergey Chaban for researching
654 // how to do this. And coming up with a shorter mechanism than I
655 // was able to figure out.
657 // This works but makes an implicit public struct $ArrayType$SIZE and
658 // makes the fields point to it. We could get more control if we did
661 // 1. DefineNestedType on the impl_details_class with our struct.
663 // 2. Define the field on the impl_details_class
665 static public FieldBuilder MakeStaticData (byte [] data)
669 if (impl_details_class == null){
670 impl_details_class = CodeGen.Module.Builder.DefineType (
671 "<PrivateImplementationDetails>",
672 TypeAttributes.NotPublic,
673 TypeManager.object_type);
675 RegisterCompilerGeneratedType (impl_details_class);
678 fb = impl_details_class.DefineInitializedData (
679 "$$field-" + (field_count++), data,
680 FieldAttributes.Static | FieldAttributes.Assembly);