Skip to content

Commit 011a95d

Browse files
committed
C#: Fix extracted type for nested object initializers
1 parent 70d47b7 commit 011a95d

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

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

Lines changed: 12 additions & 3 deletions
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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,9 @@ initializers
7979
initializerType
8080
| csharp6.cs:68:50:68:91 | { ..., ... } | Dictionary<Int32, String> |
8181
| csharp6.cs:72:9:79:9 | { ..., ... } | Compound |
82-
| csharp6.cs:73:31:73:72 | { ..., ... } | null |
83-
| csharp6.cs:74:34:74:76 | { ..., ... } | null |
84-
| csharp6.cs:75:26:75:54 | { ..., ... } | null |
85-
| csharp6.cs:76:27:76:56 | { ..., ... } | null |
86-
| csharp6.cs:77:29:77:56 | { ..., ... } | null |
87-
| csharp6.cs:78:30:78:59 | { ..., ... } | null |
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[,] |

0 commit comments

Comments
 (0)