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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions ICSharpCode.CodeConverter/CSharp/NodesVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public override CSharpSyntaxNode VisitCompilationUnit(VBSyntax.CompilationUnitSy
foreach (var importClause in importsClauses.OfType<VBSyntax.SimpleImportsClauseSyntax>()) {
importedNamespaces[importClause.Name.ToString()] = importClause.Alias != null ? importClause.Alias.Identifier.ToString() : "";
}

var attributes = SyntaxFactory.List(node.Attributes.SelectMany(a => a.AttributeLists).SelectMany(ConvertAttribute));
var members = SyntaxFactory.List(node.Members.Select(m => (MemberDeclarationSyntax)m.Accept(TriviaConvertingVisitor)));

Expand Down Expand Up @@ -161,7 +161,6 @@ IEnumerable<MemberDeclarationSyntax> ConvertMembers(SyntaxList<VBSyntax.Statemen
yield return additionalStatement;
}
}

}
}

Expand Down Expand Up @@ -664,7 +663,7 @@ public override CSharpSyntaxNode VisitParameter(VBSyntax.ParameterSyntax node)
if (rankSpecifiers.Any() && returnType != null) {
returnType = SyntaxFactory.ArrayType(returnType, rankSpecifiers);
}

if (returnType != null && !SyntaxTokenExtensions.IsKind(node.Identifier.Nullable, SyntaxKind.None)) {
var arrayType = returnType as ArrayTypeSyntax;
if (arrayType == null) {
Expand Down
15 changes: 15 additions & 0 deletions ICSharpCode.CodeConverter/CSharp/TriviaConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace ICSharpCode.CodeConverter.CSharp
{
public class TriviaConverter
{
public const string SelectedNodeAnnotationKind = "CodeConverter.SelectedNode";
private static readonly string TrailingTriviaConversionKind = $"{nameof(TriviaConverter)}.TrailingTriviaConversion.Id";

/// <summary>
Expand Down Expand Up @@ -37,6 +38,8 @@ public T PortConvertedTrivia<T>(SyntaxNode sourceNode, T destination) where T :
destination = destination.ReplaceToken(lastDestToken, WithDelegateToParentAnnotation(sourceNode, lastDestToken));
}

destination = WithAnnotations(sourceNode, destination);

var containingSubModuleBlock = sourceNode.FirstAncestorOrSelf<StatementSyntax>(IsFirstLineOfBlockConstruct);
var hasVisitedContainingBlock = containingSubModuleBlock == null;
var firstLineOfBlockConstruct = sourceNode.ChildNodes().OfType<StatementSyntax>().FirstOrDefault(IsFirstLineOfBlockConstruct);
Expand All @@ -54,6 +57,18 @@ public T PortConvertedTrivia<T>(SyntaxNode sourceNode, T destination) where T :
return WithTrailingTriviaConversions(destination, sourceNode.Parent?.GetLastToken(), hasVisitedContainingBlock);
}

private static T WithAnnotations<T>(SyntaxNode sourceNode, T destination) where T : SyntaxNode
{
destination = sourceNode.CopyAnnotationsTo(destination);

var sourceChildAnnotations = new HashSet<SyntaxAnnotation>(sourceNode.ChildNodes()
.SelectMany(n => n.GetAnnotations(SelectedNodeAnnotationKind)));
foreach (var annotation in destination.ChildNodes().SelectMany(n => n.GetAnnotations(SelectedNodeAnnotationKind))) {
sourceChildAnnotations.Remove(annotation);
}
return destination.WithAdditionalAnnotations(sourceChildAnnotations);
}

private SyntaxToken MoveChildTrailingEndOfLinesToToken<T>(T destination, SyntaxToken beforeOpenBraceToken)
where T : SyntaxNode
{
Expand Down
42 changes: 35 additions & 7 deletions ICSharpCode.CodeConverter/CSharp/VisualBasicConverter.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.CodeConverter.Util;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using ArrayRankSpecifierSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.ArrayRankSpecifierSyntax;
using ArrayTypeSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.ArrayTypeSyntax;
Expand Down Expand Up @@ -37,11 +36,35 @@ enum TokenContext
MemberInInterface
}

public static CSharpSyntaxNode ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree)
public static async Task<ConversionResult> ConvertSingle(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree, TextSpan selected)
{
return ConvertMultiple(compilation, new[] {syntaxTree}).Values.Single();
var root = await syntaxTree.GetRootAsync();
if (selected.Length > 0) {
var annotatedSyntaxTree = GetSyntaxTreeWithAnnotatedSelection(selected, root);
compilation = compilation.ReplaceSyntaxTree(syntaxTree, annotatedSyntaxTree);
syntaxTree = (VBasic.VisualBasicSyntaxTree) annotatedSyntaxTree;
}

try {
var cSharpSyntaxNode = ConvertSingleUnhandled(compilation, syntaxTree);
var annotatedNode = cSharpSyntaxNode.GetAnnotatedNodes(TriviaConverter.SelectedNodeAnnotationKind).SingleOrDefault();
if (annotatedNode != null) cSharpSyntaxNode = (CSharpSyntaxNode) annotatedNode;
var formattedNode = Formatter.Format(cSharpSyntaxNode, new AdhocWorkspace());
return new ConversionResult(formattedNode.ToFullString());
} catch (Exception ex) {
return new ConversionResult(ex);
}
}

private static SyntaxTree GetSyntaxTreeWithAnnotatedSelection(TextSpan selected, SyntaxNode root)
{
var selectedNode = root.FindNode(selected);
var annotatatedNode = selectedNode.WithAdditionalAnnotations(new SyntaxAnnotation(TriviaConverter.SelectedNodeAnnotationKind));
var syntaxTree = root.ReplaceNode(selectedNode, annotatatedNode).SyntaxTree;
return syntaxTree;
}


public static Dictionary<string, CSharpSyntaxNode> ConvertMultiple(VBasic.VisualBasicCompilation compilation, IEnumerable<VBasic.VisualBasicSyntaxTree> syntaxTrees)
{
var cSharpFirstPass = syntaxTrees.ToDictionary(tree => tree.FilePath ?? "unknown",
Expand All @@ -50,6 +73,11 @@ public static Dictionary<string, CSharpSyntaxNode> ConvertMultiple(VBasic.Visual
return cSharpFirstPass.ToDictionary(cs => cs.Key, cs => new CompilationErrorFixer(cSharpCompilation, cs.Value).Fix());
}

private static CSharpSyntaxNode ConvertSingleUnhandled(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree syntaxTree)
{
return ConvertMultiple(compilation, new[] {syntaxTree}).Values.Single();
}

private static CSharpSyntaxTree ConvertCompilationTree(VBasic.VisualBasicCompilation compilation, VBasic.VisualBasicSyntaxTree tree)
{
var visualBasicSyntaxVisitor = new NodesVisitor(compilation.GetSemanticModel(tree, true));
Expand All @@ -65,15 +93,15 @@ public static ConversionResult ConvertText(string text, IReadOnlyCollection<Meta
throw new ArgumentNullException(nameof(references));

try {
var cSharpSyntaxNode = ConvertText(references, text);
var cSharpSyntaxNode = ConvertTextUnhandled(references, text);
var formattedNode = Formatter.Format(cSharpSyntaxNode, new AdhocWorkspace());
return new ConversionResult(formattedNode.ToFullString());
} catch (Exception ex) {
return new ConversionResult(ex);
}
}

private static SyntaxNode ConvertText(IReadOnlyCollection<MetadataReference> references, string text)
private static SyntaxNode ConvertTextUnhandled(IReadOnlyCollection<MetadataReference> references, string text)
{
try
{
Expand All @@ -94,7 +122,7 @@ private static SyntaxNode ConvertFullTree(IReadOnlyCollection<MetadataReference>
{
var tree = CreateTree(fullTreeText);
var compilation = CreateCompilationFromTree(tree, references);
return ConvertSingle(compilation, tree);
return ConvertSingleUnhandled(compilation, tree);
}

private static VBasic.VisualBasicSyntaxTree CreateTree(string text)
Expand Down
2 changes: 1 addition & 1 deletion ICSharpCode.CodeConverter/Util/SyntaxNodeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ public static async Task<TRoot> ReplaceSyntaxAsync<TRoot>(
});

// compute replacements for all nodes that will go in the same batch
// only spans that do not overlap go in the same batch.
// only spans that do not overlap go in the same batch.
TextSpan previous = default(TextSpan);
foreach (var span in spans) {
// only add to replacement map if we don't intersect with the previous node. This taken with the sort order
Expand Down
74 changes: 46 additions & 28 deletions Vsix/CodeConversion.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
using Microsoft.VisualStudio.Shell;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using ICSharpCode.CodeConverter;
using ICSharpCode.CodeConverter.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using System;
using System.Windows;
using ICSharpCode.CodeConverter;
using Task = System.Threading.Tasks.Task;

namespace RefactoringEssentials.VsExtension
namespace CodeConverter.VsExtension
{
static class CodeConversion
class CodeConversion
{
private readonly IServiceProvider serviceProvider;
private readonly VisualStudioWorkspace visualStudioWorkspace;
public static readonly string CSToVBConversionTitle = "Convert C# to VB:";
public static readonly string VBToCSConversionTitle = "Convert VB to C#:";

public static void PerformCSToVBConversion(IServiceProvider serviceProvider, string inputCode)
public CodeConversion(IServiceProvider serviceProvider, VisualStudioWorkspace visualStudioWorkspace)
{
this.serviceProvider = serviceProvider;
this.visualStudioWorkspace = visualStudioWorkspace;
}

public void PerformCSToVBConversion(string inputCode)
{
string convertedText = null;
try {
Expand Down Expand Up @@ -46,25 +62,25 @@ public static void PerformCSToVBConversion(IServiceProvider serviceProvider, str
// OLEMSGBUTTON.OLEMSGBUTTON_OK,
// OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

WriteStatusBarText(serviceProvider, "Copied converted VB code to clipboard.");
WriteStatusBarText("Copied converted VB code to clipboard.");

Clipboard.SetText(convertedText);
}

static ConversionResult TryConvertingCSToVBCode(string inputCode)
ConversionResult TryConvertingCSToVBCode(string inputCode)
{
var codeWithOptions = new CodeWithOptions(inputCode)
.SetFromLanguage("C#")
.SetToLanguage("Visual Basic")
.WithDefaultReferences();
return CodeConverter.Convert(codeWithOptions);
return ICSharpCode.CodeConverter.CodeConverter.Convert(codeWithOptions);
}

public static void PerformVBToCSConversion(IServiceProvider serviceProvider, string inputCode)
public async Task PerformVBToCSConversion(string documentFilePath, Span selected)
{
string convertedText = null;
try {
var result = TryConvertingVBToCSCode(inputCode);
var result = await TryConvertingVBToCSCode(documentFilePath, selected);
if (!result.Success) {
var newLines = Environment.NewLine + Environment.NewLine;
VsShellUtilities.ShowMessageBox(
Expand Down Expand Up @@ -93,21 +109,23 @@ public static void PerformVBToCSConversion(IServiceProvider serviceProvider, str
// OLEMSGBUTTON.OLEMSGBUTTON_OK,
// OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

WriteStatusBarText(serviceProvider, "Copied converted C# code to clipboard.");
WriteStatusBarText("Copied converted C# code to clipboard.");

Clipboard.SetText(convertedText);
}

static ConversionResult TryConvertingVBToCSCode(string inputCode)
{
var codeWithOptions = new CodeWithOptions(inputCode)
.SetFromLanguage("Visual Basic", 14)
.SetToLanguage("C#", 6)
.WithDefaultReferences();
return CodeConverter.Convert(codeWithOptions);
}
async Task<ConversionResult> TryConvertingVBToCSCode(string documentPath, Span selected)
{
//TODO Figure out when there are multiple document ids for a single file path
var documentId = visualStudioWorkspace.CurrentSolution.GetDocumentIdsWithFilePath(documentPath).Single();
var document = visualStudioWorkspace.CurrentSolution.GetDocument(documentId);
var compilation = await document.Project.GetCompilationAsync();
var documentSyntaxTree = await document.GetSyntaxTreeAsync();

static void WriteStatusBarText(IServiceProvider serviceProvider, string text)
var selectedTextSpan = new TextSpan(selected.Start, selected.Length);
return await VisualBasicConverter.ConvertSingle((VisualBasicCompilation)compilation, (VisualBasicSyntaxTree)documentSyntaxTree, selectedTextSpan);
}
void WriteStatusBarText(string text)
{
IVsStatusbar statusBar = (IVsStatusbar)serviceProvider.GetService(typeof(SVsStatusbar));
if (statusBar == null)
Expand All @@ -124,7 +142,7 @@ static void WriteStatusBarText(IServiceProvider serviceProvider, string text)
statusBar.FreezeOutput(1);
}

static IWpfTextViewHost GetCurrentCSViewHost(IServiceProvider serviceProvider)
IWpfTextViewHost GetCurrentCSViewHost()
{
IWpfTextViewHost viewHost = VisualStudioInteraction.GetCurrentViewHost(serviceProvider);
if (viewHost == null)
Expand All @@ -142,16 +160,16 @@ public static bool IsCSFileName(string fileName)
return fileName.EndsWith(".cs", StringComparison.OrdinalIgnoreCase);
}

public static ITextSelection GetCSSelectionInCurrentView(IServiceProvider serviceProvider)
public ITextSelection GetCSSelectionInCurrentView()
{
IWpfTextViewHost viewHost = GetCurrentCSViewHost(serviceProvider);
IWpfTextViewHost viewHost = GetCurrentCSViewHost();
if (viewHost == null)
return null;

return viewHost.TextView.Selection;
}

static IWpfTextViewHost GetCurrentVBViewHost(IServiceProvider serviceProvider)
public IWpfTextViewHost GetCurrentVBViewHost()
{
IWpfTextViewHost viewHost = VisualStudioInteraction.GetCurrentViewHost(serviceProvider);
if (viewHost == null)
Expand All @@ -169,9 +187,9 @@ public static bool IsVBFileName(string fileName)
return fileName.EndsWith(".vb", StringComparison.OrdinalIgnoreCase);
}

public static ITextSelection GetVBSelectionInCurrentView(IServiceProvider serviceProvider)
public ITextSelection GetVBSelectionInCurrentView()
{
IWpfTextViewHost viewHost = GetCurrentVBViewHost(serviceProvider);
IWpfTextViewHost viewHost = GetCurrentVBViewHost();
if (viewHost == null)
return null;

Expand Down
25 changes: 12 additions & 13 deletions Vsix/ConvertCSToVBCommand.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.Shell;
using System.IO;
using Microsoft.VisualStudio.Shell;

namespace RefactoringEssentials.VsExtension
namespace CodeConverter.VsExtension
{
/// <summary>
/// Command handler
Expand Down Expand Up @@ -32,6 +32,8 @@ public static ConvertCSToVBCommand Instance {
private set;
}

private readonly CodeConversion codeConversion;

/// <summary>
/// Gets the service provider from the owner package.
/// </summary>
Expand All @@ -57,11 +59,8 @@ public static void Initialize(REConverterPackage package)
/// <param name="package">Owner package, not null.</param>
ConvertCSToVBCommand(REConverterPackage package)
{
if (package == null) {
throw new ArgumentNullException(nameof(package));
}

this.package = package;
this.package = package ?? throw new ArgumentNullException(nameof(package));
codeConversion = new CodeConversion(package, package.VsWorkspace);

OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
if (commandService != null) {
Expand Down Expand Up @@ -90,7 +89,7 @@ void CodeEditorMenuItem_BeforeQueryStatus(object sender, EventArgs e)
var menuItem = sender as OleMenuCommand;
if (menuItem != null) {

menuItem.Visible = !CodeConversion.GetCSSelectionInCurrentView(ServiceProvider)?.StreamSelectionSpan.IsEmpty ?? false;
menuItem.Visible = !codeConversion.GetCSSelectionInCurrentView()?.StreamSelectionSpan.IsEmpty ?? false;
}
}

Expand All @@ -101,7 +100,7 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e)
menuItem.Visible = false;
menuItem.Enabled = false;

string itemPath = VisualStudioInteraction.GetSingleSelectedItemPath();
string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath;
var fileInfo = new FileInfo(itemPath);
if (!CodeConversion.IsCSFileName(fileInfo.Name))
return;
Expand All @@ -113,21 +112,21 @@ void ProjectItemMenuItem_BeforeQueryStatus(object sender, EventArgs e)

void CodeEditorMenuItemCallback(object sender, EventArgs e)
{
string selectedText = CodeConversion.GetCSSelectionInCurrentView(ServiceProvider)?.StreamSelectionSpan.GetText();
CodeConversion.PerformCSToVBConversion(ServiceProvider, selectedText);
string selectedText = codeConversion.GetCSSelectionInCurrentView()?.StreamSelectionSpan.GetText();
codeConversion.PerformCSToVBConversion(selectedText);
}

async void ProjectItemMenuItemCallback(object sender, EventArgs e)
{
string itemPath = VisualStudioInteraction.GetSingleSelectedItemPath();
string itemPath = VisualStudioInteraction.GetSingleSelectedItemOrDefault()?.ItemPath;
var fileInfo = new FileInfo(itemPath);
if (!CodeConversion.IsCSFileName(fileInfo.Name))
return;

try {
using (StreamReader reader = new StreamReader(itemPath)) {
string csCode = await reader.ReadToEndAsync();
CodeConversion.PerformCSToVBConversion(ServiceProvider, csCode);
codeConversion.PerformCSToVBConversion(csCode);
}
} catch (Exception ex) {
VisualStudioInteraction.ShowException(ServiceProvider, CodeConversion.CSToVBConversionTitle, ex);
Expand Down
Loading