**** Merged from MCS ****
[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 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 //
11
12 using System;
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16
17 namespace Mono.CSharp {
18
19         /// <summary>
20         ///   Enumeration container
21         /// </summary>
22         public class Enum : DeclSpace {
23                 ArrayList ordered_enums;
24                 
25                 public Expression BaseType;
26                 
27                 public Type UnderlyingType;
28
29                 Hashtable member_to_location;
30                 Hashtable member_to_attributes;
31
32                 //
33                 // This is for members that have been defined
34                 //
35                 Hashtable member_to_value;
36
37                 //
38                 // This is used to mark members we're currently defining
39                 //
40                 Hashtable in_transit;
41                 
42                 ArrayList field_builders;
43                 
44                 public const int AllowedModifiers =
45                         Modifiers.NEW |
46                         Modifiers.PUBLIC |
47                         Modifiers.PROTECTED |
48                         Modifiers.INTERNAL |
49                         Modifiers.PRIVATE;
50
51                 public Enum (NamespaceEntry ns, TypeContainer parent, Expression type,
52                              int mod_flags, MemberName name, Attributes attrs, Location l)
53                         : base (ns, parent, name, attrs, l)
54                 {
55                         this.BaseType = type;
56                         ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
57                                                     IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE, l);
58
59                         ordered_enums = new ArrayList ();
60                         member_to_location = new Hashtable ();
61                         member_to_value = new Hashtable ();
62                         in_transit = new Hashtable ();
63                         field_builders = new ArrayList ();
64                 }
65
66                 /// <summary>
67                 ///   Adds @name to the enumeration space, with @expr
68                 ///   being its definition.  
69                 /// </summary>
70                 public AdditionResult AddEnumMember (string name, Expression expr, Location loc,
71                                                      Attributes opt_attrs)
72                 {
73                         if (defined_names.Contains (name))
74                                 return AdditionResult.NameExists;
75
76                         if (name == "value__") {
77                                 Report.Error (76, loc, "An item in an enumeration can't have an identifier `value__'");
78                                 return AdditionResult.Error;
79                         }
80
81                         DefineName (name, expr);
82
83                         ordered_enums.Add (name);
84                         member_to_location.Add (name, loc);
85
86                         if (member_to_attributes == null)
87                                 member_to_attributes = new Hashtable ();
88
89                         member_to_attributes.Add (name, opt_attrs);
90                         
91                         return AdditionResult.Success;
92                 }
93
94                 public override void ApplyAttributeBuilder (object builder, Attribute a, CustomAttributeBuilder cb)
95                 {
96                         ((TypeBuilder) builder).SetCustomAttribute (cb);
97                 }
98
99                 //
100                 // This is used by corlib compilation: we map from our
101                 // type to a type that is consumable by the DefineField
102                 //
103                 Type MapToInternalType (Type t)
104                 {
105                         if (t == TypeManager.int32_type)
106                                 return typeof (int);
107                         if (t == TypeManager.int64_type)
108                                 return typeof (long);
109                         if (t == TypeManager.uint32_type)
110                                 return typeof (uint);
111                         if (t == TypeManager.uint64_type)
112                                 return typeof (ulong);
113                         if (t == TypeManager.float_type)
114                                 return typeof (float);
115                         if (t == TypeManager.double_type)
116                                 return typeof (double);
117                         if (t == TypeManager.byte_type)
118                                 return typeof (byte);
119                         if (t == TypeManager.sbyte_type)
120                                 return typeof (sbyte);
121                         if (t == TypeManager.char_type)
122                                 return typeof (char);
123                         if (t == TypeManager.short_type)
124                                 return typeof (short);
125                         if (t == TypeManager.ushort_type)
126                                 return typeof (ushort);
127
128                         throw new Exception ();
129                 }
130                 
131                 public override TypeBuilder DefineType ()
132                 {
133                         if (TypeBuilder != null)
134                                 return TypeBuilder;
135
136                         TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel);
137
138                         attr |= TypeAttributes.Class | TypeAttributes.Sealed;
139
140                         UnderlyingType = ResolveType (BaseType, false, Location);
141
142                         if (UnderlyingType != TypeManager.int32_type &&
143                             UnderlyingType != TypeManager.uint32_type &&
144                             UnderlyingType != TypeManager.int64_type &&
145                             UnderlyingType != TypeManager.uint64_type &&
146                             UnderlyingType != TypeManager.short_type &&
147                             UnderlyingType != TypeManager.ushort_type &&
148                             UnderlyingType != TypeManager.byte_type  &&
149                             UnderlyingType != TypeManager.sbyte_type) {
150                                 Report.Error (1008, Location,
151                                               "Type byte, sbyte, short, ushort, int, uint, " +
152                                               "long, or ulong expected (got: " +
153                                               TypeManager.CSharpName (UnderlyingType) + ")");
154                                 return null;
155                         }
156
157                         if (IsTopLevel) {
158                                 if (TypeManager.NamespaceClash (Name, Location))
159                                         return null;
160                                 
161                                 ModuleBuilder builder = CodeGen.Module.Builder;
162
163                                 TypeBuilder = builder.DefineType (Name, attr, TypeManager.enum_type);
164                         } else {
165                                 TypeBuilder builder = Parent.TypeBuilder;
166
167                                 TypeBuilder = builder.DefineNestedType (
168                                         Basename, attr, TypeManager.enum_type);
169                         }
170
171                         //
172                         // Call MapToInternalType for corlib
173                         //
174                         TypeBuilder.DefineField ("value__", UnderlyingType,
175                                                  FieldAttributes.Public | FieldAttributes.SpecialName
176                                                  | FieldAttributes.RTSpecialName);
177
178                         TypeManager.AddEnumType (Name, TypeBuilder, this);
179
180                         return TypeBuilder;
181                 }
182
183                 bool IsValidEnumConstant (Expression e)
184                 {
185                         if (!(e is Constant))
186                                 return false;
187
188                         if (e is IntConstant || e is UIntConstant || e is LongConstant ||
189                             e is ByteConstant || e is SByteConstant || e is ShortConstant ||
190                             e is UShortConstant || e is ULongConstant || e is EnumConstant ||
191                             e is CharConstant)
192                                 return true;
193                         else
194                                 return false;
195                 }
196
197                 object GetNextDefaultValue (object default_value)
198                 {
199                         if (UnderlyingType == TypeManager.int32_type) {
200                                 int i = (int) default_value;
201                                 
202                                 if (i < System.Int32.MaxValue)
203                                         return ++i;
204                                 else
205                                         return null;
206                         } else if (UnderlyingType == TypeManager.uint32_type) {
207                                 uint i = (uint) default_value;
208
209                                 if (i < System.UInt32.MaxValue)
210                                         return ++i;
211                                 else
212                                         return null;
213                         } else if (UnderlyingType == TypeManager.int64_type) {
214                                 long i = (long) default_value;
215
216                                 if (i < System.Int64.MaxValue)
217                                         return ++i;
218                                 else
219                                         return null;
220                         } else if (UnderlyingType == TypeManager.uint64_type) {
221                                 ulong i = (ulong) default_value;
222
223                                 if (i < System.UInt64.MaxValue)
224                                         return ++i;
225                                 else
226                                         return null;
227                         } else if (UnderlyingType == TypeManager.short_type) {
228                                 short i = (short) default_value;
229
230                                 if (i < System.Int16.MaxValue)
231                                         return ++i;
232                                 else
233                                         return null;
234                         } else if (UnderlyingType == TypeManager.ushort_type) {
235                                 ushort i = (ushort) default_value;
236
237                                 if (i < System.UInt16.MaxValue)
238                                         return ++i;
239                                 else
240                                         return null;
241                         } else if (UnderlyingType == TypeManager.byte_type) {
242                                 byte i = (byte) default_value;
243
244                                 if (i < System.Byte.MaxValue)
245                                         return ++i;
246                                 else
247                                         return null;
248                         } else if (UnderlyingType == TypeManager.sbyte_type) {
249                                 sbyte i = (sbyte) default_value;
250
251                                 if (i < System.SByte.MaxValue)
252                                         return ++i;
253                                 else
254                                         return null;
255                         }
256
257                         return null;
258                 }
259
260                 void Error_ConstantValueCannotBeConverted (object val, Location loc)
261                 {
262                         if (val is Constant)
263                                 Report.Error (31, loc, "Constant value '" + ((Constant) val).AsString () +
264                                               "' cannot be converted" +
265                                               " to a " + TypeManager.CSharpName (UnderlyingType));
266                         else 
267                                 Report.Error (31, loc, "Constant value '" + val +
268                                               "' cannot be converted" +
269                                               " to a " + TypeManager.CSharpName (UnderlyingType));
270                         return;
271                 }
272
273                 /// <summary>
274                 ///  Determines if a standard implicit conversion exists from
275                 ///  expr_type to target_type
276                 /// </summary>
277                 public static bool ImplicitConversionExists (Type expr_type, Type target_type)
278                 {
279                         expr_type = TypeManager.TypeToCoreType (expr_type);
280
281                         if (expr_type == TypeManager.void_type)
282                                 return false;
283                         
284                         if (expr_type == target_type)
285                                 return true;
286
287                         // First numeric conversions 
288
289                         if (expr_type == TypeManager.sbyte_type){
290                                 //
291                                 // From sbyte to short, int, long, float, double.
292                                 //
293                                 if ((target_type == TypeManager.int32_type) || 
294                                     (target_type == TypeManager.int64_type) ||
295                                     (target_type == TypeManager.double_type) ||
296                                     (target_type == TypeManager.float_type)  ||
297                                     (target_type == TypeManager.short_type) ||
298                                     (target_type == TypeManager.decimal_type))
299                                         return true;
300                                 
301                         } else if (expr_type == TypeManager.byte_type){
302                                 //
303                                 // From byte to short, ushort, int, uint, long, ulong, float, double
304                                 // 
305                                 if ((target_type == TypeManager.short_type) ||
306                                     (target_type == TypeManager.ushort_type) ||
307                                     (target_type == TypeManager.int32_type) ||
308                                     (target_type == TypeManager.uint32_type) ||
309                                     (target_type == TypeManager.uint64_type) ||
310                                     (target_type == TypeManager.int64_type) ||
311                                     (target_type == TypeManager.float_type) ||
312                                     (target_type == TypeManager.double_type) ||
313                                     (target_type == TypeManager.decimal_type))
314                                         return true;
315         
316                         } else if (expr_type == TypeManager.short_type){
317                                 //
318                                 // From short to int, long, float, double
319                                 // 
320                                 if ((target_type == TypeManager.int32_type) ||
321                                     (target_type == TypeManager.int64_type) ||
322                                     (target_type == TypeManager.double_type) ||
323                                     (target_type == TypeManager.float_type) ||
324                                     (target_type == TypeManager.decimal_type))
325                                         return true;
326                                         
327                         } else if (expr_type == TypeManager.ushort_type){
328                                 //
329                                 // From ushort to int, uint, long, ulong, float, double
330                                 //
331                                 if ((target_type == TypeManager.uint32_type) ||
332                                     (target_type == TypeManager.uint64_type) ||
333                                     (target_type == TypeManager.int32_type) ||
334                                     (target_type == TypeManager.int64_type) ||
335                                     (target_type == TypeManager.double_type) ||
336                                     (target_type == TypeManager.float_type) ||
337                                     (target_type == TypeManager.decimal_type))
338                                         return true;
339                                     
340                         } else if (expr_type == TypeManager.int32_type){
341                                 //
342                                 // From int to long, float, double
343                                 //
344                                 if ((target_type == TypeManager.int64_type) ||
345                                     (target_type == TypeManager.double_type) ||
346                                     (target_type == TypeManager.float_type) ||
347                                     (target_type == TypeManager.decimal_type))
348                                         return true;
349                                         
350                         } else if (expr_type == TypeManager.uint32_type){
351                                 //
352                                 // From uint to long, ulong, float, double
353                                 //
354                                 if ((target_type == TypeManager.int64_type) ||
355                                     (target_type == TypeManager.uint64_type) ||
356                                     (target_type == TypeManager.double_type) ||
357                                     (target_type == TypeManager.float_type) ||
358                                     (target_type == TypeManager.decimal_type))
359                                         return true;
360                                         
361                         } else if ((expr_type == TypeManager.uint64_type) ||
362                                    (expr_type == TypeManager.int64_type)) {
363                                 //
364                                 // From long/ulong to float, double
365                                 //
366                                 if ((target_type == TypeManager.double_type) ||
367                                     (target_type == TypeManager.float_type) ||
368                                     (target_type == TypeManager.decimal_type))
369                                         return true;
370                                     
371                         } else if (expr_type == TypeManager.char_type){
372                                 //
373                                 // From char to ushort, int, uint, long, ulong, float, double
374                                 // 
375                                 if ((target_type == TypeManager.ushort_type) ||
376                                     (target_type == TypeManager.int32_type) ||
377                                     (target_type == TypeManager.uint32_type) ||
378                                     (target_type == TypeManager.uint64_type) ||
379                                     (target_type == TypeManager.int64_type) ||
380                                     (target_type == TypeManager.float_type) ||
381                                     (target_type == TypeManager.double_type) ||
382                                     (target_type == TypeManager.decimal_type))
383                                         return true;
384
385                         } else if (expr_type == TypeManager.float_type){
386                                 //
387                                 // float to double
388                                 //
389                                 if (target_type == TypeManager.double_type)
390                                         return true;
391                         }       
392                         
393                         return false;
394                 }
395
396                 //
397                 // Horrible, horrible.  But there is no other way we can pass the EmitContext
398                 // to the recursive definition triggered by the evaluation of a forward
399                 // expression
400                 //
401                 static EmitContext current_ec = null;
402                 
403                 /// <summary>
404                 ///  This is used to lookup the value of an enum member. If the member is undefined,
405                 ///  it attempts to define it and return its value
406                 /// </summary>
407                 public object LookupEnumValue (EmitContext ec, string name, Location loc)
408                 {
409                         
410                         object default_value = null;
411                         Constant c = null;
412
413                         default_value = member_to_value [name];
414
415                         if (default_value != null)
416                                 return default_value;
417
418                         //
419                         // This may happen if we're calling a method in System.Enum, for instance
420                         // Enum.IsDefined().
421                         //
422                         if (!defined_names.Contains (name))
423                                 return null;
424
425                         if (in_transit.Contains (name)) {
426                                 Report.Error (110, loc, "The evaluation of the constant value for `" +
427                                               Name + "." + name + "' involves a circular definition.");
428                                 return null;
429                         }
430
431                         //
432                         // So if the above doesn't happen, we have a member that is undefined
433                         // We now proceed to define it 
434                         //
435                         Expression val = this [name];
436
437                         if (val == null) {
438                                 
439                                 int idx = ordered_enums.IndexOf (name);
440
441                                 if (idx == 0)
442                                         default_value = 0;
443                                 else {
444                                         for (int i = 0; i < idx; ++i) {
445                                                 string n = (string) ordered_enums [i];
446                                                 Location m_loc = (Mono.CSharp.Location)
447                                                         member_to_location [n];
448                                                 in_transit.Add (name, true);
449
450                                                 EmitContext old_ec = current_ec;
451                                                 current_ec = ec;
452                         
453                                                 default_value = LookupEnumValue (ec, n, m_loc);
454
455                                                 current_ec = old_ec;
456                                                 
457                                                 in_transit.Remove (name);
458                                                 if (default_value == null)
459                                                         return null;
460                                         }
461                                         
462                                         default_value = GetNextDefaultValue (default_value);
463                                 }
464                                 
465                         } else {
466                                 bool old = ec.InEnumContext;
467                                 ec.InEnumContext = true;
468                                 in_transit.Add (name, true);
469
470                                 EmitContext old_ec = current_ec;
471                                 current_ec = ec;
472                                 val = val.Resolve (ec);
473                                 current_ec = old_ec;
474                                 
475                                 in_transit.Remove (name);
476                                 ec.InEnumContext = old;
477
478                                 if (val == null)
479                                         return null;
480
481                                 if (!IsValidEnumConstant (val)) {
482                                         Report.Error (
483                                                 1008, loc,
484                                                 "Type byte, sbyte, short, ushort, int, uint, long, or " +
485                                                 "ulong expected (have: " + val + ")");
486                                         return null;
487                                 }
488
489                                 c = (Constant) val;
490                                 default_value = c.GetValue ();
491
492                                 if (default_value == null) {
493                                         Error_ConstantValueCannotBeConverted (c, loc);
494                                         return null;
495                                 }
496
497                                 if (val is EnumConstant){
498                                         Type etype = TypeManager.EnumToUnderlying (c.Type);
499                                         
500                                         if (!ImplicitConversionExists (etype, UnderlyingType)){
501                                                 Convert.Error_CannotImplicitConversion (
502                                                         loc, c.Type, UnderlyingType);
503                                                 return null;
504                                         }
505                                 }
506                         }
507
508                         FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
509                                         | FieldAttributes.Literal;
510                         
511                         FieldBuilder fb = TypeBuilder.DefineField (name, TypeBuilder, attr);
512
513                         bool fail;
514                         default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
515                         if (fail){
516                                 Error_ConstantValueCannotBeConverted (c, loc);
517                                 return null;
518                         }
519
520                         fb.SetConstant (default_value);
521                         field_builders.Add (fb);
522                         member_to_value [name] = default_value;
523
524                         if (!TypeManager.RegisterFieldValue (fb, default_value))
525                                 return null;
526
527                         //
528                         // Now apply attributes
529                         //
530                         Attribute.ApplyAttributes (ec, fb, fb, (Attributes) member_to_attributes [name]); 
531                         
532                         return default_value;
533                 }
534
535                 public override bool DefineMembers (TypeContainer parent)
536                 {
537                         return true;
538                 }
539                 
540                 public override bool Define (TypeContainer parent)
541                 {
542                         //
543                         // If there was an error during DefineEnum, return
544                         //
545                         if (TypeBuilder == null)
546                                 return false;
547                         
548                         EmitContext ec = new EmitContext (this, this, Location, null,
549                                                           UnderlyingType, ModFlags, false);
550
551                         
552                         object default_value = 0;
553                         
554                         FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
555                                              | FieldAttributes.Literal;
556
557                         
558                         foreach (string name in ordered_enums) {
559                                 //
560                                 // Have we already been defined, thanks to some cross-referencing ?
561                                 // 
562                                 if (member_to_value.Contains (name))
563                                         continue;
564                                 
565                                 Location loc = (Mono.CSharp.Location) member_to_location [name];
566
567                                 if (this [name] != null) {
568                                         default_value = LookupEnumValue (ec, name, loc);
569
570                                         if (default_value == null)
571                                                 return true;
572                                 } else {
573                                         if (name == "value__"){
574                                                 Report.Error (76, loc, "The name `value__' is reserved for enumerations");
575                                                 return false;
576                                         }
577
578                                         FieldBuilder fb = TypeBuilder.DefineField (
579                                                 name, TypeBuilder, attr);
580                                         
581                                         if (default_value == null) {
582                                            Report.Error (543, loc, "Enumerator value for '" + name + "' is too large to " +
583                                                               "fit in its type");
584                                                 return false;
585                                         }
586
587                                         bool fail;
588                                         default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
589                                         if (fail){
590                                                 Error_ConstantValueCannotBeConverted (default_value, loc);
591                                                 return false;
592                                         }
593
594                                         fb.SetConstant (default_value);
595                                         field_builders.Add (fb);
596                                         member_to_value [name] = default_value;
597                                         
598                                         if (!TypeManager.RegisterFieldValue (fb, default_value))
599                                                 return false;
600
601                                         //
602                                         // Apply attributes on the enum member
603                                         //
604                                         Attribute.ApplyAttributes (ec, fb, fb, (Attributes) member_to_attributes [name]);
605                                 }
606
607                                 default_value = GetNextDefaultValue (default_value);
608                         }
609                         return true;
610                 }
611                         
612                 public override void Emit (TypeContainer tc)
613                 {
614                         if (OptAttributes != null) {
615                                 EmitContext ec = new EmitContext (tc, this, Location, null, null, ModFlags, false);
616                         Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes);
617                         }
618
619                         base.Emit (tc);
620                 }
621                 
622                 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
623                 {
624                         if (!base.IsIdentifierClsCompliant (ds))
625                                 return false;
626
627                         for (int i = 1; i < ordered_enums.Count; ++i) {
628                                 string checked_name = ordered_enums [i] as string;
629                                 for (int ii = 0; ii < ordered_enums.Count; ++ii) {
630                                         if (ii == i)
631                                                 continue;
632
633                                         string enumerator_name = ordered_enums [ii] as string;
634                                         if (String.Compare (checked_name, enumerator_name, true) == 0) {
635                                                 Report.SymbolRelatedToPreviousError ((Location)member_to_location [enumerator_name], enumerator_name);
636                                                 Report.Error_T (3005, (Location)member_to_location [checked_name], GetEnumeratorName (checked_name));
637                                                 break;
638                                         }
639                                 }
640                         }
641                         return true;
642                 }
643
644                 protected override bool VerifyClsCompliance (DeclSpace ds)
645                 {
646                         if (!base.VerifyClsCompliance (ds))
647                                 return false;
648
649                         if (!AttributeTester.IsClsCompliant (UnderlyingType)) {
650                                 Report.Error_T (3009, Location, GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
651                         }
652
653                         return true;
654                 }
655                 
656                 /// <summary>
657                 /// Returns full enum name.
658                 /// </summary>
659                 string GetEnumeratorName (string valueName)
660                 {
661                         return String.Concat (Name, ".", valueName);
662                 }
663
664                 //
665                 // IMemberFinder
666                 //
667                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
668                                                         MemberFilter filter, object criteria)
669                 {
670                         ArrayList members = new ArrayList ();
671
672                         if ((mt & MemberTypes.Field) != 0) {
673                                 if (criteria is string){
674                                         if (member_to_value [criteria] == null && current_ec != null){
675                                                 LookupEnumValue (current_ec, (string) criteria, Location.Null);
676                                         }
677                                 }
678                                 
679                                 foreach (FieldBuilder fb in field_builders)
680                                         if (filter (fb, criteria) == true)
681                                                 members.Add (fb);
682                         }
683
684                         return new MemberList (members);
685                 }
686
687                 public override MemberCache MemberCache {
688                         get {
689                                 return null;
690                         }
691                 }
692
693                 public ArrayList ValueNames {
694                         get {
695                                 return ordered_enums;
696                         }
697                 }
698
699                 // indexer
700                 public Expression this [string name] {
701                         get {
702                                 return (Expression) defined_names [name];
703                         }
704                 }
705         }
706 }