Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 54 additions & 98 deletions csharp/extractor/Semmle.Extraction.CSharp.Util/SymbolExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;

Expand All @@ -18,114 +20,68 @@ public static string GetName(this ISymbol symbol, bool useMetadataName = false)
return symbol.CanBeReferencedByName ? name : name.Substring(symbol.Name.LastIndexOf('.') + 1);
}

private static readonly ReadOnlyDictionary<string, string> methodToOperator = new(new Dictionary<string, string>
{
{ "op_LogicalNot", "!" },
{ "op_BitwiseAnd", "&" },
{ "op_Equality", "==" },
{ "op_Inequality", "!=" },
{ "op_UnaryPlus", "+" },
{ "op_Addition", "+" },
{ "op_UnaryNegation", "-" },
{ "op_Subtraction", "-" },
{ "op_Multiply", "*" },
{ "op_Multiplication", "*" },
{ "op_Division", "/" },
{ "op_Modulus", "%" },
{ "op_GreaterThan", ">" },
{ "op_GreaterThanOrEqual", ">=" },
{ "op_LessThan", "<" },
{ "op_LessThanOrEqual", "<=" },
{ "op_Decrement", "--" },
{ "op_Increment", "++" },
{ "op_Implicit", "implicit conversion" },
{ "op_Explicit", "explicit conversion" },
{ "op_OnesComplement", "~" },
{ "op_RightShift", ">>" },
{ "op_UnsignedRightShift", ">>>" },
{ "op_LeftShift", "<<" },
{ "op_BitwiseOr", "|" },
{ "op_ExclusiveOr", "^" },
{ "op_True", "true" },
{ "op_False", "false" }
});

/// <summary>
/// Convert an operator method name in to a symbolic name.
/// A return value indicates whether the conversion succeeded.
/// </summary>
public static bool TryGetOperatorSymbol(this ISymbol symbol, out string operatorName)
{
static bool TryGetOperatorSymbolFromName(string methodName, out string operatorName)
var methodName = symbol.GetName(useMetadataName: false);

// Most common use-case.
if (methodToOperator.TryGetValue(methodName, out var opName))
{
var success = true;
switch (methodName)
{
case "op_LogicalNot":
operatorName = "!";
break;
case "op_BitwiseAnd":
operatorName = "&";
break;
case "op_Equality":
operatorName = "==";
break;
case "op_Inequality":
operatorName = "!=";
break;
case "op_UnaryPlus":
case "op_Addition":
operatorName = "+";
break;
case "op_UnaryNegation":
case "op_Subtraction":
operatorName = "-";
break;
case "op_Multiply":
operatorName = "*";
break;
case "op_Division":
operatorName = "/";
break;
case "op_Modulus":
operatorName = "%";
break;
case "op_GreaterThan":
operatorName = ">";
break;
case "op_GreaterThanOrEqual":
operatorName = ">=";
break;
case "op_LessThan":
operatorName = "<";
break;
case "op_LessThanOrEqual":
operatorName = "<=";
break;
case "op_Decrement":
operatorName = "--";
break;
case "op_Increment":
operatorName = "++";
break;
case "op_Implicit":
operatorName = "implicit conversion";
break;
case "op_Explicit":
operatorName = "explicit conversion";
break;
case "op_OnesComplement":
operatorName = "~";
break;
case "op_RightShift":
operatorName = ">>";
break;
case "op_UnsignedRightShift":
operatorName = ">>>";
break;
case "op_LeftShift":
operatorName = "<<";
break;
case "op_BitwiseOr":
operatorName = "|";
break;
case "op_ExclusiveOr":
operatorName = "^";
break;
case "op_True":
operatorName = "true";
break;
case "op_False":
operatorName = "false";
break;
default:
var match = CheckedRegex().Match(methodName);
if (match.Success)
{
TryGetOperatorSymbolFromName($"op_{match.Groups[1]}", out var uncheckedName);
operatorName = $"checked {uncheckedName}";
break;
}
operatorName = methodName;
success = false;
break;
}
return success;
operatorName = opName;
return true;
}

var methodName = symbol.GetName(useMetadataName: false);
return TryGetOperatorSymbolFromName(methodName, out operatorName);
// Attempt to parse using a regexp.
var match = OperatorRegex().Match(methodName);
if (match.Success && methodToOperator.TryGetValue($"op_{match.Groups[2]}", out var rawOperatorName))
{
var prefix = match.Groups[1].Success ? "checked " : "";
var postfix = match.Groups[3].Success ? "=" : "";
operatorName = $"{prefix}{rawOperatorName}{postfix}";
return true;
}

operatorName = methodName;
return false;
}

[GeneratedRegex("^op_Checked(.*)$")]
private static partial Regex CheckedRegex();
[GeneratedRegex("^op_(Checked)?(.*?)(Assignment)?$")]
private static partial Regex OperatorRegex();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,41 @@ type.SpecialType is SpecialType.System_IntPtr ||
return Literal.CreateGenerated(cx, parent, childIndex, type, defaultValue, location);
}

/// <summary>
/// Given an expression syntax node, attempt to resolve the target method symbol for it.
/// The operation takes extension methods into account.
/// </summary>
/// <param name="node">The expression syntax node.</param>
/// <returns>Returns the target method symbol, or null if it cannot be resolved.</returns>
protected IMethodSymbol? GetTargetSymbol(ExpressionSyntax node)
{
var si = Context.GetSymbolInfo(node);
if (si.Symbol is ISymbol symbol)
{
var method = symbol as IMethodSymbol;
// Case for compiler-generated extension methods.
return method?.TryGetExtensionMethod() ?? method;
}

if (si.CandidateReason == CandidateReason.OverloadResolutionFailure && node is InvocationExpressionSyntax syntax)
{
// This seems to be a bug in Roslyn
// For some reason, typeof(X).InvokeMember(...) fails to resolve the correct
// InvokeMember() method, even though the number of parameters clearly identifies the correct method

var candidates = si.CandidateSymbols
.OfType<IMethodSymbol>()
.Where(method => method.Parameters.Length >= syntax.ArgumentList.Arguments.Count)
.Where(method => method.Parameters.Count(p => !p.HasExplicitDefaultValue) <= syntax.ArgumentList.Arguments.Count);

return Context.ExtractionContext.IsStandalone ?
candidates.FirstOrDefault() :
candidates.SingleOrDefault();
}

return si.Symbol as IMethodSymbol;
}

/// <summary>
/// Adapt the operator kind depending on whether it's a dynamic call or a user-operator call.
/// </summary>
Expand All @@ -244,10 +279,10 @@ public static ExprKind UnaryOperatorKind(Context cx, ExprKind originalKind, Expr
/// name if available.
/// </summary>
/// <param name="node">The expression.</param>
public void OperatorCall(TextWriter trapFile, ExpressionSyntax node)
public void AddOperatorCall(TextWriter trapFile, ExpressionSyntax node)
{
var @operator = Context.GetSymbolInfo(node);
if (@operator.Symbol is IMethodSymbol method)
var @operator = GetTargetSymbol(node);
if (@operator is IMethodSymbol method)
{
var callType = GetCallType(Context, node);
if (callType == CallType.Dynamic)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@ protected override void PopulateExpression(TextWriter trapFile)
{
Create(Context, Syntax.Left, this, 0);
Create(Context, Syntax.Right, this, 1);

if (Kind != ExprKind.SIMPLE_ASSIGN && Kind != ExprKind.ASSIGN_COALESCE)
{
OperatorCall(trapFile, Syntax);
AddOperatorCall(trapFile, Syntax);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ private void CreateDeferred(Context cx, ExpressionSyntax node, int child)

protected override void PopulateExpression(TextWriter trapFile)
{
OperatorCall(trapFile, Syntax);
AddOperatorCall(trapFile, Syntax);
CreateDeferred(Context, Syntax.Left, 0);
CreateDeferred(Context, Syntax.Right, 1);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected override void PopulateExpression(TextWriter trapFile)
else
{
// Type conversion
OperatorCall(trapFile, Syntax);
AddOperatorCall(trapFile, Syntax);
TypeMention.Create(Context, Syntax.Type, this, Type);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected override void PopulateExpression(TextWriter trapFile)

var child = -1;
string? memberName = null;
var target = TargetSymbol;
var target = GetTargetSymbol(Syntax);
switch (Syntax.Expression)
{
case MemberAccessExpressionSyntax memberAccess when IsValidMemberAccessKind():
Expand Down Expand Up @@ -129,39 +129,6 @@ private static bool IsOperatorLikeCall(ExpressionNodeInfo info)
method.TryGetExtensionMethod()?.MethodKind == MethodKind.UserDefinedOperator;
}

public IMethodSymbol? TargetSymbol
{
get
{
var si = SymbolInfo;

if (si.Symbol is ISymbol symbol)
{
var method = symbol as IMethodSymbol;
// Case for compiler-generated extension methods.
return method?.TryGetExtensionMethod() ?? method;
}

if (si.CandidateReason == CandidateReason.OverloadResolutionFailure)
{
// This seems to be a bug in Roslyn
// For some reason, typeof(X).InvokeMember(...) fails to resolve the correct
// InvokeMember() method, even though the number of parameters clearly identifies the correct method

var candidates = si.CandidateSymbols
.OfType<IMethodSymbol>()
.Where(method => method.Parameters.Length >= Syntax.ArgumentList.Arguments.Count)
.Where(method => method.Parameters.Count(p => !p.HasExplicitDefaultValue) <= Syntax.ArgumentList.Arguments.Count);

return Context.ExtractionContext.IsStandalone ?
candidates.FirstOrDefault() :
candidates.SingleOrDefault();
}

return si.Symbol as IMethodSymbol;
}
}

private static bool IsDelegateLikeCall(ExpressionNodeInfo info)
{
return IsDelegateLikeCall(info, symbol => IsFunctionPointer(symbol) || IsDelegateInvoke(symbol));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected override void PopulateExpression(TextWriter trapFile)
if ((operatorKind == ExprKind.POST_INCR || operatorKind == ExprKind.POST_DECR) &&
Kind == ExprKind.OPERATOR_INVOCATION)
{
OperatorCall(trapFile, Syntax);
AddOperatorCall(trapFile, Syntax);
trapFile.mutator_invocation_mode(this, 2);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static Unary Create(ExpressionNodeInfo info)
protected override void PopulateExpression(TextWriter trapFile)
{
Create(Context, Syntax.Operand, this, 0);
OperatorCall(trapFile, Syntax);
AddOperatorCall(trapFile, Syntax);

if ((operatorKind == ExprKind.PRE_INCR || operatorKind == ExprKind.PRE_DECR) &&
Kind == ExprKind.OPERATOR_INVOCATION)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* C# 14: Added support for user-defined compound assignment operators.
3 changes: 2 additions & 1 deletion csharp/ql/lib/semmle/code/csharp/Assignable.qll
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,8 @@ module AssignableInternal {
TAddressOfDefinition(AddressOfExpr aoe) or
TPatternDefinition(TopLevelPatternDecl tlpd) or
TAssignOperationDefinition(AssignOperation ao) {
ao instanceof AssignCallOperation or
ao instanceof AssignCallOperation and not ao instanceof CompoundAssignmentOperatorCall
or
ao instanceof AssignCoalesceExpr
}

Expand Down
Loading
Loading