Skip to content

Commit 285f3f6

Browse files
committed
Rewrite GenerateEnumFromMacros to search through multiple translation units.
1 parent a6fc9fa commit 285f3f6

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

src/Generator/Library.cs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ static bool ParseToNumber(string num, Enumeration @enum, out long val)
119119
evaluator.Variables.Add(item.Name.ToLower(), item.Value);
120120
}
121121
try
122-
{
122+
{
123123
var ret = evaluator.Evaluate("(long)" + num.ReplaceLineBreaks(" ").Replace('\\',' '));
124124
val = (long)ret;
125125
return true;
@@ -149,8 +149,14 @@ public static Enumeration GenerateEnumFromMacros(this ASTContext context, string
149149
var pattern = string.Join("|", macros);
150150
var regex = new Regex(pattern);
151151

152+
int maxItems = 0;
153+
TranslationUnit unitToAttach = null;
154+
ulong maxValue = 0;
155+
152156
foreach (var unit in context.TranslationUnits)
153157
{
158+
int numItems = 0;
159+
154160
foreach (var macro in unit.PreprocessedEntities.OfType<MacroDefinition>())
155161
{
156162
var match = regex.Match(macro.Name);
@@ -159,27 +165,31 @@ public static Enumeration GenerateEnumFromMacros(this ASTContext context, string
159165
if (macro.Enumeration != null)
160166
continue;
161167

162-
// Skip this macro if the enum already has an item with same entry.
168+
// Skip this macro if the enum already has an item with same name.
163169
if (@enum.Items.Exists(it => it.Name == macro.Name))
164170
continue;
165171

166-
// Set the namespace to the namespace we found the 1st item in
167-
if (@enum.Namespace == null)
168-
@enum.Namespace = unit;
169-
170172
var item = @enum.GenerateEnumItemFromMacro(macro);
171173
@enum.AddItem(item);
172-
173174
macro.Enumeration = @enum;
175+
176+
maxValue = Math.Max(maxValue, item.Value);
177+
numItems++;
174178
}
175179

176-
if (@enum.Items.Count > 0)
180+
if (numItems > maxItems)
177181
{
178-
unit.Declarations.Add(@enum);
179-
break;
182+
maxItems = numItems;
183+
unitToAttach = unit;
180184
}
181185
}
182186

187+
if (@enum.Items.Count > 0)
188+
{
189+
@enum.Namespace = unitToAttach;
190+
unitToAttach.Declarations.Add(@enum);
191+
}
192+
183193
return @enum;
184194
}
185195

0 commit comments

Comments
 (0)