Skip to content

Commit 499e349

Browse files
authored
Merge pull request #3529 from hvitved/csharp/cs6-nested-initializer-type
C#: Fix extracted type for nested object initializers
2 parents 8b8c00d + 011a95d commit 499e349

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Initializer.cs

+12-3
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,18 @@ protected override void PopulateExpression(TextWriter trapFile)
6969

7070
if (assignment != null)
7171
{
72-
var assignmentEntity = new Expression(new ExpressionNodeInfo(cx, init, this, child++).SetKind(ExprKind.SIMPLE_ASSIGN));
73-
74-
CreateFromNode(new ExpressionNodeInfo(cx, assignment.Right, assignmentEntity, 0));
72+
var assignmentInfo = new ExpressionNodeInfo(cx, init, this, child++).SetKind(ExprKind.SIMPLE_ASSIGN);
73+
var assignmentEntity = new Expression(assignmentInfo);
74+
var typeInfoRight = cx.GetTypeInfo(assignment.Right);
75+
if (typeInfoRight.Type is null)
76+
// The type may be null for nested initializers such as
77+
// ```
78+
// new ClassWithArrayField() { As = { [0] = a } }
79+
// ```
80+
// In this case we take the type from the assignment
81+
// `As = { [0] = a }` instead
82+
typeInfoRight = assignmentInfo.TypeInfo;
83+
CreateFromNode(new ExpressionNodeInfo(cx, assignment.Right, assignmentEntity, 0, typeInfoRight));
7584

7685
var target = cx.GetSymbolInfo(assignment.Left);
7786

csharp/ql/test/library-tests/csharp6/MemberInitializer.expected

+9
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,12 @@ initializers
7676
| csharp6.cs:77:29:77:56 | { ..., ... } | 1 | csharp6.cs:77:44:77:54 | ... = ... |
7777
| csharp6.cs:78:30:78:59 | { ..., ... } | 0 | csharp6.cs:78:32:78:43 | ... = ... |
7878
| csharp6.cs:78:30:78:59 | { ..., ... } | 1 | csharp6.cs:78:46:78:57 | ... = ... |
79+
initializerType
80+
| csharp6.cs:68:50:68:91 | { ..., ... } | Dictionary<Int32, String> |
81+
| csharp6.cs:72:9:79:9 | { ..., ... } | Compound |
82+
| csharp6.cs:73:31:73:72 | { ..., ... } | Dictionary<Int32, String> |
83+
| csharp6.cs:74:34:74:76 | { ..., ... } | Dictionary<Int32, String> |
84+
| csharp6.cs:75:26:75:54 | { ..., ... } | String[] |
85+
| csharp6.cs:76:27:76:56 | { ..., ... } | String[,] |
86+
| csharp6.cs:77:29:77:56 | { ..., ... } | String[] |
87+
| csharp6.cs:78:30:78:59 | { ..., ... } | String[,] |

csharp/ql/test/library-tests/csharp6/MemberInitializer.ql

+4
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,7 @@ query predicate arrayQualifiers(ElementAccess access, Expr qualifier) {
2222
query predicate initializers(ObjectInitializer init, int item, Expr expr) {
2323
expr = init.getMemberInitializer(item)
2424
}
25+
26+
query predicate initializerType(ObjectInitializer init, string type) {
27+
type = init.getType().toStringWithTypes()
28+
}

0 commit comments

Comments
 (0)