Browse Source

Merge NRefactory commit 'e54b06b3be07cbc97e2d81f0eda86516454d109b' into SharpDevelop newNR branch

newNRvisualizers
Daniel Grunwald 14 years ago
parent
commit
3b54e2665c
  1. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs
  2. 84
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj
  3. 273
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs
  4. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/BaseRefactoringContext.cs
  5. 55
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeAction.cs
  6. 29
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/AddAnotherAccessor.cs
  7. 36
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CheckIfParameterIsNull.cs
  8. 24
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertDecToHex.cs
  9. 33
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertForeachToFor.cs
  10. 24
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertHexToDec.cs
  11. 76
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateBackingStore.cs
  12. 112
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateEventInvocator.cs
  13. 24
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateField.cs
  14. 32
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateLocalVariable.cs
  15. 22
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateProperty.cs
  16. 19
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/FlipOperatorArguments.cs
  17. 34
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GenerateGetter.cs
  18. 33
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GenerateProperty.cs
  19. 29
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GenerateSwitchLabels.cs
  20. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/InsertAnonymousMethodSignature.cs
  21. 35
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/IntroduceFormatItem.cs
  22. 20
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/InvertIf.cs
  23. 20
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveBackingStore.cs
  24. 18
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveBraces.cs
  25. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveRegion.cs
  26. 18
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ReplaceEmptyString.cs
  27. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/SplitDeclarationAndAssignment.cs
  28. 37
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/SplitString.cs
  29. 25
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/UseExplicitType.cs
  30. 21
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/UseVarKeyword.cs
  31. 16
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssue.cs
  32. 25
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/ConditionalToNullCoalescingInspector.cs
  33. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/GatherVisitorBase.cs
  34. 41
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/IssueCategories.cs
  35. 21
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/NotImplementedExceptionInspector.cs
  36. 24
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantInternalInspector.cs
  37. 26
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantNamespaceUsageInspector.cs
  38. 26
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantPrivateInspector.cs
  39. 26
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantThisInspector.cs
  40. 128
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantUsingInspector.cs
  41. 25
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/StringIsNullOrEmptyInspector.cs
  42. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/UseVarKeywordInspector.cs
  43. 78
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CreateBackingStore.cs
  44. 110
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CreateEventInvocator.cs
  45. 42
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextActionAttribute.cs
  46. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ICodeActionProvider.cs
  47. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ICodeIssueProvider.cs
  48. 77
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/RedundantUsingInspector.cs
  49. 50
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/IssueAttribute.cs
  50. 52
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/IssueMarker.cs
  51. 61
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Severity.cs
  52. 32
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs
  53. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/MethodGroupResolveResult.cs
  54. 15
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/ContextActionTestBase.cs
  55. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/GenerateGetterTests.cs
  56. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/GeneratePropertyTests.cs
  57. 16
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/TestRefactoringContext.cs
  58. 133
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/ConditionalToNullCoalescingInspectorTests.cs
  59. 53
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/InspectionActionTestBase.cs
  60. 53
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/NotImplementedExceptionInspectorTests.cs
  61. 51
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantInternalInspectorTests.cs
  62. 54
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantNamespaceUsageInspectorTests.cs
  63. 52
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantPrivateInspectorTests.cs
  64. 53
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantThisInspectorTests.cs
  65. 54
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantUsingInspectorTests.cs
  66. 55
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/StringIsNullOrEmptyInspectorTests.cs
  67. 53
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/UseVarKeywordInspectorTests.cs
  68. 18
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs
  69. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/FormattingTests/TestStatementIndentation.cs
  70. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj

3
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs

@ -1261,7 +1261,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1261,7 +1261,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
var isAsWrapper = new CompletionDataWrapper (this);
AddTypesAndNamespaces(isAsWrapper, GetState(), null, t => isAsType == null || t.GetDefinition().IsDerivedFrom(isAsType.GetDefinition()), m => false);
var def = isAsType != null ? isAsType.GetDefinition() : null;
AddTypesAndNamespaces(isAsWrapper, GetState(), null, t => t.GetDefinition() == null || def == null || t.GetDefinition().IsDerivedFrom(def), m => false);
return isAsWrapper.Result;
// {
// CompletionDataList completionList = new ProjectDomCompletionDataList ();

84
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj

@ -240,31 +240,7 @@ @@ -240,31 +240,7 @@
<Compile Include="Parser\mcs\typespec.cs" />
<Compile Include="Parser\mcs\visit.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Refactoring\ContextAction\AddAnotherAccessor.cs" />
<Compile Include="Refactoring\ContextAction\CheckIfParameterIsNull.cs" />
<Compile Include="Refactoring\ContextAction\ConvertDecToHex.cs" />
<Compile Include="Refactoring\ContextAction\ConvertForeachToFor.cs" />
<Compile Include="Refactoring\ContextAction\ConvertHexToDec.cs" />
<Compile Include="Refactoring\ContextAction\CreateBackingStore.cs" />
<Compile Include="Refactoring\ContextAction\CreateEventInvocator.cs" />
<Compile Include="Refactoring\ContextAction\CreateField.cs" />
<Compile Include="Refactoring\ContextAction\CreateLocalVariable.cs" />
<Compile Include="Refactoring\ContextAction\CreateProperty.cs" />
<Compile Include="Refactoring\ContextAction\FlipOperatorArguments.cs" />
<Compile Include="Refactoring\ContextAction\GenerateGetter.cs" />
<Compile Include="Refactoring\ContextAction\GenerateSwitchLabels.cs" />
<Compile Include="Refactoring\ContextAction\InsertAnonymousMethodSignature.cs" />
<Compile Include="Refactoring\ContextAction\IntroduceFormatItem.cs" />
<Compile Include="Refactoring\ContextAction\InvertIf.cs" />
<Compile Include="Refactoring\ContextAction\RemoveBackingStore.cs" />
<Compile Include="Refactoring\ContextAction\RemoveBraces.cs" />
<Compile Include="Refactoring\ContextAction\ReplaceEmptyString.cs" />
<Compile Include="Refactoring\ContextAction\SplitDeclarationAndAssignment.cs" />
<Compile Include="Refactoring\ContextAction\SplitString.cs" />
<Compile Include="Refactoring\ContextAction\UseExplicitType.cs" />
<Compile Include="Refactoring\ContextAction\UseVarKeyword.cs" />
<Compile Include="Refactoring\DocumentScript.cs" />
<Compile Include="Refactoring\IContextAction.cs" />
<Compile Include="Refactoring\PatternHelper.cs" />
<Compile Include="Refactoring\RefactoringAstHelper.cs" />
<Compile Include="Refactoring\RefactoringContext.cs" />
@ -321,22 +297,52 @@ @@ -321,22 +297,52 @@
<Compile Include="Parser\mcs\settings.cs" />
<Compile Include="Parser\mcs\SourceMethodBuilder.cs" />
<Compile Include="Ast\TokenRole.cs" />
<Compile Include="Refactoring\ContextAction\RemoveRegion.cs" />
<Compile Include="Refactoring\ContextAction\GenerateProperty.cs" />
<Compile Include="Ast\Roles.cs" />
<Compile Include="Refactoring\Inspector\ConditionalToNullCoalescingInspector.cs" />
<Compile Include="Refactoring\IInspector.cs" />
<Compile Include="Refactoring\InspectionIssue.cs" />
<Compile Include="Refactoring\BaseRefactoringContext.cs" />
<Compile Include="Refactoring\Inspector\GatherVisitorBase.cs" />
<Compile Include="Refactoring\Inspector\NotImplementedExceptionInspector.cs" />
<Compile Include="Refactoring\Inspector\RedundantInternalInspector.cs" />
<Compile Include="Refactoring\Inspector\RedundantNamespaceUsageInspector.cs" />
<Compile Include="Refactoring\Inspector\RedundantPrivateInspector.cs" />
<Compile Include="Refactoring\Inspector\RedundantThisInspector.cs" />
<Compile Include="Refactoring\Inspector\RedundantUsingInspector.cs" />
<Compile Include="Refactoring\Inspector\StringIsNullOrEmptyInspector.cs" />
<Compile Include="Refactoring\Inspector\UseVarKeywordInspector.cs" />
<Compile Include="Refactoring\CodeIssue.cs" />
<Compile Include="Refactoring\CodeAction.cs" />
<Compile Include="Refactoring\ICodeActionProvider.cs" />
<Compile Include="Refactoring\CodeActions\AddAnotherAccessor.cs" />
<Compile Include="Refactoring\ICodeIssueProvider.cs" />
<Compile Include="Refactoring\CodeActions\CheckIfParameterIsNull.cs" />
<Compile Include="Refactoring\CodeActions\ConvertDecToHex.cs" />
<Compile Include="Refactoring\CodeActions\ConvertForeachToFor.cs" />
<Compile Include="Refactoring\CodeActions\ConvertHexToDec.cs" />
<Compile Include="Refactoring\CodeActions\CreateBackingStore.cs" />
<Compile Include="Refactoring\CodeActions\CreateEventInvocator.cs" />
<Compile Include="Refactoring\CodeActions\CreateField.cs" />
<Compile Include="Refactoring\CodeActions\CreateLocalVariable.cs" />
<Compile Include="Refactoring\CodeActions\CreateProperty.cs" />
<Compile Include="Refactoring\CodeActions\FlipOperatorArguments.cs" />
<Compile Include="Refactoring\CodeActions\GenerateGetter.cs" />
<Compile Include="Refactoring\CodeActions\GenerateSwitchLabels.cs" />
<Compile Include="Refactoring\CodeActions\InsertAnonymousMethodSignature.cs" />
<Compile Include="Refactoring\CodeActions\IntroduceFormatItem.cs" />
<Compile Include="Refactoring\CodeActions\InvertIf.cs" />
<Compile Include="Refactoring\CodeActions\RemoveBackingStore.cs" />
<Compile Include="Refactoring\CodeActions\RemoveBraces.cs" />
<Compile Include="Refactoring\CodeActions\ReplaceEmptyString.cs" />
<Compile Include="Refactoring\CodeActions\SplitDeclarationAndAssignment.cs" />
<Compile Include="Refactoring\CodeActions\SplitString.cs" />
<Compile Include="Refactoring\CodeActions\UseExplicitType.cs" />
<Compile Include="Refactoring\CodeActions\UseVarKeyword.cs" />
<Compile Include="Refactoring\CodeActions\RemoveRegion.cs" />
<Compile Include="Refactoring\CodeActions\GenerateProperty.cs" />
<Compile Include="Refactoring\ContextActionAttribute.cs" />
<Compile Include="Refactoring\IssueAttribute.cs" />
<Compile Include="Refactoring\CodeIssues\IssueCategories.cs" />
<Compile Include="Refactoring\Severity.cs" />
<Compile Include="Refactoring\IssueMarker.cs" />
<Compile Include="Refactoring\CodeIssues\ConditionalToNullCoalescingInspector.cs" />
<Compile Include="Refactoring\CodeIssues\GatherVisitorBase.cs" />
<Compile Include="Refactoring\CodeIssues\NotImplementedExceptionInspector.cs" />
<Compile Include="Refactoring\CodeIssues\RedundantInternalInspector.cs" />
<Compile Include="Refactoring\CodeIssues\RedundantNamespaceUsageInspector.cs" />
<Compile Include="Refactoring\CodeIssues\RedundantPrivateInspector.cs" />
<Compile Include="Refactoring\CodeIssues\RedundantThisInspector.cs" />
<Compile Include="Refactoring\CodeIssues\RedundantUsingInspector.cs" />
<Compile Include="Refactoring\CodeIssues\StringIsNullOrEmptyInspector.cs" />
<Compile Include="Refactoring\CodeIssues\UseVarKeywordInspector.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
@ -347,7 +353,7 @@ @@ -347,7 +353,7 @@
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
<ItemGroup>
<Folder Include="Completion\" />
<Folder Include="Refactoring\Inspector\" />
<Folder Include="Refactoring\CodeIssues\" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>

273
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs

@ -15,7 +15,6 @@ @@ -15,7 +15,6 @@
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
@ -58,20 +57,24 @@ namespace ICSharpCode.NRefactory.CSharp @@ -58,20 +57,24 @@ namespace ICSharpCode.NRefactory.CSharp
public CSharpOutputVisitor (TextWriter textWriter, CSharpFormattingOptions formattingPolicy)
{
if (textWriter == null)
if (textWriter == null) {
throw new ArgumentNullException ("textWriter");
if (formattingPolicy == null)
}
if (formattingPolicy == null) {
throw new ArgumentNullException ("formattingPolicy");
}
this.formatter = new TextWriterOutputFormatter (textWriter);
this.policy = formattingPolicy;
}
public CSharpOutputVisitor (IOutputFormatter formatter, CSharpFormattingOptions formattingPolicy)
{
if (formatter == null)
if (formatter == null) {
throw new ArgumentNullException ("formatter");
if (formattingPolicy == null)
}
if (formattingPolicy == null) {
throw new ArgumentNullException ("formattingPolicy");
}
this.formatter = formatter;
this.policy = formattingPolicy;
}
@ -82,8 +85,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -82,8 +85,9 @@ namespace ICSharpCode.NRefactory.CSharp
// Ensure that nodes are visited in the proper nested order.
// Jumps to different subtrees are allowed only for the child of a placeholder node.
Debug.Assert(containerStack.Count == 0 || node.Parent == containerStack.Peek() || containerStack.Peek().NodeType == NodeType.Pattern);
if (positionStack.Count > 0)
if (positionStack.Count > 0) {
WriteSpecialsUpToNode(node);
}
containerStack.Push(node);
positionStack.Push(node.FirstChild);
formatter.StartNode(node);
@ -124,8 +128,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -124,8 +128,9 @@ namespace ICSharpCode.NRefactory.CSharp
void WriteSpecialsUpToRole(Role role, AstNode nextNode)
{
if (positionStack.Count == 0)
if (positionStack.Count == 0) {
return;
}
// Look for the role between the current position and the nextNode.
for (AstNode pos = positionStack.Peek(); pos != null && pos != nextNode; pos = pos.NextSibling) {
if (pos.Role == role) {
@ -145,8 +150,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -145,8 +150,9 @@ namespace ICSharpCode.NRefactory.CSharp
/// </summary>
void WriteSpecialsUpToNode(AstNode node)
{
if (positionStack.Count == 0)
if (positionStack.Count == 0) {
return;
}
for (AstNode pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) {
if (pos == node) {
WriteSpecials(positionStack.Pop(), pos);
@ -169,10 +175,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -169,10 +175,12 @@ namespace ICSharpCode.NRefactory.CSharp
void Comma(AstNode nextNode, bool noSpaceAfterComma = false)
{
WriteSpecialsUpToRole(Roles.Comma, nextNode);
Space (policy.SpaceBeforeBracketComma); // TODO: Comma policy has changed.
Space(policy.SpaceBeforeBracketComma);
// TODO: Comma policy has changed.
formatter.WriteToken(",");
lastWritten = LastWritten.Other;
Space (!noSpaceAfterComma && policy.SpaceAfterBracketComma); // TODO: Comma policy has changed.
Space(!noSpaceAfterComma && policy.SpaceAfterBracketComma);
// TODO: Comma policy has changed.
}
/// <summary>
@ -182,11 +190,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -182,11 +190,13 @@ namespace ICSharpCode.NRefactory.CSharp
{
// Look if there's a comma after the current node, and insert it if it exists.
AstNode pos = positionStack.Peek();
while (pos != null && pos.NodeType == NodeType.Whitespace)
while (pos != null && pos.NodeType == NodeType.Whitespace) {
pos = pos.NextSibling;
if (pos != null && pos.Role == Roles.Comma)
}
if (pos != null && pos.Role == Roles.Comma) {
Comma(null, noSpaceAfterComma: true);
}
}
/// <summary>
/// Writes an optional semicolon, e.g. at the end of a type or namespace declaration.
@ -195,11 +205,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -195,11 +205,13 @@ namespace ICSharpCode.NRefactory.CSharp
{
// Look if there's a semicolon after the current node, and insert it if it exists.
AstNode pos = positionStack.Peek();
while (pos != null && pos.NodeType == NodeType.Whitespace)
while (pos != null && pos.NodeType == NodeType.Whitespace) {
pos = pos.NextSibling;
if (pos != null && pos.Role == Roles.Semicolon)
}
if (pos != null && pos.Role == Roles.Semicolon) {
Semicolon();
}
}
void WriteCommaSeparatedList(IEnumerable<AstNode> list)
{
@ -282,10 +294,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -282,10 +294,12 @@ namespace ICSharpCode.NRefactory.CSharp
void WriteKeyword(string token, Role tokenRole = null)
{
if (tokenRole != null)
if (tokenRole != null) {
WriteSpecialsUpToRole(tokenRole);
if (lastWritten == LastWritten.KeywordOrIdentifier)
}
if (lastWritten == LastWritten.KeywordOrIdentifier) {
formatter.Space();
}
formatter.WriteKeyword(token);
lastWritten = LastWritten.KeywordOrIdentifier;
}
@ -303,11 +317,14 @@ namespace ICSharpCode.NRefactory.CSharp @@ -303,11 +317,14 @@ namespace ICSharpCode.NRefactory.CSharp
{
WriteSpecialsUpToRole(identifierRole ?? Roles.Identifier);
if (IsKeyword(identifier, containerStack.Peek())) {
if (lastWritten == LastWritten.KeywordOrIdentifier)
Space (); // this space is not strictly required, so we call Space()
if (lastWritten == LastWritten.KeywordOrIdentifier) {
Space();
}
// this space is not strictly required, so we call Space()
formatter.WriteToken("@");
} else if (lastWritten == LastWritten.KeywordOrIdentifier) {
formatter.Space (); // this space is strictly required, so we directly call the formatter
formatter.Space();
// this space is strictly required, so we directly call the formatter
}
formatter.WriteIdentifier(identifier);
lastWritten = LastWritten.KeywordOrIdentifier;
@ -335,19 +352,20 @@ namespace ICSharpCode.NRefactory.CSharp @@ -335,19 +352,20 @@ namespace ICSharpCode.NRefactory.CSharp
formatter.Space();
}
formatter.WriteToken(token);
if (token == "+")
if (token == "+") {
lastWritten = LastWritten.Plus;
else if (token == "-")
} else if (token == "-") {
lastWritten = LastWritten.Minus;
else if (token == "&")
} else if (token == "&") {
lastWritten = LastWritten.Ampersand;
else if (token == "?")
} else if (token == "?") {
lastWritten = LastWritten.QuestionMark;
else if (token == "/")
} else if (token == "/") {
lastWritten = LastWritten.Division;
else
} else {
lastWritten = LastWritten.Other;
}
}
void LPar()
{
@ -364,7 +382,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -364,7 +382,8 @@ namespace ICSharpCode.NRefactory.CSharp
/// </summary>
void Semicolon()
{
Role role = containerStack.Peek ().Role; // get the role of the current node
Role role = containerStack.Peek().Role;
// get the role of the current node
if (!(role == ForStatement.InitializerRole || role == ForStatement.IteratorRole || role == UsingStatement.ResourceAcquisitionRole)) {
WriteToken(Roles.Semicolon);
NewLine();
@ -427,21 +446,26 @@ namespace ICSharpCode.NRefactory.CSharp @@ -427,21 +446,26 @@ namespace ICSharpCode.NRefactory.CSharp
/// </summary>
public static bool IsKeyword(string identifier, AstNode context)
{
if (unconditionalKeywords.Contains (identifier))
if (unconditionalKeywords.Contains(identifier)) {
return true;
}
foreach (AstNode ancestor in context.Ancestors) {
if (ancestor is QueryExpression && queryKeywords.Contains (identifier))
if (ancestor is QueryExpression && queryKeywords.Contains(identifier)) {
return true;
}
if (identifier == "await") {
// with lambdas/anonymous methods,
if (ancestor is LambdaExpression)
if (ancestor is LambdaExpression) {
return ((LambdaExpression)ancestor).IsAsync;
if (ancestor is AnonymousMethodExpression)
}
if (ancestor is AnonymousMethodExpression) {
return ((AnonymousMethodExpression)ancestor).IsAsync;
if (ancestor is EntityDeclaration)
}
if (ancestor is EntityDeclaration) {
return (((EntityDeclaration)ancestor).Modifiers & Modifiers.Async) == Modifiers.Async;
}
}
}
return false;
}
#endregion
@ -478,8 +502,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -478,8 +502,9 @@ namespace ICSharpCode.NRefactory.CSharp
foreach (Identifier ident in identifiers) {
if (first) {
first = false;
if (lastWritten == LastWritten.KeywordOrIdentifier)
if (lastWritten == LastWritten.KeywordOrIdentifier) {
formatter.Space();
}
} else {
WriteSpecialsUpToRole(Roles.Dot, ident);
formatter.WriteToken(".");
@ -493,12 +518,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -493,12 +518,13 @@ namespace ICSharpCode.NRefactory.CSharp
void WriteEmbeddedStatement(Statement embeddedStatement)
{
if (embeddedStatement.IsNull)
if (embeddedStatement.IsNull) {
return;
}
BlockStatement block = embeddedStatement as BlockStatement;
if (block != null)
if (block != null) {
VisitBlockStatement(block);
else {
} else {
NewLine();
formatter.Indent();
embeddedStatement.AcceptVisitor(this);
@ -508,11 +534,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -508,11 +534,12 @@ namespace ICSharpCode.NRefactory.CSharp
void WriteMethodBody(BlockStatement body)
{
if (body.IsNull)
if (body.IsNull) {
Semicolon();
else
} else {
VisitBlockStatement(body);
}
}
void WriteAttributes(IEnumerable<AttributeSection> attributes)
{
@ -578,10 +605,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -578,10 +605,12 @@ namespace ICSharpCode.NRefactory.CSharp
StartNode(arrayCreateExpression);
WriteKeyword(ArrayCreateExpression.NewKeywordRole);
arrayCreateExpression.Type.AcceptVisitor(this);
if (arrayCreateExpression.Arguments.Count > 0)
if (arrayCreateExpression.Arguments.Count > 0) {
WriteCommaSeparatedListInBrackets(arrayCreateExpression.Arguments);
foreach (var specifier in arrayCreateExpression.AdditionalArraySpecifiers)
}
foreach (var specifier in arrayCreateExpression.AdditionalArraySpecifiers) {
specifier.AcceptVisitor(this);
}
arrayCreateExpression.Initializer.AcceptVisitor(this);
EndNode(arrayCreateExpression);
}
@ -615,22 +644,26 @@ namespace ICSharpCode.NRefactory.CSharp @@ -615,22 +644,26 @@ namespace ICSharpCode.NRefactory.CSharp
bool IsObjectOrCollectionInitializer(AstNode node)
{
if (!(node is ArrayInitializerExpression))
if (!(node is ArrayInitializerExpression)) {
return false;
if (node.Parent is ObjectCreateExpression)
}
if (node.Parent is ObjectCreateExpression) {
return node.Role == ObjectCreateExpression.InitializerRole;
if (node.Parent is NamedExpression)
}
if (node.Parent is NamedExpression) {
return node.Role == Roles.Expression;
}
return false;
}
void PrintInitializerElements(AstNodeCollection<Expression> elements)
{
BraceStyle style;
if (policy.PlaceArrayInitializersOnNewLine == ArrayInitializerPlacement.AlwaysNewLine)
if (policy.PlaceArrayInitializersOnNewLine == ArrayInitializerPlacement.AlwaysNewLine) {
style = BraceStyle.NextLine;
else
} else {
style = BraceStyle.EndOfLine;
}
OpenBrace(style);
bool isFirst = true;
foreach (AstNode node in elements) {
@ -863,8 +896,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -863,8 +896,9 @@ namespace ICSharpCode.NRefactory.CSharp
bool LambdaNeedsParenthesis(LambdaExpression lambdaExpression)
{
if (lambdaExpression.Parameters.Count != 1)
if (lambdaExpression.Parameters.Count != 1) {
return true;
}
var p = lambdaExpression.Parameters.Single();
return !(p.Type.IsNull && p.ParameterModifier == ParameterModifier.None);
}
@ -882,7 +916,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -882,7 +916,7 @@ namespace ICSharpCode.NRefactory.CSharp
public void VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
{
StartNode(namedArgumentExpression);
WriteIdentifier (namedArgumentExpression.Identifier);
namedArgumentExpression.IdentifierToken.AcceptVisitor(this);
WriteToken(Roles.Colon);
Space();
namedArgumentExpression.Expression.AcceptVisitor(this);
@ -892,7 +926,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -892,7 +926,7 @@ namespace ICSharpCode.NRefactory.CSharp
public void VisitNamedExpression(NamedExpression namedExpression)
{
StartNode(namedExpression);
WriteIdentifier (namedExpression.Identifier);
namedExpression.IdentifierToken.AcceptVisitor(this);
Space();
WriteToken(Roles.Assign);
Space();
@ -914,8 +948,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -914,8 +948,9 @@ namespace ICSharpCode.NRefactory.CSharp
objectCreateExpression.Type.AcceptVisitor(this);
bool useParenthesis = objectCreateExpression.Arguments.Any() || objectCreateExpression.Initializer.IsNull;
// also use parenthesis if there is an '(' token
if (!objectCreateExpression.LParToken.IsNull)
if (!objectCreateExpression.LParToken.IsNull) {
useParenthesis = true;
}
if (useParenthesis) {
Space(policy.SpaceBeforeMethodCallParentheses);
WriteCommaSeparatedListInParenthesis(objectCreateExpression.Arguments, policy.SpaceWithinMethodCallParentheses);
@ -1004,12 +1039,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1004,12 +1039,13 @@ namespace ICSharpCode.NRefactory.CSharp
// but we still support writing these to make life easier for code generators.
WriteKeyword("float");
WriteToken(Roles.Dot);
if (float.IsPositiveInfinity (f))
if (float.IsPositiveInfinity(f)) {
WriteIdentifier("PositiveInfinity");
else if (float.IsNegativeInfinity (f))
} else if (float.IsNegativeInfinity(f)) {
WriteIdentifier("NegativeInfinity");
else
} else {
WriteIdentifier("NaN");
}
return;
}
formatter.WriteToken(f.ToString("R", NumberFormatInfo.InvariantInfo) + "f");
@ -1021,17 +1057,19 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1021,17 +1057,19 @@ namespace ICSharpCode.NRefactory.CSharp
// but we still support writing these to make life easier for code generators.
WriteKeyword("double");
WriteToken(Roles.Dot);
if (double.IsPositiveInfinity (f))
if (double.IsPositiveInfinity(f)) {
WriteIdentifier("PositiveInfinity");
else if (double.IsNegativeInfinity (f))
} else if (double.IsNegativeInfinity(f)) {
WriteIdentifier("NegativeInfinity");
else
} else {
WriteIdentifier("NaN");
}
return;
}
string number = f.ToString("R", NumberFormatInfo.InvariantInfo);
if (number.IndexOf ('.') < 0 && number.IndexOf ('E') < 0)
if (number.IndexOf('.') < 0 && number.IndexOf('E') < 0) {
number += ".0";
}
formatter.WriteToken(number);
// needs space if identifier follows number; this avoids mistaking the following identifier as type suffix
lastWritten = LastWritten.KeywordOrIdentifier;
@ -1060,8 +1098,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1060,8 +1098,9 @@ namespace ICSharpCode.NRefactory.CSharp
static string ConvertCharLiteral(char ch)
{
if (ch == '\'')
if (ch == '\'') {
return "\\'";
}
return ConvertChar(ch);
}
@ -1108,11 +1147,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1108,11 +1147,12 @@ namespace ICSharpCode.NRefactory.CSharp
{
StringBuilder sb = new StringBuilder ();
foreach (char ch in str) {
if (ch == '"')
if (ch == '"') {
sb.Append("\\\"");
else
} else {
sb.Append(ConvertChar(ch));
}
}
return sb.ToString();
}
@ -1180,8 +1220,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1180,8 +1220,9 @@ namespace ICSharpCode.NRefactory.CSharp
WriteToken(opSymbol);
}
unaryOperatorExpression.Expression.AcceptVisitor(this);
if (opType == UnaryOperatorType.PostIncrement || opType == UnaryOperatorType.PostDecrement)
if (opType == UnaryOperatorType.PostIncrement || opType == UnaryOperatorType.PostDecrement) {
WriteToken(opSymbol);
}
EndNode(unaryOperatorExpression);
}
@ -1213,13 +1254,15 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1213,13 +1254,15 @@ namespace ICSharpCode.NRefactory.CSharp
if (first) {
first = false;
} else {
if (!(clause is QueryContinuationClause))
if (!(clause is QueryContinuationClause)) {
NewLine();
}
}
clause.AcceptVisitor(this);
}
if (indent)
if (indent) {
formatter.Unindent();
}
EndNode(queryExpression);
}
@ -1230,7 +1273,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1230,7 +1273,7 @@ namespace ICSharpCode.NRefactory.CSharp
Space();
WriteKeyword(QueryContinuationClause.IntoKeywordRole);
Space();
WriteIdentifier (queryContinuationClause.Identifier);
queryContinuationClause.IdentifierToken.AcceptVisitor(this);
EndNode(queryContinuationClause);
}
@ -1240,7 +1283,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1240,7 +1283,7 @@ namespace ICSharpCode.NRefactory.CSharp
WriteKeyword(QueryFromClause.FromKeywordRole);
queryFromClause.Type.AcceptVisitor(this);
Space();
WriteIdentifier (queryFromClause.Identifier);
queryFromClause.IdentifierToken.AcceptVisitor(this);
Space();
WriteKeyword(QueryFromClause.InKeywordRole);
Space();
@ -1253,7 +1296,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1253,7 +1296,7 @@ namespace ICSharpCode.NRefactory.CSharp
StartNode(queryLetClause);
WriteKeyword(QueryLetClause.LetKeywordRole);
Space();
WriteIdentifier (queryLetClause.Identifier);
queryLetClause.IdentifierToken.AcceptVisitor(this);
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
Space(policy.SpaceAroundAssignment);
@ -1370,10 +1413,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1370,10 +1413,11 @@ namespace ICSharpCode.NRefactory.CSharp
}
WriteCommaSeparatedList(attributeSection.Attributes);
WriteToken(Roles.RBracket);
if (attributeSection.Parent is ParameterDeclaration || attributeSection.Parent is TypeParameterDeclaration)
if (attributeSection.Parent is ParameterDeclaration || attributeSection.Parent is TypeParameterDeclaration) {
Space();
else
} else {
NewLine();
}
EndNode(attributeSection);
}
@ -1385,7 +1429,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1385,7 +1429,7 @@ namespace ICSharpCode.NRefactory.CSharp
WriteKeyword(Roles.DelegateKeyword);
delegateDeclaration.ReturnType.AcceptVisitor(this);
Space();
WriteIdentifier (delegateDeclaration.Name);
delegateDeclaration.NameToken.AcceptVisitor(this);
WriteTypeParameters(delegateDeclaration.TypeParameters);
Space(policy.SpaceBeforeDelegateDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(delegateDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
@ -1402,8 +1446,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1402,8 +1446,9 @@ namespace ICSharpCode.NRefactory.CSharp
WriteKeyword(Roles.NamespaceKeyword);
WriteQualifiedIdentifier(namespaceDeclaration.Identifiers);
OpenBrace(policy.NamespaceBraceStyle);
foreach (var member in namespaceDeclaration.Members)
foreach (var member in namespaceDeclaration.Members) {
member.AcceptVisitor(this);
}
CloseBrace(policy.NamespaceBraceStyle);
OptionalSemicolon();
NewLine();
@ -1434,7 +1479,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1434,7 +1479,7 @@ namespace ICSharpCode.NRefactory.CSharp
braceStyle = policy.ClassBraceStyle;
break;
}
WriteIdentifier(typeDeclaration.Name);
typeDeclaration.NameToken.AcceptVisitor(this);
WriteTypeParameters(typeDeclaration.TypeParameters);
if (typeDeclaration.BaseTypes.Any()) {
Space();
@ -1520,16 +1565,17 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1520,16 +1565,17 @@ namespace ICSharpCode.NRefactory.CSharp
} else if (blockStatement.Parent is MethodDeclaration) {
style = policy.MethodBraceStyle;
} else if (blockStatement.Parent is Accessor) {
if (blockStatement.Parent.Role == PropertyDeclaration.GetterRole)
if (blockStatement.Parent.Role == PropertyDeclaration.GetterRole) {
style = policy.PropertyGetBraceStyle;
else if (blockStatement.Parent.Role == PropertyDeclaration.SetterRole)
} else if (blockStatement.Parent.Role == PropertyDeclaration.SetterRole) {
style = policy.PropertySetBraceStyle;
else if (blockStatement.Parent.Role == CustomEventDeclaration.AddAccessorRole)
} else if (blockStatement.Parent.Role == CustomEventDeclaration.AddAccessorRole) {
style = policy.EventAddBraceStyle;
else if (blockStatement.Parent.Role == CustomEventDeclaration.RemoveAccessorRole)
} else if (blockStatement.Parent.Role == CustomEventDeclaration.RemoveAccessorRole) {
style = policy.EventRemoveBraceStyle;
else
} else {
style = policy.StatementBraceStyle;
}
} else {
style = policy.StatementBraceStyle;
}
@ -1622,7 +1668,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1622,7 +1668,7 @@ namespace ICSharpCode.NRefactory.CSharp
Space(policy.SpacesWithinForeachParentheses);
foreachStatement.VariableType.AcceptVisitor(this);
Space();
WriteIdentifier (foreachStatement.VariableName);
foreachStatement.VariableNameToken.AcceptVisitor(this);
WriteKeyword(ForeachStatement.InKeywordRole);
Space();
foreachStatement.InExpression.AcceptVisitor(this);
@ -1761,14 +1807,17 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1761,14 +1807,17 @@ namespace ICSharpCode.NRefactory.CSharp
Space(policy.SpacesWithinSwitchParentheses);
RPar();
OpenBrace(policy.StatementBraceStyle);
if (!policy.IndentSwitchBody)
if (!policy.IndentSwitchBody) {
formatter.Unindent();
}
foreach (var section in switchStatement.SwitchSections)
foreach (var section in switchStatement.SwitchSections) {
section.AcceptVisitor(this);
}
if (!policy.IndentSwitchBody)
if (!policy.IndentSwitchBody) {
formatter.Indent();
}
CloseBrace(policy.StatementBraceStyle);
NewLine();
EndNode(switchStatement);
@ -1779,21 +1828,24 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1779,21 +1828,24 @@ namespace ICSharpCode.NRefactory.CSharp
StartNode(switchSection);
bool first = true;
foreach (var label in switchSection.CaseLabels) {
if (!first)
if (!first) {
NewLine();
}
label.AcceptVisitor(this);
first = false;
}
if (policy.IndentCaseBody)
if (policy.IndentCaseBody) {
formatter.Indent();
}
foreach (var statement in switchSection.Statements) {
NewLine();
statement.AcceptVisitor(this);
}
if (policy.IndentCaseBody)
if (policy.IndentCaseBody) {
formatter.Unindent();
}
EndNode(switchSection);
}
@ -1829,8 +1881,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1829,8 +1881,9 @@ namespace ICSharpCode.NRefactory.CSharp
StartNode(tryCatchStatement);
WriteKeyword(TryCatchStatement.TryKeywordRole);
tryCatchStatement.TryBlock.AcceptVisitor(this);
foreach (var catchClause in tryCatchStatement.CatchClauses)
foreach (var catchClause in tryCatchStatement.CatchClauses) {
catchClause.AcceptVisitor(this);
}
if (!tryCatchStatement.FinallyBlock.IsNull) {
WriteKeyword(TryCatchStatement.FinallyKeywordRole);
tryCatchStatement.FinallyBlock.AcceptVisitor(this);
@ -1849,7 +1902,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1849,7 +1902,7 @@ namespace ICSharpCode.NRefactory.CSharp
catchClause.Type.AcceptVisitor(this);
if (!string.IsNullOrEmpty(catchClause.VariableName)) {
Space();
WriteIdentifier (catchClause.VariableName);
catchClause.VariableNameToken.AcceptVisitor(this);
}
Space(policy.SpacesWithinCatchParentheses);
RPar();
@ -1964,7 +2017,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1964,7 +2017,9 @@ namespace ICSharpCode.NRefactory.CSharp
WriteAttributes(constructorDeclaration.Attributes);
WriteModifiers(constructorDeclaration.ModifierTokens);
TypeDeclaration type = constructorDeclaration.Parent as TypeDeclaration;
StartNode(constructorDeclaration.NameToken);
WriteIdentifier(type != null ? type.Name : constructorDeclaration.Name);
EndNode(constructorDeclaration.NameToken);
Space(policy.SpaceBeforeConstructorDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(constructorDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
if (!constructorDeclaration.Initializer.IsNull) {
@ -1997,7 +2052,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1997,7 +2052,9 @@ namespace ICSharpCode.NRefactory.CSharp
WriteModifiers(destructorDeclaration.ModifierTokens);
WriteToken(DestructorDeclaration.TildeRole);
TypeDeclaration type = destructorDeclaration.Parent as TypeDeclaration;
StartNode(destructorDeclaration.NameToken);
WriteIdentifier(type != null ? type.Name : destructorDeclaration.Name);
EndNode(destructorDeclaration.NameToken);
Space(policy.SpaceBeforeConstructorDeclarationParentheses);
LPar();
RPar();
@ -2010,7 +2067,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2010,7 +2067,7 @@ namespace ICSharpCode.NRefactory.CSharp
StartNode(enumMemberDeclaration);
WriteAttributes(enumMemberDeclaration.Attributes);
WriteModifiers(enumMemberDeclaration.ModifierTokens);
WriteIdentifier (enumMemberDeclaration.Name);
enumMemberDeclaration.NameToken.AcceptVisitor(this);
if (!enumMemberDeclaration.Initializer.IsNull) {
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
@ -2042,7 +2099,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2042,7 +2099,7 @@ namespace ICSharpCode.NRefactory.CSharp
customEventDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(customEventDeclaration.PrivateImplementationType);
WriteIdentifier (customEventDeclaration.Name);
customEventDeclaration.NameToken.AcceptVisitor(this);
OpenBrace(policy.EventBraceStyle);
// output add/remove in their original order
foreach (AstNode node in customEventDeclaration.Children) {
@ -2084,7 +2141,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2084,7 +2141,7 @@ namespace ICSharpCode.NRefactory.CSharp
public void VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
{
StartNode(fixedVariableInitializer);
WriteIdentifier (fixedVariableInitializer.Name);
fixedVariableInitializer.NameToken.AcceptVisitor(this);
if (!fixedVariableInitializer.CountExpression.IsNull) {
WriteToken(Roles.LBracket);
Space(policy.SpacesWithinBrackets);
@ -2125,7 +2182,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2125,7 +2182,7 @@ namespace ICSharpCode.NRefactory.CSharp
methodDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(methodDeclaration.PrivateImplementationType);
WriteIdentifier (methodDeclaration.Name);
methodDeclaration.NameToken.AcceptVisitor(this);
WriteTypeParameters(methodDeclaration.TypeParameters);
Space(policy.SpaceBeforeMethodDeclarationParentheses);
WriteCommaSeparatedListInParenthesis(methodDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
@ -2181,10 +2238,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2181,10 +2238,12 @@ namespace ICSharpCode.NRefactory.CSharp
break;
}
parameterDeclaration.Type.AcceptVisitor(this);
if (!parameterDeclaration.Type.IsNull && !string.IsNullOrEmpty (parameterDeclaration.Name))
if (!parameterDeclaration.Type.IsNull && !string.IsNullOrEmpty(parameterDeclaration.Name)) {
Space();
if (!string.IsNullOrEmpty (parameterDeclaration.Name))
WriteIdentifier (parameterDeclaration.Name);
}
if (!string.IsNullOrEmpty(parameterDeclaration.Name)) {
parameterDeclaration.NameToken.AcceptVisitor(this);
}
if (!parameterDeclaration.DefaultExpression.IsNull) {
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
@ -2202,7 +2261,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2202,7 +2261,7 @@ namespace ICSharpCode.NRefactory.CSharp
propertyDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(propertyDeclaration.PrivateImplementationType);
WriteIdentifier (propertyDeclaration.Name);
propertyDeclaration.NameToken.AcceptVisitor(this);
OpenBrace(policy.PropertyBraceStyle);
// output get/set in their original order
foreach (AstNode node in propertyDeclaration.Children) {
@ -2221,7 +2280,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2221,7 +2280,7 @@ namespace ICSharpCode.NRefactory.CSharp
public void VisitVariableInitializer(VariableInitializer variableInitializer)
{
StartNode(variableInitializer);
WriteIdentifier (variableInitializer.Name);
variableInitializer.NameToken.AcceptVisitor(this);
if (!variableInitializer.Initializer.IsNull) {
Space(policy.SpaceAroundAssignment);
WriteToken(Roles.Assign);
@ -2234,9 +2293,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2234,9 +2293,10 @@ namespace ICSharpCode.NRefactory.CSharp
public void VisitCompilationUnit(CompilationUnit compilationUnit)
{
// don't do node tracking as we visit all children directly
foreach (AstNode node in compilationUnit.Children)
foreach (AstNode node in compilationUnit.Children) {
node.AcceptVisitor(this);
}
}
public void VisitSimpleType(SimpleType simpleType)
{
@ -2250,10 +2310,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2250,10 +2310,11 @@ namespace ICSharpCode.NRefactory.CSharp
{
StartNode(memberType);
memberType.Target.AcceptVisitor(this);
if (memberType.IsDoubleColon)
if (memberType.IsDoubleColon) {
WriteToken(Roles.DoubleColon);
else
} else {
WriteToken(Roles.Dot);
}
WriteIdentifier(memberType.MemberName);
WriteTypeArguments(memberType.TypeArguments);
EndNode(memberType);
@ -2263,12 +2324,15 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2263,12 +2324,15 @@ namespace ICSharpCode.NRefactory.CSharp
{
StartNode(composedType);
composedType.BaseType.AcceptVisitor(this);
if (composedType.HasNullableSpecifier)
if (composedType.HasNullableSpecifier) {
WriteToken(ComposedType.NullableRole);
for (int i = 0; i < composedType.PointerRank; i++)
}
for (int i = 0; i < composedType.PointerRank; i++) {
WriteToken(ComposedType.PointerRole);
foreach (var node in composedType.ArraySpecifiers)
}
foreach (var node in composedType.ArraySpecifiers) {
node.AcceptVisitor(this);
}
EndNode(composedType);
}
@ -2334,7 +2398,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2334,7 +2398,7 @@ namespace ICSharpCode.NRefactory.CSharp
default:
throw new NotSupportedException ("Invalid value for VarianceModifier");
}
WriteIdentifier (typeParameterDeclaration.Name);
typeParameterDeclaration.NameToken.AcceptVisitor(this);
EndNode(typeParameterDeclaration);
}
@ -2413,8 +2477,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2413,8 +2477,9 @@ namespace ICSharpCode.NRefactory.CSharp
formatter.Indent();
foreach (INode alternative in choice) {
VisitNodeInPattern(alternative);
if (alternative != choice.Last ())
if (alternative != choice.Last()) {
WriteToken(Roles.Comma);
}
NewLine();
}
formatter.Unindent();
@ -2482,9 +2547,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2482,9 +2547,10 @@ namespace ICSharpCode.NRefactory.CSharp
StartNode(documentationReference);
if (!documentationReference.DeclaringType.IsNull) {
documentationReference.DeclaringType.AcceptVisitor(this);
if (documentationReference.EntityType != EntityType.TypeDefinition)
if (documentationReference.EntityType != EntityType.TypeDefinition) {
WriteToken(Roles.Dot);
}
}
switch (documentationReference.EntityType) {
case EntityType.TypeDefinition:
// we already printed the DeclaringType
@ -2514,11 +2580,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2514,11 +2580,12 @@ namespace ICSharpCode.NRefactory.CSharp
WriteTypeArguments(documentationReference.TypeArguments);
if (documentationReference.HasParameterList) {
Space(policy.SpaceBeforeMethodDeclarationParentheses);
if (documentationReference.EntityType == EntityType.Indexer)
if (documentationReference.EntityType == EntityType.Indexer) {
WriteCommaSeparatedListInBrackets(documentationReference.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
else
} else {
WriteCommaSeparatedListInParenthesis(documentationReference.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
}
}
EndNode(documentationReference);
}
#endregion

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/BaseRefactoringContext.cs

@ -98,6 +98,16 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -98,6 +98,16 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public abstract Script StartScript();
/// <summary>
/// Translates the english input string to the context language.
/// </summary>
/// <returns>
/// The translated string.
/// </returns>
public virtual string TranslateString(string str)
{
return str;
}
}
}

55
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeAction.cs

@ -0,0 +1,55 @@ @@ -0,0 +1,55 @@
//
// CodeAction.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class CodeAction
{
public string Description {
get;
private set;
}
public Action<Script> Run {
get;
private set;
}
public CodeAction (string description, Action<Script> action)
{
if (action == null) {
throw new ArgumentNullException ("action");
}
if (description == null) {
throw new ArgumentNullException ("description");
}
Description = description;
Run = action;
}
}
}

29
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/AddAnotherAccessor.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/AddAnotherAccessor.cs

@ -24,46 +24,45 @@ @@ -24,46 +24,45 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Add another accessor to a property declaration that has only one.
/// </summary>
public class AddAnotherAccessor : IContextAction
[ContextAction("Add another accessor", Description = "Adds second accessor to a property.")]
public class AddAnotherAccessor : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var pdecl = GetPropertyDeclaration(context);
if (pdecl == null)
return false;
var type = pdecl.Parent as TypeDeclaration;
if (type != null && type.ClassType == ClassType.Interface)
return false;
return pdecl.Setter.IsNull || pdecl.Getter.IsNull;
if (pdecl == null) {
yield break;
}
public void Run (RefactoringContext context)
{
var pdecl = GetPropertyDeclaration (context);
var type = pdecl.Parent as TypeDeclaration;
if (type != null && type.ClassType == ClassType.Interface) {
yield break;
}
yield return new CodeAction (pdecl.Setter.IsNull ? context.TranslateString("Add getter") : context.TranslateString("Add setter"), script => {
var accessorStatement = BuildAccessorStatement(context, pdecl);
Accessor accessor = new Accessor () {
Body = new BlockStatement { accessorStatement }
};
accessor.Role = pdecl.Setter.IsNull ? PropertyDeclaration.SetterRole : PropertyDeclaration.GetterRole;
using (var script = context.StartScript ()) {
if (pdecl.Setter.IsNull && !pdecl.Getter.IsNull) {
script.InsertBefore(pdecl.RBraceToken, accessor);
} else if (pdecl.Getter.IsNull && !pdecl.Setter.IsNull) {
script.InsertBefore(pdecl.Setter, accessor);
} else {
script.InsertBefore(pdecl.Getter, accessor);
}
script.Select(accessorStatement);
script.FormatText(pdecl);
}
});
}
static Statement BuildAccessorStatement (RefactoringContext context, PropertyDeclaration pdecl)

36
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CheckIfParameterIsNull.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CheckIfParameterIsNull.cs

@ -25,48 +25,42 @@ @@ -25,48 +25,42 @@
// THE SOFTWARE.
using ICSharpCode.NRefactory.PatternMatching;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Creates a 'if (param == null) throw new System.ArgumentNullException ();' contruct for a parameter.
/// </summary>
public class CheckIfParameterIsNull : IContextAction
[ContextAction("Check if parameter is null", Description = "Checks function parameter is not null.")]
public class CheckIfParameterIsNull : ICodeActionProvider
{
//TODO: Create 'multiple' null checks when more than 1 parameter is selected.
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var parameter = GetParameterDeclaration(context);
if (parameter == null)
return false;
if (parameter == null) {
yield break;
}
var bodyStatement = parameter.Parent.GetChildByRole(Roles.Body);
if (bodyStatement == null)
return false;
if (bodyStatement == null) {
yield break;
}
var type = context.ResolveType(parameter.Type);
if (type.IsReferenceType == false)
return false;
return !HasNullCheck (parameter);
if (type.IsReferenceType == false || HasNullCheck(parameter)) {
yield break;
}
public void Run (RefactoringContext context)
{
var parameter = GetParameterDeclaration (context);
var bodyStatement = parameter.Parent.GetChildByRole (Roles.Body);
yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
var statement = new IfElseStatement () {
Condition = new BinaryOperatorExpression (new IdentifierExpression (parameter.Name), BinaryOperatorType.Equality, new NullReferenceExpression ()),
TrueStatement = new ThrowStatement (new ObjectCreateExpression (context.CreateShortType("System", "ArgumentNullException"), new PrimitiveExpression (parameter.Name)))
};
using (var script = context.StartScript ()) {
script.AddTo(bodyStatement, statement);
}
});
}
static ParameterDeclaration GetParameterDeclaration (RefactoringContext context)
@ -89,7 +83,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -89,7 +83,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public CheckNullVisitor (ParameterDeclaration parameter)
{
this.pattern = PatternHelper.CommutativeOperator(new IdentifierExpression(parameter.Name), BinaryOperatorType.Any, new NullReferenceExpression());
pattern = PatternHelper.CommutativeOperator(new IdentifierExpression(parameter.Name), BinaryOperatorType.Any, new NullReferenceExpression());
}
public override object VisitIfElseStatement (IfElseStatement ifElseStatement, object data)

24
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/ConvertDecToHex.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertDecToHex.cs

@ -24,30 +24,30 @@ @@ -24,30 +24,30 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Convert a dec numer to hex. For example: 16 -> 0x10
/// </summary>
public class ConvertDecToHex : IContextAction
[ContextAction("Convert dec to hex.", Description = "Convert dec to hex.")]
public class ConvertDecToHex : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || pexpr.LiteralValue.StartsWith ("0X", System.StringComparison.OrdinalIgnoreCase))
return false;
return (pexpr.Value is int) || (pexpr.Value is long) || (pexpr.Value is short) || (pexpr.Value is sbyte) ||
(pexpr.Value is uint) || (pexpr.Value is ulong) || (pexpr.Value is ushort) || (pexpr.Value is byte);
if (pexpr == null || pexpr.LiteralValue.StartsWith("0X", System.StringComparison.OrdinalIgnoreCase)) {
yield break;
}
if (!((pexpr.Value is int) || (pexpr.Value is long) || (pexpr.Value is short) || (pexpr.Value is sbyte) ||
(pexpr.Value is uint) || (pexpr.Value is ulong) || (pexpr.Value is ushort) || (pexpr.Value is byte))) {
yield break;
}
public void Run (RefactoringContext context)
{
var pexpr = context.GetNode<PrimitiveExpression> ();
using (var script = context.StartScript ()) {
yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
script.Replace(pexpr, new PrimitiveExpression (pexpr.Value, string.Format("0x{0:x}", pexpr.Value)));
}
});
}
}
}

33
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/ConvertForeachToFor.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertForeachToFor.cs

@ -27,30 +27,23 @@ using System; @@ -27,30 +27,23 @@ using System;
using System.Linq;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Converts a foreach loop to for.
/// </summary>
public class ConvertForeachToFor : IContextAction
[ContextAction("Convert 'foreach' loop to 'for'", Description = "Works on 'foreach' loops that allow direct access to its elements.")]
public class ConvertForeachToFor : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
return GetForeachStatement (context) != null;
}
static string GetCountProperty (IType type)
{
if (type.Kind == TypeKind.Array)
return "Length";
return "Count";
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var foreachStatement = GetForeachStatement(context);
if (foreachStatement == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
var result = context.Resolve (foreachStatement.InExpression);
var countProperty = GetCountProperty (result.Type);
@ -77,10 +70,18 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -77,10 +70,18 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
}
using (var script = context.StartScript ()) {
script.Replace (foreachStatement, forStatement);
script.Link (initializer.Variables.First ().NameToken, id1, id2, id3);
});
}
static string GetCountProperty(IType type)
{
if (type.Kind == TypeKind.Array) {
return "Length";
}
return "Count";
}
static ForeachStatement GetForeachStatement (RefactoringContext context)

24
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/ConvertHexToDec.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertHexToDec.cs

@ -24,30 +24,30 @@ @@ -24,30 +24,30 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Convert a hex numer to dec. For example: 0x10 -> 16
/// </summary>
public class ConvertHexToDec: IContextAction
[ContextAction("Convert hex to dec.", Description = "Convert hex to dec.")]
public class ConvertHexToDec: ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || !pexpr.LiteralValue.StartsWith ("0X", System.StringComparison.OrdinalIgnoreCase))
return false;
return (pexpr.Value is int) || (pexpr.Value is long) || (pexpr.Value is short) || (pexpr.Value is sbyte) ||
(pexpr.Value is uint) || (pexpr.Value is ulong) || (pexpr.Value is ushort) || (pexpr.Value is byte);
if (pexpr == null || !pexpr.LiteralValue.StartsWith("0X", System.StringComparison.OrdinalIgnoreCase)) {
yield break;
}
if (!((pexpr.Value is int) || (pexpr.Value is long) || (pexpr.Value is short) || (pexpr.Value is sbyte) ||
(pexpr.Value is uint) || (pexpr.Value is ulong) || (pexpr.Value is ushort) || (pexpr.Value is byte))) {
yield break;
}
public void Run (RefactoringContext context)
{
var pexpr = context.GetNode<PrimitiveExpression> ();
using (var script = context.StartScript ()) {
yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
script.Replace(pexpr, new PrimitiveExpression (pexpr.Value));
}
});
}
}
}

76
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateBackingStore.cs

@ -0,0 +1,76 @@ @@ -0,0 +1,76 @@
//
// CreateBackingStore.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[ContextAction("Create backing store for auto property", Description = "Creates a backing field for an auto property.")]
public class CreateBackingStore : ICodeActionProvider
{
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var property = context.GetNode<PropertyDeclaration>();
if (!(property != null &&
!property.Getter.IsNull && !property.Setter.IsNull && // automatic properties always need getter & setter
property.Getter.Body.IsNull &&
property.Setter.Body.IsNull)) {
yield break;
}
yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
string backingStoreName = context.GetNameProposal (property.Name);
// create field
var backingStore = new FieldDeclaration ();
backingStore.ReturnType = property.ReturnType.Clone ();
var initializer = new VariableInitializer (backingStoreName);
backingStore.Variables.Add (initializer);
// create new property & implement the get/set bodies
var newProperty = (PropertyDeclaration)property.Clone ();
Expression id1;
if (backingStoreName == "value")
id1 = new ThisReferenceExpression().Member("value");
else
id1 = new IdentifierExpression (backingStoreName);
Expression id2 = id1.Clone();
newProperty.Getter.Body = new BlockStatement () {
new ReturnStatement (id1)
};
newProperty.Setter.Body = new BlockStatement () {
new AssignmentExpression (id2, AssignmentOperatorType.Assign, new IdentifierExpression ("value"))
};
script.Replace (property, newProperty);
script.InsertBefore (property, backingStore);
script.Link (initializer, id1, id2);
});
}
}
}

112
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateEventInvocator.cs

@ -0,0 +1,112 @@ @@ -0,0 +1,112 @@
//
// CreateEventInvocator.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[ContextAction("Create event invocator", Description = "Creates a standard OnXXX event method.")]
public class CreateEventInvocator : ICodeActionProvider
{
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
VariableInitializer initializer;
var eventDeclaration = GetEventDeclaration(context, out initializer);
if (eventDeclaration == null) {
yield break;
}
var type = (TypeDeclaration)eventDeclaration.Parent;
if (type.Members.Any(m => m is MethodDeclaration && ((MethodDeclaration)m).Name == "On" + initializer.Name)) {
yield break;
}
var resolvedType = context.Resolve(eventDeclaration.ReturnType).Type;
if (resolvedType.Kind == TypeKind.Unknown) {
yield break;
}
var invokeMethod = resolvedType.GetDelegateInvokeMethod();
if (invokeMethod == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Create event invocator"), script => {
bool hasSenderParam = false;
IEnumerable<IParameter> pars = invokeMethod.Parameters;
if (invokeMethod.Parameters.Any ()) {
var first = invokeMethod.Parameters [0];
if (first.Name == "sender" /*&& first.Type == "System.Object"*/) {
hasSenderParam = true;
pars = invokeMethod.Parameters.Skip (1);
}
}
const string handlerName = "handler";
var arguments = new List<Expression> ();
if (hasSenderParam)
arguments.Add (new ThisReferenceExpression ());
foreach (var par in pars)
arguments.Add (new IdentifierExpression (par.Name));
var methodDeclaration = new MethodDeclaration () {
Name = "On" + initializer.Name,
ReturnType = new PrimitiveType ("void"),
Modifiers = ICSharpCode.NRefactory.CSharp.Modifiers.Protected | ICSharpCode.NRefactory.CSharp.Modifiers.Virtual,
Body = new BlockStatement () {
new VariableDeclarationStatement (eventDeclaration.ReturnType.Clone (), handlerName, new MemberReferenceExpression (new ThisReferenceExpression (), initializer.Name)),
new IfElseStatement () {
Condition = new BinaryOperatorExpression (new IdentifierExpression (handlerName), BinaryOperatorType.InEquality, new PrimitiveExpression (null)),
TrueStatement = new ExpressionStatement (new InvocationExpression (new IdentifierExpression (handlerName), arguments))
}
}
};
foreach (var par in pars) {
var typeName = context.CreateShortType (par.Type);
var decl = new ParameterDeclaration (typeName, par.Name);
methodDeclaration.Parameters.Add (decl);
}
script.InsertWithCursor (context.TranslateString("Create event invocator"), methodDeclaration, Script.InsertPosition.After);
});
}
static EventDeclaration GetEventDeclaration (RefactoringContext context, out VariableInitializer initializer)
{
var result = context.GetNode<EventDeclaration> ();
if (result == null) {
initializer = null;
return null;
}
initializer = result.Variables.FirstOrDefault (v => v.NameToken.Contains (context.Location));
return initializer != null ? result : null;
}
}
}

24
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CreateField.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateField.cs

@ -29,28 +29,30 @@ using ICSharpCode.NRefactory.PatternMatching; @@ -29,28 +29,30 @@ using ICSharpCode.NRefactory.PatternMatching;
using System.Linq;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class CreateField : IContextAction
[ContextAction("Create field", Description = "Creates a field for a undefined variable.")]
public class CreateField : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var identifier = GetIdentifier(context);
if (identifier == null)
return false;
return context.Resolve (identifier) == null && GuessType (context, identifier) != null;
if (identifier == null) {
yield break;
}
public void Run (RefactoringContext context)
{
var identifier = GetIdentifier (context);
using (var script = context.StartScript ()) {
script.InsertWithCursor ("Create field", GenerateFieldDeclaration (context, identifier), Script.InsertPosition.Before);
if (!(context.Resolve(identifier).IsError && GuessType(context, identifier) != null)) {
yield break;
}
yield return new CodeAction (context.TranslateString("Create field"), script => {
script.InsertWithCursor(context.TranslateString("Create field"), GenerateFieldDeclaration(context, identifier), Script.InsertPosition.Before);
});
}
static AstNode GenerateFieldDeclaration (RefactoringContext context, IdentifierExpression identifier)
{
return new FieldDeclaration () {

32
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CreateLocalVariable.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateLocalVariable.cs

@ -32,7 +32,8 @@ using System.Threading; @@ -32,7 +32,8 @@ using System.Threading;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class CreateLocalVariable : IContextAction
[ContextAction("Create local variable", Description = "Creates a local variable for a undefined variable.")]
public class CreateLocalVariable : ICodeActionProvider
{
public List<IdentifierExpression> GetUnresolvedArguments (RefactoringContext context)
{
@ -59,34 +60,33 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -59,34 +60,33 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
return expressions;
}
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
if (GetUnresolvedArguments (context).Count > 0)
return true;
if (GetUnresolvedArguments(context).Count <= 0) {
yield break;
}
var identifier = CreateField.GetIdentifier(context);
if (identifier == null)
return false;
if (context.GetNode<Statement> () == null)
return false;
return context.Resolve (identifier) == null && GuessType (context, identifier) != null;
if (identifier == null) {
yield break;
}
public void Run (RefactoringContext context)
{
if (context.GetNode<Statement>() == null) {
yield break;
}
if (!(context.Resolve(identifier).IsError && GuessType(context, identifier) != null)) {
yield break;
}
yield return new CodeAction (context.TranslateString("Create local variable"), script => {
var stmt = context.GetNode<Statement> ();
var unresolvedArguments = GetUnresolvedArguments (context);
if (unresolvedArguments.Count > 0) {
using (var script = context.StartScript ()) {
foreach (var id in unresolvedArguments) {
script.InsertBefore (stmt, GenerateLocalVariableDeclaration (context, id));
}
}
return;
}
using (var script = context.StartScript ()) {
script.InsertBefore (stmt, GenerateLocalVariableDeclaration (context, CreateField.GetIdentifier (context)));
}
});
}
AstNode GenerateLocalVariableDeclaration (RefactoringContext context, IdentifierExpression identifier)

22
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CreateProperty.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/CreateProperty.cs

@ -27,25 +27,25 @@ using System; @@ -27,25 +27,25 @@ using System;
using ICSharpCode.NRefactory.PatternMatching;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class CreateProperty : IContextAction
[ContextAction("Create property", Description = "Creates a property for a undefined variable.")]
public class CreateProperty : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var identifier = CreateField.GetIdentifier(context);
if (identifier == null)
return false;
return context.Resolve (identifier) == null && CreateField.GuessType (context, identifier) != null;
if (identifier == null) {
yield break;
}
public void Run (RefactoringContext context)
{
var identifier = GetIdentifier (context);
using (var script = context.StartScript ()) {
script.InsertWithCursor ("Create property", GeneratePropertyDeclaration (context, identifier), Script.InsertPosition.Before);
if (!(context.Resolve(identifier).IsError && CreateField.GuessType(context, identifier) != null)) {
yield break;
}
yield return new CodeAction (context.TranslateString("Create property"), script => {
script.InsertWithCursor(context.TranslateString("Create property"), GeneratePropertyDeclaration(context, identifier), Script.InsertPosition.Before);
});
}
AstNode GeneratePropertyDeclaration (RefactoringContext context, IdentifierExpression identifier)

19
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/FlipOperatorArguments.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/FlipOperatorArguments.cs

@ -25,24 +25,23 @@ @@ -25,24 +25,23 @@
// THE SOFTWARE.
using System;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class FlipOperatorArguments : IContextAction
[ContextAction("Swaps left and right arguments.", Description = "Swaps left and right arguments.")]
public class FlipOperatorArguments : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
return GetBinaryOperatorExpression (context) != null;
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var binop = GetBinaryOperatorExpression(context);
using (var script = context.StartScript ()) {
if (binop == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Swap left and right arguments"), script => {
script.Replace(binop.Left, binop.Right.Clone());
script.Replace(binop.Right, binop.Left.Clone());
}
});
}
public static BinaryOperatorExpression GetBinaryOperatorExpression (RefactoringContext context)

34
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/GenerateGetter.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GenerateGetter.cs

@ -28,34 +28,36 @@ using System; @@ -28,34 +28,36 @@ using System;
using ICSharpCode.NRefactory.PatternMatching;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class GenerateGetter : IContextAction
[ContextAction("Generate getter", Description = "Generates a getter for a field.")]
public class GenerateGetter : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var initializer = GetVariableInitializer(context);
if (initializer == null || !initializer.NameToken.Contains (context.Location.Line, context.Location.Column))
return false;
if (initializer == null || !initializer.NameToken.Contains(context.Location.Line, context.Location.Column)) {
yield break;
}
var type = initializer.Parent.Parent as TypeDeclaration;
if (type == null)
return false;
if (type == null) {
yield break;
}
foreach (var member in type.Members) {
if (member is PropertyDeclaration && ContainsGetter ((PropertyDeclaration)member, initializer))
return false;
if (member is PropertyDeclaration && ContainsGetter((PropertyDeclaration)member, initializer)) {
yield break;
}
return initializer.Parent is FieldDeclaration;
}
public void Run (RefactoringContext context)
{
var initializer = GetVariableInitializer (context);
var field = initializer.Parent as FieldDeclaration;
using (var script = context.StartScript ()) {
script.InsertWithCursor ("Create getter", GeneratePropertyDeclaration (context, field, initializer), Script.InsertPosition.After);
if (field == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Create getter"), script => {
script.InsertWithCursor(context.TranslateString("Create getter"), GeneratePropertyDeclaration(context, field, initializer), Script.InsertPosition.After);
});
}
static PropertyDeclaration GeneratePropertyDeclaration (RefactoringContext context, FieldDeclaration field, VariableInitializer initializer)

33
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/GenerateProperty.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GenerateProperty.cs

@ -27,34 +27,35 @@ using System; @@ -27,34 +27,35 @@ using System;
using ICSharpCode.NRefactory.PatternMatching;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class GenerateProperty : IContextAction
[ContextAction("Generate property", Description = "Generates a getter and setter for a field.")]
public class GenerateProperty : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var initializer = GetVariableInitializer(context);
if (initializer == null || !initializer.NameToken.Contains (context.Location.Line, context.Location.Column))
return false;
if (initializer == null || !initializer.NameToken.Contains(context.Location.Line, context.Location.Column)) {
yield break;
}
var type = initializer.Parent.Parent as TypeDeclaration;
if (type == null)
return false;
if (type == null) {
yield break;
}
foreach (var member in type.Members) {
if (member is PropertyDeclaration && ContainsGetter ((PropertyDeclaration)member, initializer))
return false;
if (member is PropertyDeclaration && ContainsGetter((PropertyDeclaration)member, initializer)) {
yield break;
}
return initializer.Parent is FieldDeclaration;
}
public void Run (RefactoringContext context)
{
var initializer = GetVariableInitializer (context);
var field = initializer.Parent as FieldDeclaration;
using (var script = context.StartScript ()) {
script.InsertWithCursor ("Create property", GeneratePropertyDeclaration (context, field, initializer), Script.InsertPosition.After);
if (field == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Create property"), script => {
script.InsertWithCursor(context.TranslateString("Create property"), GeneratePropertyDeclaration(context, field, initializer), Script.InsertPosition.After);
});
}
static PropertyDeclaration GeneratePropertyDeclaration (RefactoringContext context, FieldDeclaration field, VariableInitializer initializer)

29
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/GenerateSwitchLabels.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GenerateSwitchLabels.cs

@ -26,34 +26,32 @@ @@ -26,34 +26,32 @@
using System;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class GenerateSwitchLabels : IContextAction
[ContextAction("Generate switch labels", Description = "Creates switch lables for enumerations.")]
public class GenerateSwitchLabels : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var switchStatement = GetSwitchStatement(context);
if (switchStatement == null)
return false;
var result = context.Resolve (switchStatement.Expression);
if (result == null)
return false;
return result.Type.Kind == TypeKind.Enum;
if (switchStatement == null) {
yield break;
}
public void Run (RefactoringContext context)
{
var switchStatement = GetSwitchStatement (context);
var result = context.Resolve(switchStatement.Expression);
if (result.Type.Kind != TypeKind.Enum) {
yield break;
}
yield return new CodeAction (context.TranslateString("Create switch labels"), script => {
var type = result.Type;
var newSwitch = (SwitchStatement)switchStatement.Clone();
var target = new TypeReferenceExpression (context.CreateShortType(result.Type));
foreach (var field in type.GetFields ()) {
if (field.IsSynthetic || !field.IsConst)
if (field.IsSynthetic || !field.IsConst) {
continue;
}
newSwitch.SwitchSections.Add(new SwitchSection () {
CaseLabels = {
new CaseLabel (new MemberReferenceExpression (target.Clone(), field.Name))
@ -73,9 +71,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -73,9 +71,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
});
using (var script = context.StartScript ()) {
script.Replace(switchStatement, newSwitch);
}
});
}
static SwitchStatement GetSwitchStatement (RefactoringContext context)

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/InsertAnonymousMethodSignature.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/InsertAnonymousMethodSignature.cs

@ -28,28 +28,28 @@ using ICSharpCode.NRefactory.TypeSystem; @@ -28,28 +28,28 @@ using ICSharpCode.NRefactory.TypeSystem;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class InsertAnonymousMethodSignature : IContextAction
[ContextAction("Insert anonymous method signature", Description = "Inserts a signature to parameterless anonymous methods.")]
public class InsertAnonymousMethodSignature : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
IType type;
return GetAnonymousMethodExpression (context, out type) != null;
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
IType type;
var anonymousMethodExpression = GetAnonymousMethodExpression(context, out type);
if (anonymousMethodExpression == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Insert anonymous method signature"), script => {
var delegateMethod = type.GetDelegateInvokeMethod();
var sb = new StringBuilder ("(");
for (int k = 0; k < delegateMethod.Parameters.Count; k++) {
if (k > 0)
if (k > 0) {
sb.Append(", ");
}
var paramType = delegateMethod.Parameters [k].Type;
@ -59,9 +59,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -59,9 +59,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
sb.Append(")");
using (var script = context.StartScript ()) {
script.InsertText(context.GetOffset(anonymousMethodExpression.DelegateToken.EndLocation), sb.ToString());
}
});
}
static AnonymousMethodExpression GetAnonymousMethodExpression (RefactoringContext context, out IType delegateType)

35
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/IntroduceFormatItem.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/IntroduceFormatItem.cs

@ -36,26 +36,31 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -36,26 +36,31 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// Introduce format item. Works on strings that contain selections.
/// "this is <some> string" => string.Format ("this is {0} string", <some>)
/// </summary>
public class IntroduceFormatItem : IContextAction
[ContextAction("Introduce format item", Description = "Creates a string.format call with the selection as parameter.")]
public class IntroduceFormatItem : ICodeActionProvider
{
readonly static MemberReferenceExpression PrototypeFormatReference = new MemberReferenceExpression (new TypeReferenceExpression (new PrimitiveType ("string")), "Format");
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
if (!context.IsSomethingSelected)
return false;
if (!context.IsSomethingSelected) {
yield break;
}
var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || !(pexpr.Value is string))
return false;
if (pexpr.LiteralValue.StartsWith ("@"))
return pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 1) &&
new TextLocation (context.Location.Line, context.Location.Column + 1) < pexpr.EndLocation;
return pexpr.StartLocation < context.Location && context.Location < pexpr.EndLocation;
if (pexpr == null || !(pexpr.Value is string)) {
yield break;
}
if (pexpr.LiteralValue.StartsWith("@")) {
if (!(pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 1) && new TextLocation (context.Location.Line, context.Location.Column + 1) < pexpr.EndLocation)) {
yield break;
}
} else {
if (!(pexpr.StartLocation < context.Location && context.Location < pexpr.EndLocation)) {
yield break;
}
}
public void Run (RefactoringContext context)
{
var pexpr = context.GetNode<PrimitiveExpression> ();
yield return new CodeAction (context.TranslateString("Introduce format item"), script => {
var invocation = context.GetNode<InvocationExpression>();
if (invocation != null && invocation.Target.IsMatch(PrototypeFormatReference)) {
AddFormatCallToInvocation(context, pexpr, invocation);
@ -67,10 +72,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -67,10 +72,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
Arguments = { CreateFormatString(context, pexpr, 0), arg }
};
using (var script = context.StartScript ()) {
script.Replace(pexpr, newInvocation);
script.Select(arg);
}
});
}
void AddFormatCallToInvocation (RefactoringContext context, PrimitiveExpression pExpr, InvocationExpression invocation)

20
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/InvertIf.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/InvertIf.cs

@ -25,30 +25,30 @@ @@ -25,30 +25,30 @@
// THE SOFTWARE.
using System;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class InvertIf : IContextAction
[ContextAction("Invert if", Description = "Inverts an 'if ... else' expression.")]
public class InvertIf : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var ifStatement = GetIfElseStatement (context);
return ifStatement != null && !ifStatement.TrueStatement.IsNull && !ifStatement.FalseStatement.IsNull;
}
// TODO: Invert if without else
// ex. if (cond) DoSomething () == if (!cond) return; DoSomething ()
// beware of loop contexts return should be continue then.
public void Run (RefactoringContext context)
{
var ifStatement = GetIfElseStatement(context);
if (!(ifStatement != null && !ifStatement.TrueStatement.IsNull && !ifStatement.FalseStatement.IsNull)) {
yield break;
using (var script = context.StartScript ()) {
}
yield return new CodeAction (context.TranslateString("Invert if"), script => {
script.Replace(ifStatement.Condition, CSharpUtil.InvertCondition(ifStatement.Condition.Clone()));
script.Replace(ifStatement.TrueStatement, ifStatement.FalseStatement.Clone());
script.Replace(ifStatement.FalseStatement, ifStatement.TrueStatement.Clone());
script.FormatText(ifStatement);
}
});
}
static IfElseStatement GetIfElseStatement (RefactoringContext context)

20
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/RemoveBackingStore.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveBackingStore.cs

@ -29,32 +29,30 @@ using ICSharpCode.NRefactory.CSharp.Resolver; @@ -29,32 +29,30 @@ using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class RemoveBackingStore : IContextAction
[ContextAction("Remove backing store for property", Description = "Removes the backing store of a property and creates an auto property.")]
public class RemoveBackingStore : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
return GetBackingField (context) != null;
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var property = context.GetNode<PropertyDeclaration>();
var field = GetBackingField(context);
if (field == null) {
yield break;
}
// create new auto property
var newProperty = (PropertyDeclaration)property.Clone();
newProperty.Getter.Body = BlockStatement.Null;
newProperty.Setter.Body = BlockStatement.Null;
using (var script = context.StartScript ()) {
yield return new CodeAction (context.TranslateString("Remove backing store"), script => {
script.Remove (context.RootNode.GetNodeAt<FieldDeclaration> (field.Region.BeginLine, field.Region.BeginColumn));
script.Replace (property, newProperty);
script.Rename (field, newProperty.Name);
}
});
}
// void ReplaceBackingFieldReferences (MDRefactoringContext context, IField backingStore, PropertyDeclaration property)

18
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/RemoveBraces.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveBraces.cs

@ -26,25 +26,25 @@ @@ -26,25 +26,25 @@
using System;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class RemoveBraces : IContextAction
[ContextAction("Remove braces", Description = "Removes redundant braces around a statement.")]
public class RemoveBraces : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
return GetBlockStatement (context) != null;
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var block = GetBlockStatement(context);
if (block == null) {
yield break;
}
using (var script = context.StartScript ()) {
yield return new CodeAction (context.TranslateString("Remove braces"), script => {
script.Remove(block.LBraceToken);
script.Remove(block.RBraceToken);
script.FormatText(block.Parent);
}
});
}
static BlockStatement GetBlockStatement (RefactoringContext context)

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/RemoveRegion.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveRegion.cs

@ -26,26 +26,27 @@ @@ -26,26 +26,27 @@
using System;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class RemoveRegion : IContextAction
[ContextAction("Remove region", Description = "Removes a pre processor #region/#endregion directive.")]
public class RemoveRegion : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
return GetDirective (context) != null;
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var directive = GetDirective(context);
if (directive == null) {
yield break;
}
var endDirective = DirectiveSearcher.GetEndRegion(context.RootNode, directive);
if (endDirective == null)
return;
using (var script = context.StartScript ()) {
if (endDirective == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Remove region"), script => {
script.Remove (directive);
script.Remove (endDirective);
}
});
}
class DirectiveSearcher : DepthFirstAstVisitor

18
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/ReplaceEmptyString.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ReplaceEmptyString.cs

@ -25,22 +25,22 @@ @@ -25,22 +25,22 @@
// THE SOFTWARE.
using System;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class ReplaceEmptyString : IContextAction
[ContextAction("Use string.Empty", Description = "Replaces \"\" with string.Empty")]
public class ReplaceEmptyString : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
return GetEmptyString (context) != null;
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var expr = GetEmptyString(context);
using (var script = context.StartScript ()) {
script.Replace (expr, new MemberReferenceExpression (new TypeReferenceExpression (new PrimitiveType ("string")), "Empty"));
if (expr == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Remove braces"), script => {
script.Replace(expr, new MemberReferenceExpression (new TypeReferenceExpression (new PrimitiveType ("string")), "Empty"));
});
}
static PrimitiveExpression GetEmptyString (RefactoringContext context)

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/SplitDeclarationAndAssignment.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/SplitDeclarationAndAssignment.cs

@ -27,36 +27,35 @@ using System; @@ -27,36 +27,35 @@ using System;
using System.Linq;
using ICSharpCode.NRefactory.PatternMatching;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class SplitDeclarationAndAssignment : IContextAction
[ContextAction("Split local variable declaration and assignment", Description = "Splits local variable declaration and assignment.")]
public class SplitDeclarationAndAssignment : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
{
AstType type;
return GetVariableDeclarationStatement (context, out type) != null;
}
public void Run (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
AstType type;
var varDecl = GetVariableDeclarationStatement(context, out type);
if (varDecl == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Remove braces"), script => {
var assign = new AssignmentExpression (new IdentifierExpression (varDecl.Variables.First().Name), AssignmentOperatorType.Assign, varDecl.Variables.First().Initializer.Clone());
var newVarDecl = (VariableDeclarationStatement)varDecl.Clone();
newVarDecl.Role = BlockStatement.StatementRole;
if (newVarDecl.Type.IsMatch (new SimpleType ("var")))
if (newVarDecl.Type.IsMatch(new SimpleType ("var"))) {
newVarDecl.Type = type;
}
newVarDecl.Variables.First().Initializer = Expression.Null;
using (var script = context.StartScript ()) {
script.InsertBefore(varDecl, newVarDecl);
script.Replace(varDecl, varDecl.Parent is ForStatement ? (AstNode)assign : new ExpressionStatement (assign));
}
});
}
static VariableDeclarationStatement GetVariableDeclarationStatement (RefactoringContext context, out AstType resolvedType, CancellationToken cancellationToken = default(CancellationToken))

37
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/SplitString.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/SplitString.cs

@ -25,32 +25,37 @@ @@ -25,32 +25,37 @@
// THE SOFTWARE.
using System;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class SplitString: IContextAction
[ContextAction("Split string literal", Description = "Splits string literal into two.")]
public class SplitString: ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
if (context.IsSomethingSelected)
return false;
if (context.IsSomethingSelected) {
yield break;
}
var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || !(pexpr.Value is string))
return false;
if (pexpr.LiteralValue.StartsWith ("@"))
return pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 2) &&
new TextLocation (context.Location.Line, context.Location.Column + 2) < pexpr.EndLocation;
return pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 1) &&
new TextLocation (context.Location.Line, context.Location.Column + 1) < pexpr.EndLocation;
if (pexpr == null || !(pexpr.Value is string)) {
yield break;
}
if (pexpr.LiteralValue.StartsWith("@")) {
if (!(pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 2) &&
new TextLocation (context.Location.Line, context.Location.Column + 2) < pexpr.EndLocation)) {
yield break;
}
} else {
if (!(pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 1) && new TextLocation (context.Location.Line, context.Location.Column + 1) < pexpr.EndLocation)) {
yield break;
}
}
public void Run (RefactoringContext context)
{
var pexpr = context.GetNode<PrimitiveExpression> ();
yield return new CodeAction (context.TranslateString("Remove braces"), script => {
int offset = context.GetOffset (context.Location);
using (var script = context.StartScript ()) {
script.InsertText (offset, pexpr.LiteralValue.StartsWith ("@") ? "\" + @\"" : "\" + \"");
}
});
}
}
}

25
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/UseExplicitType.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/UseExplicitType.cs

@ -28,13 +28,14 @@ using System.Linq; @@ -28,13 +28,14 @@ using System.Linq;
using ICSharpCode.NRefactory.PatternMatching;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class UseExplicitType: IContextAction
[ContextAction("Use explicit type", Description = "Converts local variable declaration to be explicit typed.")]
public class UseExplicitType: ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
var varDecl = GetVariableDeclarationStatement(context);
IType type;
@ -42,27 +43,23 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -42,27 +43,23 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
type = context.Resolve(varDecl.Variables.First().Initializer).Type;
} else {
var foreachStatement = GetForeachStatement(context);
if (foreachStatement == null)
return false;
if (foreachStatement == null) {
yield break;
}
type = context.Resolve(foreachStatement.VariableType).Type;
}
return !type.Equals (SpecialType.NullType) && !type.Equals (SpecialType.UnknownType);
if (!(!type.Equals(SpecialType.NullType) && !type.Equals(SpecialType.UnknownType))) {
yield break;
}
public void Run (RefactoringContext context)
{
using (var script = context.StartScript ()) {
var varDecl = GetVariableDeclarationStatement (context);
yield return new CodeAction (context.TranslateString("Remove braces"), script => {
if (varDecl != null) {
var type = context.Resolve (varDecl.Variables.First ().Initializer).Type;
script.Replace (varDecl.Type, context.CreateShortType (type));
} else {
var foreachStatement = GetForeachStatement (context);
var type = context.Resolve (foreachStatement.VariableType).Type;
script.Replace (foreachStatement.VariableType, context.CreateShortType (type));
}
}
});
}
static readonly AstType varType = new SimpleType ("var");

21
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/UseVarKeyword.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/UseVarKeyword.cs

@ -27,26 +27,27 @@ using System; @@ -27,26 +27,27 @@ using System;
using System.Linq;
using ICSharpCode.NRefactory.PatternMatching;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class UseVarKeyword : IContextAction
[ContextAction("Use 'var' keyword", Description = "Converts local variable declaration to be implicit typed.")]
public class UseVarKeyword : ICodeActionProvider
{
public bool IsValid (RefactoringContext context)
public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
return GetVariableDeclarationStatement (context) != null || GetForeachStatement (context) != null;
}
public void Run (RefactoringContext context)
{
using (var script = context.StartScript ()) {
var varDecl = GetVariableDeclarationStatement(context);
var foreachStmt = GetForeachStatement(context);
if (varDecl == null && foreachStmt == null) {
yield break;
}
yield return new CodeAction (context.TranslateString("Remove braces"), script => {
if (varDecl != null) {
script.Replace(varDecl.Type, new SimpleType ("var"));
} else {
script.Replace (GetForeachStatement (context).VariableType, new SimpleType ("var"));
}
script.Replace(foreachStmt.VariableType, new SimpleType ("var"));
}
});
}
static readonly AstType varType = new SimpleType ("var");

16
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/InspectionIssue.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssue.cs

@ -27,9 +27,9 @@ using System; @@ -27,9 +27,9 @@ using System;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class InspectionIssue
public class CodeIssue
{
public string Title {
public string Desription {
get;
private set;
}
@ -44,17 +44,17 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -44,17 +44,17 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
private set;
}
public System.Action Fix {
public CodeAction Action {
get;
private set;
}
public InspectionIssue (string title, TextLocation start, TextLocation end, System.Action fix)
public CodeIssue (string description, TextLocation start, TextLocation end, CodeAction action = null)
{
this.Title = title;
this.Start = start;
this.End = end;
this.Fix = fix;
Desription = description;
Start = start;
End = end;
Action = action;
}
}
}

25
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/ConditionalToNullCoalescingInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/ConditionalToNullCoalescingInspector.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// ConditionalToNullCoalescingInspector.cs
//
// Author:
@ -34,7 +34,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -34,7 +34,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// Checks for "a != null ? a : other"<expr>
/// Converts to: "a ?? other"<expr>
/// </summary>
public class ConditionalToNullCoalescingInspector : IInspector
[IssueDescription("'?:' expression can be converted to '??' expression",
Description="'?:' expression can be converted to '??' expression.",
Category = IssueCategories.Opportunities,
Severity = Severity.Suggestion)]
public class ConditionalToNullCoalescingInspector : ICodeIssueProvider
{
static readonly Pattern pattern = new Choice {
// a != null ? a : other
@ -51,18 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -51,18 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
),
};
string title = "Convert to '??' expression";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -84,11 +77,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -84,11 +77,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
if (m.Success) {
var a = m.Get<Expression>("a").Single();
var other = m.Get<Expression>("other").Single();
AddIssue(conditionalExpression, inspector.Title, delegate {
using (var script = ctx.StartScript ()) {
AddIssue(conditionalExpression, ctx.TranslateString("Convert to '??' expression"), script => {
var expr = new BinaryOperatorExpression (a.Clone (), BinaryOperatorType.NullCoalescing, other.Clone ());
script.Replace (conditionalExpression, expr);
}
});
}
base.VisitConditionalExpression (conditionalExpression);

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/GatherVisitorBase.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/GatherVisitorBase.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -33,7 +33,7 @@ namespace ICSharpCode.NRefactory.CSharp
{
protected readonly BaseRefactoringContext ctx;
public readonly List<InspectionIssue> FoundIssues = new List<InspectionIssue> ();
public readonly List<CodeIssue> FoundIssues = new List<CodeIssue> ();
public GatherVisitorBase (BaseRefactoringContext ctx)
{
@ -47,14 +47,14 @@ namespace ICSharpCode.NRefactory.CSharp @@ -47,14 +47,14 @@ namespace ICSharpCode.NRefactory.CSharp
base.VisitChildren (node);
}
protected void AddIssue (AstNode node, string title, System.Action fix = null)
protected void AddIssue(AstNode node, string title, System.Action<Script> fix = null)
{
FoundIssues.Add (new InspectionIssue (title, node.StartLocation, node.EndLocation, fix));
FoundIssues.Add(new CodeIssue (title, node.StartLocation, node.EndLocation, fix != null ? new CodeAction (title, fix) : null));
}
protected void AddIssue(TextLocation start, TextLocation end, string title, System.Action fix = null)
protected void AddIssue(TextLocation start, TextLocation end, string title, System.Action<Script> fix = null)
{
FoundIssues.Add (new InspectionIssue (title, start, end, fix));
FoundIssues.Add(new CodeIssue (title, start, end, fix != null ? new CodeAction (title, fix) : null));
}
}

41
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/IssueCategories.cs

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
//
// IssueCategories.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace ICSharpCode.NRefactory.CSharp
{
public class IssueCategories
{
public const string Improvements = "Code Improvements";
public const string CodeQualityIssues = "Code Quality Issues";
public const string ConstraintViolations = "Constraint Violations";
public const string Redundancies = "Redundancies";
public const string Opportunities = "Language Usage Opportunities";
public const string Notifications = "Code Notifications";
}
}

21
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/NotImplementedExceptionInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/NotImplementedExceptionInspector.cs

@ -34,20 +34,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -34,20 +34,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// This inspector just shows that there is a not implemented exception. It doesn't offer a fix.
/// Should only be shown in overview bar, no underlining.
/// </summary>
public class NotImplementedExceptionInspector : IInspector
[IssueDescription("Show NotImplementedExceptions", Description="Shows NotImplementedException throws in the quick task bar.", Category = IssueCategories.Notifications, Severity = Severity.Suggestion)]
public class NotImplementedExceptionInspector : ICodeIssueProvider
{
string title = "NotImplemented exception thrown";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -66,8 +56,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -66,8 +56,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public override void VisitThrowStatement(ThrowStatement throwStatement)
{
var result = ctx.Resolve(throwStatement.Expression);
if (result.Type.Equals (ctx.Compilation.FindType (typeof(System.NotImplementedException))))
AddIssue (throwStatement, inspector.Title);
if (result.Type.Equals(ctx.Compilation.FindType(typeof(System.NotImplementedException)))) {
AddIssue(throwStatement, ctx.TranslateString("NotImplemented exception thrown"));
}
base.VisitThrowStatement(throwStatement);
}

24
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/RedundantInternalInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantInternalInspector.cs

@ -34,20 +34,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -34,20 +34,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary>
/// Finds redundant internal modifiers.
/// </summary>
public class RedundantInternalInspector : IInspector
[IssueDescription("Remove redunant 'internal' modifier",
Description="Removes 'internal' modifiers that are not required.",
Category = IssueCategories.Redundancies,
Severity = Severity.Hint,
IssueMarker = IssueMarker.GrayOut)]
public class RedundantInternalInspector : ICodeIssueProvider
{
string title = "Remove redundant 'internal' modifier";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -68,10 +62,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -68,10 +62,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
foreach (var token_ in typeDeclaration.ModifierTokens) {
var token = token_;
if (token.Modifier == Modifiers.Internal) {
AddIssue(token, inspector.Title, delegate {
using (var script = ctx.StartScript ()) {
AddIssue(token, ctx.TranslateString ("Remove 'internal' modifier"), script => {
script.Remove(token);
}
});
}
}

26
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/RedundantNamespaceUsageInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantNamespaceUsageInspector.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// RedundantNamespaceUsageInspector.cs
//
// Author:
@ -36,20 +36,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -36,20 +36,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary>
/// Finds redundant namespace usages.
/// </summary>
public class RedundantNamespaceUsageInspector : IInspector
[IssueDescription("Remove redundant namespace usages",
Description = "Removes namespace usages that are obsolete.",
Category = IssueCategories.Redundancies,
Severity = Severity.Hint,
IssueMarker = IssueMarker.GrayOut)]
public class RedundantNamespaceUsageInspector : ICodeIssueProvider
{
string title = "Remove redundant namespace usage";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -82,11 +76,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -82,11 +76,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
var lookupName = state.LookupSimpleNameOrTypeName(memberReferenceExpression.MemberName, new List<IType> (), SimpleNameLookupMode.Expression);
if (lookupName is TypeResolveResult && !lookupName.IsError && wholeResult.Type.Equals(lookupName.Type)) {
AddIssue(memberReferenceExpression.StartLocation, memberReferenceExpression.MemberNameToken.StartLocation, inspector.Title, delegate {
using (var script = ctx.StartScript ()) {
AddIssue(memberReferenceExpression.StartLocation, memberReferenceExpression.MemberNameToken.StartLocation, ctx.TranslateString("Remove redundant namespace usage"), script => {
script.Replace(memberReferenceExpression, RefactoringAstHelper.RemoveTarget(memberReferenceExpression));
}
}
);
}
}

26
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/RedundantPrivateInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantPrivateInspector.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// RedundantPrivateInspector.cs
//
// Author:
@ -34,20 +34,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -34,20 +34,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary>
/// Finds redundant internal modifiers.
/// </summary>
public class RedundantPrivateInspector : IInspector
[IssueDescription("Remove redundant 'private' modifier.",
Description = "Removes 'private' modifiers that are not required.",
Category = IssueCategories.Redundancies,
Severity = Severity.Hint,
IssueMarker = IssueMarker.GrayOut)]
public class RedundantPrivateInspector : ICodeIssueProvider
{
string title = "Remove redundant 'private' modifier";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -68,10 +62,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -68,10 +62,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
foreach (var token_ in node.ModifierTokens) {
var token = token_;
if (token.Modifier == Modifiers.Private) {
AddIssue(token, inspector.Title, delegate {
using (var script = ctx.StartScript ()) {
AddIssue(token, ctx.TranslateString("Remove redundant 'private' modifier"), script => {
script.Remove(token);
}
});
}
}

26
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/RedundantThisInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantThisInspector.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// RedundantThisInspector.cs
//
// Author:
@ -38,20 +38,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -38,20 +38,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary>
/// Finds redundant namespace usages.
/// </summary>
public class RedundantThisInspector : IInspector
[IssueDescription("Remove redundant 'this.'",
Description= "Removes 'this.' references that are not required.",
Category = IssueCategories.Redundancies,
Severity = Severity.Hint,
IssueMarker = IssueMarker.GrayOut)]
public class RedundantThisInspector : ICodeIssueProvider
{
string title = "Remove redundant 'this.'";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -106,11 +100,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -106,11 +100,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
if (isRedundant) {
AddIssue(thisReferenceExpression.StartLocation, memberReference.MemberNameToken.StartLocation, inspector.Title, delegate {
using (var script = ctx.StartScript ()) {
AddIssue(thisReferenceExpression.StartLocation, memberReference.MemberNameToken.StartLocation, ctx.TranslateString("Remove redundant 'this.'"), script => {
script.Replace(memberReference, RefactoringAstHelper.RemoveTarget(memberReference));
}
}
);
}
}

128
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantUsingInspector.cs

@ -0,0 +1,128 @@ @@ -0,0 +1,128 @@
//
// RedundantUsingInspector.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin <http://xamarin.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.PatternMatching;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.CSharp.Resolver;
using System.Linq;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Finds redundant using declarations.
/// </summary>
[IssueDescription("Remove unused usings",
Description = "Removes used declarations that are not required.",
Category = IssueCategories.Redundancies,
Severity = Severity.Hint,
IssueMarker = IssueMarker.GrayOut)]
public class RedundantUsingInspector : ICodeIssueProvider
{
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
visitor.Collect ();
return visitor.FoundIssues;
}
class GatherVisitor : GatherVisitorBase
{
readonly RedundantUsingInspector inspector;
Dictionary<UsingDeclaration, bool> usingDeclarations = new Dictionary<UsingDeclaration, bool> ();
Stack<List<UsingDeclaration>> usingStack = new Stack<List<UsingDeclaration>> ();
public GatherVisitor (BaseRefactoringContext ctx, RedundantUsingInspector inspector) : base (ctx)
{
this.inspector = inspector;
usingStack.Push (new List<UsingDeclaration> ());
}
public void Collect()
{
foreach (var u in usingDeclarations.Where (u => !u.Value)) {
var decl = u.Key;
AddIssue(decl, ctx.TranslateString("Remove redundant usings"), script => {
foreach (var u2 in usingDeclarations.Where (a => !a.Value)) {
script.Remove (u2.Key);
}
}
);
}
}
public override void VisitUsingDeclaration(UsingDeclaration usingDeclaration)
{
base.VisitUsingDeclaration(usingDeclaration);
usingDeclarations [usingDeclaration] = false;
usingStack.Peek().Add(usingDeclaration);
}
public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
{
usingStack.Push(new List<UsingDeclaration> (usingStack.Peek()));
base.VisitNamespaceDeclaration(namespaceDeclaration);
usingStack.Pop();
}
void UseNamespace(string ns)
{
foreach (var u in usingStack.Peek ()) {
if (u.Namespace == ns) {
usingDeclarations [u] = true;
}
}
}
public override void VisitIdentifierExpression(IdentifierExpression identifierExpression)
{
base.VisitIdentifierExpression(identifierExpression);
UseNamespace(ctx.Resolve(identifierExpression).Type.Namespace);
}
public override void VisitSimpleType(SimpleType simpleType)
{
base.VisitSimpleType(simpleType);
UseNamespace(ctx.Resolve(simpleType).Type.Namespace);
}
public override void VisitInvocationExpression (InvocationExpression invocationExpression)
{
base.VisitInvocationExpression (invocationExpression);
var mg = ctx.Resolve (invocationExpression) as CSharpInvocationResolveResult;
if (mg == null || !mg.IsExtensionMethodInvocation) {
return;
}
UseNamespace (mg.Member.DeclaringType.Namespace);
}
}
}
}

25
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/StringIsNullOrEmptyInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/StringIsNullOrEmptyInspector.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// StringIsNullOrEmptyInspector.cs
//
// Author:
@ -34,7 +34,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -34,7 +34,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// Checks for str == null && str == ""
/// Converts to: string.IsNullOrEmpty (str)
/// </summary>
public class StringIsNullOrEmptyInspector : IInspector
[IssueDescription("Use string.IsNullOrEmpty",
Description = "Uses shorter string.IsNullOrEmpty call instead of a longer condition.",
Category = IssueCategories.Improvements,
Severity = Severity.Suggestion)]
public class StringIsNullOrEmptyInspector : ICodeIssueProvider
{
static readonly Pattern pattern = new Choice {
// str == null || str == ""
@ -66,18 +70,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -66,18 +70,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
),
};
string title = "Use string.IsNullOrEmpty";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -104,13 +97,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -104,13 +97,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
if (m.Success) {
var str = m.Get<Expression>("str").Single();
AddIssue(binaryOperatorExpression, inspector.Title, delegate {
using (var script = ctx.StartScript ()) {
AddIssue(binaryOperatorExpression, ctx.TranslateString("Use string.IsNullOrEmpty"), script => {
Expression expr = new PrimitiveType ("string").Invoke("IsNullOrEmpty", str.Clone());
if (isNegated)
expr = new UnaryOperatorExpression (UnaryOperatorType.Not, expr);
script.Replace(binaryOperatorExpression, expr);
}
});
return;
}

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/UseVarKeywordInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/UseVarKeywordInspector.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// UseVarKeywordInspector.cs
//
// Author:
@ -36,20 +36,13 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -36,20 +36,13 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// Checks for places where the 'var' keyword can be used. Note that the action is actually done with a context
/// action.
/// </summary>
public class UseVarKeywordInspector : IInspector
[IssueDescription("Use 'var' keyword",
Description = "Use implicitly typed local variable decaration",
Category = IssueCategories.Opportunities,
Severity = Severity.Hint)]
public class UseVarKeywordInspector : ICodeIssueProvider
{
string title = "Use 'var' keyword";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
@ -106,7 +99,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -106,7 +99,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
void AddIssue(VariableDeclarationStatement variableDeclarationStatement)
{
AddIssue(variableDeclarationStatement.Type, inspector.Title);
AddIssue(variableDeclarationStatement.Type, ctx.TranslateString("Use 'var' keyword"));
}
}
}

78
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CreateBackingStore.cs

@ -1,78 +0,0 @@ @@ -1,78 +0,0 @@
//
// CreateBackingStore.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Threading;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class CreateBackingStore : IContextAction
{
public bool IsValid (RefactoringContext context)
{
var propertyDeclaration = context.GetNode<PropertyDeclaration> ();
return propertyDeclaration != null &&
!propertyDeclaration.Getter.IsNull && !propertyDeclaration.Setter.IsNull && // automatic properties always need getter & setter
propertyDeclaration.Getter.Body.IsNull &&
propertyDeclaration.Setter.Body.IsNull;
}
public void Run (RefactoringContext context)
{
var property = context.GetNode<PropertyDeclaration> ();
string backingStoreName = context.GetNameProposal (property.Name);
// create field
var backingStore = new FieldDeclaration ();
backingStore.ReturnType = property.ReturnType.Clone ();
var initializer = new VariableInitializer (backingStoreName);
backingStore.Variables.Add (initializer);
// create new property & implement the get/set bodies
var newProperty = (PropertyDeclaration)property.Clone ();
Expression id1;
if (backingStoreName == "value")
id1 = new ThisReferenceExpression().Member("value");
else
id1 = new IdentifierExpression (backingStoreName);
Expression id2 = id1.Clone();
newProperty.Getter.Body = new BlockStatement () {
new ReturnStatement (id1)
};
newProperty.Setter.Body = new BlockStatement () {
new AssignmentExpression (id2, AssignmentOperatorType.Assign, new IdentifierExpression ("value"))
};
using (var script = context.StartScript ()) {
script.Replace (property, newProperty);
script.InsertBefore (property, backingStore);
script.Link (initializer, id1, id2);
}
}
}
}

110
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/CreateEventInvocator.cs

@ -1,110 +0,0 @@ @@ -1,110 +0,0 @@
//
// CreateEventInvocator.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public class CreateEventInvocator : IContextAction
{
public bool IsValid (RefactoringContext context)
{
VariableInitializer initializer;
var eventDeclaration = GetEventDeclaration (context, out initializer);
if (eventDeclaration == null)
return false;
var type = (TypeDeclaration)eventDeclaration.Parent;
return !type.Members.Any (m => m is MethodDeclaration && ((MethodDeclaration)m).Name == "On" + initializer.Name);
}
public void Run (RefactoringContext context)
{
VariableInitializer initializer;
var eventDeclaration = GetEventDeclaration (context, out initializer);
var type = context.Resolve (eventDeclaration.ReturnType).Type;
if (type == null)
return;
var invokeMethod = type.GetDelegateInvokeMethod ();
if (invokeMethod == null)
return;
bool hasSenderParam = false;
IEnumerable<IParameter> pars = invokeMethod.Parameters;
if (invokeMethod.Parameters.Any ()) {
var first = invokeMethod.Parameters [0];
if (first.Name == "sender" /*&& first.Type == "System.Object"*/) {
hasSenderParam = true;
pars = invokeMethod.Parameters.Skip (1);
}
}
const string handlerName = "handler";
var arguments = new List<Expression> ();
if (hasSenderParam)
arguments.Add (new ThisReferenceExpression ());
foreach (var par in pars)
arguments.Add (new IdentifierExpression (par.Name));
var methodDeclaration = new MethodDeclaration () {
Name = "On" + initializer.Name,
ReturnType = new PrimitiveType ("void"),
Modifiers = ICSharpCode.NRefactory.CSharp.Modifiers.Protected | ICSharpCode.NRefactory.CSharp.Modifiers.Virtual,
Body = new BlockStatement () {
new VariableDeclarationStatement (eventDeclaration.ReturnType.Clone (), handlerName, new MemberReferenceExpression (new ThisReferenceExpression (), initializer.Name)),
new IfElseStatement () {
Condition = new BinaryOperatorExpression (new IdentifierExpression (handlerName), BinaryOperatorType.InEquality, new PrimitiveExpression (null)),
TrueStatement = new ExpressionStatement (new InvocationExpression (new IdentifierExpression (handlerName), arguments))
}
}
};
foreach (var par in pars) {
var typeName = context.CreateShortType (par.Type);
var decl = new ParameterDeclaration (typeName, par.Name);
methodDeclaration.Parameters.Add (decl);
}
using (var script = context.StartScript ()) {
script.InsertWithCursor ("Create event invocator", methodDeclaration, Script.InsertPosition.After);
}
}
static EventDeclaration GetEventDeclaration (RefactoringContext context, out VariableInitializer initializer)
{
var result = context.GetNode<EventDeclaration> ();
if (result == null) {
initializer = null;
return null;
}
initializer = result.Variables.FirstOrDefault (v => v.NameToken.Contains (context.Location));
return initializer != null ? result : null;
}
}
}

42
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextActionAttribute.cs

@ -0,0 +1,42 @@ @@ -0,0 +1,42 @@
//
// ProviderDescriptionAttribute.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace ICSharpCode.NRefactory.CSharp
{
public class ContextActionAttribute : System.Attribute
{
public string Title { get; private set;}
public string Description { get; set; }
public string Category { get; set; }
public ContextActionAttribute (string title)
{
Title = title;
}
}
}

6
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/IContextAction.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ICodeActionProvider.cs

@ -25,13 +25,13 @@ @@ -25,13 +25,13 @@
// THE SOFTWARE.
using System;
using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public interface IContextAction
public interface ICodeActionProvider
{
bool IsValid (RefactoringContext context);
void Run (RefactoringContext context);
IEnumerable<CodeAction> GetActions (RefactoringContext context);
}
}

4
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/IInspector.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ICodeIssueProvider.cs

@ -28,9 +28,9 @@ using System.Collections.Generic; @@ -28,9 +28,9 @@ using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public interface IInspector
public interface ICodeIssueProvider
{
IEnumerable<InspectionIssue> Run (BaseRefactoringContext context);
IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context);
}
}

77
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Inspector/RedundantUsingInspector.cs

@ -1,77 +0,0 @@ @@ -1,77 +0,0 @@
//
// RedundantUsingInspector.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin <http://xamarin.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.PatternMatching;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
/// <summary>
/// Finds redundant using declarations.
/// </summary>
public class RedundantUsingInspector : IInspector
{
string title = "Remove redundant using";
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{
var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor);
return visitor.FoundIssues;
}
class GatherVisitor : GatherVisitorBase
{
readonly RedundantUsingInspector inspector;
public GatherVisitor (BaseRefactoringContext ctx, RedundantUsingInspector inspector) : base (ctx)
{
this.inspector = inspector;
}
public override void VisitUsingDeclaration(UsingDeclaration usingDeclaration)
{
base.VisitUsingDeclaration(usingDeclaration);
// TODO
// return cSharpResolver.usedScopes
// .OfType<ITypeOrNamespaceReference> ()
// .Any (u => u.ResolveNamespace (ctx).NamespaceName == ns) || additionalNamespaces.Contains (ns);
}
}
}
}

50
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/IssueAttribute.cs

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
//
// IssueAttribute.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace ICSharpCode.NRefactory.CSharp
{
public class IssueDescriptionAttribute : System.Attribute
{
public string Title { get; private set;}
public string Description { get; set; }
public string Category { get; set; }
public Severity Severity { get; set; }
public IssueMarker IssueMarker { get; set; }
public IssueDescriptionAttribute (string title)
{
Title = title;
Severity = Severity.Suggestion;
IssueMarker = IssueMarker.Underline;
}
}
}

52
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/IssueMarker.cs

@ -0,0 +1,52 @@ @@ -0,0 +1,52 @@
//
// IssueMarker.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace ICSharpCode.NRefactory.CSharp
{
/// <summary>
/// The issue marker is used to set how an issue should be marked inside the text editor.
/// </summary>
public enum IssueMarker
{
/// <summary>
/// The issue is not shown inside the text editor. (But in the task bar)
/// </summary>
None,
/// <summary>
/// The region is marked as underline in the severity color.
/// </summary>
Underline,
/// <summary>
/// The text is grayed out.
/// </summary>
GrayOut
}
}

61
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Severity.cs

@ -0,0 +1,61 @@ @@ -0,0 +1,61 @@
//
// Severity.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace ICSharpCode.NRefactory.CSharp
{
/// <summary>
/// The severity influences how the task bar reacts on found issues.
/// </summary>
public enum Severity
{
/// <summary>
/// None means that the task bar doesn't show the issue.
/// </summary>
None,
/// <summary>
/// Errors are shown in red and that the task bar is in error state if 1 error is found.
/// </summary>
Error,
/// <summary>
/// Warnings are shown in yellow and set the task bar to warning state (if no error is found).
/// </summary>
Warning,
/// <summary>
/// Suggestions are shown in green and doesn't influence the task bar state
/// </summary>
Suggestion,
/// <summary>
/// Hints are shown in blue and doesn't influence the task bar state
/// </summary>
Hint
}
}

32
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs

@ -1730,10 +1730,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -1730,10 +1730,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (method.TypeParameters.Count != typeArguments.Count)
continue;
SpecializedMethod sm = new SpecializedMethod(method, new TypeParameterSubstitution(null, typeArguments));
if (IsEligibleExtensionMethod(targetType, method, false, out inferredTypes))
if (IsEligibleExtensionMethod(compilation, conversions, targetType, method, false, out inferredTypes))
outputGroup.Add(sm);
} else {
if (IsEligibleExtensionMethod(targetType, method, true, out inferredTypes)) {
if (IsEligibleExtensionMethod(compilation, conversions, targetType, method, true, out inferredTypes)) {
if (substituteInferredTypes && inferredTypes != null) {
outputGroup.Add(new SpecializedMethod(method, new TypeParameterSubstitution(null, inferredTypes)));
} else {
@ -1748,12 +1748,32 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -1748,12 +1748,32 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return extensionMethodGroups;
}
internal bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
/// <summary>
/// Checks whether the specified extension method is eligible on the target type.
/// </summary>
/// <param name="targetType">Target type that is passed as first argument to the extension method.</param>
/// <param name="method">The extension method.</param>
/// <param name="useTypeInference">Whether to perform type inference for the method.
/// Use <c>false</c> if <paramref name="method"/> is already specialized (e.g. when type arguments were given explicitly).
/// Otherwise, use <c>true</c>.
/// </param>
/// <param name="outInferredTypes">If the method is generic and <paramref name="useTypeInference"/> is <c>true</c>,
/// and at least some of the type arguments could be inferred, this parameter receives the inferred type arguments.
/// Since only the type for the first parameter is considered, not all type arguments may be inferred.
/// If an array is returned, any slot with an uninferred type argument will be set to the method's
/// corresponding type parameter.
/// </param>
public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
{
return IsEligibleExtensionMethod(compilation, conversions, targetType, method, useTypeInference, out outInferredTypes);
if (targetType == null)
throw new ArgumentNullException("targetType");
if (method == null)
throw new ArgumentNullException("method");
var compilation = method.Compilation;
return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes);
}
internal static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
{
outInferredTypes = null;
if (targetType == null)
@ -2133,7 +2153,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -2133,7 +2153,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (t != null) {
foreach (IType baseType in t.DirectBaseTypes) {
if (baseType.Kind != TypeKind.Unknown && baseType.Kind != TypeKind.Interface) {
return new ThisResolveResult(baseType);
return new ThisResolveResult(baseType, causesNonVirtualInvocation: true);
}
}
}

5
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/MethodGroupResolveResult.cs

@ -159,10 +159,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -159,10 +159,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
var outputGroup = new List<IMethod>();
foreach (var method in methodGroup) {
IType[] inferredTypes;
if (CSharpResolver.IsEligibleExtensionMethod(
method.Compilation, CSharpConversions.Get(method.Compilation),
this.TargetType, method, true, out inferredTypes))
{
if (CSharpResolver.IsEligibleExtensionMethod(this.TargetType, method, true, out inferredTypes)) {
if (substituteInferredTypes && inferredTypes != null) {
outputGroup.Add(new SpecializedMethod(method, new TypeParameterSubstitution(null, inferredTypes)));
} else {

15
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/ContextActionTestBase.cs

@ -28,28 +28,31 @@ using System; @@ -28,28 +28,31 @@ using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using System.Threading;
using System.Linq;
namespace ICSharpCode.NRefactory.CSharp.ContextActions
{
public abstract class ContextActionTestBase
{
protected static string RunContextAction (IContextAction action, string input)
protected static string RunContextAction (ICodeActionProvider action, string input)
{
var context = TestRefactoringContext.Create (input);
bool isValid = action.IsValid (context);
bool isValid = action.GetActions (context).Any ();
if (!isValid)
Console.WriteLine ("invalid node is:" + context.GetNode ());
Assert.IsTrue (isValid, action.GetType () + " is invalid.");
action.Run (context);
using (var script = context.StartScript ()) {
action.GetActions (context).First ().Run (script);
}
return context.doc.Text;
}
protected static void TestWrongContext (IContextAction action, string input)
protected static void TestWrongContext (ICodeActionProvider action, string input)
{
var context = TestRefactoringContext.Create (input);
bool isValid = action.IsValid (context);
bool isValid = action.GetActions (context).Any ();
if (!isValid)
Console.WriteLine ("invalid node is:" + context.GetNode ());
Assert.IsTrue (!isValid, action.GetType () + " shouldn't be valid there.");

1
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/GenerateGetterTests.cs

@ -33,6 +33,7 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions @@ -33,6 +33,7 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions
[TestFixture]
public class GenerateGetterTests : ContextActionTestBase
{
[Ignore("Implement missing feature")]
[Test()]
public void Test ()
{

1
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/GeneratePropertyTests.cs

@ -32,6 +32,7 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions @@ -32,6 +32,7 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions
[TestFixture]
public class GeneratePropertyTests : ContextActionTestBase
{
[Ignore("Implement missing feature")]
[Test()]
public void Test ()
{

16
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/ContextAction/TestRefactoringContext.cs

@ -39,7 +39,7 @@ using System.Threading; @@ -39,7 +39,7 @@ using System.Threading;
namespace ICSharpCode.NRefactory.CSharp.ContextActions
{
class TestRefactoringContext : RefactoringContext
public class TestRefactoringContext : RefactoringContext
{
internal readonly IDocument doc;
readonly TextLocation location;
@ -70,6 +70,14 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions @@ -70,6 +70,14 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions
{
this.eolMarker = context.EolMarker;
}
public override void Link (params AstNode[] nodes)
{
// check that all links are valid.
foreach (var node in nodes) {
Assert.IsNotNull (GetSegment (node));
}
}
}
#region Text stuff
@ -112,7 +120,11 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions @@ -112,7 +120,11 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions
return doc.GetLineByOffset (offset);
}
#endregion
public string Text {
get {
return doc.Text;
}
}
public static TestRefactoringContext Create(string content)
{
int idx = content.IndexOf ("$");

133
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/ConditionalToNullCoalescingInspectorTests.cs

@ -0,0 +1,133 @@ @@ -0,0 +1,133 @@
//
// ConditionalToNullCoalescingInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class ConditionalToNullCoalescingInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"class Foo
{
void Bar (string str)
{
string c = str != null ? str : ""default"";
}
}";
TestRefactoringContext context;
var issues = GetIssues (new ConditionalToNullCoalescingInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
CheckFix (context, issues [0], @"class Foo
{
void Bar (string str)
{
string c = str ?? ""default"";
}
}");
}
[Test]
public void TestInspectorCase2 ()
{
var input = @"class Foo
{
void Bar (string str)
{
string c = null != str ? str : ""default"";
}
}";
TestRefactoringContext context;
var issues = GetIssues (new ConditionalToNullCoalescingInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
CheckFix (context, issues [0], @"class Foo
{
void Bar (string str)
{
string c = str ?? ""default"";
}
}");
}
[Test]
public void TestInspectorCase3 ()
{
var input = @"class Foo
{
void Bar (string str)
{
string c = null == str ? ""default"" : str;
}
}";
TestRefactoringContext context;
var issues = GetIssues (new ConditionalToNullCoalescingInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
CheckFix (context, issues [0], @"class Foo
{
void Bar (string str)
{
string c = str ?? ""default"";
}
}");
}
[Test]
public void TestInspectorCase4 ()
{
var input = @"class Foo
{
void Bar (string str)
{
string c = str == null ? ""default"" : str;
}
}";
TestRefactoringContext context;
var issues = GetIssues (new ConditionalToNullCoalescingInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
CheckFix (context, issues [0], @"class Foo
{
void Bar (string str)
{
string c = str ?? ""default"";
}
}");
}
}
}

53
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/InspectionActionTestBase.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
//
// InspectionActionTestBase.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
using System.Collections.Generic;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
public abstract class InspectionActionTestBase
{
protected static List<CodeIssue> GetIssues (ICodeIssueProvider action, string input, out TestRefactoringContext context)
{
context = TestRefactoringContext.Create (input);
return new List<CodeIssue> (action.GetIssues (context));
}
protected static void CheckFix (TestRefactoringContext ctx, CodeIssue issue, string expectedOutput)
{
using (var script = ctx.StartScript ())
issue.Action.Run (script);
Assert.AreEqual (expectedOutput, ctx.Text);
}
}
}

53
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/NotImplementedExceptionInspectorTests.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
//
// NotImplementedExceptionInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class NotImplementedExceptionInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"class Foo
{
void Bar (string str)
{
throw new System.NotImplementedException ();
}
}";
TestRefactoringContext context;
var issues = GetIssues (new NotImplementedExceptionInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

51
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantInternalInspectorTests.cs

@ -0,0 +1,51 @@ @@ -0,0 +1,51 @@
//
// RedundantInternalInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class RedundantInternalInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"internal class Foo
{
internal void Bar (string str)
{
}
}";
TestRefactoringContext context;
var issues = GetIssues (new RedundantInternalInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

54
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantNamespaceUsageInspectorTests.cs

@ -0,0 +1,54 @@ @@ -0,0 +1,54 @@
//
// RedundantNamespaceUsageInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class RedundantNamespaceUsageInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"using System;
class Foo
{
void Bar (string str)
{
System.Console.WriteLine ();
}
}";
TestRefactoringContext context;
var issues = GetIssues (new RedundantNamespaceUsageInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

52
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantPrivateInspectorTests.cs

@ -0,0 +1,52 @@ @@ -0,0 +1,52 @@
//
// RedundantPrivateInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class RedundantPrivateInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"class Foo
{
private void Bar (string str)
{
}
}";
TestRefactoringContext context;
var issues = GetIssues (new RedundantPrivateInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

53
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantThisInspectorTests.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
//
// RedundantThisInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class RedundantThisInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"class Foo
{
void Bar (string str)
{
this.Bar (str);
}
}";
TestRefactoringContext context;
var issues = GetIssues (new RedundantThisInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

54
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/RedundantUsingInspectorTests.cs

@ -0,0 +1,54 @@ @@ -0,0 +1,54 @@
//
// RedundantUsingInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class RedundantUsingInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"using System;
class Foo
{
void Bar (string str)
{
}
}";
TestRefactoringContext context;
var issues = GetIssues (new RedundantUsingInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

55
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/StringIsNullOrEmptyInspectorTests.cs

@ -0,0 +1,55 @@ @@ -0,0 +1,55 @@
//
// StringIsNullOrEmptyInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class StringIsNullOrEmptyInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"class Foo
{
void Bar (string str)
{
if (str != null && str != """")
;
}
}";
TestRefactoringContext context;
var issues = GetIssues (new StringIsNullOrEmptyInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

53
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Inspector/UseVarKeywordInspectorTests.cs

@ -0,0 +1,53 @@ @@ -0,0 +1,53 @@
//
// UseVarKeywordInspectorTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.ContextActions;
namespace ICSharpCode.NRefactory.CSharp.Inspector
{
[TestFixture]
public class UseVarKeywordInspectorTests : InspectionActionTestBase
{
[Test]
public void TestInspectorCase1 ()
{
var input = @"class Foo
{
void Bar (object o)
{
Foo foo = (Foo)o;
}
}";
TestRefactoringContext context;
var issues = GetIssues (new UseVarKeywordInspector (), input, out context);
Assert.AreEqual (1, issues.Count);
}
}
}

18
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs

@ -521,5 +521,23 @@ class C { @@ -521,5 +521,23 @@ class C {
Assert.That(rr.TargetResult, Is.InstanceOf<TypeResolveResult>());
}
[Test]
public void BaseInvocation()
{
string program = @"
class B {
public virtual void F(int x, int y) {}
}
class D : B {
public override void F(int x, int y) {}
public void M() {
$base.F(0, 1)$;
}
}";
var rr = Resolve<CSharpInvocationResolveResult>(program);
Assert.IsFalse(rr.IsError);
Assert.IsFalse(rr.IsVirtualCall);
}
}
}

5
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/FormattingTests/TestStatementIndentation.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// TestStatementIndentation.cs
//
// Author:
@ -948,6 +948,7 @@ do { @@ -948,6 +948,7 @@ do {
}
[Test()]
[Ignore("Crashes due to overlapping changes")]
public void TestForEachBraceForcementRemove ()
{
CSharpFormattingOptions policy = new CSharpFormattingOptions ();
@ -1104,6 +1105,7 @@ do { @@ -1104,6 +1105,7 @@ do {
}
[Test()]
[Ignore("Crashes due to overlapping changes")]
public void TestIfForcementRemove ()
{
CSharpFormattingOptions policy = new CSharpFormattingOptions ();
@ -1412,6 +1414,7 @@ if (b) { @@ -1412,6 +1414,7 @@ if (b) {
}
[Test()]
[Ignore("Crashes due to overlapping changes")]
public void TestWhileForcementRemove ()
{
CSharpFormattingOptions policy = new CSharpFormattingOptions ();

14
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj

@ -71,9 +71,8 @@ @@ -71,9 +71,8 @@
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="nunit.framework, Version=2.6.0.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<Reference Include="nunit.framework">
<HintPath>..\..\Mono.Cecil\Test\libs\nunit-2.5.10\nunit.framework.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
</Reference>
</ItemGroup>
<ItemGroup>
@ -238,6 +237,16 @@ @@ -238,6 +237,16 @@
<Compile Include="CSharp\ContextAction\AddAnotherAccessorTests.cs" />
<Compile Include="CSharp\ContextAction\RemoveRegionTests.cs" />
<Compile Include="CSharp\ContextAction\GeneratePropertyTests.cs" />
<Compile Include="CSharp\Inspector\ConditionalToNullCoalescingInspectorTests.cs" />
<Compile Include="CSharp\Inspector\InspectionActionTestBase.cs" />
<Compile Include="CSharp\Inspector\NotImplementedExceptionInspectorTests.cs" />
<Compile Include="CSharp\Inspector\RedundantInternalInspectorTests.cs" />
<Compile Include="CSharp\Inspector\RedundantNamespaceUsageInspectorTests.cs" />
<Compile Include="CSharp\Inspector\RedundantPrivateInspectorTests.cs" />
<Compile Include="CSharp\Inspector\RedundantThisInspectorTests.cs" />
<Compile Include="CSharp\Inspector\RedundantUsingInspectorTests.cs" />
<Compile Include="CSharp\Inspector\StringIsNullOrEmptyInspectorTests.cs" />
<Compile Include="CSharp\Inspector\UseVarKeywordInspectorTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Mono.Cecil\Mono.Cecil.csproj">
@ -264,6 +273,7 @@ @@ -264,6 +273,7 @@
<Folder Include="CSharp\" />
<Folder Include="CSharp\Parser\" />
<Folder Include="CSharp\ContextAction\" />
<Folder Include="CSharp\Inspector\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ProjectExtensions>

Loading…
Cancel
Save