2 // roottypes.cs: keeps a tree representation of the generated code
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Marek Safar (marek.safar@gmail.com)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2003-2008 Novell, Inc.
14 using System.Collections.Generic;
15 using System.Runtime.InteropServices;
16 using Mono.CompilerServices.SymbolWriter;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using System.Reflection;
23 using System.Reflection.Emit;
29 // Module (top-level type) container
31 public class ModuleContainer : TypeContainer
35 // Compiler generated container for static data
37 sealed class StaticDataContainer : CompilerGeneratedClass
39 Dictionary<int, Struct> size_types;
42 public StaticDataContainer (ModuleContainer module)
43 : base (module, new MemberName ("<PrivateImplementationDetails>" + module.builder.ModuleVersionId.ToString ("B"), Location.Null), Modifiers.STATIC)
45 size_types = new Dictionary<int, Struct> ();
48 public override void CloseType ()
52 foreach (var entry in size_types) {
53 entry.Value.CloseType ();
57 public FieldSpec DefineInitializedData (byte[] data, Location loc)
60 if (!size_types.TryGetValue (data.Length, out size_type)) {
62 // Build common type for this data length. We cannot use
63 // DefineInitializedData because it creates public type,
64 // and its name is not unique among modules
66 size_type = new Struct (null, this, new MemberName ("$ArrayType=" + data.Length, Location), Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED, null);
67 size_type.CreateType ();
68 size_type.DefineType ();
70 size_types.Add (data.Length, size_type);
72 var pa = Module.PredefinedAttributes.StructLayout;
73 if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.short_type)) {
74 var argsEncoded = new AttributeEncoder ();
75 argsEncoded.Encode ((short) LayoutKind.Explicit);
77 var field_size = pa.GetField ("Size", TypeManager.int32_type, Location);
78 var pack = pa.GetField ("Pack", TypeManager.int32_type, Location);
79 if (field_size != null) {
80 argsEncoded.EncodeNamedArguments (
81 new[] { field_size, pack },
82 new[] { new IntConstant ((int) data.Length, Location), new IntConstant (1, Location) }
86 pa.EmitAttribute (size_type.TypeBuilder, argsEncoded);
90 var name = "$field-" + fields.ToString ("X");
92 const Modifiers fmod = Modifiers.STATIC | Modifiers.INTERNAL;
93 var fbuilder = TypeBuilder.DefineField (name, size_type.CurrentType.GetMetaInfo (), ModifiersExtensions.FieldAttr (fmod) | FieldAttributes.HasFieldRVA);
94 fbuilder.__SetDataAndRVA (data);
96 return new FieldSpec (CurrentType, null, size_type.CurrentType, fbuilder, fmod);
100 StaticDataContainer static_data;
103 // Makes const data field inside internal type container
105 public FieldSpec MakeStaticData (byte[] data, Location loc)
107 if (static_data == null) {
108 static_data = new StaticDataContainer (this);
109 static_data.CreateType ();
110 static_data.DefineType ();
112 AddCompilerGeneratedClass (static_data);
115 return static_data.DefineInitializedData (data, loc);
119 public CharSet? DefaultCharSet;
120 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
122 Dictionary<int, List<AnonymousTypeClass>> anonymous_types;
124 AssemblyDefinition assembly;
125 readonly CompilerContext context;
126 readonly RootNamespace global_ns;
127 Dictionary<string, RootNamespace> alias_ns;
129 ModuleBuilder builder;
131 bool has_extenstion_method;
133 PredefinedAttributes predefined_attributes;
134 PredefinedTypes predefined_types;
136 static readonly string[] attribute_targets = new string[] { "assembly", "module" };
138 public ModuleContainer (CompilerContext context)
139 : base (null, null, MemberName.Null, null, 0)
141 this.context = context;
143 caching_flags &= ~(Flags.Obsolete_Undetected | Flags.Excluded_Undetected);
145 types = new List<TypeContainer> ();
146 anonymous_types = new Dictionary<int, List<AnonymousTypeClass>> ();
147 global_ns = new GlobalRootNamespace ();
148 alias_ns = new Dictionary<string, RootNamespace> ();
153 public override AttributeTargets AttributeTargets {
155 return AttributeTargets.Assembly;
159 public ModuleBuilder Builder {
165 public override CompilerContext Compiler {
171 public override AssemblyDefinition DeclaringAssembly {
177 public bool HasDefaultCharSet {
179 return DefaultCharSet.HasValue;
183 public bool HasExtensionMethod {
185 return has_extenstion_method;
188 has_extenstion_method = value;
193 // Returns module global:: namespace
195 public RootNamespace GlobalRootNamespace {
201 public override ModuleContainer Module {
207 internal PredefinedAttributes PredefinedAttributes {
209 return predefined_attributes;
213 internal PredefinedTypes PredefinedTypes {
215 return predefined_types;
219 public override string[] ValidAttributeTargets {
221 return attribute_targets;
227 public void AddAnonymousType (AnonymousTypeClass type)
229 List<AnonymousTypeClass> existing;
230 if (!anonymous_types.TryGetValue (type.Parameters.Count, out existing))
231 if (existing == null) {
232 existing = new List<AnonymousTypeClass> ();
233 anonymous_types.Add (type.Parameters.Count, existing);
239 public void AddAttributes (List<Attribute> attrs)
241 AddAttributes (attrs, this);
244 public void AddAttributes (List<Attribute> attrs, IMemberContext context)
246 foreach (Attribute a in attrs)
247 a.AttachTo (this, context);
249 if (attributes == null) {
250 attributes = new Attributes (attrs);
253 attributes.AddAttributes (attrs);
256 public override TypeContainer AddPartial (TypeContainer nextPart)
258 return AddPartial (nextPart, nextPart.Name);
261 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
263 if (a.Target == AttributeTargets.Assembly) {
264 assembly.ApplyAttributeBuilder (a, ctor, cdata, pa);
268 if (a.Type == pa.DefaultCharset) {
269 switch (a.GetCharSetValue ()) {
274 DefaultCharSet = CharSet.Auto;
275 DefaultCharSetType = TypeAttributes.AutoClass;
277 case CharSet.Unicode:
278 DefaultCharSet = CharSet.Unicode;
279 DefaultCharSetType = TypeAttributes.UnicodeClass;
282 Report.Error (1724, a.Location, "Value specified for the argument to `{0}' is not valid",
283 a.GetSignatureForError ());
286 } else if (a.Type == pa.CLSCompliant) {
287 Attribute cls = DeclaringAssembly.CLSCompliantAttribute;
289 Report.Warning (3012, 1, a.Location,
290 "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
291 } else if (DeclaringAssembly.IsCLSCompliant != a.GetBoolean ()) {
292 Report.SymbolRelatedToPreviousError (cls.Location, cls.GetSignatureForError ());
293 Report.Warning (3017, 1, a.Location,
294 "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
299 builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
302 public override void CloseType ()
304 foreach (TypeContainer tc in types) {
308 if (compiler_generated != null)
309 foreach (CompilerGeneratedClass c in compiler_generated)
313 public TypeBuilder CreateBuilder (string name, TypeAttributes attr, int typeSize)
315 return builder.DefineType (name, attr, null, typeSize);
319 // Creates alias global namespace
321 public RootNamespace CreateRootNamespace (string alias)
323 if (alias == global_ns.Alias) {
324 NamespaceEntry.Error_GlobalNamespaceRedefined (Location.Null, Report);
329 if (!alias_ns.TryGetValue (alias, out rn)) {
330 rn = new RootNamespace (alias);
331 alias_ns.Add (alias, rn);
337 public void Create (AssemblyDefinition assembly, ModuleBuilder moduleBuilder)
339 this.assembly = assembly;
340 builder = moduleBuilder;
343 public new void CreateType ()
345 foreach (TypeContainer tc in types)
349 public new void Define ()
351 InitializePredefinedTypes ();
353 foreach (TypeContainer tc in types)
356 foreach (TypeContainer tc in types)
357 tc.ResolveTypeParameters ();
359 foreach (TypeContainer tc in types) {
362 } catch (Exception e) {
363 throw new InternalErrorException (tc, e);
368 public override void Emit ()
370 if (OptAttributes != null)
371 OptAttributes.Emit ();
373 if (RootContext.Unsafe) {
374 var pa = PredefinedAttributes.UnverifiableCode;
376 pa.EmitAttribute (builder);
379 foreach (var tc in types)
380 tc.DefineConstants ();
382 foreach (TypeContainer tc in types)
385 if (Compiler.Report.Errors > 0)
388 foreach (TypeContainer tc in types)
391 if (compiler_generated != null)
392 foreach (var c in compiler_generated)
396 public AnonymousTypeClass GetAnonymousType (IList<AnonymousTypeParameter> parameters)
398 List<AnonymousTypeClass> candidates;
399 if (!anonymous_types.TryGetValue (parameters.Count, out candidates))
403 foreach (AnonymousTypeClass at in candidates) {
404 for (i = 0; i < parameters.Count; ++i) {
405 if (!parameters [i].Equals (at.Parameters [i]))
409 if (i == parameters.Count)
416 public RootNamespace GetRootNamespace (string name)
419 alias_ns.TryGetValue (name, out rn);
423 public override string GetSignatureForError ()
428 public void InitializePredefinedTypes ()
430 predefined_attributes = new PredefinedAttributes (this);
431 predefined_types = new PredefinedTypes (this);
434 public override bool IsClsComplianceRequired ()
436 return DeclaringAssembly.IsCLSCompliant;
439 protected override bool AddMemberType (TypeContainer ds)
441 if (!AddToContainer (ds, ds.Name))
443 ds.NamespaceEntry.NS.AddType (ds.Definition);
447 protected override void RemoveMemberType (DeclSpace ds)
449 ds.NamespaceEntry.NS.RemoveDeclSpace (ds.Basename);
450 base.RemoveMemberType (ds);
453 public Attribute ResolveAssemblyAttribute (PredefinedAttribute a_type)
455 Attribute a = OptAttributes.Search ("assembly", a_type);
462 public void SetDeclaringAssembly (AssemblyDefinition assembly)
464 // TODO: This setter is quite ugly but I have not found a way around it yet
465 this.assembly = assembly;
469 class RootDeclSpace : TypeContainer {
470 public RootDeclSpace (NamespaceEntry ns)
471 : base (ns, null, MemberName.Null, null, 0)
473 PartialContainer = RootContext.ToplevelTypes;
476 public override AttributeTargets AttributeTargets {
477 get { throw new InternalErrorException ("should not be called"); }
480 public override CompilerContext Compiler {
482 return PartialContainer.Compiler;
486 public override string DocCommentHeader {
487 get { throw new InternalErrorException ("should not be called"); }
490 public override void DefineType ()
492 throw new InternalErrorException ("should not be called");
495 public override ModuleContainer Module {
497 return PartialContainer.Module;
501 public override bool IsClsComplianceRequired ()
503 return PartialContainer.IsClsComplianceRequired ();
506 public override FullNamedExpression LookupNamespaceAlias (string name)
508 return NamespaceEntry.LookupNamespaceAlias (name);