Skip to content

Commit f449bcc

Browse files
authored
Merge pull request #1122 from microsoft/fix1121
Define constant members of structs as constants
2 parents 6d384e2 + e0acc19 commit f449bcc

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/Microsoft.Windows.CsWin32/Generator.Struct.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,28 @@ private StructDeclarationSyntax DeclareStruct(TypeDefinitionHandle typeDefHandle
3434
foreach (FieldDefinitionHandle fieldDefHandle in typeDef.GetFields())
3535
{
3636
FieldDefinition fieldDef = this.Reader.GetFieldDefinition(fieldDefHandle);
37+
FieldDeclarationSyntax field;
38+
39+
if (fieldDef.Attributes.HasFlag(FieldAttributes.Static))
40+
{
41+
if (fieldDef.Attributes.HasFlag(FieldAttributes.Literal))
42+
{
43+
field = this.DeclareConstant(fieldDef);
44+
members.Add(field);
45+
continue;
46+
}
47+
else
48+
{
49+
throw new NotSupportedException();
50+
}
51+
}
52+
3753
string fieldName = this.Reader.GetString(fieldDef.Name);
3854

3955
try
4056
{
4157
CustomAttribute? fixedBufferAttribute = this.FindAttribute(fieldDef.GetCustomAttributes(), SystemRuntimeCompilerServices, nameof(FixedBufferAttribute));
4258

43-
FieldDeclarationSyntax field;
4459
VariableDeclaratorSyntax fieldDeclarator = VariableDeclarator(SafeIdentifier(fieldName));
4560
if (fixedBufferAttribute.HasValue)
4661
{

test/Microsoft.Windows.CsWin32.Tests/StructTests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,16 @@ public void SpecialStruct_ByRequest(string structName)
234234
var type = (StructDeclarationSyntax)Assert.Single(this.FindGeneratedType(structName));
235235
}
236236

237+
[Fact]
238+
public void StructConstantsAreGeneratedAsConstants()
239+
{
240+
this.GenerateApi("Color");
241+
var type = (StructDeclarationSyntax)Assert.Single(this.FindGeneratedType("Color"));
242+
FieldDeclarationSyntax argb = Assert.Single(type.Members.OfType<FieldDeclarationSyntax>().Where(f => !(f.Modifiers.Any(SyntaxKind.StaticKeyword) || f.Modifiers.Any(SyntaxKind.ConstKeyword))));
243+
Assert.Equal("Argb", argb.Declaration.Variables.Single().Identifier.ValueText);
244+
Assert.NotEmpty(type.Members.OfType<FieldDeclarationSyntax>().Where(f => f.Modifiers.Any(SyntaxKind.ConstKeyword)));
245+
}
246+
237247
[Theory]
238248
[CombinatorialData]
239249
public void InterestingStructs(

0 commit comments

Comments
 (0)