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
} }
} }
var isAsWrapper = new CompletionDataWrapper (this); 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; return isAsWrapper.Result;
// { // {
// CompletionDataList completionList = new ProjectDomCompletionDataList (); // CompletionDataList completionList = new ProjectDomCompletionDataList ();

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

@ -240,31 +240,7 @@
<Compile Include="Parser\mcs\typespec.cs" /> <Compile Include="Parser\mcs\typespec.cs" />
<Compile Include="Parser\mcs\visit.cs" /> <Compile Include="Parser\mcs\visit.cs" />
<Compile Include="Properties\AssemblyInfo.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\DocumentScript.cs" />
<Compile Include="Refactoring\IContextAction.cs" />
<Compile Include="Refactoring\PatternHelper.cs" /> <Compile Include="Refactoring\PatternHelper.cs" />
<Compile Include="Refactoring\RefactoringAstHelper.cs" /> <Compile Include="Refactoring\RefactoringAstHelper.cs" />
<Compile Include="Refactoring\RefactoringContext.cs" /> <Compile Include="Refactoring\RefactoringContext.cs" />
@ -321,22 +297,52 @@
<Compile Include="Parser\mcs\settings.cs" /> <Compile Include="Parser\mcs\settings.cs" />
<Compile Include="Parser\mcs\SourceMethodBuilder.cs" /> <Compile Include="Parser\mcs\SourceMethodBuilder.cs" />
<Compile Include="Ast\TokenRole.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="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\BaseRefactoringContext.cs" />
<Compile Include="Refactoring\Inspector\GatherVisitorBase.cs" /> <Compile Include="Refactoring\CodeIssue.cs" />
<Compile Include="Refactoring\Inspector\NotImplementedExceptionInspector.cs" /> <Compile Include="Refactoring\CodeAction.cs" />
<Compile Include="Refactoring\Inspector\RedundantInternalInspector.cs" /> <Compile Include="Refactoring\ICodeActionProvider.cs" />
<Compile Include="Refactoring\Inspector\RedundantNamespaceUsageInspector.cs" /> <Compile Include="Refactoring\CodeActions\AddAnotherAccessor.cs" />
<Compile Include="Refactoring\Inspector\RedundantPrivateInspector.cs" /> <Compile Include="Refactoring\ICodeIssueProvider.cs" />
<Compile Include="Refactoring\Inspector\RedundantThisInspector.cs" /> <Compile Include="Refactoring\CodeActions\CheckIfParameterIsNull.cs" />
<Compile Include="Refactoring\Inspector\RedundantUsingInspector.cs" /> <Compile Include="Refactoring\CodeActions\ConvertDecToHex.cs" />
<Compile Include="Refactoring\Inspector\StringIsNullOrEmptyInspector.cs" /> <Compile Include="Refactoring\CodeActions\ConvertForeachToFor.cs" />
<Compile Include="Refactoring\Inspector\UseVarKeywordInspector.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>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj"> <ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
@ -347,7 +353,7 @@
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
<ItemGroup> <ItemGroup>
<Folder Include="Completion\" /> <Folder Include="Completion\" />
<Folder Include="Refactoring\Inspector\" /> <Folder Include="Refactoring\CodeIssues\" />
</ItemGroup> </ItemGroup>
<ProjectExtensions> <ProjectExtensions>
<MonoDevelop> <MonoDevelop>

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

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

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

@ -98,6 +98,16 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public abstract Script StartScript(); 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 @@
//
// 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 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
/// <summary> /// <summary>
/// Add another accessor to a property declaration that has only one. /// Add another accessor to a property declaration that has only one.
/// </summary> /// </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); var pdecl = GetPropertyDeclaration(context);
if (pdecl == null) if (pdecl == null) {
return false; yield break;
var type = pdecl.Parent as TypeDeclaration;
if (type != null && type.ClassType == ClassType.Interface)
return false;
return pdecl.Setter.IsNull || pdecl.Getter.IsNull;
} }
public void Run (RefactoringContext context) var type = pdecl.Parent as TypeDeclaration;
{ if (type != null && type.ClassType == ClassType.Interface) {
var pdecl = GetPropertyDeclaration (context); yield break;
}
yield return new CodeAction (pdecl.Setter.IsNull ? context.TranslateString("Add getter") : context.TranslateString("Add setter"), script => {
var accessorStatement = BuildAccessorStatement(context, pdecl); var accessorStatement = BuildAccessorStatement(context, pdecl);
Accessor accessor = new Accessor () { Accessor accessor = new Accessor () {
Body = new BlockStatement { accessorStatement } Body = new BlockStatement { accessorStatement }
}; };
accessor.Role = pdecl.Setter.IsNull ? PropertyDeclaration.SetterRole : PropertyDeclaration.GetterRole; accessor.Role = pdecl.Setter.IsNull ? PropertyDeclaration.SetterRole : PropertyDeclaration.GetterRole;
using (var script = context.StartScript ()) {
if (pdecl.Setter.IsNull && !pdecl.Getter.IsNull) { if (pdecl.Setter.IsNull && !pdecl.Getter.IsNull) {
script.InsertBefore(pdecl.RBraceToken, accessor); script.InsertBefore(pdecl.RBraceToken, accessor);
} else if (pdecl.Getter.IsNull && !pdecl.Setter.IsNull) {
script.InsertBefore(pdecl.Setter, accessor);
} else { } else {
script.InsertBefore(pdecl.Getter, accessor); script.InsertBefore(pdecl.Getter, accessor);
} }
script.Select(accessorStatement); script.Select(accessorStatement);
script.FormatText(pdecl); script.FormatText(pdecl);
} });
} }
static Statement BuildAccessorStatement (RefactoringContext context, PropertyDeclaration 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 @@
// THE SOFTWARE. // THE SOFTWARE.
using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.PatternMatching;
using System.Threading; using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
/// <summary> /// <summary>
/// Creates a 'if (param == null) throw new System.ArgumentNullException ();' contruct for a parameter. /// Creates a 'if (param == null) throw new System.ArgumentNullException ();' contruct for a parameter.
/// </summary> /// </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 IEnumerable<CodeAction> GetActions(RefactoringContext context)
public bool IsValid (RefactoringContext context)
{ {
var parameter = GetParameterDeclaration(context); var parameter = GetParameterDeclaration(context);
if (parameter == null) if (parameter == null) {
return false; yield break;
}
var bodyStatement = parameter.Parent.GetChildByRole(Roles.Body); var bodyStatement = parameter.Parent.GetChildByRole(Roles.Body);
if (bodyStatement == null) if (bodyStatement == null) {
return false; yield break;
}
var type = context.ResolveType(parameter.Type); var type = context.ResolveType(parameter.Type);
if (type.IsReferenceType == false) if (type.IsReferenceType == false || HasNullCheck(parameter)) {
return false; yield break;
return !HasNullCheck (parameter);
} }
public void Run (RefactoringContext context) yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
{
var parameter = GetParameterDeclaration (context);
var bodyStatement = parameter.Parent.GetChildByRole (Roles.Body);
var statement = new IfElseStatement () { var statement = new IfElseStatement () {
Condition = new BinaryOperatorExpression (new IdentifierExpression (parameter.Name), BinaryOperatorType.Equality, new NullReferenceExpression ()), Condition = new BinaryOperatorExpression (new IdentifierExpression (parameter.Name), BinaryOperatorType.Equality, new NullReferenceExpression ()),
TrueStatement = new ThrowStatement (new ObjectCreateExpression (context.CreateShortType("System", "ArgumentNullException"), new PrimitiveExpression (parameter.Name))) TrueStatement = new ThrowStatement (new ObjectCreateExpression (context.CreateShortType("System", "ArgumentNullException"), new PrimitiveExpression (parameter.Name)))
}; };
using (var script = context.StartScript ()) {
script.AddTo(bodyStatement, statement); script.AddTo(bodyStatement, statement);
} });
} }
static ParameterDeclaration GetParameterDeclaration (RefactoringContext context) static ParameterDeclaration GetParameterDeclaration (RefactoringContext context)
@ -89,7 +83,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public CheckNullVisitor (ParameterDeclaration parameter) 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) 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 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
/// <summary> /// <summary>
/// Convert a dec numer to hex. For example: 16 -> 0x10 /// Convert a dec numer to hex. For example: 16 -> 0x10
/// </summary> /// </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>(); var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || pexpr.LiteralValue.StartsWith ("0X", System.StringComparison.OrdinalIgnoreCase)) if (pexpr == null || pexpr.LiteralValue.StartsWith("0X", System.StringComparison.OrdinalIgnoreCase)) {
return false; yield break;
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.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) yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
{
var pexpr = context.GetNode<PrimitiveExpression> ();
using (var script = context.StartScript ()) {
script.Replace(pexpr, new PrimitiveExpression (pexpr.Value, string.Format("0x{0:x}", pexpr.Value))); 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;
using System.Linq; using System.Linq;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
/// <summary> /// <summary>
/// Converts a foreach loop to for. /// Converts a foreach loop to for.
/// </summary> /// </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) public IEnumerable<CodeAction> GetActions(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)
{ {
var foreachStatement = GetForeachStatement(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 result = context.Resolve (foreachStatement.InExpression);
var countProperty = GetCountProperty (result.Type); var countProperty = GetCountProperty (result.Type);
@ -77,10 +70,18 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole); forStatement.EmbeddedStatement.AddChild (foreachStatement.EmbeddedStatement.Clone (), BlockStatement.StatementRole);
} }
using (var script = context.StartScript ()) {
script.Replace (foreachStatement, forStatement); script.Replace (foreachStatement, forStatement);
script.Link (initializer.Variables.First ().NameToken, id1, id2, id3); 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) 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 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
/// <summary> /// <summary>
/// Convert a hex numer to dec. For example: 0x10 -> 16 /// Convert a hex numer to dec. For example: 0x10 -> 16
/// </summary> /// </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>(); var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || !pexpr.LiteralValue.StartsWith ("0X", System.StringComparison.OrdinalIgnoreCase)) if (pexpr == null || !pexpr.LiteralValue.StartsWith("0X", System.StringComparison.OrdinalIgnoreCase)) {
return false; yield break;
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.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) yield return new CodeAction (context.TranslateString("Add null check for parameter"), script => {
{
var pexpr = context.GetNode<PrimitiveExpression> ();
using (var script = context.StartScript ()) {
script.Replace(pexpr, new PrimitiveExpression (pexpr.Value)); script.Replace(pexpr, new PrimitiveExpression (pexpr.Value));
} });
} }
} }
} }

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

@ -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 @@
//
// 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;
using System.Linq; using System.Linq;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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); var identifier = GetIdentifier(context);
if (identifier == null) if (identifier == null) {
return false; yield break;
return context.Resolve (identifier) == null && GuessType (context, identifier) != null;
} }
public void Run (RefactoringContext context) if (!(context.Resolve(identifier).IsError && GuessType(context, identifier) != null)) {
{ yield break;
var identifier = GetIdentifier (context);
using (var script = context.StartScript ()) {
script.InsertWithCursor ("Create field", GenerateFieldDeclaration (context, identifier), Script.InsertPosition.Before);
} }
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) static AstNode GenerateFieldDeclaration (RefactoringContext context, IdentifierExpression identifier)
{ {
return new FieldDeclaration () { 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;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public List<IdentifierExpression> GetUnresolvedArguments (RefactoringContext context)
{ {
@ -59,34 +60,33 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
return expressions; return expressions;
} }
public bool IsValid (RefactoringContext context) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{ {
if (GetUnresolvedArguments (context).Count > 0) if (GetUnresolvedArguments(context).Count <= 0) {
return true; yield break;
}
var identifier = CreateField.GetIdentifier(context); var identifier = CreateField.GetIdentifier(context);
if (identifier == null) if (identifier == null) {
return false; yield break;
if (context.GetNode<Statement> () == null)
return false;
return context.Resolve (identifier) == null && GuessType (context, identifier) != null;
} }
if (context.GetNode<Statement>() == null) {
public void Run (RefactoringContext context) 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 stmt = context.GetNode<Statement> ();
var unresolvedArguments = GetUnresolvedArguments (context); var unresolvedArguments = GetUnresolvedArguments (context);
if (unresolvedArguments.Count > 0) { if (unresolvedArguments.Count > 0) {
using (var script = context.StartScript ()) {
foreach (var id in unresolvedArguments) { foreach (var id in unresolvedArguments) {
script.InsertBefore (stmt, GenerateLocalVariableDeclaration (context, id)); script.InsertBefore (stmt, GenerateLocalVariableDeclaration (context, id));
} }
}
return; return;
} }
using (var script = context.StartScript ()) {
script.InsertBefore (stmt, GenerateLocalVariableDeclaration (context, CreateField.GetIdentifier (context))); script.InsertBefore (stmt, GenerateLocalVariableDeclaration (context, CreateField.GetIdentifier (context)));
} });
} }
AstNode GenerateLocalVariableDeclaration (RefactoringContext context, IdentifierExpression identifier) 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;
using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.PatternMatching;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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); var identifier = CreateField.GetIdentifier(context);
if (identifier == null) if (identifier == null) {
return false; yield break;
return context.Resolve (identifier) == null && CreateField.GuessType (context, identifier) != null;
} }
if (!(context.Resolve(identifier).IsError && CreateField.GuessType(context, identifier) != null)) {
public void Run (RefactoringContext context) yield break;
{
var identifier = GetIdentifier (context);
using (var script = context.StartScript ()) {
script.InsertWithCursor ("Create property", GeneratePropertyDeclaration (context, identifier), Script.InsertPosition.Before);
} }
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) 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 @@
// THE SOFTWARE. // THE SOFTWARE.
using System; using System;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
return GetBinaryOperatorExpression (context) != null;
}
public void Run (RefactoringContext context)
{ {
var binop = GetBinaryOperatorExpression(context); var binop = GetBinaryOperatorExpression(context);
if (binop == null) {
using (var script = context.StartScript ()) { yield break;
}
yield return new CodeAction (context.TranslateString("Swap left and right arguments"), script => {
script.Replace(binop.Left, binop.Right.Clone()); script.Replace(binop.Left, binop.Right.Clone());
script.Replace(binop.Right, binop.Left.Clone()); script.Replace(binop.Right, binop.Left.Clone());
} });
} }
public static BinaryOperatorExpression GetBinaryOperatorExpression (RefactoringContext context) 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;
using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.PatternMatching;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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); var initializer = GetVariableInitializer(context);
if (initializer == null || !initializer.NameToken.Contains (context.Location.Line, context.Location.Column)) if (initializer == null || !initializer.NameToken.Contains(context.Location.Line, context.Location.Column)) {
return false; yield break;
}
var type = initializer.Parent.Parent as TypeDeclaration; var type = initializer.Parent.Parent as TypeDeclaration;
if (type == null) if (type == null) {
return false; yield break;
}
foreach (var member in type.Members) { foreach (var member in type.Members) {
if (member is PropertyDeclaration && ContainsGetter ((PropertyDeclaration)member, initializer)) if (member is PropertyDeclaration && ContainsGetter((PropertyDeclaration)member, initializer)) {
return false; yield break;
} }
return initializer.Parent is FieldDeclaration;
} }
public void Run (RefactoringContext context)
{
var initializer = GetVariableInitializer (context);
var field = initializer.Parent as FieldDeclaration; var field = initializer.Parent as FieldDeclaration;
if (field == null) {
using (var script = context.StartScript ()) { yield break;
script.InsertWithCursor ("Create getter", GeneratePropertyDeclaration (context, field, initializer), Script.InsertPosition.After);
} }
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) 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;
using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.PatternMatching;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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); var initializer = GetVariableInitializer(context);
if (initializer == null || !initializer.NameToken.Contains (context.Location.Line, context.Location.Column)) if (initializer == null || !initializer.NameToken.Contains(context.Location.Line, context.Location.Column)) {
return false; yield break;
}
var type = initializer.Parent.Parent as TypeDeclaration; var type = initializer.Parent.Parent as TypeDeclaration;
if (type == null) if (type == null) {
return false; yield break;
}
foreach (var member in type.Members) { foreach (var member in type.Members) {
if (member is PropertyDeclaration && ContainsGetter ((PropertyDeclaration)member, initializer)) if (member is PropertyDeclaration && ContainsGetter((PropertyDeclaration)member, initializer)) {
return false; yield break;
} }
return initializer.Parent is FieldDeclaration;
} }
public void Run (RefactoringContext context)
{
var initializer = GetVariableInitializer (context);
var field = initializer.Parent as FieldDeclaration; var field = initializer.Parent as FieldDeclaration;
if (field == null) {
using (var script = context.StartScript ()) { yield break;
script.InsertWithCursor ("Create property", GeneratePropertyDeclaration (context, field, initializer), Script.InsertPosition.After);
} }
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) 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 @@
using System; using System;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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); var switchStatement = GetSwitchStatement(context);
if (switchStatement == null) if (switchStatement == null) {
return false; yield break;
var result = context.Resolve (switchStatement.Expression);
if (result == null)
return false;
return result.Type.Kind == TypeKind.Enum;
} }
public void Run (RefactoringContext context)
{
var switchStatement = GetSwitchStatement (context);
var result = context.Resolve(switchStatement.Expression); 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 type = result.Type;
var newSwitch = (SwitchStatement)switchStatement.Clone(); var newSwitch = (SwitchStatement)switchStatement.Clone();
var target = new TypeReferenceExpression (context.CreateShortType(result.Type)); var target = new TypeReferenceExpression (context.CreateShortType(result.Type));
foreach (var field in type.GetFields ()) { foreach (var field in type.GetFields ()) {
if (field.IsSynthetic || !field.IsConst) if (field.IsSynthetic || !field.IsConst) {
continue; continue;
}
newSwitch.SwitchSections.Add(new SwitchSection () { newSwitch.SwitchSections.Add(new SwitchSection () {
CaseLabels = { CaseLabels = {
new CaseLabel (new MemberReferenceExpression (target.Clone(), field.Name)) new CaseLabel (new MemberReferenceExpression (target.Clone(), field.Name))
@ -73,9 +71,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
}); });
using (var script = context.StartScript ()) {
script.Replace(switchStatement, newSwitch); script.Replace(switchStatement, newSwitch);
} });
} }
static SwitchStatement GetSwitchStatement (RefactoringContext context) 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;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
IType type;
return GetAnonymousMethodExpression (context, out type) != null;
}
public void Run (RefactoringContext context)
{ {
IType type; IType type;
var anonymousMethodExpression = GetAnonymousMethodExpression(context, out 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 delegateMethod = type.GetDelegateInvokeMethod();
var sb = new StringBuilder ("("); var sb = new StringBuilder ("(");
for (int k = 0; k < delegateMethod.Parameters.Count; k++) { for (int k = 0; k < delegateMethod.Parameters.Count; k++) {
if (k > 0) if (k > 0) {
sb.Append(", "); sb.Append(", ");
}
var paramType = delegateMethod.Parameters [k].Type; var paramType = delegateMethod.Parameters [k].Type;
@ -59,9 +59,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
sb.Append(")"); sb.Append(")");
using (var script = context.StartScript ()) {
script.InsertText(context.GetOffset(anonymousMethodExpression.DelegateToken.EndLocation), sb.ToString()); script.InsertText(context.GetOffset(anonymousMethodExpression.DelegateToken.EndLocation), sb.ToString());
} });
} }
static AnonymousMethodExpression GetAnonymousMethodExpression (RefactoringContext context, out IType delegateType) 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
/// Introduce format item. Works on strings that contain selections. /// Introduce format item. Works on strings that contain selections.
/// "this is <some> string" => string.Format ("this is {0} string", <some>) /// "this is <some> string" => string.Format ("this is {0} string", <some>)
/// </summary> /// </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"); 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) if (!context.IsSomethingSelected) {
return false; yield break;
}
var pexpr = context.GetNode<PrimitiveExpression>(); var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || !(pexpr.Value is string)) if (pexpr == null || !(pexpr.Value is string)) {
return false; yield break;
if (pexpr.LiteralValue.StartsWith ("@")) }
return pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 1) && if (pexpr.LiteralValue.StartsWith("@")) {
new TextLocation (context.Location.Line, context.Location.Column + 1) < pexpr.EndLocation; if (!(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; yield break;
}
} else {
if (!(pexpr.StartLocation < context.Location && context.Location < pexpr.EndLocation)) {
yield break;
}
} }
public void Run (RefactoringContext context) yield return new CodeAction (context.TranslateString("Introduce format item"), script => {
{
var pexpr = context.GetNode<PrimitiveExpression> ();
var invocation = context.GetNode<InvocationExpression>(); var invocation = context.GetNode<InvocationExpression>();
if (invocation != null && invocation.Target.IsMatch(PrototypeFormatReference)) { if (invocation != null && invocation.Target.IsMatch(PrototypeFormatReference)) {
AddFormatCallToInvocation(context, pexpr, invocation); AddFormatCallToInvocation(context, pexpr, invocation);
@ -67,10 +72,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
Arguments = { CreateFormatString(context, pexpr, 0), arg } Arguments = { CreateFormatString(context, pexpr, 0), arg }
}; };
using (var script = context.StartScript ()) {
script.Replace(pexpr, newInvocation); script.Replace(pexpr, newInvocation);
script.Select(arg); script.Select(arg);
} });
} }
void AddFormatCallToInvocation (RefactoringContext context, PrimitiveExpression pExpr, InvocationExpression invocation) 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 @@
// THE SOFTWARE. // THE SOFTWARE.
using System; using System;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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 // TODO: Invert if without else
// ex. if (cond) DoSomething () == if (!cond) return; DoSomething () // ex. if (cond) DoSomething () == if (!cond) return; DoSomething ()
// beware of loop contexts return should be continue then. // beware of loop contexts return should be continue then.
public void Run (RefactoringContext context)
{
var ifStatement = GetIfElseStatement(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.Condition, CSharpUtil.InvertCondition(ifStatement.Condition.Clone()));
script.Replace(ifStatement.TrueStatement, ifStatement.FalseStatement.Clone()); script.Replace(ifStatement.TrueStatement, ifStatement.FalseStatement.Clone());
script.Replace(ifStatement.FalseStatement, ifStatement.TrueStatement.Clone()); script.Replace(ifStatement.FalseStatement, ifStatement.TrueStatement.Clone());
script.FormatText(ifStatement); script.FormatText(ifStatement);
} });
} }
static IfElseStatement GetIfElseStatement (RefactoringContext context) 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;
using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
return GetBackingField (context) != null;
}
public void Run (RefactoringContext context)
{ {
var property = context.GetNode<PropertyDeclaration>(); var property = context.GetNode<PropertyDeclaration>();
var field = GetBackingField(context); var field = GetBackingField(context);
if (field == null) {
yield break;
}
// create new auto property // create new auto property
var newProperty = (PropertyDeclaration)property.Clone(); var newProperty = (PropertyDeclaration)property.Clone();
newProperty.Getter.Body = BlockStatement.Null; newProperty.Getter.Body = BlockStatement.Null;
newProperty.Setter.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.Remove (context.RootNode.GetNodeAt<FieldDeclaration> (field.Region.BeginLine, field.Region.BeginColumn));
script.Replace (property, newProperty); script.Replace (property, newProperty);
script.Rename (field, newProperty.Name); script.Rename (field, newProperty.Name);
} });
} }
// void ReplaceBackingFieldReferences (MDRefactoringContext context, IField backingStore, PropertyDeclaration property) // 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 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
return GetBlockStatement (context) != null;
}
public void Run (RefactoringContext context)
{ {
var block = GetBlockStatement(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.LBraceToken);
script.Remove(block.RBraceToken); script.Remove(block.RBraceToken);
script.FormatText(block.Parent); script.FormatText(block.Parent);
} });
} }
static BlockStatement GetBlockStatement (RefactoringContext context) 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 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
return GetDirective (context) != null;
}
public void Run (RefactoringContext context)
{ {
var directive = GetDirective(context); var directive = GetDirective(context);
if (directive == null) {
yield break;
}
var endDirective = DirectiveSearcher.GetEndRegion(context.RootNode, directive); var endDirective = DirectiveSearcher.GetEndRegion(context.RootNode, directive);
if (endDirective == null) if (endDirective == null) {
return; yield break;
using (var script = context.StartScript ()) { }
yield return new CodeAction (context.TranslateString("Remove region"), script => {
script.Remove (directive); script.Remove (directive);
script.Remove (endDirective); script.Remove (endDirective);
} });
} }
class DirectiveSearcher : DepthFirstAstVisitor 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 @@
// THE SOFTWARE. // THE SOFTWARE.
using System; using System;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
return GetEmptyString (context) != null;
}
public void Run (RefactoringContext context)
{ {
var expr = GetEmptyString(context); var expr = GetEmptyString(context);
using (var script = context.StartScript ()) { if (expr == null) {
script.Replace (expr, new MemberReferenceExpression (new TypeReferenceExpression (new PrimitiveType ("string")), "Empty")); 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) 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;
using System.Linq; using System.Linq;
using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.PatternMatching;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) public IEnumerable<CodeAction> GetActions(RefactoringContext context)
{
AstType type;
return GetVariableDeclarationStatement (context, out type) != null;
}
public void Run (RefactoringContext context)
{ {
AstType type; AstType type;
var varDecl = GetVariableDeclarationStatement(context, out 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 assign = new AssignmentExpression (new IdentifierExpression (varDecl.Variables.First().Name), AssignmentOperatorType.Assign, varDecl.Variables.First().Initializer.Clone());
var newVarDecl = (VariableDeclarationStatement)varDecl.Clone(); var newVarDecl = (VariableDeclarationStatement)varDecl.Clone();
newVarDecl.Role = BlockStatement.StatementRole; newVarDecl.Role = BlockStatement.StatementRole;
if (newVarDecl.Type.IsMatch (new SimpleType ("var"))) if (newVarDecl.Type.IsMatch(new SimpleType ("var"))) {
newVarDecl.Type = type; newVarDecl.Type = type;
}
newVarDecl.Variables.First().Initializer = Expression.Null; newVarDecl.Variables.First().Initializer = Expression.Null;
using (var script = context.StartScript ()) {
script.InsertBefore(varDecl, newVarDecl); script.InsertBefore(varDecl, newVarDecl);
script.Replace(varDecl, varDecl.Parent is ForStatement ? (AstNode)assign : new ExpressionStatement (assign)); script.Replace(varDecl, varDecl.Parent is ForStatement ? (AstNode)assign : new ExpressionStatement (assign));
} });
} }
static VariableDeclarationStatement GetVariableDeclarationStatement (RefactoringContext context, out AstType resolvedType, CancellationToken cancellationToken = default(CancellationToken)) 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 @@
// THE SOFTWARE. // THE SOFTWARE.
using System; using System;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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) if (context.IsSomethingSelected) {
return false; yield break;
}
var pexpr = context.GetNode<PrimitiveExpression>(); var pexpr = context.GetNode<PrimitiveExpression>();
if (pexpr == null || !(pexpr.Value is string)) if (pexpr == null || !(pexpr.Value is string)) {
return false; yield break;
if (pexpr.LiteralValue.StartsWith ("@")) }
return pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 2) && if (pexpr.LiteralValue.StartsWith("@")) {
new TextLocation (context.Location.Line, context.Location.Column + 2) < pexpr.EndLocation; if (!(pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 2) &&
return pexpr.StartLocation < new TextLocation (context.Location.Line, context.Location.Column - 1) && new TextLocation (context.Location.Line, context.Location.Column + 2) < pexpr.EndLocation)) {
new TextLocation (context.Location.Line, context.Location.Column + 1) < 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) yield return new CodeAction (context.TranslateString("Remove braces"), script => {
{
var pexpr = context.GetNode<PrimitiveExpression> ();
int offset = context.GetOffset (context.Location); int offset = context.GetOffset (context.Location);
using (var script = context.StartScript ()) {
script.InsertText (offset, pexpr.LiteralValue.StartsWith ("@") ? "\" + @\"" : "\" + \""); 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;
using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.PatternMatching;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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); var varDecl = GetVariableDeclarationStatement(context);
IType type; IType type;
@ -42,27 +43,23 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
type = context.Resolve(varDecl.Variables.First().Initializer).Type; type = context.Resolve(varDecl.Variables.First().Initializer).Type;
} else { } else {
var foreachStatement = GetForeachStatement(context); var foreachStatement = GetForeachStatement(context);
if (foreachStatement == null) if (foreachStatement == null) {
return false; yield break;
}
type = context.Resolve(foreachStatement.VariableType).Type; 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;
} }
yield return new CodeAction (context.TranslateString("Remove braces"), script => {
public void Run (RefactoringContext context)
{
using (var script = context.StartScript ()) {
var varDecl = GetVariableDeclarationStatement (context);
if (varDecl != null) { if (varDecl != null) {
var type = context.Resolve (varDecl.Variables.First ().Initializer).Type;
script.Replace (varDecl.Type, context.CreateShortType (type)); script.Replace (varDecl.Type, context.CreateShortType (type));
} else { } else {
var foreachStatement = GetForeachStatement (context); var foreachStatement = GetForeachStatement (context);
var type = context.Resolve (foreachStatement.VariableType).Type;
script.Replace (foreachStatement.VariableType, context.CreateShortType (type)); script.Replace (foreachStatement.VariableType, context.CreateShortType (type));
} }
} });
} }
static readonly AstType varType = new SimpleType ("var"); 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;
using System.Linq; using System.Linq;
using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.PatternMatching;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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 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) { if (varDecl != null) {
script.Replace(varDecl.Type, new SimpleType ("var")); script.Replace(varDecl.Type, new SimpleType ("var"));
} else { } else {
script.Replace (GetForeachStatement (context).VariableType, new SimpleType ("var")); script.Replace(foreachStmt.VariableType, new SimpleType ("var"));
}
} }
});
} }
static readonly AstType varType = 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;
namespace ICSharpCode.NRefactory.CSharp.Refactoring namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
public class InspectionIssue public class CodeIssue
{ {
public string Title { public string Desription {
get; get;
private set; private set;
} }
@ -44,17 +44,17 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
private set; private set;
} }
public System.Action Fix { public CodeAction Action {
get; get;
private set; 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; Desription = description;
this.Start = start; Start = start;
this.End = end; End = end;
this.Fix = fix; 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 @@
// //
// ConditionalToNullCoalescingInspector.cs // ConditionalToNullCoalescingInspector.cs
// //
// Author: // Author:
@ -34,7 +34,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// Checks for "a != null ? a : other"<expr> /// Checks for "a != null ? a : other"<expr>
/// Converts to: "a ?? other"<expr> /// Converts to: "a ?? other"<expr>
/// </summary> /// </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 { static readonly Pattern pattern = new Choice {
// a != null ? a : other // a != null ? a : other
@ -51,18 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
), ),
}; };
string title = "Convert to '??' expression"; public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -84,11 +77,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
if (m.Success) { if (m.Success) {
var a = m.Get<Expression>("a").Single(); var a = m.Get<Expression>("a").Single();
var other = m.Get<Expression>("other").Single(); var other = m.Get<Expression>("other").Single();
AddIssue(conditionalExpression, inspector.Title, delegate { AddIssue(conditionalExpression, ctx.TranslateString("Convert to '??' expression"), script => {
using (var script = ctx.StartScript ()) {
var expr = new BinaryOperatorExpression (a.Clone (), BinaryOperatorType.NullCoalescing, other.Clone ()); var expr = new BinaryOperatorExpression (a.Clone (), BinaryOperatorType.NullCoalescing, other.Clone ());
script.Replace (conditionalExpression, expr); script.Replace (conditionalExpression, expr);
}
}); });
} }
base.VisitConditionalExpression (conditionalExpression); 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
{ {
protected readonly BaseRefactoringContext ctx; protected readonly BaseRefactoringContext ctx;
public readonly List<InspectionIssue> FoundIssues = new List<InspectionIssue> (); public readonly List<CodeIssue> FoundIssues = new List<CodeIssue> ();
public GatherVisitorBase (BaseRefactoringContext ctx) public GatherVisitorBase (BaseRefactoringContext ctx)
{ {
@ -47,14 +47,14 @@ namespace ICSharpCode.NRefactory.CSharp
base.VisitChildren (node); 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 @@
//
// 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
/// This inspector just shows that there is a not implemented exception. It doesn't offer a fix. /// 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. /// Should only be shown in overview bar, no underlining.
/// </summary> /// </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 IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -66,8 +56,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public override void VisitThrowStatement(ThrowStatement throwStatement) public override void VisitThrowStatement(ThrowStatement throwStatement)
{ {
var result = ctx.Resolve(throwStatement.Expression); var result = ctx.Resolve(throwStatement.Expression);
if (result.Type.Equals (ctx.Compilation.FindType (typeof(System.NotImplementedException)))) if (result.Type.Equals(ctx.Compilation.FindType(typeof(System.NotImplementedException)))) {
AddIssue (throwStatement, inspector.Title); AddIssue(throwStatement, ctx.TranslateString("NotImplemented exception thrown"));
}
base.VisitThrowStatement(throwStatement); 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
/// <summary> /// <summary>
/// Finds redundant internal modifiers. /// Finds redundant internal modifiers.
/// </summary> /// </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 IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -68,10 +62,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
foreach (var token_ in typeDeclaration.ModifierTokens) { foreach (var token_ in typeDeclaration.ModifierTokens) {
var token = token_; var token = token_;
if (token.Modifier == Modifiers.Internal) { if (token.Modifier == Modifiers.Internal) {
AddIssue(token, inspector.Title, delegate { AddIssue(token, ctx.TranslateString ("Remove 'internal' modifier"), script => {
using (var script = ctx.StartScript ()) {
script.Remove(token); 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 @@
// //
// RedundantNamespaceUsageInspector.cs // RedundantNamespaceUsageInspector.cs
// //
// Author: // Author:
@ -36,20 +36,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary> /// <summary>
/// Finds redundant namespace usages. /// Finds redundant namespace usages.
/// </summary> /// </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 IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -82,11 +76,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
var lookupName = state.LookupSimpleNameOrTypeName(memberReferenceExpression.MemberName, new List<IType> (), SimpleNameLookupMode.Expression); var lookupName = state.LookupSimpleNameOrTypeName(memberReferenceExpression.MemberName, new List<IType> (), SimpleNameLookupMode.Expression);
if (lookupName is TypeResolveResult && !lookupName.IsError && wholeResult.Type.Equals(lookupName.Type)) { if (lookupName is TypeResolveResult && !lookupName.IsError && wholeResult.Type.Equals(lookupName.Type)) {
AddIssue(memberReferenceExpression.StartLocation, memberReferenceExpression.MemberNameToken.StartLocation, inspector.Title, delegate { AddIssue(memberReferenceExpression.StartLocation, memberReferenceExpression.MemberNameToken.StartLocation, ctx.TranslateString("Remove redundant namespace usage"), script => {
using (var script = ctx.StartScript ()) {
script.Replace(memberReferenceExpression, RefactoringAstHelper.RemoveTarget(memberReferenceExpression)); 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 @@
// //
// RedundantPrivateInspector.cs // RedundantPrivateInspector.cs
// //
// Author: // Author:
@ -34,20 +34,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary> /// <summary>
/// Finds redundant internal modifiers. /// Finds redundant internal modifiers.
/// </summary> /// </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 IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -68,10 +62,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
foreach (var token_ in node.ModifierTokens) { foreach (var token_ in node.ModifierTokens) {
var token = token_; var token = token_;
if (token.Modifier == Modifiers.Private) { if (token.Modifier == Modifiers.Private) {
AddIssue(token, inspector.Title, delegate { AddIssue(token, ctx.TranslateString("Remove redundant 'private' modifier"), script => {
using (var script = ctx.StartScript ()) {
script.Remove(token); 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 @@
// //
// RedundantThisInspector.cs // RedundantThisInspector.cs
// //
// Author: // Author:
@ -38,20 +38,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary> /// <summary>
/// Finds redundant namespace usages. /// Finds redundant namespace usages.
/// </summary> /// </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 IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -106,11 +100,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
if (isRedundant) { if (isRedundant) {
AddIssue(thisReferenceExpression.StartLocation, memberReference.MemberNameToken.StartLocation, inspector.Title, delegate { AddIssue(thisReferenceExpression.StartLocation, memberReference.MemberNameToken.StartLocation, ctx.TranslateString("Remove redundant 'this.'"), script => {
using (var script = ctx.StartScript ()) {
script.Replace(memberReference, RefactoringAstHelper.RemoveTarget(memberReference)); script.Replace(memberReference, RefactoringAstHelper.RemoveTarget(memberReference));
} }
}
); );
} }
} }

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

@ -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 @@
// //
// StringIsNullOrEmptyInspector.cs // StringIsNullOrEmptyInspector.cs
// //
// Author: // Author:
@ -34,7 +34,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// Checks for str == null && str == "" /// Checks for str == null && str == ""
/// Converts to: string.IsNullOrEmpty (str) /// Converts to: string.IsNullOrEmpty (str)
/// </summary> /// </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 { static readonly Pattern pattern = new Choice {
// str == null || str == "" // str == null || str == ""
@ -66,18 +70,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
), ),
}; };
string title = "Use string.IsNullOrEmpty"; public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -104,13 +97,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
if (m.Success) { if (m.Success) {
var str = m.Get<Expression>("str").Single(); var str = m.Get<Expression>("str").Single();
AddIssue(binaryOperatorExpression, inspector.Title, delegate { AddIssue(binaryOperatorExpression, ctx.TranslateString("Use string.IsNullOrEmpty"), script => {
using (var script = ctx.StartScript ()) {
Expression expr = new PrimitiveType ("string").Invoke("IsNullOrEmpty", str.Clone()); Expression expr = new PrimitiveType ("string").Invoke("IsNullOrEmpty", str.Clone());
if (isNegated) if (isNegated)
expr = new UnaryOperatorExpression (UnaryOperatorType.Not, expr); expr = new UnaryOperatorExpression (UnaryOperatorType.Not, expr);
script.Replace(binaryOperatorExpression, expr); script.Replace(binaryOperatorExpression, expr);
}
}); });
return; 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 @@
// //
// UseVarKeywordInspector.cs // UseVarKeywordInspector.cs
// //
// Author: // Author:
@ -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 /// Checks for places where the 'var' keyword can be used. Note that the action is actually done with a context
/// action. /// action.
/// </summary> /// </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 IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
public string Title {
get {
return title;
}
set {
title = value;
}
}
public IEnumerable<InspectionIssue> Run (BaseRefactoringContext context)
{ {
var visitor = new GatherVisitor (context, this); var visitor = new GatherVisitor (context, this);
context.RootNode.AcceptVisitor (visitor); context.RootNode.AcceptVisitor (visitor);
@ -106,7 +99,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
void AddIssue(VariableDeclarationStatement variableDeclarationStatement) 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
// THE SOFTWARE. // THE SOFTWARE.
using System; using System;
using System.Threading; using System.Threading;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Refactoring namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
public interface IContextAction public interface ICodeActionProvider
{ {
bool IsValid (RefactoringContext context); IEnumerable<CodeAction> GetActions (RefactoringContext context);
void Run (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;
namespace ICSharpCode.NRefactory.CSharp.Refactoring 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
//
// 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
if (method.TypeParameters.Count != typeArguments.Count) if (method.TypeParameters.Count != typeArguments.Count)
continue; continue;
SpecializedMethod sm = new SpecializedMethod(method, new TypeParameterSubstitution(null, typeArguments)); 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); outputGroup.Add(sm);
} else { } else {
if (IsEligibleExtensionMethod(targetType, method, true, out inferredTypes)) { if (IsEligibleExtensionMethod(compilation, conversions, targetType, method, true, out inferredTypes)) {
if (substituteInferredTypes && inferredTypes != null) { if (substituteInferredTypes && inferredTypes != null) {
outputGroup.Add(new SpecializedMethod(method, new TypeParameterSubstitution(null, inferredTypes))); outputGroup.Add(new SpecializedMethod(method, new TypeParameterSubstitution(null, inferredTypes)));
} else { } else {
@ -1748,12 +1748,32 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return extensionMethodGroups; 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; outInferredTypes = null;
if (targetType == null) if (targetType == null)
@ -2133,7 +2153,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (t != null) { if (t != null) {
foreach (IType baseType in t.DirectBaseTypes) { foreach (IType baseType in t.DirectBaseTypes) {
if (baseType.Kind != TypeKind.Unknown && baseType.Kind != TypeKind.Interface) { 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
var outputGroup = new List<IMethod>(); var outputGroup = new List<IMethod>();
foreach (var method in methodGroup) { foreach (var method in methodGroup) {
IType[] inferredTypes; IType[] inferredTypes;
if (CSharpResolver.IsEligibleExtensionMethod( if (CSharpResolver.IsEligibleExtensionMethod(this.TargetType, method, true, out inferredTypes)) {
method.Compilation, CSharpConversions.Get(method.Compilation),
this.TargetType, method, true, out inferredTypes))
{
if (substituteInferredTypes && inferredTypes != null) { if (substituteInferredTypes && inferredTypes != null) {
outputGroup.Add(new SpecializedMethod(method, new TypeParameterSubstitution(null, inferredTypes))); outputGroup.Add(new SpecializedMethod(method, new TypeParameterSubstitution(null, inferredTypes)));
} else { } else {

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

@ -28,28 +28,31 @@ using System;
using NUnit.Framework; using NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring; using ICSharpCode.NRefactory.CSharp.Refactoring;
using System.Threading; using System.Threading;
using System.Linq;
namespace ICSharpCode.NRefactory.CSharp.ContextActions namespace ICSharpCode.NRefactory.CSharp.ContextActions
{ {
public abstract class ContextActionTestBase 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); var context = TestRefactoringContext.Create (input);
bool isValid = action.IsValid (context); bool isValid = action.GetActions (context).Any ();
if (!isValid) if (!isValid)
Console.WriteLine ("invalid node is:" + context.GetNode ()); Console.WriteLine ("invalid node is:" + context.GetNode ());
Assert.IsTrue (isValid, action.GetType () + " is invalid."); Assert.IsTrue (isValid, action.GetType () + " is invalid.");
using (var script = context.StartScript ()) {
action.Run (context); action.GetActions (context).First ().Run (script);
}
return context.doc.Text; 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); var context = TestRefactoringContext.Create (input);
bool isValid = action.IsValid (context); bool isValid = action.GetActions (context).Any ();
if (!isValid) if (!isValid)
Console.WriteLine ("invalid node is:" + context.GetNode ()); Console.WriteLine ("invalid node is:" + context.GetNode ());
Assert.IsTrue (!isValid, action.GetType () + " shouldn't be valid there."); 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
[TestFixture] [TestFixture]
public class GenerateGetterTests : ContextActionTestBase public class GenerateGetterTests : ContextActionTestBase
{ {
[Ignore("Implement missing feature")]
[Test()] [Test()]
public void Test () public void Test ()
{ {

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

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

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

@ -39,7 +39,7 @@ using System.Threading;
namespace ICSharpCode.NRefactory.CSharp.ContextActions namespace ICSharpCode.NRefactory.CSharp.ContextActions
{ {
class TestRefactoringContext : RefactoringContext public class TestRefactoringContext : RefactoringContext
{ {
internal readonly IDocument doc; internal readonly IDocument doc;
readonly TextLocation location; readonly TextLocation location;
@ -70,6 +70,14 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions
{ {
this.eolMarker = context.EolMarker; 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 #region Text stuff
@ -112,7 +120,11 @@ namespace ICSharpCode.NRefactory.CSharp.ContextActions
return doc.GetLineByOffset (offset); return doc.GetLineByOffset (offset);
} }
#endregion #endregion
public string Text {
get {
return doc.Text;
}
}
public static TestRefactoringContext Create(string content) public static TestRefactoringContext Create(string content)
{ {
int idx = content.IndexOf ("$"); int idx = content.IndexOf ("$");

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

@ -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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 @@
//
// 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 {
Assert.That(rr.TargetResult, Is.InstanceOf<TypeResolveResult>()); 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 @@
// //
// TestStatementIndentation.cs // TestStatementIndentation.cs
// //
// Author: // Author:
@ -948,6 +948,7 @@ do {
} }
[Test()] [Test()]
[Ignore("Crashes due to overlapping changes")]
public void TestForEachBraceForcementRemove () public void TestForEachBraceForcementRemove ()
{ {
CSharpFormattingOptions policy = new CSharpFormattingOptions (); CSharpFormattingOptions policy = new CSharpFormattingOptions ();
@ -1104,6 +1105,7 @@ do {
} }
[Test()] [Test()]
[Ignore("Crashes due to overlapping changes")]
public void TestIfForcementRemove () public void TestIfForcementRemove ()
{ {
CSharpFormattingOptions policy = new CSharpFormattingOptions (); CSharpFormattingOptions policy = new CSharpFormattingOptions ();
@ -1412,6 +1414,7 @@ if (b) {
} }
[Test()] [Test()]
[Ignore("Crashes due to overlapping changes")]
public void TestWhileForcementRemove () public void TestWhileForcementRemove ()
{ {
CSharpFormattingOptions policy = new CSharpFormattingOptions (); CSharpFormattingOptions policy = new CSharpFormattingOptions ();

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

@ -71,9 +71,8 @@
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" /> <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> <HintPath>..\..\Mono.Cecil\Test\libs\nunit-2.5.10\nunit.framework.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -238,6 +237,16 @@
<Compile Include="CSharp\ContextAction\AddAnotherAccessorTests.cs" /> <Compile Include="CSharp\ContextAction\AddAnotherAccessorTests.cs" />
<Compile Include="CSharp\ContextAction\RemoveRegionTests.cs" /> <Compile Include="CSharp\ContextAction\RemoveRegionTests.cs" />
<Compile Include="CSharp\ContextAction\GeneratePropertyTests.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>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Mono.Cecil\Mono.Cecil.csproj"> <ProjectReference Include="..\..\Mono.Cecil\Mono.Cecil.csproj">
@ -264,6 +273,7 @@
<Folder Include="CSharp\" /> <Folder Include="CSharp\" />
<Folder Include="CSharp\Parser\" /> <Folder Include="CSharp\Parser\" />
<Folder Include="CSharp\ContextAction\" /> <Folder Include="CSharp\ContextAction\" />
<Folder Include="CSharp\Inspector\" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ProjectExtensions> <ProjectExtensions>

Loading…
Cancel
Save