diff --git a/CodeConverter/CSharp/CommonConversions.cs b/CodeConverter/CSharp/CommonConversions.cs index 3f37f1985..b42a2bf52 100644 --- a/CodeConverter/CSharp/CommonConversions.cs +++ b/CodeConverter/CSharp/CommonConversions.cs @@ -2,6 +2,7 @@ using System.Linq.Expressions; using System.Runtime.CompilerServices; using ICSharpCode.CodeConverter.Util.FromRoslyn; +using ICSharpCode.CodeConverter.CSharp.OnError; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editing; @@ -40,8 +41,9 @@ internal class CommonConversions public CommonConversions(Document document, SemanticModel semanticModel, TypeConversionAnalyzer typeConversionAnalyzer, SyntaxGenerator csSyntaxGenerator, Compilation compilation, - CSharpCompilation csCompilation, ITypeContext typeContext, VisualBasicEqualityComparison visualBasicEqualityComparison) + CSharpCompilation csCompilation, ITypeContext typeContext, VisualBasicEqualityComparison visualBasicEqualityComparison, ErrUsage errUsage) { + ErrUsage = errUsage; TypeConversionAnalyzer = typeConversionAnalyzer; Document = document; SemanticModel = semanticModel; @@ -55,6 +57,7 @@ public CommonConversions(Document document, SemanticModel semanticModel, } public KnownNamedTypes KnownTypes { get; } + public ErrUsage ErrUsage { get; } public record VariablePair(CSSyntax.VariableDeclaratorSyntax CsVar, VBSyntax.ModifiedIdentifierSyntax VbVar); public record VariablesDeclaration(CSSyntax.VariableDeclarationSyntax Decl, ITypeSymbol Type, List Variables); diff --git a/CodeConverter/CSharp/DeclarationNodeVisitor.cs b/CodeConverter/CSharp/DeclarationNodeVisitor.cs index 74a905a13..2392c8bd8 100644 --- a/CodeConverter/CSharp/DeclarationNodeVisitor.cs +++ b/CodeConverter/CSharp/DeclarationNodeVisitor.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; @@ -6,6 +6,7 @@ using Microsoft.CodeAnalysis.Editing; using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; using ICSharpCode.CodeConverter.Util.FromRoslyn; +using ICSharpCode.CodeConverter.CSharp.OnError; using ISymbolExtensions = ICSharpCode.CodeConverter.Util.ISymbolExtensions; namespace ICSharpCode.CodeConverter.CSharp; @@ -42,7 +43,7 @@ internal class DeclarationNodeVisitor : VBasic.VisualBasicSyntaxVisitor _typeContext.PerScopeState; public DeclarationNodeVisitor(Document document, Compilation compilation, SemanticModel semanticModel, - CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors) + CSharpCompilation csCompilation, SyntaxGenerator csSyntaxGenerator, ILookup typeToInheritors, ErrUsage errUsage) { _vbCompilation = compilation; _csSyntaxGenerator = csSyntaxGenerator; @@ -54,7 +55,7 @@ public DeclarationNodeVisitor(Document document, Compilation compilation, Semant var expressionEvaluator = new ExpressionEvaluator(semanticModel, _visualBasicEqualityComparison); var nullableExpressionsConverter = new VisualBasicNullableExpressionsConverter(_semanticModel); var typeConversionAnalyzer = new TypeConversionAnalyzer(semanticModel, csCompilation, _extraUsingDirectives, _csSyntaxGenerator, expressionEvaluator, nullableExpressionsConverter); - CommonConversions = new CommonConversions(document, semanticModel, typeConversionAnalyzer, csSyntaxGenerator, compilation, csCompilation, _typeContext, _visualBasicEqualityComparison); + CommonConversions = new CommonConversions(document, semanticModel, typeConversionAnalyzer, csSyntaxGenerator, compilation, csCompilation, _typeContext, _visualBasicEqualityComparison, errUsage); var expressionNodeVisitor = new ExpressionNodeVisitor(semanticModel, _visualBasicEqualityComparison, _typeContext, CommonConversions, _extraUsingDirectives, _xmlImportContext, nullableExpressionsConverter); _accessorDeclarationNodeConverter = new AccessorDeclarationNodeConverter(semanticModel, CommonConversions, TriviaConvertingDeclarationVisitor, _additionalDeclarations, expressionNodeVisitor.ConvertMethodBodyStatementsAsync); _triviaConvertingExpressionVisitor = CommonConversions.TriviaConvertingExpressionVisitor; diff --git a/CodeConverter/CSharp/LambdaConverter.cs b/CodeConverter/CSharp/LambdaConverter.cs index 12f520017..2c720f4a5 100644 --- a/CodeConverter/CSharp/LambdaConverter.cs +++ b/CodeConverter/CSharp/LambdaConverter.cs @@ -1,6 +1,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; +using ICSharpCode.CodeConverter.CSharp.OnError; namespace ICSharpCode.CodeConverter.CSharp; @@ -200,47 +201,8 @@ public async Task> ConvertMethodBodyStateme { var innerMethodBodyVisitor = await MethodBodyExecutableStatementVisitor.CreateAsync(node, _semanticModel, CommonConversions.TriviaConvertingExpressionVisitor, CommonConversions, CommonConversions.VisualBasicEqualityComparison, _withBlockLhs, _extraUsingDirectives, _typeContext, isIterator, csReturnVariable); - return await GetWithConvertedGotosOrNull(statements) ?? await ConvertStatements(statements); - - async Task> ConvertStatements(IEnumerable readOnlyCollection) - { - return (await readOnlyCollection.SelectManyAsync(async s => (IEnumerable)await s.Accept(innerMethodBodyVisitor.CommentConvertingVisitor))).ToList(); - } - - async Task> GetWithConvertedGotosOrNull(IReadOnlyCollection statements) - { - var onlyIdentifierLabel = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.LabelStatement)); - var onlyOnErrorGotoStatement = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.OnErrorGoToLabelStatement)); - - // See https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/on-error-statement - if (onlyIdentifierLabel != null && onlyOnErrorGotoStatement != null) { - var statementsList = statements.ToList(); - var onlyIdentifierLabelIndex = statementsList.IndexOf(onlyIdentifierLabel); - var onlyOnErrorGotoStatementIndex = statementsList.IndexOf(onlyOnErrorGotoStatement); - - // Even this very simple case can generate compile errors if the error handling uses statements declared in the scope of the try block - // For now, the user will have to fix these manually, in future it'd be possible to hoist any used declarations out of the try block - if (onlyOnErrorGotoStatementIndex < onlyIdentifierLabelIndex) { - var beforeStatements = await ConvertStatements(statements.Take(onlyOnErrorGotoStatementIndex)); - var tryBlockStatements = await ConvertStatements(statements.Take(onlyIdentifierLabelIndex).Skip(onlyOnErrorGotoStatementIndex + 1)); - var tryBlock = SyntaxFactory.Block(tryBlockStatements); - var afterStatements = await ConvertStatements(statements.Skip(onlyIdentifierLabelIndex + 1)); - - var catchClauseSyntax = SyntaxFactory.CatchClause(); - - // Default to putting the statements after the catch block in case logic falls through, but if the last statement is a return, put them inside the catch block for neatness. - if (tryBlockStatements.LastOrDefault().IsKind(SyntaxKind.ReturnStatement)) { - catchClauseSyntax = catchClauseSyntax.WithBlock(SyntaxFactory.Block(afterStatements)); - afterStatements = new List(); - } - - var tryStatement = SyntaxFactory.TryStatement(SyntaxFactory.SingletonList(catchClauseSyntax)).WithBlock(tryBlock); - return beforeStatements.Append(tryStatement).Concat(afterStatements).ToList(); - } - } - - return null; - } + var onErrorContext = new OnErrorConversionContext(node, _semanticModel, CommonConversions, innerMethodBodyVisitor, _extraUsingDirectives); + return await OnErrorMethodBodyConverter.ConvertOrNullAsync(onErrorContext, statements) ?? await onErrorContext.ConvertAsync(statements); } /// diff --git a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs index 6e9720622..9e6de7b87 100644 --- a/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs +++ b/CodeConverter/CSharp/MethodBodyExecutableStatementVisitor.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis.Text; using ICSharpCode.CodeConverter.Util.FromRoslyn; using ICSharpCode.CodeConverter.VB; +using ICSharpCode.CodeConverter.CSharp.OnError; using ComparisonKind = ICSharpCode.CodeConverter.CSharp.VisualBasicEqualityComparison.ComparisonKind; namespace ICSharpCode.CodeConverter.CSharp; @@ -28,14 +29,29 @@ internal class MethodBodyExecutableStatementVisitor : VBasic.VisualBasicSyntaxVi private readonly HashSet _generatedNames = new(); private readonly HashSet _localsToInlineInLoop; private readonly PerScopeState _perScopeState; + private VBasic.VisualBasicSyntaxVisitor>> _statementVisitor; public bool IsIterator { get; set; } public IdentifierNameSyntax ReturnVariable { get; set; } public bool HasReturnVariable => ReturnVariable != null; - public VBasic.VisualBasicSyntaxVisitor>> CommentConvertingVisitor { get; } + /// How nested statements are converted: every statement is visited through this, whatever its depth. + public VBasic.VisualBasicSyntaxVisitor>> CommentConvertingVisitor { get; private set; } + + /// Set by the On Error conversion for the shape it emits. Until then, On Error and Resume statements can't be converted. + public IOnErrorStatementConverter OnErrorStatementConverter { get; set; } private CommonConversions CommonConversions { get; } + /// + /// Lets another class change the conversion of each statement at every nesting depth, without this visitor knowing why. + /// The decorator sits inside the comment conversion, so comments attach to whatever it returns for the statement. + /// + public void DecorateStatementVisitor(Func>>, VBasic.VisualBasicSyntaxVisitor>>> decorate) + { + _statementVisitor = decorate(_statementVisitor); + CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(_statementVisitor); + } + public static async Task CreateAsync(VisualBasicSyntaxNode node, SemanticModel semanticModel, CommentConvertingVisitorWrapper triviaConvertingExpressionVisitor, CommonConversions commonConversions, VisualBasicEqualityComparison visualBasicEqualityComparison, Stack withBlockLhs, HashSet extraUsingDirectives, @@ -64,8 +80,8 @@ private MethodBodyExecutableStatementVisitor(VisualBasicSyntaxNode methodNode, S _extraUsingDirectives = extraUsingDirectives; _handledEventsAnalysis = typeContext.HandledEventsAnalysis; _perScopeState = typeContext.PerScopeState; - var byRefParameterVisitor = new PerScopeStateVisitorDecorator(this, _perScopeState, semanticModel, _generatedNames); - CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(byRefParameterVisitor); + _statementVisitor = new PerScopeStateVisitorDecorator(this, _perScopeState, semanticModel, _generatedNames); + CommentConvertingVisitor = new CommentConvertingMethodBodyVisitor(_statementVisitor); _localsToInlineInLoop = localsToInlineInLoop; } @@ -75,6 +91,15 @@ public override async Task> DefaultVisit(SyntaxNode .WithNodeInformation(node); } + public override Task> VisitOnErrorGoToStatement(VBSyntax.OnErrorGoToStatementSyntax node) => + OnErrorStatementConverter is { } converter ? Task.FromResult(converter.ConvertOnError(node)) : DefaultVisit(node); + + public override Task> VisitOnErrorResumeNextStatement(VBSyntax.OnErrorResumeNextStatementSyntax node) => + OnErrorStatementConverter is { } converter ? Task.FromResult(converter.ConvertOnError(node)) : DefaultVisit(node); + + public override Task> VisitResumeStatement(VBSyntax.ResumeStatementSyntax node) => + OnErrorStatementConverter is { } converter ? Task.FromResult(converter.ConvertResume(node)) : DefaultVisit(node); + public override async Task> VisitStopOrEndStatement(VBSyntax.StopOrEndStatementSyntax node) { return SingleStatement(SyntaxFactory.ParseStatement(ConvertStopOrEndToCSharpStatementText(node))); @@ -148,6 +173,18 @@ public override async Task> VisitLocalDeclarationSta return SyntaxFactory.List(declarations); } + /// + /// Declares a local that was converted in a loop body before the outermost loop instead, as a VB local keeps its value from one iteration to the next. + /// Call it after the declaration has been converted, as the scope of the declaration itself has then been left. + /// + /// False when the declaration isn't in a loop, so the caller declares it where it is. + public bool TryHoistOutOfLoop(string name, TypeSyntax type) + { + if (!_perScopeState.IsWithinLoopBody()) return false; + _perScopeState.Hoist(new HoistedDefaultInitializedLoopVariable(name, SyntaxFactory.DefaultExpression(type), type, _perScopeState.IsWithinNestedLoopBody())); + return true; + } + private IEnumerable HoistVariablesBeforeLoopWhenNeeded(IEnumerable variablesDeclarations) { foreach (var variablesDecl in variablesDeclarations) { @@ -525,29 +562,37 @@ public override async Task> VisitExitStatement(VBSyn return SingleStatement(SyntaxFactory.ReturnStatement()); case VBasic.SyntaxKind.FunctionKeyword: case VBasic.SyntaxKind.PropertyKeyword when node.GetAncestor()?.IsKind(VBasic.SyntaxKind.GetAccessorBlock) == true: - VBasic.VisualBasicSyntaxNode typeContainer = node.GetAncestor() - ?? (VBasic.VisualBasicSyntaxNode)node.GetAncestor() - ?? node.GetAncestor(); - var enclosingMethodInfo = typeContainer switch { - VBSyntax.LambdaExpressionSyntax e => _semanticModel.GetSymbolInfo(e).Symbol, - VBSyntax.MethodBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.SubOrFunctionStatement), - VBSyntax.AccessorBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.AccessorStatement), - _ => null - } as IMethodSymbol; - - if (IsIterator) return SingleStatement(SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement)); - - if (!enclosingMethodInfo.ReturnsVoidOrAsyncTask()) { - ExpressionSyntax expr = HasReturnVariable ? ReturnVariable : SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression); - return SingleStatement(SyntaxFactory.ReturnStatement(expr)); - } - - return SingleStatement(SyntaxFactory.ReturnStatement()); + return SingleStatement(CreateMethodExitStatement(node)); default: return SyntaxFactory.List(_perScopeState.ConvertExit(vbBlockKeywordKind)); } } + /// + /// What leaving the method containing without a Return statement does: for a function, return its return variable or the default value. + /// + public StatementSyntax CreateMethodExitStatement(VBasic.VisualBasicSyntaxNode node) + { + VBasic.VisualBasicSyntaxNode typeContainer = node.GetAncestor() + ?? (VBasic.VisualBasicSyntaxNode)node.GetAncestor() + ?? node.GetAncestor(); + var enclosingMethodInfo = typeContainer switch { + VBSyntax.LambdaExpressionSyntax e => _semanticModel.GetSymbolInfo(e).Symbol, + VBSyntax.MethodBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.SubOrFunctionStatement), + VBSyntax.AccessorBlockSyntax e => _semanticModel.GetDeclaredSymbol(e.AccessorStatement), + _ => null + } as IMethodSymbol; + + if (IsIterator) return SyntaxFactory.YieldStatement(SyntaxKind.YieldBreakStatement); + + if (!enclosingMethodInfo.ReturnsVoidOrAsyncTask()) { + ExpressionSyntax expr = HasReturnVariable ? ReturnVariable : SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression); + return SyntaxFactory.ReturnStatement(expr); + } + + return SyntaxFactory.ReturnStatement(); + } + public override async Task> VisitRaiseEventStatement(VBSyntax.RaiseEventStatementSyntax node) { var argumentListSyntax = await node.ArgumentList.AcceptAsync(_expressionVisitor) ?? SyntaxFactory.ArgumentList(); @@ -1098,11 +1143,16 @@ public override async Task> VisitWithBlock(VBSyntax. } } - private string GetUniqueVariableNameInScope(VBasic.VisualBasicSyntaxNode node, string variableNameBase) + public string GetUniqueVariableNameInScope(VBasic.VisualBasicSyntaxNode node, string variableNameBase) { return NameGenerator.CS.GetUniqueVariableNameInScope(_semanticModel, _generatedNames, node, variableNameBase); } + public string GetUniqueLabelNameInScope(VBasic.VisualBasicSyntaxNode node, string labelNameBase) + { + return NameGenerator.CS.GetUniqueLabelNameInScope(_semanticModel, _generatedNames, node, labelNameBase); + } + public override async Task> VisitTryBlock(VBSyntax.TryBlockSyntax node) { var block = SyntaxFactory.Block(await ConvertStatementsAsync(node.Statements)); @@ -1238,4 +1288,4 @@ private static SyntaxList SingleStatement(CSharpSyntaxNode node ? statement : SyntaxFactory.ExpressionStatement((ExpressionSyntax)node)); } -} \ No newline at end of file +} \ No newline at end of file diff --git a/CodeConverter/CSharp/OnError/ActiveHandler.cs b/CodeConverter/CSharp/OnError/ActiveHandler.cs new file mode 100644 index 000000000..8a89d5497 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ActiveHandler.cs @@ -0,0 +1,18 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +internal enum ActiveHandlerKind +{ + None, + ResumeNext, + Label +} + +/// +/// What VB does with an error raised by a statement: the value of the lowered method's "active handler" local, set by the last On Error statement executed. +/// +internal sealed record ActiveHandler(ActiveHandlerKind Kind, string Label = null) +{ + public static ActiveHandler None { get; } = new(ActiveHandlerKind.None); + public static ActiveHandler ResumeNext { get; } = new(ActiveHandlerKind.ResumeNext); + public static ActiveHandler ForLabel(string label) => new(ActiveHandlerKind.Label, LabelName.Normalize(label)); +} diff --git a/CodeConverter/CSharp/OnError/ClearErrOnReturnRewriter.cs b/CodeConverter/CSharp/OnError/ClearErrOnReturnRewriter.cs new file mode 100644 index 000000000..1c4ade844 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ClearErrOnReturnRewriter.cs @@ -0,0 +1,54 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Clears Err at each return from a handler, since VB clears it when the method is left while in a handler. +/// +/// +/// VB evaluates the returned value first, which may read Err, so a returned value that isn't obviously independent of it +/// is returned from a try with the clear in its finally. +/// Returns inside lambdas and local functions leave those, not the method, so are left alone. +/// +internal sealed class ClearErrOnReturnRewriter : CSharpSyntaxRewriter +{ + private static readonly SyntaxAnnotation SpliceAnnotation = new(); + private readonly ErrStatements _err; + private readonly IdentifierNameSyntax _returnVariable; + + private ClearErrOnReturnRewriter(ErrStatements err, IdentifierNameSyntax returnVariable) + { + _err = err; + _returnVariable = returnVariable; + } + + public static IEnumerable Rewrite(IEnumerable statements, ErrStatements err, IdentifierNameSyntax returnVariable) + { + var rewriter = new ClearErrOnReturnRewriter(err, returnVariable); + return Splice(statements.Select(s => (StatementSyntax)rewriter.Visit(s))); + } + + public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node) + { + if (node.Expression == null || IsIndependentOfErr(node.Expression)) { + return SyntaxFactory.Block(_err.Clear().Add(node)).WithAdditionalAnnotations(SpliceAnnotation); + } + return SyntaxFactory.TryStatement(SyntaxFactory.Block(node), default, SyntaxFactory.FinallyClause(SyntaxFactory.Block(_err.Clear()))); + } + + public override SyntaxNode VisitBlock(BlockSyntax node) => + node.WithStatements(SyntaxFactory.List(Splice(node.Statements.Select(s => (StatementSyntax)Visit(s))))); + + public override SyntaxNode VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) => node; + public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) => node; + public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) => node; + public override SyntaxNode VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) => node; + + private bool IsIndependentOfErr(ExpressionSyntax expression) => + expression is LiteralExpressionSyntax or DefaultExpressionSyntax || + _returnVariable != null && expression is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == _returnVariable.Identifier.ValueText; + + private static IEnumerable Splice(IEnumerable statements) => + statements.SelectMany(s => s is BlockSyntax block && block.HasAnnotation(SpliceAnnotation) ? block.Statements : (IEnumerable)new[] { s }); +} diff --git a/CodeConverter/CSharp/OnError/ClearErrStatementConverter.cs b/CodeConverter/CSharp/OnError/ClearErrStatementConverter.cs new file mode 100644 index 000000000..8644e2eb5 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ClearErrStatementConverter.cs @@ -0,0 +1,18 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// An On Error GoTo 0 with no handler to deactivate only clears Err, which VB does for every On Error statement. +/// +internal sealed class ClearErrStatementConverter : IOnErrorStatementConverter +{ + private readonly ErrStatements _err; + + public ClearErrStatementConverter(ErrStatements err) => _err = err; + + public SyntaxList ConvertOnError(VBSyntax.StatementSyntax onErrorStatement) => _err.Clear(); + + public SyntaxList ConvertResume(VBSyntax.ResumeStatementSyntax resumeStatement) => + throw new NotSupportedException("The clear-only shape is only chosen when the method has no Resume statement"); +} diff --git a/CodeConverter/CSharp/OnError/DeclarationSplitter.cs b/CodeConverter/CSharp/OnError/DeclarationSplitter.cs new file mode 100644 index 000000000..71b76ab67 --- /dev/null +++ b/CodeConverter/CSharp/OnError/DeclarationSplitter.cs @@ -0,0 +1,104 @@ +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Splits a converted local declaration into a declaration of the chosen locals as = default, and the assignment of their initializers. +/// +/// +/// A C# local is scoped to its block, but a VB local lives for the whole method and starts zeroed, so declaring it earlier as = default is exact. +/// The declaration becomes an assignment, or nothing when VB had no initializer. Constants move whole. +/// +internal sealed class DeclarationSplitter +{ + private readonly SemanticModel _semanticModel; + private readonly CommonConversions _commonConversions; + + public DeclarationSplitter(SemanticModel semanticModel, CommonConversions commonConversions) + { + _semanticModel = semanticModel; + _commonConversions = commonConversions; + } + + /// The declaration that were converted from. + /// Which of its locals to split. + /// Receives the declarations to place before the statements that are returned. + /// Replaces the assignment of a split local's initializer, e.g. to guard it. Receives the local and the assignment. + /// The statements that stay where the declaration was. + public IEnumerable Split(VBSyntax.LocalDeclarationStatementSyntax vbDeclaration, IEnumerable csStatements, + Func shouldSplit, List declarations, Func transformAssignment = null) + { + var splitByName = vbDeclaration.Declarators + .SelectMany(v => v.Names.Select(n => (Symbol: _semanticModel.GetDeclaredSymbol(n) as ILocalSymbol, NeedsAssignment: NeedsAssignment(v, n)))) + .Where(x => x.Symbol != null && shouldSplit(x.Symbol)) + .ToDictionary(x => x.Symbol.Name, x => x, StringComparer.OrdinalIgnoreCase); + if (!splitByName.Any()) return csStatements; + + var inPlace = new List(); + foreach (var csStatement in csStatements) { + if (csStatement is not LocalDeclarationStatementSyntax csDeclaration || + !csDeclaration.Declaration.Variables.Any(v => splitByName.ContainsKey(v.Identifier.ValueText))) { + inPlace.Add(csStatement); + } else if (csDeclaration.IsConst) { + declarations.Add(csDeclaration); + } else { + inPlace.AddRange(SplitDeclaration(csDeclaration, splitByName, declarations, transformAssignment ?? ((_, assignment) => assignment))); + } + } + return inPlace; + } + + private IEnumerable SplitDeclaration(LocalDeclarationStatementSyntax csDeclaration, + Dictionary splitByName, List declarations, + Func transformAssignment) + { + var inOrder = new List(); + var kept = new List(); + foreach (var variable in csDeclaration.Declaration.Variables) { + if (!splitByName.TryGetValue(variable.Identifier.ValueText, out var split)) { + kept.Add(variable); + continue; + } + AddKept(); + declarations.Add(DeclareDefault(variable.Identifier, split.Symbol)); + if (split.NeedsAssignment && variable.Initializer != null) { + inOrder.Add(transformAssignment(split.Symbol, SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, + SyntaxFactory.IdentifierName(variable.Identifier.WithoutTrivia()), variable.Initializer.Value.WithoutTrivia())))); + } + } + AddKept(); + return inOrder; + + void AddKept() + { + if (!kept.Any()) return; + inOrder.Add(csDeclaration.WithDeclaration(csDeclaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(kept)))); + kept.Clear(); + } + } + + /// + /// Splitting declares the local before the statement that assigns it, so its type has to be written out. + /// An anonymous type, or the anonymous delegate type of a lambda, has no name, so such a local can't be split. + /// + public static bool CanSplit(ILocalSymbol local) => CanBeNamed(local.Type); + + private static bool CanBeNamed(ITypeSymbol type) => type switch { + IArrayTypeSymbol array => CanBeNamed(array.ElementType), + INamedTypeSymbol named => !named.IsAnonymousType && named.TypeArguments.All(CanBeNamed), + _ => true + }; + + private LocalDeclarationStatementSyntax DeclareDefault(SyntaxToken identifier, ILocalSymbol local) + { + var declarator = SyntaxFactory.VariableDeclarator(identifier.WithoutTrivia()) + .WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))); + var type = _commonConversions.GetTypeSyntax(local.Type); + return SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SingletonSeparatedList(declarator))); + } + + private static bool NeedsAssignment(VBSyntax.VariableDeclaratorSyntax declarator, VBSyntax.ModifiedIdentifierSyntax name) => + declarator.Initializer != null || declarator.AsClause is VBSyntax.AsNewClauseSyntax || name.ArrayBounds != null; +} diff --git a/CodeConverter/CSharp/OnError/DefaultInitializers.cs b/CodeConverter/CSharp/OnError/DefaultInitializers.cs new file mode 100644 index 000000000..9694c09ec --- /dev/null +++ b/CodeConverter/CSharp/OnError/DefaultInitializers.cs @@ -0,0 +1,20 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Gives locals declared without an initializer the = default that VB's zeroed locals have. +/// +/// +/// The converter leaves out an initializer that VB's flow analysis says isn't needed, but that analysis doesn't know a handler can run after any statement, +/// or that an error can skip the assignment. VB locals start zeroed, so = default is exact. +/// +internal static class DefaultInitializers +{ + public static IEnumerable Add(IEnumerable statements) => + statements.Select(s => s is LocalDeclarationStatementSyntax { IsConst: false } declaration + ? declaration.WithDeclaration(declaration.Declaration.WithVariables(SyntaxFactory.SeparatedList(declaration.Declaration.Variables.Select(v => + v.Initializer != null ? v : v.WithInitializer(SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression))))))) + : s); +} diff --git a/CodeConverter/CSharp/OnError/ElidedStatementTrivia.cs b/CodeConverter/CSharp/OnError/ElidedStatementTrivia.cs new file mode 100644 index 000000000..d74050f44 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ElidedStatementTrivia.cs @@ -0,0 +1,51 @@ +using System.Globalization; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Keeps the comments of a statement that converts to nothing (such as an On Error GoTo 0 when Err isn't maintained) with the code that follows it. +/// +/// +/// The line-based trivia mapping only attaches trivia to lines that have converted nodes, and carries the rest back to the statement before. +/// For a handler that puts the comments in the try, so they are attached to the next statement of the same block instead. +/// +internal static class ElidedStatementTrivia +{ + public static bool HasComments(VBSyntax.StatementSyntax elided) => + elided.GetFirstToken().LeadingTrivia.Concat(elided.GetLastToken().TrailingTrivia).Any(t => !t.IsWhitespaceOrEndOfLine()); + + /// + /// Puts the comments of before , and stops the line-based mapping from also moving them. + /// + /// The statement was converted from, whose own leading trivia has to be kept as the mapping skips it too. + public static StatementSyntax PrependTo(StatementSyntax next, VBSyntax.StatementSyntax nextSource, IReadOnlyCollection elided) + { + var withComments = elided.Where(HasComments).ToList(); + if (!withComments.Any()) return next; + + var carried = withComments.SelectMany(CommentLines).ToList(); + var firstToken = next.GetFirstToken(); + var nextSourceStart = nextSource.GetFirstToken().SpanStart; + var alreadyMapped = firstToken.GetAnnotations(AnnotationConstants.LeadingTriviaAlreadyMappedAnnotation).Any(a => a.Data == nextSourceStart.ToString(CultureInfo.InvariantCulture)); + var ownLeadingTrivia = alreadyMapped ? firstToken.LeadingTrivia : SyntaxFactory.TriviaList(nextSource.GetFirstToken().LeadingTrivia.ToList().ConvertTrivia()); + + var withTrivia = firstToken.WithLeadingTrivia(carried.Concat(ownLeadingTrivia)); + if (!alreadyMapped) withTrivia = withTrivia.WithAlreadyMappedStartLineAnnotation(nextSourceStart); + foreach (var statement in withComments) { + withTrivia = withTrivia + .WithAlreadyMappedStartLineAnnotation(statement.GetFirstToken().SpanStart) + .WithAlreadyMappedEndLineAnnotation(statement.GetLastToken().Span.End); + } + return next.ReplaceToken(firstToken, withTrivia); + } + + private static IEnumerable CommentLines(VBSyntax.StatementSyntax elided) + { + var leading = elided.GetFirstToken().LeadingTrivia.ToList().ConvertTrivia(); + var trailing = elided.GetLastToken().TrailingTrivia.ToList().ConvertTrivia().ToList(); + if (trailing.Any(t => !t.IsWhitespaceOrEndOfLine()) && !trailing.Last().IsEndOfLine()) trailing.Add(SyntaxFactory.CarriageReturnLineFeed); + return leading.Concat(trailing); + } +} diff --git a/CodeConverter/CSharp/OnError/ErrStatements.cs b/CodeConverter/CSharp/OnError/ErrStatements.cs new file mode 100644 index 000000000..41402dbc1 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ErrStatements.cs @@ -0,0 +1,45 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// The calls VB's lowering makes to keep Err up to date, or nothing when says nobody reads it. +/// +internal sealed class ErrStatements +{ + private const string CompilerServicesNamespace = "Microsoft.VisualBasic.CompilerServices"; + private readonly HashSet _extraUsingDirectives; + + public ErrStatements(bool isMaintained, HashSet extraUsingDirectives) + { + IsMaintained = isMaintained; + _extraUsingDirectives = extraUsingDirectives; + } + + public bool IsMaintained { get; } + + /// Where VB clears Err: each On Error and Resume statement, and leaving the method while in a handler. + public SyntaxList Clear() => + IsMaintained ? SyntaxFactory.SingletonList(ProjectDataCall("ClearProjectError")) : default; + + /// A catch-all, as VB catches any exception, recording it in Err first as VB's catch does. + /// VB's catch has a filter on the active handler; an exception filter doesn't unwind the stack when it's false, as in VB. + public CatchClauseSyntax CatchClause(string exceptionVariableName, IEnumerable statements, ExpressionSyntax filter = null) + { + var filterClause = filter == null ? null : SyntaxFactory.CatchFilterClause(filter); + if (!IsMaintained) return SyntaxFactory.CatchClause().WithFilter(filterClause).WithBlock(SyntaxFactory.Block(statements)); + _extraUsingDirectives.Add("System"); + var declaration = SyntaxFactory.CatchDeclaration(SyntaxFactory.IdentifierName(nameof(Exception)), SyntaxFactory.Identifier(exceptionVariableName)); + var setError = ProjectDataCall("SetProjectError", SyntaxFactory.IdentifierName(exceptionVariableName)); + return SyntaxFactory.CatchClause(declaration, filterClause, SyntaxFactory.Block(statements.Prepend(setError))); + } + + private StatementSyntax ProjectDataCall(string methodName, params ExpressionSyntax[] arguments) + { + _extraUsingDirectives.Add(CompilerServicesNamespace); + var method = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("ProjectData"), SyntaxFactory.IdentifierName(methodName)); + return SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(method, + SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(SyntaxFactory.Argument))))); + } +} diff --git a/CodeConverter/CSharp/OnError/ErrUsage.cs b/CodeConverter/CSharp/OnError/ErrUsage.cs new file mode 100644 index 000000000..e0091a793 --- /dev/null +++ b/CodeConverter/CSharp/OnError/ErrUsage.cs @@ -0,0 +1,67 @@ +using Microsoft.VisualStudio.Threading; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Decides whether a converted handler must maintain Err (ProjectData.SetProjectError/ClearProjectError). +/// VB's lowering always does, but in C# it's noise unless something reads Err: the handler's own type, or an "Err helper", +/// a method with no On Error of its own that reads Err, so can only be reading an error that some other method caught. +/// +/// +/// One pass per project, done the first time a method with On Error asks, and shared by every document converted from that project. +/// Only reads count: Err.Raise and Err.Clear don't depend on an earlier error. A read in a Catch block reads that block's own error, so doesn't make an Err helper. +/// Reads through reflection, late binding or from another project aren't seen. +/// +internal sealed class ErrUsage +{ + private static readonly string[] NonReadingMembers = { "Raise", "Clear" }; + + private readonly AsyncLazy _projectErrReads; + + public ErrUsage(Project project) => + _projectErrReads = new AsyncLazy(() => FindErrReadsAsync(project), JoinableTaskFactorySingleton.Instance); + + public async Task IsMaintainedInAsync(INamedTypeSymbol containingType) + { + var reads = await _projectErrReads.GetValueAsync(); + return reads.ProjectHasErrHelper || containingType != null && reads.TypesReadingErr.Contains(containingType.GetFullMetadataName()); + } + + private record ProjectErrReads(bool ProjectHasErrHelper, HashSet TypesReadingErr); + + private static async Task FindErrReadsAsync(Project project) + { + var compilation = await project.GetCompilationAsync(); + var typesReadingErr = new HashSet(StringComparer.Ordinal); + var hasErrHelper = false; + foreach (var tree in compilation.SyntaxTrees) { + var root = await tree.GetRootAsync(); + var candidates = root.DescendantNodes().OfType() + .Where(n => string.Equals(n.Identifier.ValueText, "Err", StringComparison.OrdinalIgnoreCase) && !IsNonReadingMemberAccess(n)) + .ToArray(); + if (!candidates.Any()) continue; + var semanticModel = compilation.GetSemanticModel(tree, true); + foreach (var errRead in candidates.Where(n => IsInformationErr(semanticModel.GetSymbolInfo(n).Symbol))) { + if (semanticModel.GetEnclosingSymbol(errRead.SpanStart)?.ContainingType is { } type) { + typesReadingErr.Add(type.GetFullMetadataName()); + } + hasErrHelper |= IsErrHelperRead(errRead); + } + } + return new ProjectErrReads(hasErrHelper, typesReadingErr); + } + + private static bool IsNonReadingMemberAccess(VBSyntax.IdentifierNameSyntax errName) => + errName.Parent is VBSyntax.MemberAccessExpressionSyntax memberAccess && memberAccess.Expression == errName && + NonReadingMembers.Contains(memberAccess.Name.Identifier.ValueText, StringComparer.OrdinalIgnoreCase); + + private static bool IsInformationErr(ISymbol symbol) => + symbol is IMethodSymbol { Name: "Err" } method && method.ContainingType?.GetFullMetadataName() == "Microsoft.VisualBasic.Information"; + + private static bool IsErrHelperRead(VBSyntax.IdentifierNameSyntax errRead) + { + if (errRead.GetAncestor() != null) return false; + var method = errRead.GetAncestor(); + return method == null || !OnErrorModel.ContainsOnErrorOrResume(method); + } +} diff --git a/CodeConverter/CSharp/OnError/GuardPolicy.cs b/CodeConverter/CSharp/OnError/GuardPolicy.cs new file mode 100644 index 000000000..cde6a8066 --- /dev/null +++ b/CodeConverter/CSharp/OnError/GuardPolicy.cs @@ -0,0 +1,36 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// What a guard's catch does with an error, apart from recording it in Err: the part of README.md "Output shapes" that differs between shapes 2 to 4. +/// +internal abstract class GuardPolicy +{ + /// Null for a catch that always catches. + public virtual ExpressionSyntax Filter => null; + + /// Whether may jump back to the label placed before the guarded statement, which VB's Resume does. + public virtual bool CanRetry => false; + + /// Null unless . + public virtual IEnumerable OnError(string retryLabel) => Enumerable.Empty(); +} + +/// +/// On Error Resume Next is active: the error is recorded and the next statement runs. +/// +internal sealed class ResumeNextGuardPolicy : GuardPolicy +{ +} + +/// +/// Whether On Error Resume Next is active is only known when the method runs, so a flag set where VB's On Error statements were decides whether to catch. +/// +internal sealed class DynamicGuardPolicy : GuardPolicy +{ + public DynamicGuardPolicy(string flagName) => Filter = SyntaxFactory.IdentifierName(flagName); + + public override ExpressionSyntax Filter { get; } +} diff --git a/CodeConverter/CSharp/OnError/GuardingStatementVisitor.cs b/CodeConverter/CSharp/OnError/GuardingStatementVisitor.cs new file mode 100644 index 000000000..7d319f4e2 --- /dev/null +++ b/CodeConverter/CSharp/OnError/GuardingStatementVisitor.cs @@ -0,0 +1,24 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Guards every statement the method body visitor converts, at any depth, so the visitor itself needn't know about resume points. +/// +internal sealed class GuardingStatementVisitor : VBasic.VisualBasicSyntaxVisitor>> +{ + private readonly VBasic.VisualBasicSyntaxVisitor>> _wrappedVisitor; + private readonly StatementGuards _guards; + + public GuardingStatementVisitor(VBasic.VisualBasicSyntaxVisitor>> wrappedVisitor, StatementGuards guards) + { + _wrappedVisitor = wrappedVisitor; + _guards = guards; + } + + public override async Task> DefaultVisit(SyntaxNode node) + { + var converted = await _wrappedVisitor.Visit(node); + return node is VBSyntax.StatementSyntax statement ? _guards.Guard(statement, converted) : converted; + } +} diff --git a/CodeConverter/CSharp/OnError/HandlerExit.cs b/CodeConverter/CSharp/OnError/HandlerExit.cs new file mode 100644 index 000000000..3da936836 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerExit.cs @@ -0,0 +1,20 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +internal enum HandlerExitKind +{ + ResumeNext, + Resume, + ResumeLabel, + GoToLabel, + ExitMethod, + FallsOffEnd, + FallsIntoLabel +} + +/// +/// A way control leaves a handler. Resume* also leaves VB's "in a handler" state and clears Err; GoTo and falling into a label do neither. +/// +internal sealed record HandlerExit(HandlerExitKind Kind, string TargetLabel = null) +{ + public bool IsJumpToLabel => Kind is HandlerExitKind.ResumeLabel or HandlerExitKind.GoToLabel or HandlerExitKind.FallsIntoLabel; +} diff --git a/CodeConverter/CSharp/OnError/HandlerExitRewriter.cs b/CodeConverter/CSharp/OnError/HandlerExitRewriter.cs new file mode 100644 index 000000000..a9e8d7f0d --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerExitRewriter.cs @@ -0,0 +1,66 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Turns the method's own returns in the handler into the handler function's way of saying "leave the method". +/// +/// +/// A return in a local function only leaves that function, so the value of Return expr goes into a variable that the caller returns, +/// and the function returns the value that means exit. VB clears Err on leaving the method while in a handler, after evaluating the returned value. +/// Returns inside lambdas and local functions are not the method's. +/// +internal sealed class HandlerExitRewriter : CSharpSyntaxRewriter +{ + private static readonly SyntaxAnnotation SpliceAnnotation = new(); + private readonly ErrStatements _err; + private readonly string _resultVariable; + private readonly ExpressionSyntax _exitValue; + + /// The variable the caller returns, or null when the handler has no Return expr. + /// What the function returns to leave the method. + private HandlerExitRewriter(ErrStatements err, string resultVariable, ExpressionSyntax exitValue) + { + _err = err; + _resultVariable = resultVariable; + _exitValue = exitValue; + } + + public static IEnumerable Rewrite(IEnumerable statements, ErrStatements err, string resultVariable, ExpressionSyntax exitValue) + { + var rewriter = new HandlerExitRewriter(err, resultVariable, exitValue); + return Splice(statements.Select(s => (StatementSyntax)rewriter.Visit(s))); + } + + /// The statements that leave the method when the handler runs off its end. + public static IEnumerable Exit(ErrStatements err, ExpressionSyntax exitValue) => + err.Clear().Add(SyntaxFactory.ReturnStatement(exitValue)); + + public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node) + { + if (node.HasAnnotation(HandlerFunctionStatementConverter.ResumeReturn)) return node; + var statements = new List(); + if (node.Expression != null && node.Expression is not DefaultExpressionSyntax && !IsDefaultLiteral(node.Expression) && !IsResultVariable(node.Expression)) { + statements.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, + SyntaxFactory.IdentifierName(_resultVariable), node.Expression))); + } + statements.AddRange(Exit(_err, _exitValue)); + return SyntaxFactory.Block(statements).WithAdditionalAnnotations(SpliceAnnotation); + } + + public override SyntaxNode VisitBlock(BlockSyntax node) => + node.WithStatements(SyntaxFactory.List(Splice(node.Statements.Select(s => (StatementSyntax)Visit(s))))); + + public override SyntaxNode VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) => node; + public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) => node; + public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) => node; + public override SyntaxNode VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) => node; + + private static bool IsDefaultLiteral(ExpressionSyntax expression) => expression.IsKind(SyntaxKind.DefaultLiteralExpression); + + private bool IsResultVariable(ExpressionSyntax expression) => expression is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == _resultVariable; + + private static IEnumerable Splice(IEnumerable statements) => + statements.SelectMany(s => s is BlockSyntax block && block.HasAnnotation(SpliceAnnotation) ? block.Statements : (IEnumerable)new[] { s }); +} diff --git a/CodeConverter/CSharp/OnError/HandlerFunctionGuardPolicy.cs b/CodeConverter/CSharp/OnError/HandlerFunctionGuardPolicy.cs new file mode 100644 index 000000000..54403ee83 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerFunctionGuardPolicy.cs @@ -0,0 +1,39 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Every guard calls the handler function from its catch, then does what it says: carry on, run the statement again (goto the label before its try) or leave. +/// +internal sealed class HandlerFunctionGuardPolicy : GuardPolicy +{ + private readonly HandlerFunctionPlan _plan; + private readonly string _functionName; + private readonly StatementSyntax _exitStatement; + + public HandlerFunctionGuardPolicy(HandlerFunctionPlan plan, string functionName, StatementSyntax exitStatement) + { + _plan = plan; + _functionName = functionName; + _exitStatement = exitStatement; + } + + public override bool CanRetry => _plan.CanRetry; + + public override IEnumerable OnError(string retryLabel) + { + var call = SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(_functionName)); + var retry = SyntaxFactory.GotoStatement(SyntaxKind.GotoStatement, SyntaxFactory.IdentifierName(retryLabel ?? "unused")); + switch (_plan.Ways) { + case HandlerWays.ResumeNext: + return new StatementSyntax[] { SyntaxFactory.ExpressionStatement(call) }; + case HandlerWays.RetryOrResumeNext: + return new StatementSyntax[] { SyntaxFactory.IfStatement(call, retry) }; + case HandlerWays.ExitOrResumeNext: + return new StatementSyntax[] { SyntaxFactory.IfStatement(call, _exitStatement) }; + default: + return new StatementSyntax[] { SyntaxFactory.IfStatement(call, retry), _exitStatement }; + } + } +} diff --git a/CodeConverter/CSharp/OnError/HandlerFunctionPlan.cs b/CodeConverter/CSharp/OnError/HandlerFunctionPlan.cs new file mode 100644 index 000000000..992078ea6 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerFunctionPlan.cs @@ -0,0 +1,39 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// How an On Error GoTo handler that resumes into the covered statements leaves, which decides what the local function returns. +/// +/// +/// Resuming the statement after, or running the statement again, are both decided by the caller's catch, so the function says which with a bool. +/// The name of the function says what true means. +/// +internal enum HandlerWays +{ + /// Only Resume Next: a void function. + ResumeNext, + /// Resume Next or Resume: true runs the statement again. + RetryOrResumeNext, + /// Resume Next or leaving the method: true leaves. + ExitOrResumeNext, + /// Resume or leaving the method: true runs the statement again. + RetryOrExit +} + +/// Where the handler function is declared: right after the first On Error GoTo, so what it captures is declared before it. +/// The handler has Return expr, whose value the function can only hand back through a variable. +internal sealed record HandlerFunctionPlan(HandlerRegion Handler, int FirstOnErrorIndex, HandlerWays Ways, bool ReturnsValue) +{ + public bool CanRetry => Ways is HandlerWays.RetryOrResumeNext or HandlerWays.RetryOrExit; + public bool CanExit => Ways is HandlerWays.ExitOrResumeNext or HandlerWays.RetryOrExit; + + /// The value the function returns for Resume Next, or null for a void function. + public bool? ResumeNextValue => Ways switch { + HandlerWays.ResumeNext => null, + _ => false + }; + + public bool ResumeValue => true; + + /// What the function returns to say the method is left. For that's the opposite of retrying. + public bool ExitValue => Ways == HandlerWays.ExitOrResumeNext; +} diff --git a/CodeConverter/CSharp/OnError/HandlerFunctionPlanner.cs b/CodeConverter/CSharp/OnError/HandlerFunctionPlanner.cs new file mode 100644 index 000000000..e38a4c7a3 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerFunctionPlanner.cs @@ -0,0 +1,100 @@ +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Recognises README.md shape 3: one method-level handler that resumes into the statements it covers, which each guard calls from its catch. +/// +/// +/// Anything the emitter can't express soundly returns null so the method keeps the fallback: +/// * more than one handler, or Resume L / GoTo L out of the handler, or more than two ways out; +/// * the handler is also run into without an error, or jumped into: a local function can't be entered by a jump; +/// * the function would capture a ref/out parameter, which C# doesn't allow; +/// * a guard inside a guarded block: a secondary error, thrown by the handler inside the inner catch, would be caught again by the outer one, +/// but VB's filter lets it propagate; +/// * a failing loop condition or Case expression when the handler can leave the method, which a local function can't do; +/// * a local that must be declared before its guard, or at the top for the handler, but whose type can't be written (anonymous type). +/// +internal static class HandlerFunctionPlanner +{ + public static HandlerFunctionPlan TryPlan(OnErrorModel model, SemanticModel semanticModel) + { + if (model.IsDynamic || model.Handlers.Count != 1 || model.Handlers[0] is not { IsMethodLevel: true, LabelIndex: > 0 } handler) return null; + if (!model.OnErrorStatements.All(s => s is VBSyntax.OnErrorGoToStatementSyntax) || model.ResumeStatements.Any(r => model.HandlerContaining(model.MethodLevelIndexOf(r)) == null)) return null; + var ways = WaysOf(handler.Exits); + if (ways == null || OnErrorModel.EndPointIsReachable(model.Statements[handler.LabelIndex - 1], semanticModel)) return null; + if (model.Jumps.Any(j => handler.Contains(model.IndexContainingLabel(j.TargetLabel)) && !handler.Contains(model.MethodLevelIndexOf(j.Statement)))) return null; + + var handlerStatements = model.Statements.Skip(handler.LabelIndex).Take(handler.EndIndex - handler.LabelIndex).ToArray(); + var others = model.Statements.Where((_, i) => !handler.Contains(i)).ToArray(); + if (CapturesRefParameter(handlerStatements, semanticModel) || OutsideUsesLocalsOfHandler(handlerStatements, others, semanticModel) || + HandlerUsesLocalsThatCantBeDeclaredEarly(handlerStatements, others, semanticModel)) { + return null; + } + + var firstOnErrorIndex = model.OnErrorStatements.Select(model.MethodLevelIndexOf).Min(); + var plan = new HandlerFunctionPlan(handler, firstOnErrorIndex, ways.Value, ReturnsValue(handlerStatements)); + return GuardsAreSupported(model, plan, others, semanticModel) ? plan : null; + } + + public static ResumePoints CreateResumePoints(OnErrorModel model, HandlerRegion handler, SemanticModel semanticModel) => + new(model, semanticModel, index => model.ActiveHandlers[index].Kind == ActiveHandlerKind.Label && !handler.Contains(index)); + + private static HandlerWays? WaysOf(IReadOnlyCollection exits) + { + if (exits.Any(e => e.Kind is not (HandlerExitKind.ResumeNext or HandlerExitKind.Resume or HandlerExitKind.ExitMethod or HandlerExitKind.FallsOffEnd))) return null; + var resumesNext = exits.Any(e => e.Kind == HandlerExitKind.ResumeNext); + var retries = exits.Any(e => e.Kind == HandlerExitKind.Resume); + var exitsMethod = exits.Any(e => e.Kind is HandlerExitKind.ExitMethod or HandlerExitKind.FallsOffEnd); + return (resumesNext, retries, exitsMethod) switch { + (true, false, false) => HandlerWays.ResumeNext, + (true, true, false) => HandlerWays.RetryOrResumeNext, + (true, false, true) => HandlerWays.ExitOrResumeNext, + (false, true, true) => HandlerWays.RetryOrExit, + _ => null + }; + } + + private static bool ReturnsValue(IEnumerable handlerStatements) => + handlerStatements.SelectMany(s => s.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax)) + .OfType().Any(r => r.Expression != null); + + private static bool CapturesRefParameter(IEnumerable statements, SemanticModel semanticModel) => + statements.SelectMany(s => s.DescendantNodesAndSelf()).OfType() + .Any(i => semanticModel.GetSymbolInfo(i).Symbol is IParameterSymbol { RefKind: not RefKind.None }); + + private static bool OutsideUsesLocalsOfHandler(IEnumerable handlerStatements, IEnumerable others, SemanticModel semanticModel) + { + var declared = handlerStatements.SelectMany(s => s.DescendantNodesAndSelf()).OfType() + .Select(n => semanticModel.GetDeclaredSymbol(n)).Where(l => l != null).ToArray(); + return declared.Any() && others.SelectMany(s => s.DescendantNodesAndSelf()).OfType() + .Any(i => declared.Contains(semanticModel.GetSymbolInfo(i).Symbol, SymbolEqualityComparer.Default)); + } + + /// The handler is declared before the guards, so a local it uses that is declared after it has to be declared at the top. + private static bool HandlerUsesLocalsThatCantBeDeclaredEarly(IEnumerable handlerStatements, IEnumerable others, SemanticModel semanticModel) + { + var declaredElsewhere = others.SelectMany(s => s.DescendantNodesAndSelf()).OfType() + .Select(n => semanticModel.GetDeclaredSymbol(n)).OfType().ToArray(); + return handlerStatements.SelectMany(s => s.DescendantNodesAndSelf()).OfType() + .Select(i => semanticModel.GetSymbolInfo(i).Symbol).OfType() + .Any(l => !DeclarationSplitter.CanSplit(l) && declaredElsewhere.Contains(l, SymbolEqualityComparer.Default)); + } + + private static bool GuardsAreSupported(OnErrorModel model, HandlerFunctionPlan plan, IEnumerable others, SemanticModel semanticModel) + { + var points = CreateResumePoints(model, plan.Handler, semanticModel); + if (!points.CanGuardAllDeclarations(others)) return false; + var all = others.SelectMany(s => s.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax)).OfType().ToArray(); + var guarded = all.Where(s => IsGuarded(points, s, semanticModel)).ToArray(); + var inLocalFunctions = guarded.Where(points.GuardsInALocalFunction).ToArray(); + if (inLocalFunctions.Any(points.HasConditionCapturingARefParameter) || inLocalFunctions.Any() && plan.CanExit) return false; + return !guarded.Any(s => s.Ancestors().OfType().Any(a => model.MethodLevelIndexOf(a) >= 0 && points.GuardsWholeStatement(a))); + } + + private static bool IsGuarded(ResumePoints points, VBSyntax.StatementSyntax statement, SemanticModel semanticModel) => points.KindOf(statement) switch { + ResumePointKind.None => false, + ResumePointKind.Declaration => points.IsCovered(statement) && ((VBSyntax.LocalDeclarationStatementSyntax)statement).Declarators.Any(d => ThrowAnalysis.CanThrow(d, semanticModel)), + _ => true + }; +} diff --git a/CodeConverter/CSharp/OnError/HandlerFunctionShapeEmitter.cs b/CodeConverter/CSharp/OnError/HandlerFunctionShapeEmitter.cs new file mode 100644 index 000000000..4d602bb7b --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerFunctionShapeEmitter.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Emits README.md shape 3: the handler becomes a local function and each guard's catch calls it, then resumes, retries or leaves as it says. +/// +/// +/// The function is declared right after the first On Error GoTo, so what it captures is declared before it: locals declared later that the handler uses are declared there too. +/// An exception thrown by the handler propagates out of the guard's catch, as VB's filter lets an error in a handler propagate. +/// +internal sealed class HandlerFunctionShapeEmitter +{ + private readonly OnErrorConversionContext _context; + private readonly OnErrorModel _model; + private readonly HandlerFunctionPlan _plan; + private readonly ErrStatements _err; + private readonly string _functionName; + private readonly string _resultVariable; + private readonly bool _declaresResultVariable; + private readonly StatementGuards _guards; + + public HandlerFunctionShapeEmitter(OnErrorConversionContext context, OnErrorModel model, HandlerFunctionPlan plan, ErrStatements err) + { + _context = context; + _model = model; + _plan = plan; + _err = err; + var first = model.Statements.First(); + var visitor = context.Visitor; + _functionName = visitor.GetUniqueVariableNameInScope(first, model.LabelText(plan.Handler.Label) + FunctionNameSuffix(plan.Ways)); + _declaresResultVariable = plan.ReturnsValue && !visitor.HasReturnVariable; + _resultVariable = visitor.HasReturnVariable ? visitor.ReturnVariable.Identifier.ValueText : _declaresResultVariable ? visitor.GetUniqueVariableNameInScope(first, "result") : null; + var exitStatement = _resultVariable != null && plan.ReturnsValue + ? SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(_resultVariable)) + : visitor.CreateMethodExitStatement(first); + var points = HandlerFunctionPlanner.CreateResumePoints(model, plan.Handler, context.SemanticModel); + var exceptionName = err.IsMaintained ? visitor.GetUniqueVariableNameInScope(first, "ex") : null; + _guards = new StatementGuards(points, new HandlerFunctionGuardPolicy(plan, _functionName, exitStatement), err, + new DeclarationSplitter(context.SemanticModel, context.CommonConversions), context.SemanticModel, visitor.GetUniqueVariableNameInScope, visitor.GetUniqueLabelNameInScope, exceptionName, + visitor.TryHoistOutOfLoop, DeclaredAtTop()); + } + + /// The suffix says what true means, for the functions that return a bool. + private static string FunctionNameSuffix(HandlerWays ways) => ways switch { + HandlerWays.ResumeNext => "", + HandlerWays.ExitOrResumeNext => "Exits", + _ => "Retries" + }; + + /// Locals declared after the first On Error at method level that the handler uses. + private Func DeclaredAtTop() + { + var semanticModel = _context.SemanticModel; + var used = _model.Statements.Skip(_plan.Handler.LabelIndex).Take(_plan.Handler.EndIndex - _plan.Handler.LabelIndex) + .SelectMany(s => s.DescendantNodesAndSelf()).OfType() + .Select(i => semanticModel.GetSymbolInfo(i).Symbol).OfType().ToArray(); + var declaredLater = _model.Statements.Skip(_plan.FirstOnErrorIndex + 1).Where((_, i) => !_plan.Handler.Contains(i + _plan.FirstOnErrorIndex + 1)) + .OfType().SelectMany(d => d.Declarators).SelectMany(d => d.Names) + .Select(n => semanticModel.GetDeclaredSymbol(n)).OfType().ToArray(); + return local => used.Contains(local, SymbolEqualityComparer.Default) && declaredLater.Contains(local, SymbolEqualityComparer.Default); + } + + public async Task> EmitAsync() + { + var visitor = _context.Visitor; + visitor.OnErrorStatementConverter = new HandlerFunctionStatementConverter(_err, _plan); + visitor.DecorateStatementVisitor(wrapped => new GuardingStatementVisitor(wrapped, _guards)); + + var before = await ConvertRangeAsync(0, _plan.FirstOnErrorIndex + 1); + var function = await ConvertHandlerAsync(); + var after = await _context.ConvertAsync(_model.Statements.Where((_, i) => i > _plan.FirstOnErrorIndex && !_plan.Handler.Contains(i))); + return MissingReturn.Add(_context, _model, _guards, before.Concat(_guards.TopDeclarations).Concat(DeclareResultVariable()).Append(function).Concat(after).ToList()).ToList(); + } + + private IEnumerable DeclareResultVariable() + { + if (!_declaresResultVariable) yield break; + var returnStatement = _model.Statements.Skip(_plan.Handler.LabelIndex).SelectMany(s => s.DescendantNodesAndSelf()).OfType().First(r => r.Expression != null); + var type = _context.CommonConversions.GetTypeSyntax(_context.SemanticModel.GetTypeInfo(returnStatement.Expression).ConvertedType); + yield return SyntaxFactory.LocalDeclarationStatement(SyntaxFactory.VariableDeclaration(type, SyntaxFactory.SingletonSeparatedList( + SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(_resultVariable), null, + SyntaxFactory.EqualsValueClause(SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression)))))); + } + + private async Task ConvertHandlerAsync() + { + var body = await ConvertRangeAsync(_plan.Handler.LabelIndex + 1, _plan.Handler.EndIndex); + var exitValue = SyntaxFactory.LiteralExpression(_plan.ExitValue ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression); + var statements = StatementReachability.UpToFirstLeaving(HandlerExitRewriter.Rewrite(body, _err, _resultVariable, exitValue)).ToList(); + if (_plan.Handler.Exits.Any(e => e.Kind == HandlerExitKind.FallsOffEnd) && StatementReachability.EndIsReachable(statements)) { + statements.AddRange(HandlerExitRewriter.Exit(_err, exitValue)); + } + if (_plan.Ways == HandlerWays.ResumeNext && statements.LastOrDefault() is ReturnStatementSyntax { Expression: null }) statements.RemoveAt(statements.Count - 1); + var returnType = _plan.Ways == HandlerWays.ResumeNext + ? SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)) + : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)); + return SyntaxFactory.LocalFunctionStatement(returnType, _functionName).WithBody(SyntaxFactory.Block(statements)); + } + + private Task> ConvertRangeAsync(int start, int end) => + _context.ConvertAsync(_model.Statements.Skip(start).Take(end - start)); +} diff --git a/CodeConverter/CSharp/OnError/HandlerFunctionStatementConverter.cs b/CodeConverter/CSharp/OnError/HandlerFunctionStatementConverter.cs new file mode 100644 index 000000000..d5b07f5d5 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerFunctionStatementConverter.cs @@ -0,0 +1,35 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using VBasicSyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// In the handler function shape, On Error clears Err, and Resume / Resume Next clear it and return to the guard's catch +/// with the value that says which of the two the handler chose. +/// +internal sealed class HandlerFunctionStatementConverter : IOnErrorStatementConverter +{ + /// Marks the returns made by Resume statements, so they aren't mistaken for the method's own Return statements. + public static readonly SyntaxAnnotation ResumeReturn = new(); + + private readonly ErrStatements _err; + private readonly HandlerFunctionPlan _plan; + + public HandlerFunctionStatementConverter(ErrStatements err, HandlerFunctionPlan plan) + { + _err = err; + _plan = plan; + } + + public SyntaxList ConvertOnError(VBSyntax.StatementSyntax onErrorStatement) => _err.Clear(); + + public SyntaxList ConvertResume(VBSyntax.ResumeStatementSyntax resumeStatement) + { + bool? value = resumeStatement.IsKind(VBasicSyntaxKind.ResumeStatement) ? _plan.ResumeValue : _plan.ResumeNextValue; + var returnStatement = (value is { } v + ? SyntaxFactory.ReturnStatement(SyntaxFactory.LiteralExpression(v ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression)) + : SyntaxFactory.ReturnStatement()).WithAdditionalAnnotations(ResumeReturn); + return _err.Clear().Add(returnStatement); + } +} diff --git a/CodeConverter/CSharp/OnError/HandlerRegion.cs b/CodeConverter/CSharp/OnError/HandlerRegion.cs new file mode 100644 index 000000000..c90fbfaa1 --- /dev/null +++ b/CodeConverter/CSharp/OnError/HandlerRegion.cs @@ -0,0 +1,15 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// The statements of an On Error GoTo handler: from its label to the next method-level label or the end of the method. +/// +/// Index of the handler's label among the method-level statements, or -1 when the label is inside a block. +/// Exclusive end of the handler's statements. +internal sealed record HandlerRegion(string Label, int LabelIndex, int EndIndex, IReadOnlyList Exits) +{ + public bool IsMethodLevel => LabelIndex >= 0; + + public bool Contains(int statementIndex) => IsMethodLevel && LabelIndex <= statementIndex && statementIndex < EndIndex; + + public IEnumerable ExitLabels => Exits.Where(e => e.IsJumpToLabel).Select(e => e.TargetLabel).Distinct(); +} diff --git a/CodeConverter/CSharp/OnError/IOnErrorStatementConverter.cs b/CodeConverter/CSharp/OnError/IOnErrorStatementConverter.cs new file mode 100644 index 000000000..d95389e53 --- /dev/null +++ b/CodeConverter/CSharp/OnError/IOnErrorStatementConverter.cs @@ -0,0 +1,12 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Converts the On Error and Resume statements the method body visitor meets, for the shape being emitted. +/// +internal interface IOnErrorStatementConverter +{ + SyntaxList ConvertOnError(VBSyntax.StatementSyntax onErrorStatement); + SyntaxList ConvertResume(VBSyntax.ResumeStatementSyntax resumeStatement); +} diff --git a/CodeConverter/CSharp/OnError/LabelName.cs b/CodeConverter/CSharp/OnError/LabelName.cs new file mode 100644 index 000000000..f5bc0bd8d --- /dev/null +++ b/CodeConverter/CSharp/OnError/LabelName.cs @@ -0,0 +1,12 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// VB label names are case insensitive, so they're compared in a normalized form. +/// +internal static class LabelName +{ + public static string Normalize(string label) => label.ToLowerInvariant(); + + public static string Of(VBSyntax.LabelStatementSyntax label) => Normalize(label.LabelToken.Text); + public static string Of(VBSyntax.LabelSyntax label) => Normalize(label.LabelToken.Text); +} diff --git a/CodeConverter/CSharp/OnError/LocalHoisting.cs b/CodeConverter/CSharp/OnError/LocalHoisting.cs new file mode 100644 index 000000000..fd42a2de2 --- /dev/null +++ b/CodeConverter/CSharp/OnError/LocalHoisting.cs @@ -0,0 +1,63 @@ +using static Microsoft.CodeAnalysis.VisualBasic.VisualBasicExtensions; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Declares before a try the locals that are declared in it but used after it or in the handler. +/// +/// +/// See for how a declaration is split. Static locals already become fields, so are left alone. +/// +internal sealed class LocalHoisting +{ + private readonly OnErrorConversionContext _context; + private readonly HashSet _hoisted; + private readonly DeclarationSplitter _splitter; + + public LocalHoisting(OnErrorConversionContext context, OnErrorModel model, IEnumerable segments) + { + _context = context; + _splitter = new DeclarationSplitter(context.SemanticModel, context.CommonConversions); + _hoisted = new HashSet(segments.SelectMany(s => FindUsedOutside(model, s)), SymbolEqualityComparer.Default); + } + + public bool CanDeclareAll => _hoisted.All(DeclarationSplitter.CanSplit); + + /// The declarations that go before the first try, in order. + public List Declarations { get; } = new(); + + /// + /// Converts statements that will be in a try, adding to what must be declared before it. + /// + public async Task> ConvertAsync(IEnumerable statements) + { + var converted = new List(); + foreach (var statement in statements) { + var csStatements = await _context.ConvertAsync(new[] { statement }); + converted.AddRange(statement is VBSyntax.LocalDeclarationStatementSyntax declaration + ? _splitter.Split(declaration, csStatements, _hoisted.Contains, Declarations) + : csStatements); + } + return converted; + } + + private IEnumerable FindUsedOutside(OnErrorModel model, StatementRange segment) + { + var declared = model.Statements.Skip(segment.Start).Take(segment.End - segment.Start) + .OfType() + .Where(d => !d.Modifiers.Any(m => m.IsKind(VBasic.SyntaxKind.StaticKeyword))) + .SelectMany(d => d.Declarators.SelectMany(v => v.Names)) + .Select(n => _context.SemanticModel.GetDeclaredSymbol(n) as ILocalSymbol) + .Where(l => l != null) + .ToArray(); + if (!declared.Any()) return declared; + var names = new HashSet(declared.Select(l => l.Name), StringComparer.OrdinalIgnoreCase); + var referencedOutside = model.Statements.Where((_, i) => !segment.Contains(i)) + .SelectMany(s => s.DescendantNodes().OfType()) + .Where(i => names.Contains(i.Identifier.ValueText)) + .Select(i => _context.SemanticModel.GetSymbolInfo(i).Symbol) + .ToArray(); + return declared.Where(l => referencedOutside.Contains(l, SymbolEqualityComparer.Default)); + } +} diff --git a/CodeConverter/CSharp/OnError/MissingReturn.cs b/CodeConverter/CSharp/OnError/MissingReturn.cs new file mode 100644 index 000000000..2db389a83 --- /dev/null +++ b/CodeConverter/CSharp/OnError/MissingReturn.cs @@ -0,0 +1,25 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// VB's flow analysis says a method ending in Return can't reach its end, so the caller adds no final return, but a guarded return can fall through. +/// +internal static class MissingReturn +{ + public static IEnumerable Add(OnErrorConversionContext context, OnErrorModel model, StatementGuards guards, List statements) + { + return guards.GuardedAReturn ? Add(context, model, statements) : statements; + } + + /// + /// For emitters that know the end can be reached although VB's flow analysis says otherwise, e.g. a handler that falls off the end of the method but is only reached by an error. + /// + public static IEnumerable Add(OnErrorConversionContext context, OnErrorModel model, List statements) + { + var exit = context.Visitor.CreateMethodExitStatement(model.Statements.First()); + var endIsReachable = context.SemanticModel.AnalyzeControlFlow(model.Statements.First(), model.Statements.Last()).EndPointIsReachable; + var endsInExit = statements.LastOrDefault() is ReturnStatementSyntax or ThrowStatementSyntax; + return exit is ReturnStatementSyntax { Expression: not null } && !endIsReachable && !endsInExit ? statements.Append(exit) : statements; + } +} diff --git a/CodeConverter/CSharp/OnError/OnErrorConversionContext.cs b/CodeConverter/CSharp/OnError/OnErrorConversionContext.cs new file mode 100644 index 000000000..3060bfb39 --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorConversionContext.cs @@ -0,0 +1,45 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// What an emitter needs from the method body conversion. +/// +internal sealed record OnErrorConversionContext(VBasic.VisualBasicSyntaxNode MethodNode, SemanticModel SemanticModel, CommonConversions CommonConversions, + MethodBodyExecutableStatementVisitor Visitor, HashSet ExtraUsingDirectives) +{ + public async Task> ConvertAsync(IEnumerable statements) => + (await statements.SelectManyAsync(async s => (IEnumerable)await s.Accept(Visitor.CommentConvertingVisitor))).ToList(); + + /// + /// Converts the statements of a handler, keeping the comments of those that convert to nothing with the next statement (see ). + /// + /// Statements before these that aren't converted by themselves (the handler label), whose comments are kept with the first statement. + public async Task> ConvertHandlerAsync(IEnumerable statements, IEnumerable elidedBefore) + { + var converted = new List(); + var elided = elidedBefore.ToList(); + foreach (var statement in statements) { + var csStatements = (await statement.Accept(Visitor.CommentConvertingVisitor)).ToList(); + if (!csStatements.Any()) { + elided.Add(statement); + continue; + } + if (elided.Any()) csStatements[0] = ElidedStatementTrivia.PrependTo(csStatements[0], statement, elided); + elided.Clear(); + converted.AddRange(csStatements); + } + return converted; + } + + /// The type of the member being converted: the symbol enclosing the end of the method block is the member itself. + public INamedTypeSymbol ContainingType => + SemanticModel.GetEnclosingSymbol(MethodNode.Span.End - 1) is { } symbol ? symbol as INamedTypeSymbol ?? symbol.ContainingType : null; + + /// + /// Whether the shapes that declare local functions (a handler function, or a loop condition or Case expression moved out of the statement) can be used. + /// A local function in a struct can't use this (CS1673), so an instance member of a struct can't have one. + /// + public bool CanDeclareLocalFunctions => + SemanticModel.GetEnclosingSymbol(MethodNode.Span.End - 1) is not { IsStatic: false, ContainingType.TypeKind: TypeKind.Struct }; +} diff --git a/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs new file mode 100644 index 000000000..5c8403645 --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorMethodBodyConverter.cs @@ -0,0 +1,37 @@ +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Entry point for converting a method body that contains On Error or Resume. See README.md in this directory. +/// +/// +/// Each shape in gets an emitter here; until it has one, its methods keep the output of . +/// +internal static class OnErrorMethodBodyConverter +{ + /// The converted body, or null when the statements should be converted one by one as usual. + public static async Task> ConvertOrNullAsync(OnErrorConversionContext context, IReadOnlyCollection statements) + { + var model = OnErrorModel.Create(statements, context.SemanticModel); + var shape = OnErrorShapeSelector.Select(model, context.SemanticModel); + switch (shape.Kind) { + case OnErrorShapeKind.None: + return null; + case OnErrorShapeKind.ClearErrOnly: + context.Visitor.OnErrorStatementConverter = new ClearErrStatementConverter(await CreateErrStatementsAsync(context)); + return await context.ConvertAsync(statements); + case OnErrorShapeKind.Structured when StructuredShapeEmitter.CanEmit(context, model, shape.Structured): + return await new StructuredShapeEmitter(context, model, shape.Structured, await CreateErrStatementsAsync(context)).EmitAsync(); + case OnErrorShapeKind.ResumeNext or OnErrorShapeKind.Dynamic when ResumeNextShapeEmitter.CanEmit(model, context.SemanticModel, context.CanDeclareLocalFunctions): + return await new ResumeNextShapeEmitter(context, model, await CreateErrStatementsAsync(context)).EmitAsync(); + case OnErrorShapeKind.HandlerFunction when context.CanDeclareLocalFunctions && HandlerFunctionPlanner.TryPlan(model, context.SemanticModel) is { } plan: + return await new HandlerFunctionShapeEmitter(context, model, plan, await CreateErrStatementsAsync(context)).EmitAsync(); + default: + return await PendingShapeFallback.ConvertOrNullAsync(statements, context.ConvertAsync); + } + } + + private static async Task CreateErrStatementsAsync(OnErrorConversionContext context) => + new(await context.CommonConversions.ErrUsage.IsMaintainedInAsync(context.ContainingType), context.ExtraUsingDirectives); +} diff --git a/CodeConverter/CSharp/OnError/OnErrorModel.cs b/CodeConverter/CSharp/OnError/OnErrorModel.cs new file mode 100644 index 000000000..561b2454d --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorModel.cs @@ -0,0 +1,187 @@ +using VBasicSyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Analysis of a method body's unstructured error handling, made before any statement is converted. Produces no C# syntax. +/// +/// +/// Follows VB's lowering, where an On Error statement sets the active handler when it executes: +/// https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_UnstructuredExceptionHandling.vb +/// The active handler is only known per statement when every On Error statement is at method level and no jump crosses between the regions they start. +/// +internal sealed class OnErrorModel +{ + private readonly Dictionary _methodLevelIndexes; + private readonly IReadOnlyDictionary _labels; + + private OnErrorModel(IReadOnlyList statements, SemanticModel semanticModel) + { + Statements = statements; + _methodLevelIndexes = statements.Select((s, i) => (s, i)).ToDictionary(x => (SyntaxNode)x.s, x => x.i); + var descendants = statements.SelectMany(s => s.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax)).ToArray(); + OnErrorStatements = descendants.Where(IsOnErrorStatement).Cast().ToArray(); + ResumeStatements = descendants.OfType().ToArray(); + _labels = descendants.OfType().GroupBy(LabelName.Of).ToDictionary(g => g.Key, g => g.First()); + Jumps = descendants.Select(AsJumpOrNull).Where(j => j != null).ToArray(); + Handlers = OnErrorStatements.OfType() + .Where(s => s.IsKind(VBasicSyntaxKind.OnErrorGoToLabelStatement)) + .Select(s => LabelName.Of(s.Label)).Distinct() + .Select(label => CreateHandlerRegion(label, semanticModel)) + .ToArray(); + ActiveHandlers = GetStaticActiveHandlers(ignoreGoToZeroInHandlers: false); + IsDynamic = !AreActiveHandlersStatic(ignoreGoToZeroInHandlers: false); + HandlersOnlyTurnErrorHandlingOff = IsDynamic && AreActiveHandlersStatic(ignoreGoToZeroInHandlers: true); + } + + public static OnErrorModel Create(IReadOnlyCollection statements, SemanticModel semanticModel) => + new(statements.ToArray(), semanticModel); + + public static bool ContainsOnErrorOrResume(SyntaxNode node) => + node.DescendantNodes(n => n is not VBSyntax.LambdaExpressionSyntax).Any(n => IsOnErrorStatement(n) || n is VBSyntax.ResumeStatementSyntax); + + /// The method-level statements. + public IReadOnlyList Statements { get; } + + /// On Error GoTo and On Error Resume Next statements at any depth. + public IReadOnlyList OnErrorStatements { get; } + + public IReadOnlyList ResumeStatements { get; } + + /// GoTo L and Resume L at any depth. + public IReadOnlyList Jumps { get; } + + /// The handler in effect while each method-level statement runs, assuming is false. + public IReadOnlyList ActiveHandlers { get; } + + /// One region per label named by an On Error GoTo. + public IReadOnlyList Handlers { get; } + + /// The active handler can't be known per statement, so it needs recording at runtime. + public bool IsDynamic { get; } + + /// + /// only because a handler runs On Error GoTo 0. That turns off what the handler resumes to, which the structured shape doesn't protect anyway. + /// + public bool HandlersOnlyTurnErrorHandlingOff { get; } + + public bool HasOnErrorOrResume => OnErrorStatements.Any() || ResumeStatements.Any(); + + /// Index of the method-level statement that is or contains , or -1. + public int MethodLevelIndexOf(SyntaxNode node) => + node.AncestorsAndSelf().Select(a => _methodLevelIndexes.TryGetValue(a, out var i) ? i : -1).Where(i => i >= 0).DefaultIfEmpty(-1).First(); + + /// Index of the label's statement when it's at method level, otherwise -1. + public int MethodLevelIndexOfLabel(string label) => + _labels.TryGetValue(label, out var statement) && _methodLevelIndexes.TryGetValue(statement, out var i) ? i : -1; + + /// Index of the method-level statement containing the label, or -1 if there's no such label. + public int IndexContainingLabel(string label) => _labels.TryGetValue(label, out var statement) ? MethodLevelIndexOf(statement) : -1; + + /// The label as declared: C# labels are case sensitive. + public string LabelText(string label) => _labels.TryGetValue(label, out var statement) ? statement.LabelToken.Text : label; + + public HandlerRegion HandlerContaining(int statementIndex) => Handlers.FirstOrDefault(h => h.Contains(statementIndex)); + + public static bool IsOnErrorStatement(SyntaxNode node) => node is VBSyntax.OnErrorGoToStatementSyntax or VBSyntax.OnErrorResumeNextStatementSyntax; + + /// + /// Whether execution can continue past the statement, if it starts. Jumps and exits are decided by their kind, VB's flow analysis decides the rest. + /// Flow analysis doesn't know that On Error GoTo H can reach H, so for a handler's statements it can only say they're unreachable: assume they can complete. + /// + public static bool EndPointIsReachable(VBSyntax.StatementSyntax statement, SemanticModel semanticModel) + { + switch (statement) { + case VBSyntax.GoToStatementSyntax or VBSyntax.ResumeStatementSyntax or VBSyntax.ReturnStatementSyntax or VBSyntax.ThrowStatementSyntax: + case VBSyntax.ExitStatementSyntax exit when IsMethodExit(exit): + case VBSyntax.StopOrEndStatementSyntax { StopOrEndKeyword.RawKind: (int)VBasicSyntaxKind.EndKeyword }: + return false; + case VBSyntax.LabelStatementSyntax or VBSyntax.ExitStatementSyntax or VBSyntax.OnErrorGoToStatementSyntax or VBSyntax.OnErrorResumeNextStatementSyntax: + return true; + default: + var flow = semanticModel.AnalyzeControlFlow(statement); + return !flow.StartPointIsReachable || flow.EndPointIsReachable; + } + } + + public static bool IsMethodExit(VBSyntax.ExitStatementSyntax exit) => + VBasic.VisualBasicExtensions.Kind(exit.BlockKeyword) is VBasicSyntaxKind.SubKeyword or VBasicSyntaxKind.FunctionKeyword or VBasicSyntaxKind.PropertyKeyword; + + private Jump AsJumpOrNull(SyntaxNode node) => node switch { + VBSyntax.GoToStatementSyntax goTo => new Jump(goTo, LabelName.Of(goTo.Label)), + VBSyntax.ResumeStatementSyntax { Label: { } label } resume when resume.IsKind(VBasicSyntaxKind.ResumeLabelStatement) => new Jump(resume, LabelName.Of(label)), + _ => null + }; + + /// + /// Leaves out the effect of On Error GoTo 0 inside a handler, which the linear scan would otherwise carry on to the statements after the handler, although they are only reached by jumping. + /// + private IReadOnlyList GetStaticActiveHandlers(bool ignoreGoToZeroInHandlers) + { + var activeHandlers = new List(); + var current = ActiveHandler.None; + foreach (var (statement, index) in Statements.Select((s, i) => (s, i))) { + activeHandlers.Add(current); + current = statement switch { + VBSyntax.OnErrorResumeNextStatementSyntax => ActiveHandler.ResumeNext, + VBSyntax.OnErrorGoToStatementSyntax s when s.IsKind(VBasicSyntaxKind.OnErrorGoToLabelStatement) => ActiveHandler.ForLabel(s.Label.LabelToken.Text), + VBSyntax.OnErrorGoToStatementSyntax s when s.IsKind(VBasicSyntaxKind.OnErrorGoToZeroStatement) && !(ignoreGoToZeroInHandlers && HandlerContaining(index) != null) => ActiveHandler.None, + _ => current + }; + } + return activeHandlers; + } + + /// + /// A handler's statements run with that handler still active, whatever their position. On Error inside one changes what's active wherever it resumes to. + /// + private bool AreActiveHandlersStatic(bool ignoreGoToZeroInHandlers) + { + bool IgnoredInHandler(VBSyntax.StatementSyntax s) => ignoreGoToZeroInHandlers && s.IsKind(VBasicSyntaxKind.OnErrorGoToZeroStatement) && HandlerContaining(MethodLevelIndexOf(s)) != null; + if (OnErrorStatements.Any(s => !_methodLevelIndexes.ContainsKey(s) && !IgnoredInHandler(s))) return false; + if (OnErrorStatements.Any(s => HandlerContaining(MethodLevelIndexOf(s)) != null && !IgnoredInHandler(s))) return false; + var activeHandlers = ignoreGoToZeroInHandlers ? GetStaticActiveHandlers(ignoreGoToZeroInHandlers: true) : ActiveHandlers; + return Jumps.All(j => { + var sourceIndex = MethodLevelIndexOf(j.Statement); + var targetIndex = IndexContainingLabel(j.TargetLabel); + if (targetIndex < 0) return true; + var sourceHandler = HandlerContaining(sourceIndex) is { } handler ? ActiveHandler.ForLabel(handler.Label) : activeHandlers[sourceIndex]; + return sourceHandler == activeHandlers[targetIndex]; + }); + } + + private HandlerRegion CreateHandlerRegion(string label, SemanticModel semanticModel) + { + var labelIndex = MethodLevelIndexOfLabel(label); + if (labelIndex < 0) return new HandlerRegion(label, -1, -1, Array.Empty()); + + var endIndex = Enumerable.Range(labelIndex + 1, Statements.Count - labelIndex - 1) + .Where(i => Statements[i] is VBSyntax.LabelStatementSyntax).DefaultIfEmpty(Statements.Count).First(); + var regionStatements = Statements.Skip(labelIndex + 1).Take(endIndex - labelIndex - 1).ToArray(); + var regionLabels = new HashSet(regionStatements + .SelectMany(s => s.DescendantNodesAndSelf().OfType()).Select(LabelName.Of)); + + var exits = regionStatements.SelectMany(s => s.DescendantNodesAndSelf(n => n is not VBSyntax.LambdaExpressionSyntax)) + .Select(n => AsExitOrNull(n, regionLabels)) + .Where(e => e != null) + .ToList(); + if (!regionStatements.Any() || EndPointIsReachable(regionStatements.Last(), semanticModel)) { + exits.Add(endIndex == Statements.Count + ? new HandlerExit(HandlerExitKind.FallsOffEnd) + : new HandlerExit(HandlerExitKind.FallsIntoLabel, LabelName.Of((VBSyntax.LabelStatementSyntax)Statements[endIndex]))); + } + return new HandlerRegion(label, labelIndex, endIndex, exits.Distinct().ToArray()); + } + + private static HandlerExit AsExitOrNull(SyntaxNode node, HashSet regionLabels) => node switch { + VBSyntax.ResumeStatementSyntax r when r.IsKind(VBasicSyntaxKind.ResumeNextStatement) => new HandlerExit(HandlerExitKind.ResumeNext), + VBSyntax.ResumeStatementSyntax r when r.IsKind(VBasicSyntaxKind.ResumeLabelStatement) => new HandlerExit(HandlerExitKind.ResumeLabel, LabelName.Of(r.Label)), + VBSyntax.ResumeStatementSyntax => new HandlerExit(HandlerExitKind.Resume), + VBSyntax.GoToStatementSyntax g when !regionLabels.Contains(LabelName.Of(g.Label)) => new HandlerExit(HandlerExitKind.GoToLabel, LabelName.Of(g.Label)), + VBSyntax.ExitStatementSyntax e when IsMethodExit(e) => new HandlerExit(HandlerExitKind.ExitMethod), + VBSyntax.ReturnStatementSyntax => new HandlerExit(HandlerExitKind.ExitMethod), + _ => null + }; + + public sealed record Jump(VBSyntax.StatementSyntax Statement, string TargetLabel); +} diff --git a/CodeConverter/CSharp/OnError/OnErrorShape.cs b/CodeConverter/CSharp/OnError/OnErrorShape.cs new file mode 100644 index 000000000..d2be3630a --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorShape.cs @@ -0,0 +1,23 @@ +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// The output shapes from README.md, simplest first. +/// +internal enum OnErrorShapeKind +{ + /// No On Error or Resume: convert statements as usual. + None, + Structured, + ResumeNext, + HandlerFunction, + Dynamic, + /// Only On Error GoTo 0: no handler is ever active, so it only clears Err and the statements are converted as usual. + ClearErrOnly, + Fallback +} + +/// Set when is . +internal sealed record OnErrorShape(OnErrorShapeKind Kind, StructuredPlan Structured = null) +{ + public static OnErrorShape Of(OnErrorShapeKind kind) => new(kind); +} diff --git a/CodeConverter/CSharp/OnError/OnErrorShapeSelector.cs b/CodeConverter/CSharp/OnError/OnErrorShapeSelector.cs new file mode 100644 index 000000000..724752554 --- /dev/null +++ b/CodeConverter/CSharp/OnError/OnErrorShapeSelector.cs @@ -0,0 +1,42 @@ +using VBasicSyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Chooses the simplest output shape (README.md "Output shapes") that is right for the method. +/// +internal static class OnErrorShapeSelector +{ + public static OnErrorShape Select(OnErrorModel model, SemanticModel semanticModel) + { + if (!model.HasOnErrorOrResume) return OnErrorShape.Of(OnErrorShapeKind.None); + if (model.OnErrorStatements.Any(s => s.IsKind(VBasicSyntaxKind.OnErrorGoToMinusOneStatement))) return OnErrorShape.Of(OnErrorShapeKind.Fallback); + if (model.OnErrorStatements.All(s => s.IsKind(VBasicSyntaxKind.OnErrorGoToZeroStatement)) && !model.ResumeStatements.Any()) return OnErrorShape.Of(OnErrorShapeKind.ClearErrOnly); + if (model.HandlersOnlyTurnErrorHandlingOff && model.OnErrorStatements.All(s => s is not VBSyntax.OnErrorResumeNextStatementSyntax) && + StructuredPlanner.TryPlan(model, semanticModel) is { } planWithoutTheGoToZero) { + return new OnErrorShape(OnErrorShapeKind.Structured, planWithoutTheGoToZero); + } + if (model.IsDynamic) return OnErrorShape.Of(OnErrorShapeKind.Dynamic); + if (model.Handlers.Any(h => !h.IsMethodLevel) || model.ResumeStatements.Any(r => model.HandlerContaining(model.MethodLevelIndexOf(r)) == null)) { + return OnErrorShape.Of(OnErrorShapeKind.Fallback); + } + if (model.ActiveHandlers.Contains(ActiveHandler.ResumeNext) || model.OnErrorStatements.Any(s => s is VBSyntax.OnErrorResumeNextStatementSyntax)) { + return OnErrorShape.Of(OnErrorShapeKind.ResumeNext); + } + if (StructuredPlanner.TryPlan(model, semanticModel) is { } plan) return new OnErrorShape(OnErrorShapeKind.Structured, plan); + return model.Handlers.Any(h => ResumesIntoCoveredStatements(model, h)) ? OnErrorShape.Of(OnErrorShapeKind.HandlerFunction) : OnErrorShape.Of(OnErrorShapeKind.Fallback); + } + + /// + /// Resuming into the statements a handler covers needs a way back into the middle of them, which only a handler called from each statement's catch gives. + /// Several handlers or On Error GoTo statements are also left to that shape. + /// + private static bool ResumesIntoCoveredStatements(OnErrorModel model, HandlerRegion handler) + { + var onErrorIndexes = model.OnErrorStatements.Select(model.MethodLevelIndexOf).ToArray(); + return model.Handlers.Count > 1 || handler.Exits.Any(e => + e.Kind is HandlerExitKind.Resume or HandlerExitKind.ResumeNext || + e.Kind is HandlerExitKind.ResumeLabel or HandlerExitKind.GoToLabel && model.MethodLevelIndexOfLabel(e.TargetLabel) is var target && target >= 0 && + target <= onErrorIndexes.Max()); + } +} diff --git a/CodeConverter/CSharp/OnError/PendingShapeFallback.cs b/CodeConverter/CSharp/OnError/PendingShapeFallback.cs new file mode 100644 index 000000000..cfce3c86f --- /dev/null +++ b/CodeConverter/CSharp/OnError/PendingShapeFallback.cs @@ -0,0 +1,44 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ICSharpCode.CodeConverter.CSharp.OnError; + +/// +/// Output for methods whose shape has no emitter yet: one try/catch when the method has exactly one label and one On Error GoTo, +/// otherwise null so the statements are converted one by one (each unconvertible statement gets an #error). +/// +/// +/// The try/catch ignores how the handler leaves, so it's only right for some methods. It's kept so methods that aren't handled by a shape emitter yet don't change output. +/// See https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/on-error-statement +/// +internal static class PendingShapeFallback +{ + public static async Task> ConvertOrNullAsync(IReadOnlyCollection statements, + Func, Task>> convertStatementsAsync) + { + var onlyIdentifierLabel = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.LabelStatement)); + var onlyOnErrorGotoStatement = statements.OnlyOrDefault(s => s.IsKind(VBasic.SyntaxKind.OnErrorGoToLabelStatement)); + if (onlyIdentifierLabel == null || onlyOnErrorGotoStatement == null) return null; + + var statementsList = statements.ToList(); + var onlyIdentifierLabelIndex = statementsList.IndexOf(onlyIdentifierLabel); + var onlyOnErrorGotoStatementIndex = statementsList.IndexOf(onlyOnErrorGotoStatement); + if (onlyOnErrorGotoStatementIndex >= onlyIdentifierLabelIndex) return null; + + var beforeStatements = await convertStatementsAsync(statements.Take(onlyOnErrorGotoStatementIndex)); + var tryBlockStatements = await convertStatementsAsync(statements.Take(onlyIdentifierLabelIndex).Skip(onlyOnErrorGotoStatementIndex + 1)); + var tryBlock = SyntaxFactory.Block(tryBlockStatements); + var afterStatements = await convertStatementsAsync(statements.Skip(onlyIdentifierLabelIndex + 1)); + + var catchClauseSyntax = SyntaxFactory.CatchClause(); + + // Default to putting the statements after the catch block in case logic falls through, but if the last statement is a return, put them inside the catch block for neatness. + if (tryBlockStatements.LastOrDefault().IsKind(SyntaxKind.ReturnStatement)) { + catchClauseSyntax = catchClauseSyntax.WithBlock(SyntaxFactory.Block(afterStatements)); + afterStatements = new List(); + } + + var tryStatement = SyntaxFactory.TryStatement(SyntaxFactory.SingletonList(catchClauseSyntax)).WithBlock(tryBlock); + return beforeStatements.Append(tryStatement).Concat(afterStatements).ToList(); + } +} diff --git a/CodeConverter/CSharp/OnError/README.md b/CodeConverter/CSharp/OnError/README.md new file mode 100644 index 000000000..ae1b87027 --- /dev/null +++ b/CodeConverter/CSharp/OnError/README.md @@ -0,0 +1,247 @@ +# VB → C# unstructured error handling (`On Error`, `Resume`) — design + +Status: the model, shape selection, `Err` usage, shapes 1 (structured), 2 (resume next), 3 (handler function) and 4 (dynamic, for resume next only) are implemented. What the emitters can't express keeps the previous output (`PendingShapeFallback`: one `try`/`catch` when there's exactly one label and one `On Error GoTo`, otherwise statement by statement with `#error`). Tracks [icsharpcode/CodeConverter#426](https://github.com/icsharpcode/CodeConverter/issues/426). + +Sources: +* VB: [`LocalRewriter_UnstructuredExceptionHandling.vb`](https://github.com/dotnet/roslyn/blob/main/src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_UnstructuredExceptionHandling.vb) (the lowering, with pseudo-code of the emitted method), the `RegisterUnstructuredExceptionHandlingResumeTarget` calls in the sibling `LocalRewriter_*.vb` files (which statements are resume points), and the [On Error](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/on-error-statement) / [Resume](https://learn.microsoft.com/dotnet/visual-basic/language-reference/statements/resume-statement) docs. +* C#: [the `goto` statement](https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/statements#13104-the-goto-statement) (a label is only in scope within its block, so no jumping into a block or a `try`) and [exception filters](https://learn.microsoft.com/dotnet/csharp/language-reference/statements/exception-handling-statements#exception-filters). +* Every behaviour in "Requirements" was checked by compiling and running VB (.NET 10). Every C# shape in "Output shapes" was hand-written, run, and compared with the VB output, except where marked *not spiked*. + +## Requirements + +### VB + +A method containing `On Error` or `Resume` is compiled as one `Try` around the whole body, with three hidden locals: + +| Local | Meaning | +|---|---| +| active handler | none, resume-next, or one of the method's handler labels. Set by each `On Error` statement **when it executes**. | +| resume target | non-zero while "in a handler", i.e. from an error being caught until `Resume*` or `On Error GoTo -1`. | +| current statement | index of the statement being executed, only tracked if the method contains `Resume` / `Resume Next` / `On Error Resume Next`. | + +The single catch is `Catch ex As Exception When activeHandler <> 0 And resumeTarget = 0`. Consequences: + +* The active handler is runtime state, not lexical: `If flag Then On Error Resume Next` changes how every later statement behaves. +* Any exception is caught, including ones thrown deep inside callees. +* An error while in a handler fails the filter and propagates to the caller. As it is a filter, nothing is unwound first. +* The resume point is the innermost statement. Each declarator of `Dim a = F(), b = G()` is its own resume point. After `If c Then Boom()` fails, `Resume` re-runs `Boom()` without re-testing `c`. +* A failing condition resumes at the next resume point in source order, which is usually **inside** the block: + + | Failing expression | `Resume Next` continues at | + |---|---| + | `If` / `ElseIf` condition | first statement of that branch | + | `While` / `Do While` condition (tested at the top) | first statement of the body | + | `Loop Until` / `Loop While` condition (tested at the bottom) | after the loop | + | `Select Case` expression | after `End Select` | + | `Case` expression | first statement of that case | + | `For` start value, `For Each` collection | the body, once, with a default loop variable; then after the loop | + +* `Using`, `SyncLock` and any other statement lowered to a compiler-generated `Try` is a single resume point: an error inside resumes after the block, and the dispose/unlock runs. `On Error` can't appear inside them, in a method with `Try`, or in lambdas, iterators and async methods. +* `Err`: + * set on every caught error; + * cleared by every `On Error` statement and every `Resume*` statement; + * cleared on leaving the method only if it is still in a handler. So after `On Error Resume Next` swallows an error, `Err` stays set, even after the method returns. +* Code that runs into a handler label without an error is ordinary code: an error in it is caught and enters the handler from the top. This includes cleanup code reached by `Resume Cleanup` while the same handler is still active: if the cleanup fails, the handler runs again, resumes to the cleanup again, and can loop forever. + +### C# + +* `goto` can leave a block, a `try` or a `catch`, but can't enter one. So a method-level catch can never resume in the middle of a loop or `If`. +* Iterators and async methods are compiled to state machines that can re-enter nested blocks, but not after an exception: an exception leaving `MoveNext` finishes the iterator, and `yield` isn't allowed in a `try` that has a `catch`. +* `catch (Exception ex) when (flag)` matches VB's filter, including not unwinding when it's false. +* Local functions can capture locals, but not `ref`/`out` parameters. +* Locals are block scoped and must be definitely assigned. VB locals are method-lifetime and zero-initialised, so declaring them earlier as `= default` is exact. + +## Approach + +Every idea that catches at method level needs to jump back in, which needs the whole body flattened to a `switch` in a loop. Instead, **catch at the statement that fails**. Then nothing needs to jump inwards: + +| VB | C#, inside the failing statement's own `catch` | +|---|---| +| `Resume Next` | leave the catch | +| `Resume` | `goto` a label directly before that `try` (same block) | +| `Resume L` / `GoTo L`, `L` at method level | `goto L` (out of a catch is legal) | +| handler code | a local function called from the catch. An exception in it propagates, like VB's "in a handler". | +| `Exit Sub` / `Return` in the handler | the local function returns "exit", the catch returns | + +The method keeps its structure, loops stay loops, and the cost is proportional to how much of the method is covered by a resuming handler. + +### Model + +A pass over the method body builds a model before any statement is converted, so the statement visitors don't each need to know the rules: + +* **Active handler per statement**: none, resume-next, or a handler label. Static when every `On Error` statement is a direct child of the method body and no label/`GoTo` crosses the regions between them. Otherwise *dynamic*: a local records the handler and the catches filter on it. +* **Handler regions**: for each handler label, the statements from the label to where control leaves, and the set of ways it leaves: `Resume Next`, `Resume`, `Resume L`, `GoTo L`, exit, falls off the end. +* **Guards**: the resume points that have an active handler (per the table in "VB" above). +* **Hoisted locals**: locals declared within a guard and used outside it. +* **`Err` is used**: see below. + +### Output shapes + +Chosen per method, simplest first. `…` is where the `Err` calls go when `Err` is used. + +1. **Structured.** One `On Error GoTo H` covering a run of method-level statements, `H` at method level, and the handler never resumes into the covered statements (it exits, falls off the end, or does `Resume L`/`GoTo L` to a method-level label after the covered statements or after the handler). + + ```csharp + try + { + // covered statements + } + catch (Exception ex) + { + // handler + } + // statements from L onwards + ``` + When the handler leaves to a label after itself (`Resume Done` / `GoTo Done`, with `Done:` following the handler), the statements from the end of the handler's region on come after the `try`, unprotected, and the handler's jump to them is a fall through. Like the code after a resume label, they are only protected (segmented form) when the handler is written for re-entry, which isn't supported for a label after the handler: that keeps the fallback, as does a jump into a nested block of those statements from outside. + This is the existing conversion, generalised, with locals hoisted (fixes the existing `RemainingScopeIssueCharacterizationAsync` output). When the handler is written for re-entry, the statements after `L` get their own `try` too (see "Secondary errors"). + +2. **Resume next.** The active handler is resume-next. Each guard becomes + + ```csharp + try { Statement(); } catch { } + ``` + * `If` condition: `bool cond = true; try { cond = …; } catch { }` then `if (cond)`. `ElseIf` chains become nested `if`/`else` so each condition has somewhere to go. + * Loop condition: a local function, so the loop stays a loop: `bool Cond() { try { return …; } catch { return true; } }` and `while (Cond())`. Bottom-tested conditions return whichever value leaves the loop. + * `Using`, `SyncLock`, `Select Case` and `For`/`For Each`: one guard around the whole statement, with the statements inside guarded individually where VB makes them resume points (not inside `Using`/`SyncLock`). A failing header skips the block. + * `Case` expressions: a failing one enters that case, and the cases after it aren't tried (spiked: `Case 2` / `Case Boom()` / `Case Else` on 9 runs the body of the `Boom()` case). The `when` condition of each label whose expressions can fail moves into a local function that returns true if evaluating it fails (`bool CaseMatches() { try { return selectValue == Boom(); } catch { return true; } }`), so the cases before it are still tried and the ones after it are not. The pattern variable is replaced by a local holding the `Select` expression. Evaluating every case up front would run side effects VB wouldn't. A failing `Select` expression skips the whole statement, as before. + * A `Dim` inside a loop whose initializer can fail is declared (`= default`) before the outermost loop, because a VB local keeps its value from the previous iteration when the initializer fails. + * A statement is only guarded when it can fail (`ThrowAnalysis`): constants, locals and parameters of primitive types, their comparisons, integer `+`, `-` and `*` (and `+=`, `-=`, `*=`) over locals and constants of one type (the output is unchecked, so overflow wraps; `Decimal`, `Double`, `Single`, `/`, `\`, `Mod` and `^` still count as failing), creating a lambda (its body doesn't run), `Exit`, `GoTo` and labels aren't. Every `Dim` gets `= default` so that skipping its assignment still compiles. + * `With` is guarded like a `Select` whose expression fails. A loop whose condition can fail, or a `Select` with a `Case` expression that can fail, isn't expressible when it reads a `ref`/`out` parameter (a local function can't capture it): the method keeps the fallback. + +3. **Handler function.** `On Error GoTo H` where the handler resumes into the covered statements. The handler becomes a local function and each guard calls it: + + ```csharp + void H() { /* handler */ } + try { Statement(); } catch { H(); } + ``` + If the handler leaves in two ways, it returns a `bool` and its name says what `true` means (`Retries`: run the statement again; `Exits`: leave the method): + + ```csharp + bool FailedRetries() { /* handler */ } + s3: try { Statement(); } catch { if (FailedRetries()) goto s3; } + ``` + Labels are only emitted for `Resume`. `Return expr` in the handler of a function is assigned to the return variable (or a `result` local) that the caller returns. A handler with three ways out, `Resume L` or `GoTo L` keeps the fallback, as does a method that reaches the handler label without an error (an error inside the inline run would resume after the call, not after the failing statement). + +4. **Dynamic.** The active handler isn't statically known. Same guards, filtered: `catch (Exception) when (resumeNext)`, with `resumeNext` assigned where the `On Error` statements were. Only implemented when the only handlers are resume-next and none; with handler labels (an `int` flag) the fallback stays. + + A method whose only `On Error` statements are `On Error GoTo 0` (no `Resume`) never has a handler active, so there is no shape: each converts to `ProjectData.ClearProjectError()` when `Err` is maintained (VB clears `Err` there, checked by running it), otherwise to nothing, and the statements are converted as usual. + +5. **Fallback.** Anything else keeps today's behaviour, statement-by-statement conversion plus `#error`: + * the handler jumps to a label inside a nested block; + * `On Error GoTo -1`; + * a handler that falls through into a label, without a `GoTo` or `Resume` to it, when the covered code also jumps to that label (`H:` handler, `Done:` next, `GoTo Done` in the covered code): the label would be reached from the `try` and from the `catch`; + * a `Resume Next` handler (`On Error GoTo Failed` ... `Failed: Resume Next`) around a `For Each` (or any loop, `Using`, `SyncLock`, `Select Case`) whose body statements can fail. A common legacy shape, but every body statement needs its own guard inside the guarded statement, and the handler's own error would be caught again by the outer guard where VB lets it propagate. `On Error Resume Next` in the same place is converted (shape 2); + * a handler that resumes to a label (`Resume Retry`) when the code after the label can fail, with no re-entry guard (see "Secondary errors"), and either nothing before the label can fail or the handler runs `On Error GoTo 0` (a one-shot retry): the first error would come from code the plain form leaves unprotected; + * a handler local function would need to capture a `ref`/`out` parameter; + * a local that has to be split into a declaration and an assignment (a guarded `Dim`, or one the handler or later code uses) has a type that can't be written: an anonymous type, or a lambda's anonymous delegate type. `var q = default;` doesn't compile, and declaring it later would put it out of scope; + * `On Error Resume Next` and `On Error GoTo