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 parent 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 parent's list of methods which ones are virtual
52 // or abstract as well as the parent names (to implement new,
55 static ArrayList type_container_resolve_order;
56 static ArrayList attribute_types;
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 = 2;
68 public static Target Target = Target.Exe;
69 public static string TargetExt = ".exe";
71 public static bool VerifyClsCompliance = true;
73 public static LanguageVersion Version = LanguageVersion.Default;
76 // We keep strongname related info here because
77 // it's also used as complier options from CSC 8.x
79 public static string StrongNameKeyFile;
80 public static string StrongNameKeyContainer;
81 public static bool StrongNameDelaySign = false;
84 // If set, enable XML documentation generation
86 public static Documentation Documentation;
94 type_container_resolve_order = new ArrayList ();
97 public static bool NeedsEntryPoint {
99 return RootContext.Target == Target.Exe || RootContext.Target == Target.WinExe;
103 static public Tree Tree {
109 static public string MainClass;
111 public static void RegisterOrder (TypeContainer tc)
113 type_container_resolve_order.Add (tc);
116 public static void RegisterAttribute (TypeContainer tc)
118 if (attribute_types == null)
119 attribute_types = new ArrayList ();
121 attribute_types.Add (tc);
125 // The default compiler checked state
127 static public bool Checked = false;
130 // Whether to allow Unsafe code
132 static public bool Unsafe = false;
134 static string MakeFQN (string nsn, string name)
138 return String.Concat (nsn, ".", name);
142 // This function is used to resolve the hierarchy tree.
143 // It processes interfaces, structs and classes in that order.
145 // It creates the TypeBuilder's as it processes the user defined
148 static public void ResolveTree ()
151 // Process the attribute types separately and before anything else
153 if (attribute_types != null)
154 foreach (TypeContainer tc in attribute_types)
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 (Interface 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");
278 Environment.Exit (1);
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");
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 = {
359 "System.Reflection.MemberInfo",
364 // These are not really important in the order, but they
365 // are used by the compiler later on (typemanager/CoreLookupType-d)
367 "System.Runtime.CompilerServices.RuntimeHelpers",
368 "System.Reflection.DefaultMemberAttribute",
369 "System.Threading.Monitor",
371 "System.AttributeUsageAttribute",
372 "System.Runtime.InteropServices.DllImportAttribute",
373 "System.Runtime.CompilerServices.MethodImplAttribute",
374 "System.Runtime.InteropServices.MarshalAsAttribute",
375 "System.Diagnostics.ConditionalAttribute",
376 "System.ObsoleteAttribute",
377 "System.ParamArrayAttribute",
378 "System.CLSCompliantAttribute",
379 "System.Security.UnverifiableCodeAttribute",
380 "System.Security.Permissions.SecurityAttribute",
381 "System.Runtime.CompilerServices.IndexerNameAttribute",
382 "System.Runtime.CompilerServices.DecimalConstantAttribute",
383 "System.Runtime.InteropServices.InAttribute",
384 "System.Runtime.InteropServices.OutAttribute",
385 "System.Runtime.InteropServices.StructLayoutAttribute",
386 "System.Runtime.InteropServices.FieldOffsetAttribute",
387 "System.InvalidOperationException",
388 "System.NotSupportedException",
389 "System.MarshalByRefObject",
390 "System.Security.CodeAccessPermission"
393 // We must store them here before calling BootstrapCorlib_ResolveDelegate.
394 TypeManager.string_type = BootstrapCorlib_ResolveClass (root, "System.String");
395 TypeManager.enum_type = BootstrapCorlib_ResolveClass (root, "System.Enum");
396 TypeManager.array_type = BootstrapCorlib_ResolveClass (root, "System.Array");
397 TypeManager.multicast_delegate_type = BootstrapCorlib_ResolveClass (root, "System.MulticastDelegate");
398 TypeManager.delegate_type = BootstrapCorlib_ResolveClass (root, "System.Delegate");
400 foreach (string cname in classes_second_stage)
401 BootstrapCorlib_ResolveClass (root, cname);
403 BootstrapCorlib_ResolveDelegate (root, "System.AsyncCallback");
407 // Closes all open types
411 // We usually use TypeBuilder types. When we are done
412 // creating the type (which will happen after we have added
413 // methods, fields, etc) we need to "Define" them before we
414 // can save the Assembly
416 static public void CloseTypes ()
418 TypeContainer root = Tree.Types;
420 if (root.Enums != null)
421 foreach (Enum en in root.Enums)
424 if (attribute_types != null)
425 foreach (TypeContainer tc in attribute_types)
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)
455 type_builder.CreateType ();
458 attribute_types = null;
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 RegisterHelperClass (TypeBuilder helper_class)
471 if (helper_classes == null)
472 helper_classes = new ArrayList ();
473 helper_classes.Add (helper_class);
477 // This idea is from Felix Arrese-Igor
479 // Returns : the implicit parent of a composite namespace string
480 // eg. Implicit parent of A.B is A
482 static public string ImplicitParent (string ns)
484 int i = ns.LastIndexOf ('.');
488 return ns.Substring (0, i);
491 static Type NamespaceLookup (DeclSpace ds, string name, Location loc)
493 IAlias result = ds.NamespaceEntry.LookupNamespaceOrType (ds, name, loc);
500 TypeExpr texpr = result.ResolveAsType (ds.EmitContext);
508 // Public function used to locate types, this can only
509 // be used after the ResolveTree function has been invoked.
511 // Returns: Type or null if they type can not be found.
513 // Come to think of it, this should be a DeclSpace
515 static public Type LookupType (DeclSpace ds, string name, bool silent, Location loc)
519 if (ds.Cache.Contains (name)) {
520 t = (Type) ds.Cache [name];
523 // For the case the type we are looking for is nested within this one
524 // or is in any base class
526 DeclSpace containing_ds = ds;
527 while (containing_ds != null){
529 // if the member cache has been created, lets use it.
530 // the member cache is MUCH faster.
531 if (containing_ds.MemberCache != null) {
532 t = containing_ds.MemberCache.FindNestedType (name);
534 containing_ds = containing_ds.Parent;
542 // no member cache. Do it the hard way -- reflection
543 Type current_type = containing_ds.TypeBuilder;
545 while (current_type != null &&
546 current_type != TypeManager.object_type) {
550 t = TypeManager.LookupType (current_type.FullName + "." + name);
556 current_type = current_type.BaseType;
559 containing_ds = containing_ds.Parent;
562 t = NamespaceLookup (ds, name, loc);
563 if (!silent || t != null)
567 if (t == null && !silent)
568 Report.Error (246, loc, "Cannot find type `"+name+"'");
574 // This is the silent version of LookupType, you can use this
575 // to `probe' for a type
577 static public Type LookupType (TypeContainer tc, string name, Location loc)
579 return LookupType (tc, name, true, loc);
582 static void Report1530 (Location loc)
584 Report.Error (1530, loc, "Keyword new not allowed for namespace elements");
587 static public void PopulateCoreType (TypeContainer root, string name)
589 DeclSpace ds = (DeclSpace) root.GetDefinition (name);
591 ds.DefineMembers (root);
595 static public void BootCorlib_PopulateCoreTypes ()
597 TypeContainer root = tree.Types;
599 PopulateCoreType (root, "System.Object");
600 PopulateCoreType (root, "System.ValueType");
601 PopulateCoreType (root, "System.Attribute");
605 // Populates the structs and classes with fields and methods
608 // This is invoked after all interfaces, structs and classes
609 // have been defined through `ResolveTree'
610 static public void PopulateTypes ()
612 TypeContainer root = Tree.Types;
614 if (attribute_types != null)
615 foreach (TypeContainer tc in attribute_types)
616 tc.DefineMembers (root);
618 if (type_container_resolve_order != null){
619 if (RootContext.StdLib){
620 foreach (TypeContainer tc in type_container_resolve_order)
621 tc.DefineMembers (root);
623 foreach (TypeContainer tc in type_container_resolve_order) {
624 // When compiling corlib, these types have already been
625 // populated from BootCorlib_PopulateCoreTypes ().
626 if (((tc.Name == "System.Object") ||
627 (tc.Name == "System.Attribute") ||
628 (tc.Name == "System.ValueType")))
631 tc.DefineMembers (root);
636 ArrayList delegates = root.Delegates;
637 if (delegates != null){
638 foreach (Delegate d in delegates)
639 if ((d.ModFlags & Modifiers.NEW) == 0)
640 d.DefineMembers (root);
642 Report1530 (d.Location);
645 ArrayList enums = root.Enums;
647 foreach (Enum en in enums)
648 if ((en.ModFlags & Modifiers.NEW) == 0)
649 en.DefineMembers (root);
651 Report1530 (en.Location);
655 // Check for cycles in the struct layout
657 if (type_container_resolve_order != null){
658 Hashtable seen = new Hashtable ();
659 foreach (TypeContainer tc in type_container_resolve_order)
660 TypeManager.CheckStructCycles (tc, seen);
665 // A generic hook delegate
667 public delegate void Hook ();
670 // A hook invoked when the code has been generated.
672 public static event Hook EmitCodeHook;
675 // DefineTypes is used to fill in the members of each type.
677 static public void DefineTypes ()
679 TypeContainer root = Tree.Types;
681 if (attribute_types != null)
682 foreach (TypeContainer tc in attribute_types)
685 if (type_container_resolve_order != null){
686 foreach (TypeContainer tc in type_container_resolve_order) {
687 // When compiling corlib, these types have already been
688 // populated from BootCorlib_PopulateCoreTypes ().
689 if (!RootContext.StdLib &&
690 ((tc.Name == "System.Object") ||
691 (tc.Name == "System.Attribute") ||
692 (tc.Name == "System.ValueType")))
695 if ((tc.ModFlags & Modifiers.NEW) == 0)
700 ArrayList delegates = root.Delegates;
701 if (delegates != null){
702 foreach (Delegate d in delegates)
703 if ((d.ModFlags & Modifiers.NEW) == 0)
707 ArrayList enums = root.Enums;
709 foreach (Enum en in enums)
710 if ((en.ModFlags & Modifiers.NEW) == 0)
715 static public void EmitCode ()
717 if (attribute_types != null)
718 foreach (TypeContainer tc in attribute_types)
721 CodeGen.Assembly.Emit (Tree.Types);
722 CodeGen.Module.Emit (Tree.Types);
724 if (Tree.Types.Enums != null) {
725 foreach (Enum e in Tree.Types.Enums)
729 if (type_container_resolve_order != null) {
730 foreach (TypeContainer tc in type_container_resolve_order)
734 if (Tree.Types.Delegates != null) {
735 foreach (Delegate d in Tree.Types.Delegates)
739 // Run any hooks after all the types have been defined.
740 // This is used to create nested auxiliary classes for example
743 if (EmitCodeHook != null)
748 // Public Field, used to track which method is the public entry
751 static public MethodInfo EntryPoint;
754 // Track the location of the entry point.
756 static public Location EntryPointLocation;
759 // These are used to generate unique names on the structs and fields.
761 static int field_count;
764 // Makes an initialized struct, returns the field builder that
765 // references the data. Thanks go to Sergey Chaban for researching
766 // how to do this. And coming up with a shorter mechanism than I
767 // was able to figure out.
769 // This works but makes an implicit public struct $ArrayType$SIZE and
770 // makes the fields point to it. We could get more control if we did
773 // 1. DefineNestedType on the impl_details_class with our struct.
775 // 2. Define the field on the impl_details_class
777 static public FieldBuilder MakeStaticData (byte [] data)
781 if (impl_details_class == null){
782 impl_details_class = CodeGen.Module.Builder.DefineType (
783 "<PrivateImplementationDetails>",
784 TypeAttributes.NotPublic,
785 TypeManager.object_type);
787 RegisterHelperClass (impl_details_class);
790 fb = impl_details_class.DefineInitializedData (
791 "$$field-" + (field_count++), data,
792 FieldAttributes.Static | FieldAttributes.Assembly);