Skip to content

Commit

Permalink
Merge pull request #54351 from dotnet/merges/main-to-main-vs-deps
Browse files Browse the repository at this point in the history
Merge main to main-vs-deps
  • Loading branch information
msftbot[bot] authored Jun 24, 2021
2 parents 93d1a4a + 4792724 commit c6bdb82
Show file tree
Hide file tree
Showing 35 changed files with 329 additions and 167 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.UseCompoundAssignment;

namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment
Expand All @@ -30,14 +31,32 @@ protected override AssignmentExpressionSyntax Assignment(
return SyntaxFactory.AssignmentExpression(assignmentOpKind, left, syntaxToken, right);
}

protected override ExpressionSyntax Increment(ExpressionSyntax left)
{
return SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostIncrementExpression, left);
}
protected override ExpressionSyntax Increment(ExpressionSyntax left, bool postfix)
=> postfix
? Postfix(SyntaxKind.PostIncrementExpression, left)
: Prefix(SyntaxKind.PreIncrementExpression, left);

protected override ExpressionSyntax Decrement(ExpressionSyntax left, bool postfix)
=> postfix
? Postfix(SyntaxKind.PostDecrementExpression, left)
: Prefix(SyntaxKind.PreDecrementExpression, left);

protected override ExpressionSyntax Decrement(ExpressionSyntax left)
private static ExpressionSyntax Postfix(SyntaxKind kind, ExpressionSyntax operand)
=> SyntaxFactory.PostfixUnaryExpression(kind, operand);

private static ExpressionSyntax Prefix(SyntaxKind kind, ExpressionSyntax operand)
=> SyntaxFactory.PrefixUnaryExpression(kind, operand);

protected override bool PreferPostfix(ISyntaxFactsService syntaxFacts, AssignmentExpressionSyntax currentAssignment)
{
return SyntaxFactory.PostfixUnaryExpression(SyntaxKind.PostDecrementExpression, left);
// in `for (...; x = x + 1)` we prefer to translate that idiomatically as `for (...; x++)`
if (currentAssignment.Parent is ForStatementSyntax forStatement &&
forStatement.Incrementors.Contains(currentAssignment))
{
return true;
}

return base.PreferPostfix(syntaxFacts, currentAssignment);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1093,5 +1093,109 @@ void M()
}
}");
}

[WorkItem(38054, "https://github.com/dotnet/roslyn/issues/53969")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
public async Task TestIncrementInExpressionContext()
{
await TestInRegularAndScript1Async(
@"public class C
{
void M(int i)
{
M(i [||]= i + 1);
}
}",
@"public class C
{
void M(int i)
{
M(++i);
}
}");
}

[WorkItem(38054, "https://github.com/dotnet/roslyn/issues/53969")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
[InlineData("switch($$) { }")]
[InlineData("while(($$) > 0) { }")]
[InlineData("_ = true ? $$ : 0;")]
[InlineData("_ = ($$);")]
public async Task TestPrefixIncrement1(string expressionContext)
{
var before = expressionContext.Replace("$$", "i [||]= i + 1");
var after = expressionContext.Replace("$$", "++i");
await TestInRegularAndScript1Async(
@$"public class C
{{
void M(int i)
{{
{before}
}}
}}",
@$"public class C
{{
void M(int i)
{{
{after}
}}
}}");
}

[WorkItem(38054, "https://github.com/dotnet/roslyn/issues/53969")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
[InlineData("return $$;")]
[InlineData("return true ? $$ : 0;")]
[InlineData("return ($$);")]
public async Task TestPrefixIncrement2(string expressionContext)
{
var before = expressionContext.Replace("$$", "i [||]= i + 1");
var after = expressionContext.Replace("$$", "++i");
await TestInRegularAndScript1Async(
@$"public class C
{{
int M(int i)
{{
{before}
}}
}}",
@$"public class C
{{
int M(int i)
{{
{after}
}}
}}");
}

[WorkItem(38054, "https://github.com/dotnet/roslyn/issues/53969")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseCompoundAssignment)]
[InlineData(
"/* Before */ i [||]= i + 1; /* After */",
"/* Before */ i++; /* After */")]
[InlineData(
"M( /* Before */ i [||]= i + 1 /* After */ );",
"M( /* Before */ ++i /* After */ );")]
[InlineData(
"M( /* Before */ i [||]= i - 1 /* After */ );",
"M( /* Before */ --i /* After */ );")]
public async Task TestTriviaPreserved(string before, string after)
{
await TestInRegularAndScript1Async(
@$"public class C
{{
int M(int i)
{{
{before}
}}
}}",
@$"public class C
{{
int M(int i)
{{
{after}
}}
}}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ protected AbstractUseCompoundAssignmentCodeFixProvider(
protected abstract SyntaxToken Token(TSyntaxKind kind);
protected abstract TAssignmentSyntax Assignment(
TSyntaxKind assignmentOpKind, TExpressionSyntax left, SyntaxToken syntaxToken, TExpressionSyntax right);
protected abstract TExpressionSyntax Increment(TExpressionSyntax left);
protected abstract TExpressionSyntax Decrement(TExpressionSyntax left);
protected abstract TExpressionSyntax Increment(TExpressionSyntax left, bool postfix);
protected abstract TExpressionSyntax Decrement(TExpressionSyntax left, bool postfix);

public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
Expand All @@ -68,8 +68,11 @@ protected override Task FixAllAsync(
var assignment = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken);

editor.ReplaceNode(assignment,
(currentAssignment, generator) =>
(current, generator) =>
{
if (current is not TAssignmentSyntax currentAssignment)
return current;
syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(currentAssignment,
out var leftOfAssign, out var equalsToken, out var rightOfAssign);
Expand All @@ -80,14 +83,10 @@ protected override Task FixAllAsync(
out _, out var opToken, out var rightExpr);
if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Increment))
{
return Increment((TExpressionSyntax)leftOfAssign);
}
return Increment((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment);
if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Decrement))
{
return Decrement((TExpressionSyntax)leftOfAssign);
}
return Decrement((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment);
var assignmentOpKind = _binaryToAssignmentMap[syntaxKinds.Convert<TSyntaxKind>(rightOfAssign.RawKind)];
var compoundOperator = Token(_assignmentToTokenMap[assignmentOpKind]);
Expand All @@ -102,6 +101,17 @@ protected override Task FixAllAsync(
return Task.CompletedTask;
}

protected virtual bool PreferPostfix(ISyntaxFactsService syntaxFacts, TAssignmentSyntax currentAssignment)
{
// If we have `x = x + 1;` on it's own, then we prefer `x++` as idiomatic.
if (syntaxFacts.IsSimpleAssignmentStatement(currentAssignment.Parent))
return true;

// In any other circumstance, the value of the assignment might be read, so we need to transform to
// ++x to ensure that we preserve semantics.
return false;
}

private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UseCompoundAssignment
Return SyntaxFactory.AssignmentStatement(assignmentOpKind, left, syntaxToken, right)
End Function

Protected Overrides Function Increment(left As ExpressionSyntax) As ExpressionSyntax
Protected Overrides Function Increment(left As ExpressionSyntax, postfix As Boolean) As ExpressionSyntax
Throw ExceptionUtilities.Unreachable
End Function

Protected Overrides Function Decrement(left As ExpressionSyntax) As ExpressionSyntax
Protected Overrides Function Decrement(left As ExpressionSyntax, postfix As Boolean) As ExpressionSyntax
Throw ExceptionUtilities.Unreachable
End Function
End Class
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators)
/// <param name="incrementalGenerators">The incremental generators to create this driver with</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators)
=> Create(incrementalGenerators.Select(WrapGenerator), additionalTexts: null);
=> Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null);

/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ public void TestLoadGenerators()
{
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);
var generators = reference.GetGeneratorsForAllLanguages();
var typeNames = generators.Select(g => GeneratorDriver.GetGeneratorType(g).FullName);
var typeNames = generators.Select(g => g.GetGeneratorType().FullName);

AssertEx.SetEqual(new[]
{
Expand Down Expand Up @@ -291,7 +291,7 @@ public void TestLoadCSharpGenerators()
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);
var generators = reference.GetGenerators(LanguageNames.CSharp);

var typeNames = generators.Select(g => GeneratorDriver.GetGeneratorType(g).FullName);
var typeNames = generators.Select(g => g.GetGeneratorType().FullName);
AssertEx.SetEqual(new[]
{
"Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator",
Expand All @@ -313,7 +313,7 @@ public void TestLoadVisualBasicGenerators()
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);
var generators = reference.GetGenerators(LanguageNames.VisualBasic);

var typeNames = generators.Select(g => GeneratorDriver.GetGeneratorType(g).FullName);
var typeNames = generators.Select(g => g.GetGeneratorType().FullName);
AssertEx.SetEqual(new[]
{
"Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator",
Expand Down Expand Up @@ -436,7 +436,7 @@ public void TestLoadedGeneratorOrderIsDeterministic()
{
AnalyzerFileReference reference = CreateAnalyzerFileReference(Assembly.GetExecutingAssembly().Location);

var csharpGenerators = reference.GetGenerators(LanguageNames.CSharp).Select(g => GeneratorDriver.GetGeneratorType(g).FullName).ToArray();
var csharpGenerators = reference.GetGenerators(LanguageNames.CSharp).Select(g => g.GetGeneratorType().FullName).ToArray();
Assert.Equal(10, csharpGenerators.Length);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", csharpGenerators[0]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", csharpGenerators[1]);
Expand All @@ -449,7 +449,7 @@ public void TestLoadedGeneratorOrderIsDeterministic()
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestSourceAndIncrementalGenerator", csharpGenerators[8]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicAndCSharpGenerator", csharpGenerators[9]);

var vbGenerators = reference.GetGenerators(LanguageNames.VisualBasic).Select(g => GeneratorDriver.GetGeneratorType(g).FullName).ToArray();
var vbGenerators = reference.GetGenerators(LanguageNames.VisualBasic).Select(g => g.GetGeneratorType().FullName).ToArray();
Assert.Equal(5, vbGenerators.Length);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.CSharpAndVisualBasicGenerator", vbGenerators[0]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.TestIncrementalGenerator", vbGenerators[1]);
Expand All @@ -458,7 +458,7 @@ public void TestLoadedGeneratorOrderIsDeterministic()
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.VisualBasicOnlyGenerator", vbGenerators[4]);

// generators load in language order (C#, F#, VB), and *do not* include duplicates
var allGenerators = reference.GetGeneratorsForAllLanguages().Select(g => GeneratorDriver.GetGeneratorType(g).FullName).ToArray();
var allGenerators = reference.GetGeneratorsForAllLanguages().Select(g => g.GetGeneratorType().FullName).ToArray();
Assert.Equal(12, allGenerators.Length);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+SomeType+NestedGenerator", allGenerators[0]);
Assert.Equal("Microsoft.CodeAnalysis.UnitTests.AnalyzerFileReferenceTests+TestGenerator", allGenerators[1]);
Expand Down
5 changes: 3 additions & 2 deletions src/Compilers/Core/Portable/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Co
Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle>
Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void
Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]!
Microsoft.CodeAnalysis.GeneratorExtensions
Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool
Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver?
Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void
Expand Down Expand Up @@ -86,10 +87,10 @@ override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVis
override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object?
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator!
static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type!
static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.GeneratorDriver.GetGeneratorType(Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type!
static Microsoft.CodeAnalysis.GeneratorDriver.WrapGenerator(Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator!
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)>
Expand Down
Loading

0 comments on commit c6bdb82

Please sign in to comment.