Skip to content

Commit 839ef7f

Browse files
committed
C#: Add compile time constants for some types of fields in the stub generator.
1 parent d00ff96 commit 839ef7f

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

csharp/extractor/Semmle.Extraction.CSharp.StubGenerator/StubVisitor.cs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,35 @@ private static bool IsUnsafe(ITypeSymbol symbol) =>
296296
private static string EscapeIdentifier(string identifier) =>
297297
keywords.Contains(identifier) ? "@" + identifier : identifier;
298298

299+
private static bool TryGetConstantValue(IFieldSymbol symbol, out string value)
300+
{
301+
value = "";
302+
if (!symbol.HasConstantValue)
303+
{
304+
return false;
305+
}
306+
307+
var v = symbol.ConstantValue;
308+
switch (symbol.Type.SpecialType)
309+
{
310+
case SpecialType.System_Boolean:
311+
value = (bool)v ? "true" : "false";
312+
return true;
313+
case SpecialType.System_Byte:
314+
case SpecialType.System_SByte:
315+
case SpecialType.System_UInt16:
316+
case SpecialType.System_UInt32:
317+
case SpecialType.System_UInt64:
318+
case SpecialType.System_Int16:
319+
case SpecialType.System_Int32:
320+
case SpecialType.System_Int64:
321+
value = v.ToString()!;
322+
return true;
323+
default:
324+
return false;
325+
}
326+
}
327+
299328
public override void VisitField(IFieldSymbol symbol)
300329
{
301330
if (IsNotPublic(symbol.DeclaredAccessibility))
@@ -325,7 +354,8 @@ public override void VisitField(IFieldSymbol symbol)
325354
stubWriter.Write(EscapeIdentifier(symbol.Name));
326355
if (symbol.IsConst)
327356
{
328-
stubWriter.Write(" = default");
357+
var v = TryGetConstantValue(symbol, out var value) ? value : "default";
358+
stubWriter.Write($" = {v}");
329359
}
330360
stubWriter.WriteLine(";");
331361
}

0 commit comments

Comments
 (0)