2007-01-03 Chris Toshok <toshok@ximian.com>
[mono.git] / mcs / mcs / enum.cs
1 //
2 // enum.cs: Enum handling.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Ravi Pratap     (ravi@ximian.com)
6 //         Marek Safar     (marek.safar@seznam.cz)
7 //
8 // Licensed under the terms of the GNU GPL
9 //
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
11 //
12
13 using System;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Globalization;
19
20 namespace Mono.CSharp {
21
22         public class EnumMember : MemberCore, IConstant {
23                 static string[] attribute_targets = new string [] { "field" };
24
25                 public FieldBuilder builder;
26
27                 readonly Enum parent_enum;
28                 readonly Expression ValueExpr;
29                 readonly EnumMember prev_member;
30
31                 EnumConstant value;
32                 bool in_transit;
33
34                 // TODO: remove or simplify
35                 EmitContext ec;
36
37                 public EnumMember (Enum parent_enum, EnumMember prev_member, Expression expr,
38                                 MemberName name, Attributes attrs):
39                         base (parent_enum, name, attrs)
40                 {
41                         this.parent_enum = parent_enum;
42                         this.ModFlags = parent_enum.ModFlags;
43                         this.ValueExpr = expr;
44                         this.prev_member = prev_member;
45
46                         ec = new EmitContext (this, parent_enum, parent_enum, Location, null, null, ModFlags, false);
47                         ec.InEnumContext = true;
48                 }
49
50                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
51                 {
52                         if (a.Type == TypeManager.marshal_as_attr_type) {
53                                 UnmanagedMarshal marshal = a.GetMarshal (this);
54                                 if (marshal != null) {
55                                         builder.SetMarshal (marshal);
56                                 }
57                                 return;
58                         }
59
60                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
61                                 a.Error_InvalidSecurityParent ();
62                                 return;
63                         }
64
65                         builder.SetCustomAttribute (cb);
66                 }
67
68                 public override AttributeTargets AttributeTargets {
69                         get {
70                                 return AttributeTargets.Field;
71                         }
72                 }
73
74                 static bool IsValidEnumType (Type t)
75                 {
76                         return (t == TypeManager.int32_type || t == TypeManager.uint32_type || t == TypeManager.int64_type ||
77                                 t == TypeManager.byte_type || t == TypeManager.sbyte_type || t == TypeManager.short_type ||
78                                 t == TypeManager.ushort_type || t == TypeManager.uint64_type || t == TypeManager.char_type ||
79                                 t.IsEnum);
80                 }
81         
82                 public override bool Define ()
83                 {
84                         const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal;
85                         TypeBuilder tb = parent_enum.TypeBuilder;
86                         builder = tb.DefineField (Name, tb, attr);
87                         ec.ContainerType = tb;
88
89                         TypeManager.RegisterConstant (builder, this);
90                         return true;
91                 }
92
93                 // Because parent is TypeContainer and we have DeclSpace only
94                 public override void CheckObsoleteness (Location loc)
95                 {
96                         parent_enum.CheckObsoleteness (loc);
97
98                         ObsoleteAttribute oa = GetObsoleteAttribute ();
99                         if (oa == null) {
100                                 return;
101                         }
102
103                         AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
104                 }
105
106                 public bool ResolveValue ()
107                 {
108                         if (value != null)
109                                 return true;
110
111                         if (in_transit) {
112                                 Const.Error_CyclicDeclaration (this);
113                                 return false;
114                         }
115
116                         if (ValueExpr != null) {
117                                 in_transit = true;
118                                 Constant c = ValueExpr.ResolveAsConstant (ec, this);
119                                 in_transit = false;
120
121                                 if (c == null)
122                                         return false;
123
124                                 if (c is EnumConstant)
125                                         c = ((EnumConstant)c).Child;
126                                         
127                                 c = c.ImplicitConversionRequired (parent_enum.UnderlyingType, Location);
128                                 if (c == null)
129                                         return false;
130
131                                 if (!IsValidEnumType (c.Type)) {
132                                         Report.Error (1008, Location, "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
133                                         return false;
134                                 }
135
136                                 in_transit = false;
137                                 value = new EnumConstant (c, parent_enum.TypeBuilder);
138                                 return true;
139                         }
140
141                         if (prev_member == null) {
142                                 value = new EnumConstant (New.Constantify (parent_enum.UnderlyingType), parent_enum.TypeBuilder);
143                                 return true;
144                         }
145
146                         if (!prev_member.ResolveValue ()) {
147                                 // Suppress cyclic error
148                                 prev_member.value = new EnumConstant (New.Constantify (parent_enum.UnderlyingType), parent_enum.TypeBuilder);
149                                 return false;
150                         }
151
152                         in_transit = true;
153
154                         try {
155                                 value = (EnumConstant)prev_member.value.Increment ();
156                         }
157                         catch (OverflowException) {
158                                 Report.Error (543, Location, "The enumerator value `{0}' is too large to fit in its type `{1}'",
159                                         GetSignatureForError (), TypeManager.CSharpName (parent_enum.UnderlyingType));
160                                 return false;
161                         }
162                         in_transit = false;
163
164                         return true;
165                 }
166
167                 public override void Emit ()
168                 {
169                         if (OptAttributes != null)
170                                 OptAttributes.Emit (); 
171
172                         if (!ResolveValue ()) {
173                                 // Suppress cyclic errors
174                                 value = new EnumConstant(New.Constantify(parent_enum.UnderlyingType), parent_enum.TypeBuilder);
175                                 return;
176                         }
177
178                         builder.SetConstant (value.GetValue ());
179                         base.Emit ();
180                 }
181
182                 public override string GetSignatureForError()
183                 {
184                         return String.Concat (parent_enum.GetSignatureForError (), '.', Name);
185                 }
186
187                 public override string[] ValidAttributeTargets {
188                         get {
189                                 return attribute_targets;
190                         }
191                 }
192
193                 public override string DocCommentHeader {
194                         get { return "F:"; }
195                 }
196
197                 #region IConstant Members
198
199                 public Constant CreateConstantReference (Location loc)
200                 {
201                         if (value == null)
202                                 return null;
203
204                         return new EnumConstant (Constant.CreateConstant (value.Child.Type, value.Child.GetValue(), loc),
205                                 value.Type);
206                 }
207
208                 #endregion
209         }
210
211         /// <summary>
212         ///   Enumeration container
213         /// </summary>
214         public class Enum : DeclSpace {
215                 Expression BaseType;
216                 public Type UnderlyingType;
217
218                 static MemberList no_list = new MemberList (new object[0]);
219                 
220                 public const int AllowedModifiers =
221                         Modifiers.NEW |
222                         Modifiers.PUBLIC |
223                         Modifiers.PROTECTED |
224                         Modifiers.INTERNAL |
225                         Modifiers.PRIVATE;
226
227                 public Enum (NamespaceEntry ns, DeclSpace parent, Expression type,
228                              int mod_flags, MemberName name, Attributes attrs)
229                         : base (ns, parent, name, attrs)
230                 {
231                         this.BaseType = type;
232                         ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
233                                                     IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE, name.Location);
234                 }
235
236                 public void AddEnumMember (EnumMember em)
237                 {
238                         if (em.Name == "value__") {
239                                 Report.Error (76, em.Location, "An item in an enumeration cannot have an identifier `value__'");
240                                 return;
241                         }
242
243                         if (!AddToContainer (em, em.Name))
244                                 return;
245                 }
246                 
247                 public override TypeBuilder DefineType ()
248                 {
249                         if (TypeBuilder != null)
250                                 return TypeBuilder;
251
252                         if (!(BaseType is TypeLookupExpression)) {
253                                 Report.Error (1008, Location,
254                                         "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
255                                 return null;
256                         }
257
258                         TypeExpr ute = BaseType.ResolveAsTypeTerminal (this, false);
259                         UnderlyingType = ute.Type;
260
261                         if (UnderlyingType != TypeManager.int32_type &&
262                             UnderlyingType != TypeManager.uint32_type &&
263                             UnderlyingType != TypeManager.int64_type &&
264                             UnderlyingType != TypeManager.uint64_type &&
265                             UnderlyingType != TypeManager.short_type &&
266                             UnderlyingType != TypeManager.ushort_type &&
267                             UnderlyingType != TypeManager.byte_type  &&
268                             UnderlyingType != TypeManager.sbyte_type) {
269                                 Report.Error (1008, Location,
270                                         "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
271                                 return null;
272                         }
273
274                         if (IsTopLevel) {
275                                 if (TypeManager.NamespaceClash (Name, Location))
276                                         return null;
277                                 
278                                 ModuleBuilder builder = CodeGen.Module.Builder;
279
280                                 TypeBuilder = builder.DefineType (Name, TypeAttr, TypeManager.enum_type);
281                         } else {
282                                 TypeBuilder builder = Parent.TypeBuilder;
283
284                                 TypeBuilder = builder.DefineNestedType (
285                                         Basename, TypeAttr, TypeManager.enum_type);
286                         }
287
288                         //
289                         // Call MapToInternalType for corlib
290                         //
291                         TypeBuilder.DefineField ("value__", UnderlyingType,
292                                                  FieldAttributes.Public | FieldAttributes.SpecialName
293                                                  | FieldAttributes.RTSpecialName);
294
295                         TypeManager.AddUserType (this);
296
297                         foreach (EnumMember em in defined_names.Values) {
298                                 if (!em.Define ())
299                                         return null;
300                         }
301
302                         return TypeBuilder;
303                 }
304                 
305                 public override bool Define ()
306                 {
307                         return true;
308                 }
309
310                 public override void Emit ()
311                 {
312                         if (OptAttributes != null) {
313                                 OptAttributes.Emit ();
314                         }
315
316                         foreach (EnumMember em in defined_names.Values) {
317                                 em.Emit ();
318                         }
319
320                         base.Emit ();
321                 }
322
323                 //
324                 // IMemberFinder
325                 //
326                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
327                         MemberFilter filter, object criteria)
328                 {
329                         if ((mt & MemberTypes.Field) == 0)
330                                 return no_list;
331
332                         EnumMember em = defined_names [criteria] as EnumMember;
333                         if (em == null)
334                                 return no_list;
335
336                         FieldBuilder[] fb = new FieldBuilder[] { em.builder };
337                         return new MemberList (fb);
338                 }
339
340                 void VerifyClsName ()
341                 {
342                         HybridDictionary dict = new HybridDictionary (defined_names.Count, true);
343                         foreach (EnumMember em in defined_names.Values) {
344                                 if (!em.IsClsComplianceRequired ())
345                                         continue;
346
347                                 try {
348                                         dict.Add (em.Name, em);
349                                 }
350                                 catch (ArgumentException) {
351                                         Report.SymbolRelatedToPreviousError (em);
352                                         MemberCore col = (MemberCore)dict [em.Name];
353 #if GMCS_SOURCE
354                                         Report.Warning (3005, 1, col.Location, "Identifier `{0}' differing only in case is not CLS-compliant", col.GetSignatureForError ());
355 #else
356                                         Report.Error (3005, col.Location, "Identifier `{0}' differing only in case is not CLS-compliant", col.GetSignatureForError ());
357 #endif
358                                 }
359                         }
360                 }
361
362                 protected override bool VerifyClsCompliance ()
363                 {
364                         if (!base.VerifyClsCompliance ())
365                                 return false;
366
367                         VerifyClsName ();
368
369                         if (UnderlyingType == TypeManager.uint32_type ||
370                                 UnderlyingType == TypeManager.uint64_type ||
371                                 UnderlyingType == TypeManager.ushort_type) {
372                                 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
373                         }
374
375                         return true;
376                 }
377         
378
379                 public override MemberCache MemberCache {
380                         get {
381                                 return null;
382                         }
383                 }
384
385                 public override AttributeTargets AttributeTargets {
386                         get {
387                                 return AttributeTargets.Enum;
388                         }
389                 }
390
391                 protected override TypeAttributes TypeAttr {
392                         get {
393                                 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
394                                 TypeAttributes.Class | TypeAttributes.Sealed |
395                                 base.TypeAttr;
396                         }
397                 }
398
399                 //
400                 // Generates xml doc comments (if any), and if required,
401                 // handle warning report.
402                 //
403                 internal override void GenerateDocComment (DeclSpace ds)
404                 {
405                         base.GenerateDocComment (ds);
406
407                         foreach (EnumMember em in defined_names.Values) {
408                                 em.GenerateDocComment (this);
409                         }
410                 }
411
412                 //
413                 //   Represents header string for documentation comment.
414                 //
415                 public override string DocCommentHeader {
416                         get { return "T:"; }
417                 }
418         }
419 }