|
| 1 | +using CppSharp.AST; |
| 2 | +using CppSharp.Extensions; |
| 3 | + |
| 4 | +namespace CppSharp.Passes |
| 5 | +{ |
| 6 | + /// <summary> |
| 7 | + /// Validates enumerations and checks if any should be treated as a collection |
| 8 | + /// of flags (and annotate them with the .NET [Flags] when generated). |
| 9 | + /// </summary> |
| 10 | + public class CheckEnumsPass : TranslationUnitPass |
| 11 | + { |
| 12 | + public CheckEnumsPass() |
| 13 | + => VisitOptions.ResetFlags(VisitFlags.NamespaceEnums); |
| 14 | + |
| 15 | + private static bool IsFlagEnum(Enumeration @enum) |
| 16 | + { |
| 17 | + // If the enumeration only has power of two values, assume it's |
| 18 | + // a flags enum. |
| 19 | + |
| 20 | + var isFlags = true; |
| 21 | + var hasBigRange = false; |
| 22 | + |
| 23 | + foreach (var item in @enum.Items) |
| 24 | + { |
| 25 | + var value = item.Value; |
| 26 | + |
| 27 | + if (value >= 4) |
| 28 | + hasBigRange = true; |
| 29 | + |
| 30 | + if (value <= 1 || value.IsPowerOfTwo()) |
| 31 | + continue; |
| 32 | + |
| 33 | + isFlags = false; |
| 34 | + } |
| 35 | + |
| 36 | + // Only apply this heuristic if there are enough values to have a |
| 37 | + // reasonable chance that it really is a bitfield. |
| 38 | + |
| 39 | + return isFlags && hasBigRange; |
| 40 | + } |
| 41 | + |
| 42 | + private bool IsValidEnumBaseType(Enumeration @enum) |
| 43 | + { |
| 44 | + if (Options.IsCSharpGenerator) |
| 45 | + return @enum.BuiltinType.Type.IsIntegerType(); |
| 46 | + |
| 47 | + return @enum.BuiltinType.Type.IsIntegerType() || @enum.BuiltinType.Type == PrimitiveType.Bool; |
| 48 | + } |
| 49 | + |
| 50 | + public override bool VisitEnumDecl(Enumeration @enum) |
| 51 | + { |
| 52 | + if (!base.VisitEnumDecl(@enum)) |
| 53 | + return false; |
| 54 | + |
| 55 | + if (!IsValidEnumBaseType(@enum)) |
| 56 | + { |
| 57 | + if (@enum.BuiltinType.Type == PrimitiveType.Bool) |
| 58 | + { |
| 59 | + @enum.BuiltinType = new BuiltinType(PrimitiveType.UChar); |
| 60 | + } |
| 61 | + else |
| 62 | + { |
| 63 | + Diagnostics.Warning( |
| 64 | + "The enum `{0}` has a base type of `{1}`, which is currently not supported. The base type will be ignored.", |
| 65 | + @enum, @enum.BuiltinType); |
| 66 | + @enum.BuiltinType = new BuiltinType(PrimitiveType.Int); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + if (IsFlagEnum(@enum)) |
| 71 | + @enum.Modifiers |= Enumeration.EnumModifiers.Flags; |
| 72 | + |
| 73 | + return true; |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments