Skip to content

Commit d0bc5b9

Browse files
hvitvedCopilot
andcommitted
C#: Extract defining accesses for local declarations
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent e54be54 commit d0bc5b9

52 files changed

Lines changed: 2118 additions & 754 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Patterns/Pattern.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ internal static Expression Create(Context cx, PatternSyntax syntax, IExpressionP
3434
if (cx.GetModel(syntax).GetDeclaredSymbol(singleDesignation) is ILocalSymbol symbol)
3535
{
3636
var type = symbol.GetAnnotatedType();
37-
return VariableDeclaration.Create(cx, symbol, type, declPattern.Type, cx.CreateLocation(syntax.GetLocation()), false, parent, child, isPattern: true);
37+
return VariableDeclaration.Create(cx, symbol, type, declPattern.Type, cx.CreateLocation(syntax.GetLocation()), false, parent, child);
3838
}
3939
throw new InternalError(singleDesignation, "Unable to get the declared symbol of the declaration pattern designation.");
4040
case DiscardDesignationSyntax _:
@@ -59,7 +59,7 @@ internal static Expression Create(Context cx, PatternSyntax syntax, IExpressionP
5959
if (cx.GetModel(syntax).GetDeclaredSymbol(varDesignation) is ILocalSymbol symbol)
6060
{
6161
var type = symbol.GetAnnotatedType();
62-
return VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), true, parent, child, isPattern: true);
62+
return VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), true, parent, child);
6363
}
6464

6565
throw new InternalError(varPattern, "Unable to get the declared symbol of the var pattern designation.");

‎csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Patterns/RecursivePattern.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public RecursivePattern(Context cx, RecursivePatternSyntax syntax, IExpressionPa
2626
{
2727
var type = symbol.GetAnnotatedType();
2828

29-
VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), false, this, 0, isPattern: true);
29+
VariableDeclaration.Create(cx, symbol, type, null, cx.CreateLocation(syntax.GetLocation()), false, this, 0);
3030
}
3131

3232
if (syntax.PositionalPatternClause is PositionalPatternClauseSyntax posPc)

‎csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Query.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,8 @@ protected Expression DeclareRangeVariable(Context cx, IExpressionParentEntity pa
9191
cx.CreateLocation(node.GetLocation()),
9292
true,
9393
parent,
94-
child
94+
child,
95+
createAccess: false
9596
);
9697

9798
var nameLoc = cx.CreateLocation(name.GetLocation());

‎csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/VariableDeclaration.cs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@ internal class VariableDeclaration : Expression
1313
{
1414
private VariableDeclaration(IExpressionInfo info) : base(info) { }
1515

16-
public static VariableDeclaration Create(Context cx, ISymbol symbol, AnnotatedTypeSymbol? type, TypeSyntax? optionalSyntax, Location exprLocation, bool isVar, IExpressionParentEntity parent, int child, bool isPattern = false)
16+
public static VariableDeclaration Create(Context cx, ISymbol symbol, AnnotatedTypeSymbol? type, TypeSyntax? optionalSyntax, Location exprLocation, bool isVar, IExpressionParentEntity parent, int child, bool createAccess = true)
1717
{
1818
var ret = new VariableDeclaration(new ExpressionInfo(cx, type, exprLocation, ExprKind.LOCAL_VAR_DECL, parent, child, isCompilerGenerated: false, null));
1919
cx.Try(null, null, () =>
2020
{
2121
var l = LocalVariable.Create(cx, symbol);
2222
l.PopulateManual(ret, isVar);
23-
if (isPattern)
23+
if (createAccess)
2424
ret.CreateDefiningAccess(l, type);
2525
if (optionalSyntax is not null)
2626
TypeMention.Create(cx, optionalSyntax, ret, type);
@@ -43,6 +43,9 @@ private static VariableDeclaration CreateSingle(Context cx, DeclarationExpressio
4343
{
4444
var l = LocalVariable.Create(cx, variableSymbol);
4545
l.PopulateManual(ret, node.Type.IsVar);
46+
// An out declaration is itself the access in the QL model.
47+
if (node.Parent is not ArgumentSyntax argument || !argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword))
48+
ret.CreateDefiningAccess(l, type);
4649
});
4750
return ret;
4851
}
@@ -88,7 +91,7 @@ public static Expression CreateParenthesized(Context cx, VarPatternSyntax varPat
8891
case SingleVariableDesignationSyntax single:
8992
if (cx.GetModel(variable).GetDeclaredSymbol(single) is ILocalSymbol local)
9093
{
91-
sub = Create(cx, local, local.GetAnnotatedType(), null, cx.CreateLocation(single.FixedLocation()), true, tuple, child0++, isPattern: true);
94+
sub = Create(cx, local, local.GetAnnotatedType(), null, cx.CreateLocation(single.FixedLocation()), true, tuple, child0++);
9295
}
9396
else
9497
{
@@ -159,6 +162,7 @@ public static VariableDeclaration Create(Context cx, CatchDeclarationSyntax d, b
159162
var declSymbol = cx.GetModel(d).GetDeclaredSymbol(d)!;
160163
var l = LocalVariable.Create(cx, declSymbol);
161164
l.PopulateManual(ret, isVar);
165+
ret.CreateDefiningAccess(l, type);
162166
TypeMention.Create(cx, d.Type, ret, type);
163167
});
164168
return ret;
@@ -172,10 +176,10 @@ public static VariableDeclaration CreateDeclarator(Context cx, VariableDeclarato
172176
var declSymbol = cx.GetModel(d).GetDeclaredSymbol(d)!;
173177
var localVar = LocalVariable.Create(cx, declSymbol);
174178
localVar.PopulateManual(ret, isVar);
179+
ret.CreateDefiningAccess(localVar, type);
175180

176181
if (d.Initializer is not null)
177182
{
178-
ret.CreateDefiningAccess(localVar, type);
179183
Create(cx, d.Initializer.Value, ret, 1);
180184
}
181185

‎csharp/ql/consistency-queries/SsaConsistency.ql‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ query predicate localDeclWithSsaDef(LocalVariableDeclExpr d) {
1111
exists(SsaExplicitWrite def |
1212
d = def.getDefinition().(AssignableDefinitions::LocalVariableDefinition).getDeclaration()
1313
|
14-
not d = any(ForEachStmt fs).getVariableDeclExpr() and
14+
not exists(ForEachStmt fs, int i | d.getVariable() = fs.getVariable(i)) and
1515
not d = any(SpecificCatchClause scc).getVariableDeclExpr() and
1616
not d.getVariable().getType() instanceof Struct and
1717
not d instanceof PatternExpr and

‎csharp/ql/lib/Linq/Helpers.qll‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,10 @@ private module LinqFilterOpportunity<linqCandidateSig/2 linqCandidate> {
134134
// The linq candidate expression accesses the loop variable, and the
135135
// candidate doesn't access an in, out, or ref parameter.
136136
exists(Expr candidate | linqCandidate(s, candidate) |
137-
fes.getVariable().getAnAccess() = candidate.getAChildExpr*() and
137+
exists(AssignableRead read |
138+
read = fes.getVariable().getAnAccess() and
139+
read = candidate.getAChildExpr*()
140+
) and
138141
acceptableForLinqCapture(candidate)
139142
)
140143
}
@@ -146,8 +149,8 @@ private module LinqMapOpportunity<linqCandidateSig/2 linqCandidate> {
146149
// The linq candidate (and only the candidate) expression accesses the loop variable and the
147150
// candidate doesn't access an in, out, or ref parameter.
148151
exists(Expr candidate | linqCandidate(s, candidate) |
149-
forex(VariableAccess va | va = fes.getVariable().getAnAccess() |
150-
va = candidate.getAChildExpr*()
152+
forex(AssignableRead read | read = fes.getVariable().getAnAccess() |
153+
read = candidate.getAChildExpr*()
151154
) and
152155
acceptableForLinqCapture(candidate)
153156
)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
category: fix
3+
---
4+
* The C# extractor now records defining accesses for local variable declarations without initializers and for deconstruction, `foreach`, and `catch` variables.

‎csharp/ql/lib/definitions.qll‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,7 @@ private class MethodUse extends Use, QualifiableExpr {
9696
private class AccessUse extends Access, Use {
9797
AccessUse() {
9898
not this.getTarget().(Parameter).getCallable() instanceof Accessor and
99-
not this = any(LocalVariableDeclAndInitExpr d).getLeftOperand() and
100-
not this = any(AssignableDefinitions::PatternDefinition d).getTargetAccess() and
99+
not this = any(LocalVariableDeclExpr d).getAccess() and
101100
not this.isImplicit() and
102101
not this instanceof MethodAccess and // handled by `MethodUse`
103102
not this instanceof TypeAccess and // handled by `TypeMentionUse`

‎csharp/ql/lib/semmle/code/csharp/Assignable.qll‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -385,10 +385,15 @@ module AssignableInternal {
385385
or
386386
def = TTupleAssignmentDefinition(_, result)
387387
or
388+
def =
389+
TTupleAssignmentDefinition(_, any(LocalVariableDeclExpr decl | decl.getAccess() = result))
390+
or
388391
def = TOutRefDefinition(result)
389392
or
390393
def = TMutationDefinition(any(MutatorOperation mo | mo.getOperand() = result))
391394
or
395+
def = TLocalVariableDefinition(any(LocalVariableDeclExpr decl | decl.getAccess() = result))
396+
or
392397
def = TAddressOfDefinition(any(AddressOfExpr aoe | aoe.getOperand() = result))
393398
or
394399
def = TPatternDefinition(any(LocalVariablePatternDecl decl | decl.getAccess() = result))
@@ -476,8 +481,7 @@ class AssignableDefinition extends TAssignableDefinition {
476481

477482
/**
478483
* Gets the access used in the definition of the underlying assignable,
479-
* if any. For example, an uninitialized local variable declaration or an
480-
* implicit parameter definition has no associated access.
484+
* if any. For example, an implicit parameter definition has no associated access.
481485
*/
482486
final AssignableAccess getTargetAccess() { result = getTargetAccess(this) }
483487

‎csharp/ql/src/Likely Bugs/Collections/WriteOnlyContainer.ql‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,12 @@ where
2626
a = any(AssignExpr ass | ass.getRightOperand() instanceof ObjectCreation).getLeftOperand() or
2727
a =
2828
any(LocalVariableDeclAndInitExpr ass | ass.getRightOperand() instanceof ObjectCreation)
29-
.getLeftOperand()
29+
.getLeftOperand() or
30+
a =
31+
any(LocalVariableDeclExpr decl |
32+
not decl.hasInitializer() and
33+
not decl.isOutArgument()
34+
).getAccess()
3035
) and
3136
not v = any(ForEachStmt fs).getVariable() and
3237
not v = any(BindingPatternExpr vpe).getVariableDeclExpr().getVariable() and

0 commit comments

Comments
 (0)