Skip to content

Enhance SyntaxLogicalInverter to handle CoalesceExpressions and add corresponding tests#1069

Merged
josefpihrt merged 4 commits intodotnet:mainfrom
jamesHargreaves12:fix/syntax-invert-coalesce-support
Apr 15, 2023
Merged

Enhance SyntaxLogicalInverter to handle CoalesceExpressions and add corresponding tests#1069
josefpihrt merged 4 commits intodotnet:mainfrom
jamesHargreaves12:fix/syntax-invert-coalesce-support

Conversation

@jamesHargreaves12
Copy link
Contributor

Add explicit handling of CoalesceExpressions in the SyntaxLogicalInverter class. Currently, in Debug mode the Debug.Fail on L213 will be evaluated which is a less-than-ideal experience.

This PR also adds intelligent support for the case where the RHS of the coalesce operator is either true or false.

  • x??true is inverted to x==false
  • x??false is inverted to x!=true

case SyntaxKind.CoalesceExpression:
{
var binaryExpression = (BinaryExpressionSyntax)expression;
if (binaryExpression.Right.Kind() == SyntaxKind.FalseLiteralExpression)
Copy link
Collaborator

@josefpihrt josefpihrt Apr 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use IsKind instead of Kind. It is preferred in the codebase. It has also slightly better perf.

if (binaryExpression.Right.Kind() == SyntaxKind.FalseLiteralExpression)
{
// !(x ?? false) === (x != true)
return BinaryExpression(SyntaxKind.NotEqualsExpression, binaryExpression.Left, LiteralExpression(SyntaxKind.TrueLiteralExpression));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CSharpFactory provides some helper methods to make these calls shorter: CSharpFactory.NotEqualsExpression and CSharpFactory.TrueLiteralExpression.

@josefpihrt josefpihrt merged commit e017499 into dotnet:main Apr 15, 2023
@josefpihrt
Copy link
Collaborator

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants