In .:
[mono.git] / mcs / gmcs / 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                 Constant 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                 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                                 // suppress cyclic errors
113                                 value = new EnumConstant (New.Constantify (parent_enum.UnderlyingType), parent_enum.TypeBuilder);
114                                 Const.Error_CyclicDeclaration (this);
115                                 return false;
116                         }
117
118                         if (ValueExpr != null) {
119                                 in_transit = true;
120                                 Constant c = ValueExpr.ResolveAsConstant (ec, this);
121                                 in_transit = false;
122
123                                 if (c == null)
124                                         return false;
125
126                                 if (c is EnumConstant)
127                                         c = ((EnumConstant)c).Child;
128                                         
129                                 c = c.ToType (parent_enum.UnderlyingType, Location);
130                                 if (c == null)
131                                         return false;
132
133                                 if (!IsValidEnumType (c.Type)) {
134                                         Report.Error (1008, Location, "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
135                                         return false;
136                                 }
137
138                                 in_transit = false;
139                                 value = new EnumConstant (c, parent_enum.TypeBuilder);
140                                 return true;
141                         }
142
143                         if (prev_member == null) {
144                                 value = new EnumConstant (New.Constantify (parent_enum.UnderlyingType), parent_enum.TypeBuilder);
145                                 return true;
146                         }
147
148                         if (!prev_member.ResolveValue ())
149                                 return false;
150
151                         in_transit = true;
152
153                         try {
154                                 value = prev_member.value.Increment ();
155                         }
156                         catch (OverflowException) {
157                                 Report.Error (543, Location, "The enumerator value `{0}' is too large to fit in its type `{1}'",
158                                         GetSignatureForError (), TypeManager.CSharpName (parent_enum.UnderlyingType));
159                                 return false;
160                         }
161                         in_transit = false;
162
163                         return true;
164                 }
165
166                 public override void Emit ()
167                 {
168                         if (OptAttributes != null)
169                                 OptAttributes.Emit (); 
170
171                         if (!ResolveValue ())
172                                 return;
173
174                         builder.SetConstant (value.GetValue ());
175                         base.Emit ();
176                 }
177
178                 public override string GetSignatureForError()
179                 {
180                         return String.Concat (parent_enum.GetSignatureForError (), '.', Name);
181                 }
182
183                 public override string[] ValidAttributeTargets {
184                         get {
185                                 return attribute_targets;
186                         }
187                 }
188
189                 protected override bool VerifyClsCompliance(DeclSpace ds)
190                 {
191                         // Because parent is TypeContainer and we have only DeclSpace parent.
192                         // Parameter replacing is required
193                         return base.VerifyClsCompliance (parent_enum);
194                 }
195
196                 public override string DocCommentHeader {
197                         get { return "F:"; }
198                 }
199
200                 #region IConstant Members
201
202                 public Constant Value {
203                         get {
204                                 return value;
205                         }
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, TypeContainer 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 = ResolveBaseTypeExpr (BaseType);
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                                         Report.Warning (3005, 1, col.Location, "Identifier `{0}' differing only in case is not CLS-compliant", col.GetSignatureForError ());
354                                 }
355                         }
356                 }
357
358                 protected override bool VerifyClsCompliance (DeclSpace ds)
359                 {
360                         if (!base.VerifyClsCompliance (ds))
361                                 return false;
362
363                         VerifyClsName ();
364
365                         if (UnderlyingType == TypeManager.uint32_type ||
366                                 UnderlyingType == TypeManager.uint64_type ||
367                                 UnderlyingType == TypeManager.ushort_type) {
368                                 Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
369                         }
370
371                         return true;
372                 }
373         
374
375                 public override MemberCache MemberCache {
376                         get {
377                                 return null;
378                         }
379                 }
380
381                 public override AttributeTargets AttributeTargets {
382                         get {
383                                 return AttributeTargets.Enum;
384                         }
385                 }
386
387                 protected override TypeAttributes TypeAttr {
388                         get {
389                                 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
390                                 TypeAttributes.Class | TypeAttributes.Sealed |
391                                 base.TypeAttr;
392                         }
393                 }
394
395                 //
396                 // Generates xml doc comments (if any), and if required,
397                 // handle warning report.
398                 //
399                 internal override void GenerateDocComment (DeclSpace ds)
400                 {
401                         base.GenerateDocComment (ds);
402
403                         foreach (EnumMember em in defined_names.Values) {
404                                 em.GenerateDocComment (this);
405                         }
406                 }
407
408                 //
409                 //   Represents header string for documentation comment.
410                 //
411                 public override string DocCommentHeader {
412                         get { return "T:"; }
413                 }
414         }
415 }