From 668f46f6632e027e89a35291a5f902af0e1f3d4a Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Thu, 25 Oct 2018 01:00:38 +0200 Subject: [PATCH 001/107] Extract Rewrite out of the IModuleRewriter The extraction is performed into the new IExecutableModuleRewriter, which extends IModuleRewriter. This change allows to restrict the access to triggering the actual application of the changes. This will be important in the next commits. It was necessary to change some other functionality using the rewriter with dynamic arguments in order to avoid runtime binder exceptions. (It does not see the interfaces that get extended.) The first change was to the (I)ModuleRewriter itself. I added a new overload both for Replace and Remove taking an IParseTree. This is implemented using pattern matching to prefer execution for the ITerminalNode and then falling back to ParserRuleContext, which is always a valid downcast for IParseTree. This allows to avoid using dynamic to prefer the calls with ITerminalNode. The other changes were explicit casts of the second argument of Replace, which only accepts strings anyway and a change from dynamic to patterns matching in a quickfix. --- .../AccessSheetUsingCodeNameQuickFix.cs | 4 +-- .../QuickFixes/AddStepOneQuickFix.cs | 2 +- ...gnedByValParameterMakeLocalCopyQuickFix.cs | 4 +-- .../QuickFixes/ChangeIntegerToLongQuickFix.cs | 2 +- .../RemoveDuplicatedAnnotationQuickFix.cs | 2 +- .../RemoveEmptyElseBlockQuickFix.cs | 2 +- .../QuickFixes/RemoveEmptyIfBlockQuickFix.cs | 16 ++++----- .../RemoveExplicitByRefModifierQuickFix.cs | 2 +- .../QuickFixes/RemoveStepOneQuickFix.cs | 2 +- .../SpecifyExplicitByRefModifierQuickFix.cs | 2 +- .../SplitMultipleDeclarationsQuickFix.cs | 19 +++++++++-- .../Rewriter/IExecutableModuleRewriter.cs | 10 ++++++ .../Rewriter/IModuleRewriter.cs | 19 +++++++---- .../Rewriter/IModuleRewriterFactory.cs | 4 +-- Rubberduck.Parsing/Rewriter/ModuleRewriter.cs | 34 ++++++++++++++++++- .../Rewriter/ModuleRewriterFactory.cs | 4 +-- Rubberduck.Parsing/VBA/ModuleState.cs | 8 ++--- .../VBA/Parsing/IModuleParser.cs | 8 ++--- .../VBA/RubberduckParserState.cs | 12 +++---- .../EncapsulateFieldRefactoring.cs | 6 ++-- .../ExtractInterfaceRefactoring.cs | 2 +- .../ImplementInterfaceRefactoring.cs | 6 ++-- .../IntroduceFieldRefactoring.cs | 4 +-- .../IntroduceParameterRefactoring.cs | 2 +- .../MoveCloserToUsageRefactoring.cs | 2 +- .../RemoveParametersRefactoring.cs | 8 +++-- .../ReorderParametersRefactoring.cs | 2 +- 27 files changed, 126 insertions(+), 62 deletions(-) create mode 100644 Rubberduck.Parsing/Rewriter/IExecutableModuleRewriter.cs diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs index 52c5864421..ad08179cc5 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs @@ -35,7 +35,7 @@ public override void Fix(IInspectionResult result) var indexExprContext = referenceResult.Context.Parent.Parent as VBAParser.IndexExprContext ?? referenceResult.Context.Parent as VBAParser.IndexExprContext; - rewriter.Replace(indexExprContext, referenceResult.Properties.CodeName); + rewriter.Replace(indexExprContext, (string)referenceResult.Properties.CodeName); } else { @@ -67,7 +67,7 @@ public override void Fix(IInspectionResult result) foreach (var reference in sheetDeclaration.References) { - rewriter.Replace(reference.Context, referenceResult.Properties.CodeName); + rewriter.Replace(reference.Context, (string)referenceResult.Properties.CodeName); } rewriter.Remove(setStatement); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs index 11a7f3618c..428ec78c89 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs @@ -31,7 +31,7 @@ public override string Description(IInspectionResult result) public override void Fix(IInspectionResult result) { - IModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + IExecutableModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); ForNextStmtContext context = result.Context as ForNextStmtContext; int toExpressionEnd = this.GetToExpressionEnd(context); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs index 2446a71c7f..aa47035ae9 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs @@ -103,7 +103,7 @@ private bool IsValidVariableName(string variableName) && !IsNameCollision(variableName); } - private void ReplaceAssignedByValParameterReferences(IModuleRewriter rewriter, Declaration target, string localIdentifier) + private void ReplaceAssignedByValParameterReferences(IExecutableModuleRewriter rewriter, Declaration target, string localIdentifier) { foreach (var identifierReference in target.References) { @@ -111,7 +111,7 @@ private void ReplaceAssignedByValParameterReferences(IModuleRewriter rewriter, D } } - private void InsertLocalVariableDeclarationAndAssignment(IModuleRewriter rewriter, Declaration target, string localIdentifier) + private void InsertLocalVariableDeclarationAndAssignment(IExecutableModuleRewriter rewriter, Declaration target, string localIdentifier) { var localVariableDeclaration = $"{Tokens.Dim} {localIdentifier} {Tokens.As} {target.AsTypeName}"; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs index ffcb191e1d..1ebcf98399 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs @@ -178,7 +178,7 @@ private static int GetParameterIndex(VBAParser.ArgContext context) return Array.IndexOf(((VBAParser.ArgListContext)context.Parent).arg().ToArray(), context); } - private static void ReplaceTypeHint(RuleContext context, IModuleRewriter rewriter) + private static void ReplaceTypeHint(RuleContext context, IExecutableModuleRewriter rewriter) { var typeHintContext = ((ParserRuleContext)context).GetDescendent(); rewriter.Replace(typeHintContext, "&"); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs index 929f2b3d79..508759ee69 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs @@ -64,7 +64,7 @@ public override string Description(IInspectionResult result) => public override bool CanFixInProject => true; private static void RemoveAnnotationMarker(VBAParser.AnnotationListContext annotationList, - IAnnotation annotation, IModuleRewriter rewriter) + IAnnotation annotation, IExecutableModuleRewriter rewriter) { var index = Array.IndexOf(annotationList.annotation(), annotation.Context); rewriter.Remove(annotationList.AT(index)); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs index 8d39887e7f..2968a5b88b 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs @@ -25,7 +25,7 @@ public override void Fix(IInspectionResult result) UpdateContext((dynamic)result.Context, rewriter); } - private void UpdateContext(VBAParser.ElseBlockContext context, IModuleRewriter rewriter) + private void UpdateContext(VBAParser.ElseBlockContext context, IExecutableModuleRewriter rewriter) { var elseBlock = context.block(); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs index 6760504a19..f928ecb161 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs @@ -28,7 +28,7 @@ public override void Fix(IInspectionResult result) UpdateContext((dynamic)result.Context, rewriter); } - private void UpdateContext(VBAParser.IfStmtContext context, IModuleRewriter rewriter) + private void UpdateContext(VBAParser.IfStmtContext context, IExecutableModuleRewriter rewriter) { var elseBlock = context.elseBlock(); var elseIfBlock = context.elseIfBlock().FirstOrDefault(); @@ -63,7 +63,7 @@ private void UpdateContext(VBAParser.IfStmtContext context, IModuleRewriter rewr } } - private void UpdateContext(VBAParser.IfWithEmptyThenContext context, IModuleRewriter rewriter) + private void UpdateContext(VBAParser.IfWithEmptyThenContext context, IExecutableModuleRewriter rewriter) { var elseClause = context.singleLineElseClause(); if (context.singleLineElseClause().whiteSpace() != null) @@ -79,7 +79,7 @@ private void UpdateContext(VBAParser.IfWithEmptyThenContext context, IModuleRewr UpdateCondition((dynamic)context.booleanExpression().children[0], rewriter); } - private void UpdateContext(VBAParser.ElseIfBlockContext context, IModuleRewriter rewriter) + private void UpdateContext(VBAParser.ElseIfBlockContext context, IExecutableModuleRewriter rewriter) { if (BlockHasDeclaration(context.block())) { @@ -89,7 +89,7 @@ private void UpdateContext(VBAParser.ElseIfBlockContext context, IModuleRewriter rewriter.Remove(context); } - private void UpdateCondition(VBAParser.RelationalOpContext condition, IModuleRewriter rewriter) + private void UpdateCondition(VBAParser.RelationalOpContext condition, IExecutableModuleRewriter rewriter) { if (condition.EQ() != null) { @@ -121,7 +121,7 @@ private void UpdateCondition(VBAParser.RelationalOpContext condition, IModuleRew } } - private void UpdateCondition(VBAParser.LogicalNotOpContext condition, IModuleRewriter rewriter) + private void UpdateCondition(VBAParser.LogicalNotOpContext condition, IExecutableModuleRewriter rewriter) { if (condition.whiteSpace() != null) { @@ -133,17 +133,17 @@ private void UpdateCondition(VBAParser.LogicalNotOpContext condition, IModuleRew } } - private void UpdateCondition(VBAParser.LogicalAndOpContext condition, IModuleRewriter rewriter) + private void UpdateCondition(VBAParser.LogicalAndOpContext condition, IExecutableModuleRewriter rewriter) { rewriter.Replace(condition.AND(), "Or"); } - private void UpdateCondition(VBAParser.LogicalOrOpContext condition, IModuleRewriter rewriter) + private void UpdateCondition(VBAParser.LogicalOrOpContext condition, IExecutableModuleRewriter rewriter) { rewriter.Replace(condition.OR(), "And"); } - private void UpdateCondition(ParserRuleContext condition, IModuleRewriter rewriter) + private void UpdateCondition(ParserRuleContext condition, IExecutableModuleRewriter rewriter) { if (condition.GetText().Contains(' ')) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs index f2cba020fc..66a0a0efcb 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs @@ -69,7 +69,7 @@ private static int GetParameterIndex(VBAParser.ArgContext context) return Array.IndexOf(((VBAParser.ArgListContext)context.Parent).arg().ToArray(), context); } - private static void RemoveByRefIdentifier(IModuleRewriter rewriter, VBAParser.ArgContext context) + private static void RemoveByRefIdentifier(IExecutableModuleRewriter rewriter, VBAParser.ArgContext context) { if (context.BYREF() != null) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs index 191e1ee909..88155453a9 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs @@ -26,7 +26,7 @@ public RemoveStepOneQuickFix(RubberduckParserState state) public override void Fix(IInspectionResult result) { - IModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + IExecutableModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); var context = result.Context; rewriter.Remove(context); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs index 836f7539d2..6c2d5055f9 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs @@ -72,7 +72,7 @@ private static int GetParameterIndex(VBAParser.ArgContext context) return Array.IndexOf(((VBAParser.ArgListContext)context.Parent).arg().ToArray(), context); } - private static void AddByRefIdentifier(IModuleRewriter rewriter, VBAParser.ArgContext context) + private static void AddByRefIdentifier(IExecutableModuleRewriter rewriter, VBAParser.ArgContext context) { if (context.BYREF() == null) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs index ee6a27909b..b608d712a3 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs @@ -1,4 +1,6 @@ +using System; using System.Text; +using Antlr4.Runtime; using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; @@ -19,11 +21,22 @@ public SplitMultipleDeclarationsQuickFix(RubberduckParserState state) public override void Fix(IInspectionResult result) { - dynamic context = result.Context is VBAParser.ConstStmtContext + var context = result.Context is VBAParser.ConstStmtContext ? result.Context - : result.Context.Parent; + : (ParserRuleContext)result.Context.Parent; - var declarationsText = GetDeclarationsText(context); + string declarationsText; + switch (context) + { + case VBAParser.ConstStmtContext consts: + declarationsText = GetDeclarationsText(consts); + break; + case VBAParser.VariableStmtContext variables: + declarationsText = GetDeclarationsText(variables); + break; + default: + throw new NotSupportedException(); + } var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(context, declarationsText); diff --git a/Rubberduck.Parsing/Rewriter/IExecutableModuleRewriter.cs b/Rubberduck.Parsing/Rewriter/IExecutableModuleRewriter.cs new file mode 100644 index 0000000000..c7afaf2dc4 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/IExecutableModuleRewriter.cs @@ -0,0 +1,10 @@ +namespace Rubberduck.Parsing.Rewriter +{ + public interface IExecutableModuleRewriter : IModuleRewriter + { + /// + /// Rewrites the entire module / applies all changes. + /// + void Rewrite(); + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs b/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs index 393a53bc98..ed8da6744c 100644 --- a/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs +++ b/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs @@ -1,4 +1,4 @@ -using Antlr4.Runtime; +using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using Rubberduck.Parsing.Symbols; @@ -9,11 +9,6 @@ public interface IModuleRewriter { bool IsDirty { get; } - /// - /// Rewrites the entire module / applies all changes. - /// - void Rewrite(); - /// /// Removes all tokens for specified . Use method to apply changes. /// @@ -38,6 +33,12 @@ public interface IModuleRewriter /// The to remove. /// Removes a line that would be left empty by the removal of the identifier reference token. void Remove(ITerminalNode target); + /// + /// Removes all tokens for specified . Use method to apply changes. + /// + /// The to remove. + /// Removes a line that would be left empty by the removal of the identifier reference token. + void Remove(IParseTree target); /// /// Removes all tokens from the start of the first node to the end of the second node. @@ -71,6 +72,12 @@ public interface IModuleRewriter /// The to replace. /// The literal replacement for the expression. void Replace(ITerminalNode target, string content); + /// + /// Replaces specified token with specified content. Use method to apply changes. + /// + /// The to replace. + /// The literal replacement for the expression. + void Replace(IParseTree target, string content); /// /// Replaces specified interval with specified content. Use method to apply changes. diff --git a/Rubberduck.Parsing/Rewriter/IModuleRewriterFactory.cs b/Rubberduck.Parsing/Rewriter/IModuleRewriterFactory.cs index 3db5967268..5721cc3f25 100644 --- a/Rubberduck.Parsing/Rewriter/IModuleRewriterFactory.cs +++ b/Rubberduck.Parsing/Rewriter/IModuleRewriterFactory.cs @@ -5,7 +5,7 @@ namespace Rubberduck.Parsing.Rewriter { public interface IModuleRewriterFactory { - IModuleRewriter CodePaneRewriter(QualifiedModuleName module, ITokenStream tokenStream); - IModuleRewriter AttributesRewriter(QualifiedModuleName module, ITokenStream tokenStream); + IExecutableModuleRewriter CodePaneRewriter(QualifiedModuleName module, ITokenStream tokenStream); + IExecutableModuleRewriter AttributesRewriter(QualifiedModuleName module, ITokenStream tokenStream); } } diff --git a/Rubberduck.Parsing/Rewriter/ModuleRewriter.cs b/Rubberduck.Parsing/Rewriter/ModuleRewriter.cs index e54b52b567..4b2314a0c8 100644 --- a/Rubberduck.Parsing/Rewriter/ModuleRewriter.cs +++ b/Rubberduck.Parsing/Rewriter/ModuleRewriter.cs @@ -11,7 +11,7 @@ namespace Rubberduck.Parsing.Rewriter { - public class ModuleRewriter : IModuleRewriter + public class ModuleRewriter : IExecutableModuleRewriter { private readonly QualifiedModuleName _module; private readonly ISourceCodeHandler _sourceCodeHandler; @@ -73,6 +73,22 @@ public void Remove(IToken target) _rewriter.Delete(target); } + public void Remove(IParseTree target) + { + switch (target) + { + case ITerminalNode terminalNode: + Remove(terminalNode); + break; + case ParserRuleContext context: + Remove(context); + break; + default: + //It should be impossible to end up here. + throw new NotSupportedException(); + } + } + public void RemoveRange(int start, int stop) { _rewriter.Delete(start, stop); @@ -98,6 +114,22 @@ public void Replace(ITerminalNode target, string content) _rewriter.Replace(target.Symbol.TokenIndex, content); } + public void Replace(IParseTree target, string content) + { + switch (target) + { + case ITerminalNode terminalNode: + Replace(terminalNode, content); + break; + case ParserRuleContext context: + Replace(context, content); + break; + default: + //It should be impossible to end up here. + throw new NotSupportedException(); + } + } + public void Replace(Interval tokenInterval, string content) { _rewriter.Replace(tokenInterval.a, tokenInterval.b, content); diff --git a/Rubberduck.Parsing/Rewriter/ModuleRewriterFactory.cs b/Rubberduck.Parsing/Rewriter/ModuleRewriterFactory.cs index 7968186d3b..4fb978fffa 100644 --- a/Rubberduck.Parsing/Rewriter/ModuleRewriterFactory.cs +++ b/Rubberduck.Parsing/Rewriter/ModuleRewriterFactory.cs @@ -20,12 +20,12 @@ public ModuleRewriterFactory(ISourceCodeHandler codePaneSourceCodeHandler, ISour _attributesSourceCodeHandler = attributesSourceCodeHandler; } - public IModuleRewriter CodePaneRewriter(QualifiedModuleName module, ITokenStream tokenStream) + public IExecutableModuleRewriter CodePaneRewriter(QualifiedModuleName module, ITokenStream tokenStream) { return new ModuleRewriter(module, tokenStream, _codePaneSourceCodeHandlerr); } - public IModuleRewriter AttributesRewriter(QualifiedModuleName module, ITokenStream tokenStream) + public IExecutableModuleRewriter AttributesRewriter(QualifiedModuleName module, ITokenStream tokenStream) { return new ModuleRewriter(module, tokenStream, _attributesSourceCodeHandler); } diff --git a/Rubberduck.Parsing/VBA/ModuleState.cs b/Rubberduck.Parsing/VBA/ModuleState.cs index c85b52e2cd..2b4918e019 100644 --- a/Rubberduck.Parsing/VBA/ModuleState.cs +++ b/Rubberduck.Parsing/VBA/ModuleState.cs @@ -16,8 +16,8 @@ public class ModuleState { public ConcurrentDictionary Declarations { get; private set; } public ConcurrentDictionary UnresolvedMemberDeclarations { get; private set; } - public IModuleRewriter ModuleRewriter { get; private set; } - public IModuleRewriter AttributesRewriter { get; private set; } + public IExecutableModuleRewriter ModuleRewriter { get; private set; } + public IExecutableModuleRewriter AttributesRewriter { get; private set; } public IParseTree ParseTree { get; private set; } public IParseTree AttributesPassParseTree { get; private set; } public ParserState State { get; private set; } @@ -79,7 +79,7 @@ public ModuleState(SyntaxErrorException moduleException) IsNew = true; } - public ModuleState SetCodePaneRewriter(QualifiedModuleName module, IModuleRewriter codePaneRewriter) + public ModuleState SetCodePaneRewriter(QualifiedModuleName module, IExecutableModuleRewriter codePaneRewriter) { ModuleRewriter = codePaneRewriter; return this; @@ -144,7 +144,7 @@ public ModuleState SetMembersAllowingAttributes(IDictionary<(string scopeIdentif return this; } - public ModuleState SetAttributesRewriter(IModuleRewriter rewriter) + public ModuleState SetAttributesRewriter(IExecutableModuleRewriter rewriter) { AttributesRewriter = rewriter; return this; diff --git a/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs b/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs index 6c7289f6ae..776e919e2b 100644 --- a/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs +++ b/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs @@ -18,8 +18,8 @@ public ModuleParseResults( IEnumerable annotations, IDictionary<(string scopeIdentifier, DeclarationType scopeType), Attributes> attributes, IDictionary<(string scopeIdentifier, DeclarationType scopeType), ParserRuleContext> membersAllowingAttributes, - IModuleRewriter codePaneRewriter, - IModuleRewriter attributesRewriter + IExecutableModuleRewriter codePaneRewriter, + IExecutableModuleRewriter attributesRewriter ) { CodePaneParseTree = codePaneParseTree; @@ -38,8 +38,8 @@ IModuleRewriter attributesRewriter public IEnumerable Annotations { get; } public IDictionary<(string scopeIdentifier, DeclarationType scopeType), Attributes> Attributes { get; } public IDictionary<(string scopeIdentifier, DeclarationType scopeType), ParserRuleContext> MembersAllowingAttributes { get; } - public IModuleRewriter CodePaneRewriter { get; } - public IModuleRewriter AttributesRewriter { get; } + public IExecutableModuleRewriter CodePaneRewriter { get; } + public IExecutableModuleRewriter AttributesRewriter { get; } } public interface IModuleParser diff --git a/Rubberduck.Parsing/VBA/RubberduckParserState.cs b/Rubberduck.Parsing/VBA/RubberduckParserState.cs index 4cfd0e1ad9..938679b663 100644 --- a/Rubberduck.Parsing/VBA/RubberduckParserState.cs +++ b/Rubberduck.Parsing/VBA/RubberduckParserState.cs @@ -844,7 +844,7 @@ private bool RemoveKeysFromCollections(IEnumerable keys) return success; } - public void SetCodePaneRewriter(QualifiedModuleName module, IModuleRewriter codePaneRewriter) + public void SetCodePaneRewriter(QualifiedModuleName module, IExecutableModuleRewriter codePaneRewriter) { _moduleStates[module].SetCodePaneRewriter(module, codePaneRewriter); } @@ -929,24 +929,24 @@ public bool IsDirty() return false; } - public IModuleRewriter GetRewriter(IVBComponent component) + public IExecutableModuleRewriter GetRewriter(IVBComponent component) { var qualifiedModuleName = new QualifiedModuleName(component); return GetRewriter(qualifiedModuleName); } - public IModuleRewriter GetRewriter(QualifiedModuleName qualifiedModuleName) + public IExecutableModuleRewriter GetRewriter(QualifiedModuleName qualifiedModuleName) { return _moduleStates[qualifiedModuleName].ModuleRewriter; } - public IModuleRewriter GetRewriter(Declaration declaration) + public IExecutableModuleRewriter GetRewriter(Declaration declaration) { var qualifiedModuleName = declaration.QualifiedSelection.QualifiedName; return GetRewriter(qualifiedModuleName); } - public IModuleRewriter GetAttributeRewriter(QualifiedModuleName qualifiedModuleName) + public IExecutableModuleRewriter GetAttributeRewriter(QualifiedModuleName qualifiedModuleName) { return _moduleStates[qualifiedModuleName].AttributesRewriter; } @@ -1067,7 +1067,7 @@ private void ClearAsTypeDeclarationPointingToReference(QualifiedModuleName refer } - public void AddAttributesRewriter(QualifiedModuleName module, IModuleRewriter attributesRewriter) + public void AddAttributesRewriter(QualifiedModuleName module, IExecutableModuleRewriter attributesRewriter) { var key = module; _moduleStates[key].SetAttributesRewriter(attributesRewriter); diff --git a/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs b/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs index 0c51cd0b8a..49798c650d 100644 --- a/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs +++ b/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs @@ -16,7 +16,7 @@ public class EncapsulateFieldRefactoring : IRefactoring private readonly IRefactoringPresenterFactory _factory; private EncapsulateFieldModel _model; - private readonly HashSet _referenceRewriters = new HashSet(); + private readonly HashSet _referenceRewriters = new HashSet(); public EncapsulateFieldRefactoring(IVBE vbe, IIndenter indenter, IRefactoringPresenterFactory factory) { @@ -71,7 +71,7 @@ public void Refactor(Declaration target) Refactor(); } - private void AddProperty(IModuleRewriter rewriter) + private void AddProperty(IExecutableModuleRewriter rewriter) { UpdateReferences(); SetFieldToPrivate(rewriter); @@ -120,7 +120,7 @@ private void UpdateReferences() } } - private void SetFieldToPrivate(IModuleRewriter rewriter) + private void SetFieldToPrivate(IExecutableModuleRewriter rewriter) { if (_model.TargetDeclaration.Accessibility != Accessibility.Private) { diff --git a/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs b/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs index 7fd434af56..69997a2486 100644 --- a/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs +++ b/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs @@ -121,7 +121,7 @@ private void AddInterface() } } - private void AddInterfaceMembersToClass(IModuleRewriter rewriter) + private void AddInterfaceMembersToClass(IExecutableModuleRewriter rewriter) { var implementInterfaceRefactoring = new ImplementInterfaceRefactoring(_vbe, _model.State, _messageBox); implementInterfaceRefactoring.Refactor(_model.Members.Select(m => m.Member).ToList(), rewriter, _model.InterfaceName); diff --git a/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs b/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs index 03bbfce5ce..f78f800f8c 100644 --- a/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs +++ b/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs @@ -99,12 +99,12 @@ public void Refactor(Declaration target) throw new NotSupportedException(); } - internal void Refactor(List members, IModuleRewriter rewriter, string interfaceName) + internal void Refactor(List members, IExecutableModuleRewriter rewriter, string interfaceName) { AddItems(members, rewriter, interfaceName); } - private void ImplementMissingMembers(IModuleRewriter rewriter) + private void ImplementMissingMembers(IExecutableModuleRewriter rewriter) { var implemented = _targetClass.Members .Where(decl => decl is ModuleBodyElementDeclaration member && ReferenceEquals(member.InterfaceImplemented, _targetInterface)) @@ -119,7 +119,7 @@ private void ImplementMissingMembers(IModuleRewriter rewriter) AddItems(nonImplementedMembers, rewriter, _targetInterface.IdentifierName); } - private void AddItems(IEnumerable missingMembers, IModuleRewriter rewriter, string interfaceName) + private void AddItems(IEnumerable missingMembers, IExecutableModuleRewriter rewriter, string interfaceName) { var missingMembersText = missingMembers.Aggregate(string.Empty, (current, member) => current + Environment.NewLine + GetInterfaceMember(member, interfaceName)); diff --git a/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs b/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs index 5e9054cf5c..80a5040ae8 100644 --- a/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs +++ b/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs @@ -71,7 +71,7 @@ public void Refactor(Declaration target) PromoteVariable(rewriter, target); } - private void PromoteVariable(IModuleRewriter rewriter, Declaration target) + private void PromoteVariable(IExecutableModuleRewriter rewriter, Declaration target) { if (new[] { DeclarationType.ClassModule, DeclarationType.ProceduralModule }.Contains(target.ParentDeclaration.DeclarationType)) { @@ -99,7 +99,7 @@ private void PromoteVariable(IModuleRewriter rewriter, Declaration target) rewriter.Rewrite(); } - private void AddField(IModuleRewriter rewriter, Declaration target) + private void AddField(IExecutableModuleRewriter rewriter, Declaration target) { var content = $"{Tokens.Private} {target.IdentifierName} {Tokens.As} {target.AsTypeName}\r\n"; var members = _state.DeclarationFinder.Members(target.QualifiedName.QualifiedModuleName) diff --git a/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs b/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs index 3e38a05439..85e43dbe5e 100644 --- a/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs +++ b/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs @@ -19,7 +19,7 @@ public class IntroduceParameterRefactoring : IRefactoring private readonly IList _declarations; private readonly IMessageBox _messageBox; - private readonly HashSet _rewriters = new HashSet(); + private readonly HashSet _rewriters = new HashSet(); private static readonly DeclarationType[] ValidDeclarationTypes = { diff --git a/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs b/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs index 11d83ce0a5..dd5ae4f942 100644 --- a/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs +++ b/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs @@ -24,7 +24,7 @@ public class MoveCloserToUsageRefactoring : IRefactoring private readonly IMessageBox _messageBox; private Declaration _target; - private readonly HashSet _rewriters = new HashSet(); + private readonly HashSet _rewriters = new HashSet(); public MoveCloserToUsageRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) { diff --git a/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs b/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs index d11367a9f0..0246b69023 100644 --- a/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs +++ b/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using Antlr4.Runtime; +using Antlr4.Runtime.Tree; using Rubberduck.Common; using Rubberduck.Interaction; using Rubberduck.Parsing; @@ -19,7 +21,7 @@ public class RemoveParametersRefactoring : IRefactoring private readonly IVBE _vbe; private readonly IRefactoringPresenterFactory _factory; private RemoveParametersModel _model; - private readonly HashSet _rewriters = new HashSet(); + private readonly HashSet _rewriters = new HashSet(); public RemoveParametersRefactoring(IVBE vbe, IRefactoringPresenterFactory factory) { @@ -182,7 +184,7 @@ private void RemoveCallArguments(VBAParser.ArgumentListContext argList, Qualifie var index = i == 0 ? 0 : argList.children.IndexOf(args[i - 1]) + 1; for (var j = index; j < argList.children.Count; j++) { - rewriter.Remove((dynamic)argList.children[j]); + rewriter.Remove(argList.children[j]); } break; } @@ -278,7 +280,7 @@ private void RemoveSignatureParameters(Declaration target) //Issue 4319. If there are 3 or more arguments and the user elects to remove 2 or more of //the last arguments, then we need to specifically remove the trailing comma from //the last 'kept' argument. - private void RemoveTrailingComma(IModuleRewriter rewriter, VBAParser.ArgumentListContext argList = null, bool usesNamedParams = false) + private void RemoveTrailingComma(IExecutableModuleRewriter rewriter, VBAParser.ArgumentListContext argList = null, bool usesNamedParams = false) { var commaLocator = RetrieveTrailingCommaInfo(_model.RemoveParameters, _model.Parameters); if (!commaLocator.RequiresTrailingCommaRemoval) diff --git a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs index 6e1bb934a7..54cfd1b896 100644 --- a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs +++ b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs @@ -20,7 +20,7 @@ public class ReorderParametersRefactoring : IRefactoring private readonly IRefactoringPresenterFactory _factory; private ReorderParametersModel _model; private readonly IMessageBox _messageBox; - private readonly HashSet _rewriters = new HashSet(); + private readonly HashSet _rewriters = new HashSet(); private readonly IProjectsProvider _projectsProvider; public ReorderParametersRefactoring(IVBE vbe, IRefactoringPresenterFactory factory, IMessageBox messageBox, IProjectsProvider projectsProvider) From f19e04e333de4f870d48106effd3537d469a6abf Mon Sep 17 00:00:00 2001 From: Abraham Hosch Date: Thu, 11 Oct 2018 12:28:11 -0500 Subject: [PATCH 002/107] Inspection for public members with underscores in names in class modules --- ...coreInPublicClassModuleMemberInspection.cs | 28 ++++ .../Properties/Settings.Designer.cs | 3 +- Rubberduck.Core/Properties/Settings.settings | 1 + Rubberduck.Core/app.config | 2 + .../Inspections/InspectionInfo.Designer.cs | 9 ++ .../Inspections/InspectionInfo.resx | 3 + .../Inspections/InspectionNames.Designer.cs | 9 ++ .../Inspections/InspectionNames.resx | 3 + .../Inspections/InspectionResults.Designer.cs | 9 ++ .../Inspections/InspectionResults.resx | 3 + ...nPublicClassModuleMemberInspectionTests.cs | 139 ++++++++++++++++++ 11 files changed, 208 insertions(+), 1 deletion(-) create mode 100644 Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs create mode 100644 RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs new file mode 100644 index 0000000000..21ea244f69 --- /dev/null +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using System.Linq; +using Rubberduck.Inspections.Abstract; +using Rubberduck.Inspections.Results; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Resources.Inspections; +using Rubberduck.Parsing.VBA; + +namespace Rubberduck.Inspections.Concrete +{ + public sealed class UnderscoreInPublicClassModuleMemberInspection : InspectionBase + { + public UnderscoreInPublicClassModuleMemberInspection(RubberduckParserState state) + : base(state) { } + + protected override IEnumerable DoGetInspectionResults() + { + var names = State.DeclarationFinder.UserDeclarations(Parsing.Symbols.DeclarationType.Member) + .Where(w => w.ParentDeclaration.DeclarationType == Parsing.Symbols.DeclarationType.ClassModule) + .Where(w => w.Accessibility == Parsing.Symbols.Accessibility.Public) + .Where(w => w.IdentifierName.Contains('_')) + .ToList(); + + return names.Select(issue => + new DeclarationInspectionResult(this, string.Format(InspectionResults.UnderscoreInPublicClassModuleMemberInspection, issue.IdentifierName), issue)); + } + } +} diff --git a/Rubberduck.Core/Properties/Settings.Designer.cs b/Rubberduck.Core/Properties/Settings.Designer.cs index 1fbbf7fbc5..bdcef31ecc 100644 --- a/Rubberduck.Core/Properties/Settings.Designer.cs +++ b/Rubberduck.Core/Properties/Settings.Designer.cs @@ -458,7 +458,8 @@ public static Settings Default { "=\"RubberduckOpportunities\" />\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n + true diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs index e399928601..776823ee46 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs @@ -681,6 +681,15 @@ public static string UndeclaredVariableInspection { } } + /// + /// Looks up a localized string similar to A class module with public members with underscores cannot implement interfaces that do not expose said member.. + /// + public static string UnderscoreInPublicClassModuleMemberInspection { + get { + return ResourceManager.GetString("UnderscoreInPublicClassModuleMemberInspection", resourceCulture); + } + } + /// /// Looks up a localized string similar to Error handling should be restored after using 'On Error Resume Next'.. /// diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.resx b/Rubberduck.Resources/Inspections/InspectionInfo.resx index b06e89193b..7c3c27f626 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.resx +++ b/Rubberduck.Resources/Inspections/InspectionInfo.resx @@ -349,4 +349,7 @@ If the parameter can be null, ignore this inspection result; passing a null valu An assignment is immediately overridden by another assignment or is never referenced. + + A class module with public members with underscores cannot implement interfaces that do not expose said member. + \ No newline at end of file diff --git a/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs b/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs index f13cc181ab..939a40a9e1 100644 --- a/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs @@ -681,6 +681,15 @@ public static string UndeclaredVariableInspection { } } + /// + /// Looks up a localized string similar to Underscore in public class module member. + /// + public static string UnderscoreInPublicClassModuleMemberInspection { + get { + return ResourceManager.GetString("UnderscoreInPublicClassModuleMemberInspection", resourceCulture); + } + } + /// /// Looks up a localized string similar to Unhandled 'On Error Resume Next'. /// diff --git a/Rubberduck.Resources/Inspections/InspectionNames.resx b/Rubberduck.Resources/Inspections/InspectionNames.resx index 619f5ddbb9..8d80a7bb18 100644 --- a/Rubberduck.Resources/Inspections/InspectionNames.resx +++ b/Rubberduck.Resources/Inspections/InspectionNames.resx @@ -348,4 +348,7 @@ Assignment is not used + + Underscore in public class module member + \ No newline at end of file diff --git a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs index 02946f951a..c7c3aaf895 100644 --- a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs @@ -699,6 +699,15 @@ public static string UndeclaredVariableInspection { } } + /// + /// Looks up a localized string similar to Public member '{0}' has underscore in name.. + /// + public static string UnderscoreInPublicClassModuleMemberInspection { + get { + return ResourceManager.GetString("UnderscoreInPublicClassModuleMemberInspection", resourceCulture); + } + } + /// /// Looks up a localized string similar to Errors are ignored but never handled again.. /// diff --git a/Rubberduck.Resources/Inspections/InspectionResults.resx b/Rubberduck.Resources/Inspections/InspectionResults.resx index 36ac7d58cb..42012e21e8 100644 --- a/Rubberduck.Resources/Inspections/InspectionResults.resx +++ b/Rubberduck.Resources/Inspections/InspectionResults.resx @@ -378,4 +378,7 @@ An assignment is immediately overridden by another assignment or is never referenced. + + Public member '{0}' has underscore in name. + \ No newline at end of file diff --git a/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs b/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs new file mode 100644 index 0000000000..6781d646b7 --- /dev/null +++ b/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs @@ -0,0 +1,139 @@ +using NUnit.Framework; +using Rubberduck.Inspections.Concrete; +using Rubberduck.VBEditor.SafeComWrappers; +using RubberduckTests.Mocks; +using System.Linq; +using System.Threading; + +namespace RubberduckTests.Inspections +{ + [TestFixture] + public class UnderscoreInPublicClassModuleMemberInspectionTests + { + [Test] + [Category("Inspections")] + public void BasicExample_Sub() + { + const string inputCode = + @"Public Sub Test_This_Out() +End Sub"; + var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out _); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void BasicExample_Function() + { + const string inputCode = + @"Public Function Test_This_Out() As Integer +End Function"; + var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out _); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void BasicExample_Property() + { + const string inputCode = + @"Public Property Get Test_This_Out() As Integer +End Property"; + var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out _); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void StandardModule() + { + const string inputCode = + @"Public Sub Test_This_Out() +End Sub"; + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(0, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void NoUnderscore() + { + const string inputCode = + @"Public Sub Foo() +End Sub"; + var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out _); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(0, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void FriendMember_WithUnderscore() + { + const string inputCode = + @"Friend Sub Test_This_Out() +End Sub"; + var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out _); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(0, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void Implicit_WithUnderscore() + { + const string inputCode = + @"Sub Test_This_Out() +End Sub"; + var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out _); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(0, inspectionResults.Count()); + } + } + } +} From 6d554aeceb52080334941716288032cd4f3d7a78 Mon Sep 17 00:00:00 2001 From: Abraham Hosch Date: Thu, 11 Oct 2018 12:31:13 -0500 Subject: [PATCH 003/107] Add quick fix --- Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs index ab6c2817a8..327b42826d 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs @@ -18,7 +18,7 @@ public sealed class RenameDeclarationQuickFix : QuickFixBase private readonly IMessageBox _messageBox; public RenameDeclarationQuickFix(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) - : base(typeof(HungarianNotationInspection), typeof(UseMeaningfulNameInspection), typeof(DefaultProjectNameInspection)) + : base(typeof(HungarianNotationInspection), typeof(UseMeaningfulNameInspection), typeof(DefaultProjectNameInspection), typeof(UnderscoreInPublicClassModuleMemberInspection)) { _vbe = vbe; _state = state; From 70b53ca91628a1614371ac7610679e3ca3f47034 Mon Sep 17 00:00:00 2001 From: Abraham Hosch Date: Fri, 12 Oct 2018 13:55:51 -0500 Subject: [PATCH 004/107] Ignore interface implementations --- ...coreInPublicClassModuleMemberInspection.cs | 1 + ...nPublicClassModuleMemberInspectionTests.cs | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs index 21ea244f69..22bb6ed192 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs @@ -17,6 +17,7 @@ protected override IEnumerable DoGetInspectionResults() { var names = State.DeclarationFinder.UserDeclarations(Parsing.Symbols.DeclarationType.Member) .Where(w => w.ParentDeclaration.DeclarationType == Parsing.Symbols.DeclarationType.ClassModule) + .Where(w => !State.DeclarationFinder.FindAllInterfaceImplementingMembers().Contains(w)) .Where(w => w.Accessibility == Parsing.Symbols.Accessibility.Public) .Where(w => w.IdentifierName.Contains('_')) .ToList(); diff --git a/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs b/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs index 6781d646b7..290ffab67f 100644 --- a/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs +++ b/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs @@ -135,5 +135,37 @@ public void Implicit_WithUnderscore() Assert.AreEqual(0, inspectionResults.Count()); } } + + [Test] + [Category("Inspections")] + public void ImplementsInterface() + { + const string inputCode1 = + @"Public Sub Foo() +End Sub"; + + //Expectation + const string inputCode2 = + @"Implements Class1 + +Public Sub Class1_Foo() + Err.Raise 5 'TODO implement interface member +End Sub +"; + var builder = new MockVbeBuilder(); + var project = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) + .AddComponent("Class1", ComponentType.ClassModule, inputCode1) + .AddComponent("Class2", ComponentType.ClassModule, inputCode2) + .Build(); + var vbe = builder.AddProject(project).Build(); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var inspection = new UnderscoreInPublicClassModuleMemberInspection(state); + var inspector = InspectionsHelper.GetInspector(inspection); + var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + + Assert.AreEqual(0, inspectionResults.Count()); + } + } } } From 4eb05431a63dfc34aec473a5195bbb2fd665ac97 Mon Sep 17 00:00:00 2001 From: Abraham Hosch Date: Wed, 24 Oct 2018 19:23:16 -0500 Subject: [PATCH 005/107] Address review --- .../Concrete/UnderscoreInPublicClassModuleMemberInspection.cs | 2 +- Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs | 2 +- Rubberduck.Resources/Inspections/InspectionInfo.resx | 2 +- Rubberduck.Resources/Inspections/InspectionResults.Designer.cs | 2 +- Rubberduck.Resources/Inspections/InspectionResults.resx | 2 +- .../UnderscoreInPublicClassModuleMemberInspectionTests.cs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs index 22bb6ed192..faad1120c5 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs @@ -18,7 +18,7 @@ protected override IEnumerable DoGetInspectionResults() var names = State.DeclarationFinder.UserDeclarations(Parsing.Symbols.DeclarationType.Member) .Where(w => w.ParentDeclaration.DeclarationType == Parsing.Symbols.DeclarationType.ClassModule) .Where(w => !State.DeclarationFinder.FindAllInterfaceImplementingMembers().Contains(w)) - .Where(w => w.Accessibility == Parsing.Symbols.Accessibility.Public) + .Where(w => w.Accessibility == Parsing.Symbols.Accessibility.Public || w.Accessibility == Parsing.Symbols.Accessibility.Implicit) .Where(w => w.IdentifierName.Contains('_')) .ToList(); diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs index 776823ee46..8e8e039888 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs @@ -682,7 +682,7 @@ public static string UndeclaredVariableInspection { } /// - /// Looks up a localized string similar to A class module with public members with underscores cannot implement interfaces that do not expose said member.. + /// Looks up a localized string similar to A class module that contains members with underscores cannot be implemented by other classes. The underscore is used as a separator between the interface/object name and the implemented member name: having an underscore in the member name confuses the compiler, which then refuses to compile the project. Avoid underscores in public member names by following a 'PascalCase' naming convention.. /// public static string UnderscoreInPublicClassModuleMemberInspection { get { diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.resx b/Rubberduck.Resources/Inspections/InspectionInfo.resx index 7c3c27f626..c9a1ecbe98 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.resx +++ b/Rubberduck.Resources/Inspections/InspectionInfo.resx @@ -350,6 +350,6 @@ If the parameter can be null, ignore this inspection result; passing a null valu An assignment is immediately overridden by another assignment or is never referenced. - A class module with public members with underscores cannot implement interfaces that do not expose said member. + A class module that contains members with underscores cannot be implemented by other classes. The underscore is used as a separator between the interface/object name and the implemented member name: having an underscore in the member name confuses the compiler, which then refuses to compile the project. Avoid underscores in public member names by following a 'PascalCase' naming convention. \ No newline at end of file diff --git a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs index c7c3aaf895..df90471259 100644 --- a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs @@ -700,7 +700,7 @@ public static string UndeclaredVariableInspection { } /// - /// Looks up a localized string similar to Public member '{0}' has underscore in name.. + /// Looks up a localized string similar to Public member name '{0}' contains an underscore.. /// public static string UnderscoreInPublicClassModuleMemberInspection { get { diff --git a/Rubberduck.Resources/Inspections/InspectionResults.resx b/Rubberduck.Resources/Inspections/InspectionResults.resx index 42012e21e8..eb5a76420d 100644 --- a/Rubberduck.Resources/Inspections/InspectionResults.resx +++ b/Rubberduck.Resources/Inspections/InspectionResults.resx @@ -379,6 +379,6 @@ An assignment is immediately overridden by another assignment or is never referenced. - Public member '{0}' has underscore in name. + Public member name '{0}' contains an underscore. \ No newline at end of file diff --git a/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs b/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs index 290ffab67f..99e7ac0b1c 100644 --- a/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs +++ b/RubberduckTests/Inspections/UnderscoreInPublicClassModuleMemberInspectionTests.cs @@ -132,7 +132,7 @@ public void Implicit_WithUnderscore() var inspector = InspectionsHelper.GetInspector(inspection); var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - Assert.AreEqual(0, inspectionResults.Count()); + Assert.AreEqual(1, inspectionResults.Count()); } } From e680b87bb446062e9366467564ca10ca08d3d1df Mon Sep 17 00:00:00 2001 From: bclothier Date: Wed, 24 Oct 2018 21:15:09 -0500 Subject: [PATCH 006/107] Remove all obsolete methods and its implementations --- .../Abstract/HostApplicationBase.cs | 7 -- .../VB/Abstract/IHostApplication.cs | 20 ---- .../SafeComWrappers/Application/AccessApp.cs | 34 ------ .../SafeComWrappers/Application/AutoCADApp.cs | 4 - .../Application/CorelDRAWApp.cs | 17 +-- .../SafeComWrappers/Application/ExcelApp.cs | 102 +----------------- .../Application/FallbackApp.cs | 46 +------- .../SafeComWrappers/Application/OutlookApp.cs | 27 ----- .../Application/PowerPointApp.cs | 36 ------- .../SafeComWrappers/Application/ProjectApp.cs | 12 --- .../Application/PublisherApp.cs | 9 +- .../Application/SolidWorksApp.cs | 17 --- .../SafeComWrappers/Application/Visio.cs | 19 ---- .../SafeComWrappers/Application/WordApp.cs | 39 ------- 14 files changed, 6 insertions(+), 383 deletions(-) diff --git a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs index 7d93ba8eba..5c4d16a933 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs @@ -141,13 +141,6 @@ private static IProperty ApplicationPropertyFromDocumentModule(IVBE vbe) public string ApplicationName { get; } - public abstract void Run(dynamic declaration); - - public virtual object Run(string name, params object[] args) - { - return null; - } - public override bool Equals(ISafeComWrapper other) { return IsEqualIfNull(other) || (other != null && ReferenceEquals(other.Target, Target)); diff --git a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs index f90430ec39..d651f858c0 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs @@ -4,26 +4,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.Abstract { public interface IHostApplication : IDisposable { - /// - /// Runs VBA procedure specified by name. WARNING: The parameter is declared as dynamic to prevent circular referencing. - /// This should ONLY be passed a Declaration object. - /// - /// The Declaration object for the method to be executed. - [Obsolete("Use ExecuteCode in TypeLibAPI instead", true)] - void Run(dynamic declaration); - - /// - /// Executes a VBA function by name, with specified parameters, and returns a result. - /// - /// - /// - /// - /// - /// May not be available in all host applications. - /// - [Obsolete("Use ExecuteCode in TypeLibAPI instead", true)] - object Run(string name, params object[] args); - /// /// Gets the name of the application. /// diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs index c67ff6cb98..e29c8f1188 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using System.IO; -using System.Reflection; using Rubberduck.VBEditor.SafeComWrappers.Abstract; // ReSharper disable once CheckNamespace - Special dispensation due to conflicting file vs namespace priorities @@ -10,36 +7,5 @@ public class AccessApp : HostApplicationBase FormDeclarations(QualifiedModuleName qualifiedModuleName) - { - //TODO: Drop in the optimized version that uses line indentations - return new List(); - } - - private string ExportPath - { - get - { - var assemblyLocation = Assembly.GetAssembly(typeof(AccessApp)).Location; - return Path.GetDirectoryName(assemblyLocation); - } - } - - private string GenerateMethodCall(QualifiedMemberName qualifiedMemberName) - { - //Access only supports Project.Procedure syntax. Error occurs if there are naming conflicts. - // http://msdn.microsoft.com/en-us/library/office/ff193559(v=office.15).aspx - // https://github.com/retailcoder/Rubberduck/issues/109 - - var projectName = qualifiedMemberName.QualifiedModuleName.ProjectName; - return $"{projectName}.{qualifiedMemberName.MemberName}"; - } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs index a1855cfddd..f05211a46c 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs @@ -7,9 +7,5 @@ public class AutoCADApp : HostApplicationBase { - public const int MaxPossibleLengthOfProcedureName = 255; - public ExcelApp() : base("Excel") { } public ExcelApp(IVBE vbe) : base(vbe, "Excel") { } - - public override void Run(dynamic declaration) - { - var call = GenerateMethodCall(declaration); - Application.Run(call); - } - - public override object Run(string name, params object[] args) - { - switch (args.Length) - { - case 0: - return Application.Run(name); - case 1: - return Application.Run(name, args[0]); - case 2: - return Application.Run(name, args[0], args[1]); - case 3: - return Application.Run(name, args[0], args[1], args[2]); - case 4: - return Application.Run(name, args[0], args[1], args[2], args[3]); - case 5: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4]); - case 6: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - case 8: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); - case 9: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); - case 10: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); - case 11: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10]); - case 12: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11]); - case 13: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12]); - case 14: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13]); - case 15: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14]); - case 16: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15]); - case 17: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16]); - case 18: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17]); - case 19: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18]); - case 20: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19]); - case 21: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19],args[20]); - case 22: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21]); - case 23: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22]); - case 24: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22], args[23]); - case 25: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22], args[23], args[24]); - case 26: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22], args[23], args[24], args[25]); - case 27: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22], args[23], args[24], args[25], args[26]); - case 28: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22], args[23], args[24], args[25], args[26], args[27]); - case 29: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22], args[23], args[24], args[25], args[26], args[27], args[28]); - case 30: - return Application.Run(name, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11], args[12], args[13], args[14], args[15], args[16], args[17], args[18], args[19], args[20], args[21], args[22], args[23], args[24], args[25], args[26], args[27], args[28], args[29]); - default: - throw new ArgumentException("Too many arguments."); - } - } - - protected virtual string GenerateMethodCall(dynamic declaration) - { - var qualifiedMemberName = declaration.QualifiedName; - var module = qualifiedMemberName.QualifiedModuleName; - - var documentName = string.IsNullOrEmpty(module.ProjectPath) - ? declaration.ProjectDisplayName - : Path.GetFileName(module.ProjectPath); - - var candidateString = string.IsNullOrEmpty(documentName) - ? qualifiedMemberName.ToString() - : string.Format("'{0}'!{1}", documentName.Replace("'", "''"), qualifiedMemberName); - - return candidateString.Length <= MaxPossibleLengthOfProcedureName - ? candidateString - : qualifiedMemberName.ToString(); - } + } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs index 02e1f514ad..41d94c51da 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs @@ -7,53 +7,11 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public sealed class FallbackApp : IHostApplication { - private readonly ICommandBarButton _runButton; - - private const int DebugCommandBarId = 4; - private const int RunMacroCommand = 186; - public FallbackApp(IVBE vbe) - { - var mainCommandBar = vbe.CommandBars[DebugCommandBarId]; - _runButton = (ICommandBarButton)mainCommandBar.FindControl(RunMacroCommand); - } - - public void Run(dynamic declaration) - { - var qualifiedMemberName = declaration.QualifiedName; - var component = qualifiedMemberName.QualifiedModuleName.Component; - var module = component.CodeModule; - { - var line = module.GetProcBodyStartLine(qualifiedMemberName.MemberName, ProcKind.Procedure); - var pane = module.CodePane; - { - pane.Selection = new Selection(line, 1, line, 1); - } - } - - _runButton.Execute(); - // note: this can't work... because the .Execute() call isn't blocking, so method returns before test method actually runs. - } - - public object Run(string name, object[] args) - { - return null; - } - - public TimeSpan TimedMethodCall(dynamic declaration) - { - var stopwatch = Stopwatch.StartNew(); - - Run(declaration); - - stopwatch.Stop(); - return stopwatch.Elapsed; - } + { } public string ApplicationName => "(unknown)"; - public void Dispose() - { - } + public void Dispose() { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs index 6ec9689eef..d9779c171a 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs @@ -1,5 +1,4 @@ using System.Runtime.InteropServices; -using Microsoft.Office.Core; using Rubberduck.VBEditor.SafeComWrappers.Abstract; // ReSharper disable once CheckNamespace - Special dispensation due to conflicting file vs namespace priorities @@ -11,31 +10,5 @@ public class OutlookApp : HostApplicationBase { public PublisherApp() : base("Publisher") { } - - public override void Run(dynamic declaration) - { - //Publisher does not support the Run method - throw new NotImplementedException("Unit Testing not supported for Publisher"); - } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs index 9d374b6f7c..3110e13877 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs @@ -1,4 +1,3 @@ -using Interop.SldWorks.Types; using Rubberduck.VBEditor.SafeComWrappers.Abstract; // ReSharper disable once CheckNamespace - Special dispensation due to conflicting file vs namespace priorities @@ -8,21 +7,5 @@ public class SolidWorksApp : HostApplicationBase() - .FirstOrDefault(doc => doc.Name == declaration.ProjectDisplayName - || doc.get_AttachedTemplate().Name == declaration.ProjectDisplayName); - if (activeDoc != targetDoc) - { - targetDoc?.Activate(); - } - } } } From 32597d0780453ccbd45c26279537ebbe2cbf3ee4 Mon Sep 17 00:00:00 2001 From: bclothier Date: Wed, 24 Oct 2018 23:38:02 -0500 Subject: [PATCH 007/107] Initial version with GetDocument replacing the VBComponent.Properties call to avoid COM reference leaks causing ghosting. # Conflicts: # Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs --- .../CodeExplorerComponentViewModel.cs | 26 ++-- .../CodeExplorerCustomFolderViewModel.cs | 8 +- .../CodeExplorer/CodeExplorerViewModel.cs | 4 +- .../Navigation/Folders/FolderHelper.cs | 12 +- .../Abstract/HostApplicationBase.cs | 5 + .../VB/Abstract/IHostApplication.cs | 76 ++++++++++++ .../SafeComWrappers/Application/AccessApp.cs | 116 ++++++++++++++++++ .../Application/FallbackApp.cs | 6 +- 8 files changed, 236 insertions(+), 17 deletions(-) diff --git a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs index 7735302b38..202390740a 100644 --- a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs +++ b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs @@ -10,6 +10,7 @@ using Rubberduck.VBEditor.ComManagement; using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.Resources.CodeExplorer; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; namespace Rubberduck.Navigation.CodeExplorer { @@ -36,13 +37,15 @@ public class CodeExplorerComponentViewModel : CodeExplorerItemViewModel, ICodeEx }; private readonly IProjectsProvider _projectsProvider; + private readonly IVBE _vbe; - public CodeExplorerComponentViewModel(CodeExplorerItemViewModel parent, Declaration declaration, IEnumerable declarations, IProjectsProvider projectsProvider) + public CodeExplorerComponentViewModel(CodeExplorerItemViewModel parent, Declaration declaration, IEnumerable declarations, IProjectsProvider projectsProvider, IVBE vbe) { Parent = parent; Declaration = declaration; _projectsProvider = projectsProvider; - + _vbe = vbe; + _icon = Icons.ContainsKey(DeclarationType) ? Icons[DeclarationType] : GetImageSource(CodeExplorerUI.status_offline); @@ -65,13 +68,13 @@ public CodeExplorerComponentViewModel(CodeExplorerItemViewModel parent, Declarat switch (qualifiedModuleName.ComponentType) { case ComponentType.Document: - var component = _projectsProvider.Component(qualifiedModuleName); string parenthesizedName; - using (var properties = component.Properties) + using (var app = _vbe.HostApplication()) + using (var document = app.GetDocument(qualifiedModuleName)) { - parenthesizedName = properties["Name"].Value.ToString() ?? string.Empty; + parenthesizedName = document.Name ?? string.Empty; } - + if (ContainsBuiltinDocumentPropertiesProperty()) { CodeExplorerItemViewModel node = this; @@ -113,7 +116,16 @@ private bool ContainsBuiltinDocumentPropertiesProperty() var component = _projectsProvider.Component(Declaration.QualifiedName.QualifiedModuleName); using (var properties = component.Properties) { - return properties.Any(item => item.Name == "BuiltinDocumentProperties"); + foreach (var property in properties) + using(property) + { + if (property.Name == "BuiltinDocumentProperties") + { + return true; + } + } + + return false; } } diff --git a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerCustomFolderViewModel.cs b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerCustomFolderViewModel.cs index 05e3479681..fc6333c915 100644 --- a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerCustomFolderViewModel.cs +++ b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerCustomFolderViewModel.cs @@ -5,6 +5,7 @@ using Rubberduck.Parsing.Symbols; using Rubberduck.VBEditor; using Rubberduck.VBEditor.ComManagement; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; namespace Rubberduck.Navigation.CodeExplorer { @@ -19,11 +20,14 @@ public class CodeExplorerCustomFolderViewModel : CodeExplorerItemViewModel }; private readonly IProjectsProvider _projectsProvider; + private readonly IVBE _vbe; - public CodeExplorerCustomFolderViewModel(CodeExplorerItemViewModel parent, string name, string fullPath, IProjectsProvider projectsProvider) + public CodeExplorerCustomFolderViewModel(CodeExplorerItemViewModel parent, string name, string fullPath, IProjectsProvider projectsProvider, IVBE vbe) { _parent = parent; _projectsProvider = projectsProvider; + _vbe = vbe; + FullPath = fullPath; Name = name.Replace("\"", string.Empty); FolderAttribute = string.Format("@Folder(\"{0}\")", fullPath.Replace("\"", string.Empty)); @@ -45,7 +49,7 @@ public void AddNodes(List declarations) var members = declarations.Where(item => !ComponentTypes.Contains(item.DeclarationType) && item.ComponentName == moduleName); - AddChild(new CodeExplorerComponentViewModel(this, parent, members, _projectsProvider)); + AddChild(new CodeExplorerComponentViewModel(this, parent, members, _projectsProvider, _vbe)); } catch (InvalidOperationException exception) { diff --git a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerViewModel.cs b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerViewModel.cs index 3ada509a02..cb7c0b8ca2 100644 --- a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerViewModel.cs +++ b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerViewModel.cs @@ -382,13 +382,13 @@ private void ParserState_ModuleStateChanged(object sender, ParseProgressEventArg { if (folderNode == null) { - folderNode = new CodeExplorerCustomFolderViewModel(projectNode, projectName, projectName, _state.ProjectsProvider); + folderNode = new CodeExplorerCustomFolderViewModel(projectNode, projectName, projectName, _state.ProjectsProvider, _vbe); projectNode.AddChild(folderNode); } var declaration = CreateDeclaration(e.Module); var newNode = - new CodeExplorerComponentViewModel(folderNode, declaration, new List(), _state.ProjectsProvider) + new CodeExplorerComponentViewModel(folderNode, declaration, new List(), _state.ProjectsProvider, _vbe) { IsErrorState = true }; diff --git a/Rubberduck.Core/Navigation/Folders/FolderHelper.cs b/Rubberduck.Core/Navigation/Folders/FolderHelper.cs index b58fcc5c64..65231df4e9 100644 --- a/Rubberduck.Core/Navigation/Folders/FolderHelper.cs +++ b/Rubberduck.Core/Navigation/Folders/FolderHelper.cs @@ -2,12 +2,14 @@ using Rubberduck.Navigation.CodeExplorer; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; namespace Rubberduck.Navigation.Folders { public class FolderHelper { private readonly RubberduckParserState _state; + private readonly IVBE _vbe; private static readonly DeclarationType[] ComponentTypes = { @@ -17,13 +19,17 @@ public class FolderHelper DeclarationType.UserForm, }; - public FolderHelper(RubberduckParserState state) => _state = state; + public FolderHelper(RubberduckParserState state, IVBE vbe) + { + _state = state; + _vbe = vbe; + } public CodeExplorerCustomFolderViewModel GetFolderTree(Declaration declaration = null) { var delimiter = GetDelimiter(); - var root = new CodeExplorerCustomFolderViewModel(null, string.Empty, string.Empty, _state.ProjectsProvider); + var root = new CodeExplorerCustomFolderViewModel(null, string.Empty, string.Empty, _state.ProjectsProvider, _vbe); var items = declaration == null ? _state.AllUserDeclarations.ToList() @@ -46,7 +52,7 @@ public CodeExplorerCustomFolderViewModel GetFolderTree(Declaration declaration = var node = currentNode.Items.FirstOrDefault(i => i.Name == section); if (node == null) { - node = new CodeExplorerCustomFolderViewModel(currentNode, section, fullPath, _state.ProjectsProvider); + node = new CodeExplorerCustomFolderViewModel(currentNode, section, fullPath, _state.ProjectsProvider, _vbe); currentNode.AddChild(node); } diff --git a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs index 5c4d16a933..6f3ef3aaca 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Runtime.InteropServices; namespace Rubberduck.VBEditor.SafeComWrappers.Abstract @@ -141,6 +142,10 @@ private static IProperty ApplicationPropertyFromDocumentModule(IVBE vbe) public string ApplicationName { get; } + public virtual IEnumerable GetDocuments() => null; + + public virtual IHostDocument GetDocument(QualifiedModuleName moduleName) => null; + public override bool Equals(ISafeComWrapper other) { return IsEqualIfNull(other) || (other != null && ReferenceEquals(other.Target, Target)); diff --git a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs index d651f858c0..cca80fd8be 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs @@ -1,4 +1,7 @@ using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; namespace Rubberduck.VBEditor.SafeComWrappers.Abstract { @@ -12,5 +15,78 @@ public interface IHostApplication : IDisposable /// cannot be used outside assembly boundaries because the type is generic. /// string ApplicationName { get; } + + /// + /// Gets data for the host-specific documents not otherwise exposed via VBIDE API + /// + /// + /// Not all properties are available via VBIDE API. While some properties may be + /// accessed via the , there are problems + /// with using those properties when the document is not in a design mode. For + /// that reason, it's better to get the data using host's object model instead. + /// + IEnumerable GetDocuments(); + + /// + /// Gets data for a host-specific document not otherwise exposed via VBIDE API + /// + /// representing a VBComponent object + /// data + /// + IHostDocument GetDocument(QualifiedModuleName moduleName); + } + + public enum DocumentState + { + /// + /// The document is not open and its accompanying may not be available. + /// + Closed, + /// + /// The document is open in design mode. + /// + DesignView, + /// + /// The document is open in non-design mode. It may not be safe to parse the document in this state. + /// + ActiveView + } + + public interface IHostDocument : IDisposable + { + string Name { get; } + string ClassName { get; } + WeakReference Target { get; } + DocumentState State { get; } + } + + public class HostDocument : IHostDocument + { + public HostDocument(string name, string className, object target, DocumentState state) + { + Name = name; + ClassName = className; + Target = new WeakReference(target); + State = state; + } + + public string Name { get; } + public string ClassName { get; } + public WeakReference Target { get; } + public DocumentState State { get; } + + private bool _disposed; + public void Dispose() + { + if (!_disposed) + { + _disposed = true; + + if (Target.TryGetTarget(out var target)) + { + Marshal.ReleaseComObject(target); + } + } + } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs index e29c8f1188..3a6be986a4 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs @@ -1,3 +1,7 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Microsoft.Office.Interop.Access; using Rubberduck.VBEditor.SafeComWrappers.Abstract; // ReSharper disable once CheckNamespace - Special dispensation due to conflicting file vs namespace priorities @@ -7,5 +11,117 @@ public class AccessApp : HostApplicationBase GetDocuments() + { + var result = new List(); + _CurrentProject currentProject = null; + AllObjects allObjects = null; + Forms forms = null; + Reports reports = null; + + try + { + currentProject = Application.CurrentProject; + allObjects = currentProject.AllForms; + forms = Application.Forms; + + PopulateList(ref result, "Access.Form", allObjects, forms); + + Marshal.ReleaseComObject(allObjects); + + allObjects = currentProject.AllReports; + reports = Application.Reports; + + PopulateList(ref result, "Access.Report", allObjects, reports); + } + finally + { + if (allObjects != null) Marshal.ReleaseComObject(allObjects); + if (forms != null) Marshal.ReleaseComObject(forms); + if (reports != null) Marshal.ReleaseComObject(reports); + if (currentProject != null) Marshal.ReleaseComObject(currentProject); + } + + return result; + } + + private void PopulateList(ref List result, string className, AllObjects allObjects, dynamic objects) + { + foreach (AccessObject accessObject in allObjects) + { + var item = LoadHostDocument(className, accessObject, objects); + result.Add(item); + } + } + + private HostDocument LoadHostDocument(string className, AccessObject accessObject, dynamic objects) + { + var state = DocumentState.Closed; + if (!accessObject.IsLoaded) + { + return new HostDocument(accessObject.Name, className, null, state); + } + + object target = objects[accessObject.Name]; + state = accessObject.CurrentView == AcCurrentView.acCurViewDesign + ? DocumentState.DesignView + : DocumentState.ActiveView; + return new HostDocument(accessObject.Name, className, target, state); + } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs index 41d94c51da..1ca81ccc64 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs @@ -1,5 +1,4 @@ -using System; -using System.Diagnostics; +using System.Collections.Generic; using Rubberduck.VBEditor.SafeComWrappers.Abstract; // ReSharper disable once CheckNamespace - Special dispensation due to conflicting file vs namespace priorities @@ -11,7 +10,8 @@ public FallbackApp(IVBE vbe) { } public string ApplicationName => "(unknown)"; - + public IEnumerable GetDocuments() => null; + public IHostDocument GetDocument(QualifiedModuleName moduleName) => null; public void Dispose() { } } } From 25f9dfed12e0fdf803018be988e5b86d7ad02563 Mon Sep 17 00:00:00 2001 From: Abraham Hosch Date: Thu, 25 Oct 2018 15:53:33 -0500 Subject: [PATCH 008/107] Ignore event handlers too --- .../UnderscoreInPublicClassModuleMemberInspection.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs index faad1120c5..d28ec90c9b 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/UnderscoreInPublicClassModuleMemberInspection.cs @@ -15,9 +15,12 @@ public UnderscoreInPublicClassModuleMemberInspection(RubberduckParserState state protected override IEnumerable DoGetInspectionResults() { + var interfaceMembers = State.DeclarationFinder.FindAllInterfaceImplementingMembers().ToList(); + var eventHandlers = State.DeclarationFinder.FindEventHandlers().ToList(); + var names = State.DeclarationFinder.UserDeclarations(Parsing.Symbols.DeclarationType.Member) .Where(w => w.ParentDeclaration.DeclarationType == Parsing.Symbols.DeclarationType.ClassModule) - .Where(w => !State.DeclarationFinder.FindAllInterfaceImplementingMembers().Contains(w)) + .Where(w => !interfaceMembers.Contains(w) && !eventHandlers.Contains(w)) .Where(w => w.Accessibility == Parsing.Symbols.Accessibility.Public || w.Accessibility == Parsing.Symbols.Accessibility.Implicit) .Where(w => w.IdentifierName.Contains('_')) .ToList(); From 7a64be2f74e60b9f1e86e4b23576d5502072840f Mon Sep 17 00:00:00 2001 From: bclothier Date: Fri, 26 Oct 2018 05:19:33 -0500 Subject: [PATCH 009/107] Introduce SafeIDispatchWrapper class and update HostDocument to avoid toting a object --- .../SafeComWrappers/SafeIDispatchWrapper.cs | 61 +++++++++++++++++++ .../VB/Abstract/IHostApplication.cs | 30 ++++----- 2 files changed, 77 insertions(+), 14 deletions(-) create mode 100644 Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs diff --git a/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs new file mode 100644 index 0000000000..2132ca0933 --- /dev/null +++ b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs @@ -0,0 +1,61 @@ +using System; +using System.Runtime.InteropServices; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; + +namespace Rubberduck.VBEditor.SafeComWrappers +{ + public class SafeIDispatchWrapper : SafeComWrapper + { + public SafeIDispatchWrapper(object target, bool rewrapping = false) : base(target, rewrapping) + { + if (!Marshal.IsComObject(target)) + { + throw new ArgumentException("The target object must be a COM object"); + } + + IDispatchPointer = GetPointer(target); + } + + public IntPtr IDispatchPointer { get; } + + public void Invoke(Action action) + { + action.Invoke(Target); + } + + public override bool Equals(ISafeComWrapper other) + { + if (other.IsWrappingNullReference || IsWrappingNullReference) + { + return false; + } + + var otherPtr = GetPointer(other); + + return IDispatchPointer == otherPtr; + } + + public override int GetHashCode() + { + return unchecked((int)IDispatchPointer); + } + + private static IntPtr GetPointer(object target) + { + var result = IntPtr.Zero; + try + { + result = Marshal.GetIDispatchForObject(target); + } + finally + { + if (result != IntPtr.Zero) + { + Marshal.Release(result); + } + } + + return result; + } + } +} diff --git a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs index cca80fd8be..7d24b54a87 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs @@ -52,40 +52,42 @@ public enum DocumentState ActiveView } - public interface IHostDocument : IDisposable + public interface IHostDocument { string Name { get; } string ClassName { get; } - WeakReference Target { get; } DocumentState State { get; } + bool TryGetTarget(out SafeIDispatchWrapper iDispatch) } public class HostDocument : IHostDocument { - public HostDocument(string name, string className, object target, DocumentState state) + private readonly Func _getTargetFunc; + + public HostDocument(string name, string className, DocumentState state, Func getTargetFunc) { Name = name; ClassName = className; - Target = new WeakReference(target); State = state; + + _getTargetFunc = getTargetFunc; } public string Name { get; } public string ClassName { get; } - public WeakReference Target { get; } public DocumentState State { get; } - private bool _disposed; - public void Dispose() + public bool TryGetTarget(out SafeIDispatchWrapper iDispatch) { - if (!_disposed) + try { - _disposed = true; - - if (Target.TryGetTarget(out var target)) - { - Marshal.ReleaseComObject(target); - } + iDispatch = _getTargetFunc.Invoke(); + return true; + } + catch + { + iDispatch = null; + return false; } } } From e3fceb31e82e59b921ecbc8a999ad6e4b5f50c74 Mon Sep 17 00:00:00 2001 From: bclothier Date: Fri, 26 Oct 2018 05:24:22 -0500 Subject: [PATCH 010/107] Save changes to Settings.Designer.cs after merging with the next (not sure why git think it's changed....) --- Rubberduck.Core/Properties/Settings.Designer.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Rubberduck.Core/Properties/Settings.Designer.cs b/Rubberduck.Core/Properties/Settings.Designer.cs index ee6f0cea80..9c9c23a4ea 100644 --- a/Rubberduck.Core/Properties/Settings.Designer.cs +++ b/Rubberduck.Core/Properties/Settings.Designer.cs @@ -305,7 +305,8 @@ public static Settings Default { false false 10 - 6 + false + 0 ")] public global::Rubberduck.Settings.GeneralSettings GeneralSettings { From 22a42d3a3e1e680b4ea7c412137a62bb5b786322 Mon Sep 17 00:00:00 2001 From: bclothier Date: Fri, 26 Oct 2018 07:02:12 -0500 Subject: [PATCH 011/107] Introduce SafeIDispatchWrapper class to simplify the management of COM interfaces for where we do not want to define a full SafeComWrapper Clean up the messy implementation in AccessApp and use SafeIDispatchWrapper Split HostDocument and its associated objects into its own file --- .../CodeExplorerComponentViewModel.cs | 2 +- .../Abstract/HostApplicationBase.cs | 4 +- .../SafeComWrappers/SafeIDispatchWrapper.cs | 8 ++ .../VB/Abstract/HostDocument.cs | 78 ++++++++++++++ .../VB/Abstract/IHostApplication.cs | 64 +---------- .../SafeComWrappers/Application/AccessApp.cs | 100 +++++------------- .../Application/FallbackApp.cs | 4 +- 7 files changed, 121 insertions(+), 139 deletions(-) create mode 100644 Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs diff --git a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs index 202390740a..f925e1a066 100644 --- a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs +++ b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs @@ -70,8 +70,8 @@ public CodeExplorerComponentViewModel(CodeExplorerItemViewModel parent, Declarat case ComponentType.Document: string parenthesizedName; using (var app = _vbe.HostApplication()) - using (var document = app.GetDocument(qualifiedModuleName)) { + var document = app.GetDocument(qualifiedModuleName); parenthesizedName = document.Name ?? string.Empty; } diff --git a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs index 6f3ef3aaca..c400405fcc 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs @@ -142,9 +142,9 @@ private static IProperty ApplicationPropertyFromDocumentModule(IVBE vbe) public string ApplicationName { get; } - public virtual IEnumerable GetDocuments() => null; + public virtual IEnumerable GetDocuments() => null; - public virtual IHostDocument GetDocument(QualifiedModuleName moduleName) => null; + public virtual HostDocument GetDocument(QualifiedModuleName moduleName) => null; public override bool Equals(ISafeComWrapper other) { diff --git a/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs index 2132ca0933..b9add52e87 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs @@ -4,6 +4,14 @@ namespace Rubberduck.VBEditor.SafeComWrappers { + public class SafeIDispatchWrapper : SafeIDispatchWrapper + { + public SafeIDispatchWrapper(TDispatch target, bool rewrapping = false) : base(target, rewrapping) + { } + + public new TDispatch Target => (TDispatch) base.Target; + } + public class SafeIDispatchWrapper : SafeComWrapper { public SafeIDispatchWrapper(object target, bool rewrapping = false) : base(target, rewrapping) diff --git a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs new file mode 100644 index 0000000000..8518ea65c6 --- /dev/null +++ b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs @@ -0,0 +1,78 @@ +using System; + +namespace Rubberduck.VBEditor.SafeComWrappers.Abstract +{ + /// + /// Provides a generic manner of reporting document state for use within Rubberduck + /// + /// + /// Different hosts may have different states and they may behave differently. For example, + /// Excel's Worksheet document has no true design-time state; only time it is locked is when + /// the focus is inside the formula box in the Excel UI. On the other hand, Access has both + /// a design time and a run time state for its Form document and Report document. The enum + /// is meant to provide a generic representation and must correspond exactly to how the host + /// will treat the document. All hosts need not implement the full set of the enum but must + /// represent it exactly as per the description of the enum member. + /// + public enum DocumentState + { + /// + /// The document is not open and its accompanying is not available. + /// + Closed, + /// + /// The document is open in design mode. + /// + DesignView, + /// + /// The document is open in non-design mode. Not all design-time operations are available. + /// + ActiveView + } + + public interface IHostDocument + { + string Name { get; } + string ClassName { get; } + DocumentState State { get; } + bool TryGetTarget(out SafeIDispatchWrapper iDispatch); + } + + public class HostDocument : IHostDocument + { + private readonly Func _getTargetFunc; + + public HostDocument(string name, string className, DocumentState state, Func getTargetFunc) + { + Name = name; + ClassName = className; + State = state; + + _getTargetFunc = getTargetFunc; + } + + public string Name { get; } + public string ClassName { get; } + public DocumentState State { get; } + + public bool TryGetTarget(out SafeIDispatchWrapper iDispatch) + { + if (_getTargetFunc == null) + { + iDispatch = null; + return false; + } + + try + { + iDispatch = _getTargetFunc.Invoke(); + return true; + } + catch + { + iDispatch = null; + return false; + } + } + } +} \ No newline at end of file diff --git a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs index 7d24b54a87..1a8b32c295 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/IHostApplication.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; namespace Rubberduck.VBEditor.SafeComWrappers.Abstract { @@ -25,70 +23,14 @@ public interface IHostApplication : IDisposable /// with using those properties when the document is not in a design mode. For /// that reason, it's better to get the data using host's object model instead. /// - IEnumerable GetDocuments(); + IEnumerable GetDocuments(); /// /// Gets data for a host-specific document not otherwise exposed via VBIDE API /// /// representing a VBComponent object - /// data + /// data /// - IHostDocument GetDocument(QualifiedModuleName moduleName); - } - - public enum DocumentState - { - /// - /// The document is not open and its accompanying may not be available. - /// - Closed, - /// - /// The document is open in design mode. - /// - DesignView, - /// - /// The document is open in non-design mode. It may not be safe to parse the document in this state. - /// - ActiveView - } - - public interface IHostDocument - { - string Name { get; } - string ClassName { get; } - DocumentState State { get; } - bool TryGetTarget(out SafeIDispatchWrapper iDispatch) - } - - public class HostDocument : IHostDocument - { - private readonly Func _getTargetFunc; - - public HostDocument(string name, string className, DocumentState state, Func getTargetFunc) - { - Name = name; - ClassName = className; - State = state; - - _getTargetFunc = getTargetFunc; - } - - public string Name { get; } - public string ClassName { get; } - public DocumentState State { get; } - - public bool TryGetTarget(out SafeIDispatchWrapper iDispatch) - { - try - { - iDispatch = _getTargetFunc.Invoke(); - return true; - } - catch - { - iDispatch = null; - return false; - } - } + HostDocument GetDocument(QualifiedModuleName moduleName); } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs index 3a6be986a4..95827cd10e 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Generic; -using System.Runtime.InteropServices; using Microsoft.Office.Interop.Access; using Rubberduck.VBEditor.SafeComWrappers.Abstract; @@ -11,117 +9,73 @@ public class AccessApp : HostApplicationBase(Application.CurrentProject)) + using (var allForms = new SafeIDispatchWrapper(currentProject.Target.AllForms)) + using (var forms = new SafeIDispatchWrapper(Application.Forms)) + using (var accessObject = new SafeIDispatchWrapper(allForms.Target[name])) + { return LoadHostDocument("Access.Form", accessObject, forms); } - finally - { - if (forms != null) Marshal.ReleaseComObject(forms); - if (accessObject != null) Marshal.ReleaseComObject(accessObject); - if (allForms != null) Marshal.ReleaseComObject(allForms); - if (currentProject != null) Marshal.ReleaseComObject(currentProject); - } } if (moduleName.ComponentName.StartsWith("Report_")) { var name = moduleName.ComponentName.Substring("Report_".Length); - _CurrentProject currentProject = null; - AllObjects allForms = null; - AccessObject accessObject = null; - Reports reports = null; - try + using (var currentProject = new SafeIDispatchWrapper<_CurrentProject>(Application.CurrentProject)) + using (var allReports = new SafeIDispatchWrapper(currentProject.Target.AllReports)) + using (var reports = new SafeIDispatchWrapper(Application.Reports)) + using (var accessObject = new SafeIDispatchWrapper(allReports.Target[name])) { - currentProject = Application.CurrentProject; - reports = Application.Reports; - allForms = currentProject.AllForms; - accessObject = allForms[name]; - return LoadHostDocument("Access.Report", accessObject, reports); } - finally - { - if (reports != null) Marshal.ReleaseComObject(reports); - if (accessObject != null) Marshal.ReleaseComObject(accessObject); - if (allForms != null) Marshal.ReleaseComObject(allForms); - if (currentProject != null) Marshal.ReleaseComObject(currentProject); - } } return null; } - public override IEnumerable GetDocuments() + public override IEnumerable GetDocuments() { var result = new List(); - _CurrentProject currentProject = null; - AllObjects allObjects = null; - Forms forms = null; - Reports reports = null; - - try + using (var currentProject = new SafeIDispatchWrapper<_CurrentProject>(Application.CurrentProject)) + using (var allForms = new SafeIDispatchWrapper(currentProject.Target.AllForms)) + using (var allReports = new SafeIDispatchWrapper(currentProject.Target.AllReports)) + using (var forms = new SafeIDispatchWrapper(Application.Forms)) + using (var reports = new SafeIDispatchWrapper(Application.Reports)) { - currentProject = Application.CurrentProject; - allObjects = currentProject.AllForms; - forms = Application.Forms; - - PopulateList(ref result, "Access.Form", allObjects, forms); - - Marshal.ReleaseComObject(allObjects); - - allObjects = currentProject.AllReports; - reports = Application.Reports; - - PopulateList(ref result, "Access.Report", allObjects, reports); + PopulateList(ref result, "Access.Form", allForms, forms); + PopulateList(ref result, "Access.Report", allReports, reports); } - finally - { - if (allObjects != null) Marshal.ReleaseComObject(allObjects); - if (forms != null) Marshal.ReleaseComObject(forms); - if (reports != null) Marshal.ReleaseComObject(reports); - if (currentProject != null) Marshal.ReleaseComObject(currentProject); - } - + return result; } - private void PopulateList(ref List result, string className, AllObjects allObjects, dynamic objects) + private void PopulateList(ref List result, string className, SafeIDispatchWrapper allObjects, dynamic objects) { - foreach (AccessObject accessObject in allObjects) + foreach (AccessObject rawAccessObject in allObjects.Target) + using (var accessObject = new SafeIDispatchWrapper(rawAccessObject)) { var item = LoadHostDocument(className, accessObject, objects); result.Add(item); } } - private HostDocument LoadHostDocument(string className, AccessObject accessObject, dynamic objects) + private HostDocument LoadHostDocument(string className, SafeIDispatchWrapper accessObject, dynamic objects) { var state = DocumentState.Closed; - if (!accessObject.IsLoaded) + if (!accessObject.Target.IsLoaded) { - return new HostDocument(accessObject.Name, className, null, state); + return new HostDocument(accessObject.Target.Name, className, state, null); } - object target = objects[accessObject.Name]; - state = accessObject.CurrentView == AcCurrentView.acCurViewDesign + state = accessObject.Target.CurrentView == AcCurrentView.acCurViewDesign ? DocumentState.DesignView : DocumentState.ActiveView; - return new HostDocument(accessObject.Name, className, target, state); + return new HostDocument(accessObject.Target.Name, className, state, null); } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs index 1ca81ccc64..85a9b60a73 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/FallbackApp.cs @@ -10,8 +10,8 @@ public FallbackApp(IVBE vbe) { } public string ApplicationName => "(unknown)"; - public IEnumerable GetDocuments() => null; - public IHostDocument GetDocument(QualifiedModuleName moduleName) => null; + public IEnumerable GetDocuments() => null; + public HostDocument GetDocument(QualifiedModuleName moduleName) => null; public void Dispose() { } } } From f0a2101c010c6719d891efa2b2dff9bf25658667 Mon Sep 17 00:00:00 2001 From: bclothier Date: Fri, 26 Oct 2018 07:02:35 -0500 Subject: [PATCH 012/107] Fix up unit tests --- .../CodeExplorer/CodeExplorerTests.cs | 154 +++++++++--------- 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs index 7e2211e59f..6d4a7c938f 100644 --- a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs +++ b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs @@ -68,7 +68,7 @@ public void AddStdModule() var messageBox = new Mock(); var saveFileDialog = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddStdModuleCommand = new AddStdModuleCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -106,7 +106,7 @@ public bool AddStdModule_CanExecuteBasedOnProjectType(ProjectType projectType) using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddStdModuleCommand = new AddStdModuleCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -140,7 +140,7 @@ public void AddClassModule() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddClassModuleCommand = new AddClassModuleCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -178,7 +178,7 @@ public bool AddClassModule_CanExecuteBasedOnProjectType(ProjectType projectType) using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddClassModuleCommand = new AddClassModuleCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -212,7 +212,7 @@ public void AddUserForm() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserFormCommand = new AddUserFormCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -249,7 +249,7 @@ public bool AddUserForm_CanExecuteBasedOnProjectType(ProjectType projectType) using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserFormCommand = new AddUserFormCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -280,7 +280,7 @@ public void AddVBForm() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddVBFormCommand = new AddVBFormCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -317,7 +317,7 @@ public bool AddVBForm_CanExecuteBasedOnProjectType(ProjectType projectType) using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddVBFormCommand = new AddVBFormCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -348,7 +348,7 @@ public void AddMDIForm() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddMDIFormCommand = new AddMDIFormCommand(vbe.Object, new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -385,7 +385,7 @@ public bool AddMDIForm_CanExecuteBasedOnProjectType(ProjectType projectType) using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddMDIFormCommand = new AddMDIFormCommand(vbe.Object, new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -415,7 +415,7 @@ public void AddMDIForm_CannotExecuteIfProjectAlreadyHasMDIForm() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddMDIFormCommand = new AddMDIFormCommand(vbe.Object, new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -446,7 +446,7 @@ public void AddUserControlForm() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserControlCommand = new AddUserControlCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -483,7 +483,7 @@ public bool AddUserControl_CanExecuteBasedOnProjectType(ProjectType projectType) using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserControlCommand = new AddUserControlCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -514,7 +514,7 @@ public void AddPropertyPage() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddPropertyPageCommand = new AddPropertyPageCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -550,7 +550,7 @@ public bool AddPropertyPage_CanExecuteBasedOnProjectType(ProjectType projectType using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddPropertyPageCommand = new AddPropertyPageCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -581,7 +581,7 @@ public void AddUserDocument() using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserDocumentCommand = new AddUserDocumentCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -617,7 +617,7 @@ public bool AddUserDocument_CanExecuteBasedOnProjectType(ProjectType projectType using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) { - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserDocumentCommand = new AddUserDocumentCommand(new AddComponentCommand(vbe.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -656,7 +656,7 @@ public void AddTestModule() var uiDispatcher = new Mock(); var interaction = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddTestModuleCommand = new AddTestModuleCommand(vbeWrapper, state, configLoader.Object, messageBox.Object, interaction.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -697,7 +697,7 @@ public void AddTestModuleWithStubs() var interaction = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddTestModuleWithStubsCommand = new AddTestModuleWithStubsCommand(vbeWrapper, new AddTestModuleCommand(vbeWrapper, state, configLoader.Object, messageBox.Object, interaction.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -736,7 +736,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsProject() var interaction = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddTestModuleWithStubsCommand = new AddTestModuleWithStubsCommand(vbeWrapper, new AddTestModuleCommand(vbeWrapper, state, configLoader.Object, messageBox.Object, interaction.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -774,7 +774,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsFolder() var interaction = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddTestModuleWithStubsCommand = new AddTestModuleWithStubsCommand(vbeWrapper, new AddTestModuleCommand(vbeWrapper, state, configLoader.Object, messageBox.Object, interaction.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -812,7 +812,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsModuleMember() var interaction = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddTestModuleWithStubsCommand = new AddTestModuleWithStubsCommand(vbeWrapper, new AddTestModuleCommand(vbeWrapper, state, configLoader.Object, messageBox.Object, interaction.Object)); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -858,7 +858,7 @@ public void ImportModule() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ImportCommand = new ImportCommand(vbe.Object, openFileDialog.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -905,7 +905,7 @@ public void ImportMultipleModules() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ImportCommand = new ImportCommand(vbe.Object, openFileDialog.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -953,7 +953,7 @@ public void ImportModule_Cancel() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ImportCommand = new ImportCommand(vbe.Object, openFileDialog.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -993,7 +993,7 @@ public void ExportModule_ExpectExecution() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ExportCommand = new ExportCommand(saveFileDialog.Object, state.ProjectsProvider); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1033,7 +1033,7 @@ public void ExportModule_CancelPressed_ExpectNoExecution() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ExportCommand = new ExportCommand(saveFileDialog.Object, state.ProjectsProvider); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1076,7 +1076,7 @@ public void ExportProject_TestCanExecute_ExpectTrue() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ExportAllCommand = new ExportAllCommand(vbe.Object, mockFolderBrowserFactory.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1134,7 +1134,7 @@ public void ExportProject_TestExecute_OKPressed_ExpectExecution() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ExportAllCommand = new ExportAllCommand(null, mockFolderBrowserFactory.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1192,7 +1192,7 @@ public void ExportProject_TestExecute_CancelPressed_ExpectExecution() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.ExportAllCommand = new ExportAllCommand(null, mockFolderBrowserFactory.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1228,7 +1228,7 @@ public void OpenDesigner() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.OpenDesignerCommand = new OpenDesignerCommand(state.ProjectsProvider); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1274,7 +1274,7 @@ public void RemoveCommand_RemovesModuleWhenPromptOk() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -1318,7 +1318,7 @@ public void RemoveCommand_CancelsWhenFilePromptCancels() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -1358,7 +1358,7 @@ public void RemoveCommand_GivenMsgBoxNO_RemovesModuleNoExport() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -1402,7 +1402,7 @@ public void RemoveModule_Cancel() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -1445,7 +1445,7 @@ End Sub var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1484,7 +1484,7 @@ Dim d As Boolean var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1537,7 +1537,7 @@ End Sub var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1600,7 +1600,7 @@ End Sub var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1645,7 +1645,7 @@ Dim d As Boolean var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1703,7 +1703,7 @@ End Sub var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1771,7 +1771,7 @@ End Sub var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1817,7 +1817,7 @@ Dim d As Boolean var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.IndenterCommand = new IndentCommand(state, new Indenter(vbe.Object, () => Settings.IndenterSettingsTests.GetMockIndenterSettings()), null); var parser = MockParser.Create(vbe.Object, state, projectRepository); @@ -1849,7 +1849,7 @@ public void ExpandAllNodes() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -1885,7 +1885,7 @@ public void ExpandAllNodes_StartingWithSubnode() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -1921,7 +1921,7 @@ public void CollapseAllNodes() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -1957,7 +1957,7 @@ public void CollapseAllNodes_StartingWithSubnode() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2004,7 +2004,7 @@ public void SetSortByName_NotAlreadySelectedInMenu_ExpectTrue() var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2049,7 +2049,7 @@ public void SetSortByName_AlreadySelectedInMenu_ExpectTrue() var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2094,7 +2094,7 @@ public void SetSortByName_BothSortOptionsFalse_ExpectTrueOnlyForSortByName() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2140,7 +2140,7 @@ public void SetSortByName_BothSortOptionsTrue_ExpectTrueOnlyForSortByName() _windowSettingsProvider.Setup(s => s.Create()).Returns(windowSettings); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2185,7 +2185,7 @@ public void SetSortByCodeOrder_NotAlreadySelectedInMenu_ExpectTrue() var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2230,7 +2230,7 @@ public void SetSortByCodeOrder_AlreadySelectedInMenu_ExpectTrue() var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var uiDispatcher = new Mock(); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2275,7 +2275,7 @@ public void SetSortByCodeOrder_BothSortOptionsFalse_ExpectCorrectSortPair() var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2320,7 +2320,7 @@ public void SetSortByCodeOrder_BothSortOptionsTrue_ExpectCorrectSortPair() var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2338,7 +2338,7 @@ public void SetSortByCodeOrder_BothSortOptionsTrue_ExpectCorrectSortPair() [Test] public void CompareByName_ReturnsZeroForIdenticalNodes() { - var folderNode = new CodeExplorerCustomFolderViewModel(null, "Name", "Name", null); + var folderNode = new CodeExplorerCustomFolderViewModel(null, "Name", "Name", null, null); Assert.AreEqual(0, new CompareByName().Compare(folderNode, folderNode)); } @@ -2347,8 +2347,8 @@ public void CompareByName_ReturnsZeroForIdenticalNodes() public void CompareByName_ReturnsZeroForIdenticalNames() { // this won't happen, but just to be thorough...--besides, it is good for the coverage - var folderNode1 = new CodeExplorerCustomFolderViewModel(null, "Name", "Name", null); - var folderNode2 = new CodeExplorerCustomFolderViewModel(null, "Name", "Name", null); + var folderNode1 = new CodeExplorerCustomFolderViewModel(null, "Name", "Name", null, null); + var folderNode2 = new CodeExplorerCustomFolderViewModel(null, "Name", "Name", null, null); Assert.AreEqual(0, new CompareByName().Compare(folderNode1, folderNode2)); } @@ -2358,8 +2358,8 @@ public void CompareByName_ReturnsZeroForIdenticalNames() public void CompareByName_ReturnsCorrectOrdering() { // this won't happen, but just to be thorough...--besides, it is good for the coverage - var folderNode1 = new CodeExplorerCustomFolderViewModel(null, "Name1", "Name1", null); - var folderNode2 = new CodeExplorerCustomFolderViewModel(null, "Name2", "Name2", null); + var folderNode1 = new CodeExplorerCustomFolderViewModel(null, "Name1", "Name1", null, null); + var folderNode2 = new CodeExplorerCustomFolderViewModel(null, "Name2", "Name2", null, null); Assert.IsTrue(new CompareByName().Compare(folderNode1, folderNode2) < 0); } @@ -2368,7 +2368,7 @@ public void CompareByName_ReturnsCorrectOrdering() [Test] public void CompareByType_ReturnsZeroForIdenticalNodes() { - var errorNode = new CodeExplorerCustomFolderViewModel(null, "Name", "folder1.folder2", null); + var errorNode = new CodeExplorerCustomFolderViewModel(null, "Name", "folder1.folder2", null, null); Assert.AreEqual(0, new CompareByName().Compare(errorNode, errorNode)); } @@ -2392,7 +2392,7 @@ public void CompareByType_ReturnsEventAboveConst() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2424,7 +2424,7 @@ public void CompareByType_ReturnsConstAboveField() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2459,7 +2459,7 @@ End Property { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2495,7 +2495,7 @@ End Property { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2531,7 +2531,7 @@ End Property { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2567,7 +2567,7 @@ End Property { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2603,7 +2603,7 @@ End Property { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2639,7 +2639,7 @@ End Function { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2675,7 +2675,7 @@ End Sub { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2711,7 +2711,7 @@ End Sub { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2744,7 +2744,7 @@ public void CompareByType_ReturnsClassModuleBelowDocument() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2784,7 +2784,7 @@ Sub Bar() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2820,7 +2820,7 @@ Sub Bar() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2856,7 +2856,7 @@ Sub Bar() { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); - var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); + var vm = new CodeExplorerViewModel(new FolderHelper(state, vbe.Object), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); var parser = MockParser.Create(vbe.Object, state, projectRepository); parser.Parse(new CancellationTokenSource()); @@ -2872,8 +2872,8 @@ Sub Bar() [Test] public void CompareByNodeType_FoldersAreSortedByName() { - var folderNode1 = new CodeExplorerCustomFolderViewModel(null, "AAA", string.Empty, null); - var folderNode2 = new CodeExplorerCustomFolderViewModel(null, "zzz", string.Empty, null); + var folderNode1 = new CodeExplorerCustomFolderViewModel(null, "AAA", string.Empty, null, null); + var folderNode2 = new CodeExplorerCustomFolderViewModel(null, "zzz", string.Empty, null, null); Assert.IsTrue(new CompareByNodeType().Compare(folderNode1, folderNode2) < 0); } From fdb782a45f5d24484c7dedac3897b5b2ab2747fe Mon Sep 17 00:00:00 2001 From: bclothier Date: Sat, 27 Oct 2018 00:36:01 -0500 Subject: [PATCH 013/107] Address PR comments Enhance the base to provide a useful default behavior (accessing VBComponent.Properties) Require VBE for ctor for all hosts (necessary for useful default behavior) Update all host implementation to pass in VBE in the ctor, preserving the original preferences of loading via reflection or via VBE --- .../CodeExplorerComponentViewModel.cs | 19 +- .../Abstract/HostApplicationBase.cs | 167 +++++++++++++----- .../SafeComWrappers/SafeIDispatchWrapper.cs | 4 +- .../VB/Abstract/HostDocument.cs | 16 +- .../SafeComWrappers/Application/AccessApp.cs | 139 ++++++++++++--- .../SafeComWrappers/Application/AutoCADApp.cs | 3 +- .../Application/CorelDRAWApp.cs | 4 +- .../SafeComWrappers/Application/ExcelApp.cs | 4 +- .../SafeComWrappers/Application/OutlookApp.cs | 4 +- .../Application/PowerPointApp.cs | 7 +- .../SafeComWrappers/Application/ProjectApp.cs | 3 +- .../Application/PublisherApp.cs | 2 +- .../Application/SolidWorksApp.cs | 1 - .../SafeComWrappers/Application/Visio.cs | 3 +- .../SafeComWrappers/Application/WordApp.cs | 3 +- .../SafeComWrappers/VB/VBE.cs | 39 ++-- 16 files changed, 281 insertions(+), 137 deletions(-) diff --git a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs index f925e1a066..c1dbc97079 100644 --- a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs +++ b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Runtime.InteropServices; using System.Windows.Media.Imaging; +using NLog; using Rubberduck.Parsing.Symbols; using Rubberduck.VBEditor; using Rubberduck.Parsing.Annotations; @@ -68,14 +69,19 @@ public CodeExplorerComponentViewModel(CodeExplorerItemViewModel parent, Declarat switch (qualifiedModuleName.ComponentType) { case ComponentType.Document: - string parenthesizedName; + var parenthesizedName = string.Empty; + var state = DocumentState.Inaccessible; using (var app = _vbe.HostApplication()) { - var document = app.GetDocument(qualifiedModuleName); - parenthesizedName = document.Name ?? string.Empty; + if (app != null) + { + var document = app.GetDocument(qualifiedModuleName); + parenthesizedName = document?.ModuleName ?? string.Empty; + state = document?.State ?? DocumentState.Inaccessible; + } } - if (ContainsBuiltinDocumentPropertiesProperty()) + if (state == DocumentState.DesignView && ContainsBuiltinDocumentPropertiesProperty()) { CodeExplorerItemViewModel node = this; while (node.Parent != null) @@ -87,7 +93,10 @@ public CodeExplorerComponentViewModel(CodeExplorerItemViewModel parent, Declarat } else { - _name += " (" + parenthesizedName + ")"; + if (!string.IsNullOrWhiteSpace(parenthesizedName)) + { + _name += " (" + parenthesizedName + ")"; + } } break; diff --git a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs index c400405fcc..e97d646c20 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/Abstract/HostApplicationBase.cs @@ -8,15 +8,14 @@ namespace Rubberduck.VBEditor.SafeComWrappers.Abstract public abstract class HostApplicationBase : SafeComWrapper, IHostApplication where TApplication : class { - protected HostApplicationBase(string applicationName) - :base(ApplicationFromComReflection(applicationName)) - { - ApplicationName = applicationName; - } + protected readonly IVBE Vbe; - protected HostApplicationBase(IVBE vbe, string applicationName) - :base(ApplicationFromVbe(vbe, applicationName)) + protected HostApplicationBase(IVBE vbe, string applicationName, bool useComReflection = false) + : base(useComReflection + ? ApplicationFromComReflection(applicationName) + : ApplicationFromVbe(vbe, applicationName)) { + Vbe = vbe; ApplicationName = applicationName; } @@ -30,20 +29,21 @@ private static TApplication ApplicationFromComReflection(string applicationName) catch (COMException exception) { _logger.Error(exception, $"Unexpected COM exception while acquiring the host application object for application {applicationName} via COM reflection."); - application = null; // We currently really only use the name anyway. + application = null; } catch (InvalidCastException exception) { //TODO: Find out why this ever happens. _logger.Error(exception, $"Unable to cast the host application object for application {applicationName} acquired via COM reflection to its PIA type."); - application = null; //We currently really only use the name anyway. + application = null; } catch (Exception exception) { //note: We catch all exceptions because we currently really do not need application object and there can be exceptions for unexpected system setups. _logger.Error(exception, $"Unexpected exception while acquiring the host application object for application {applicationName} from a document module."); - application = null; //We currently really only use the name anyway. + application = null; } + return application; } @@ -68,18 +68,18 @@ private static TApplication ApplicationFromVbe(IVBE vbe, string applicationName) catch (COMException exception) { _logger.Error(exception, $"Unexpected COM exception while acquiring the host application object for application {applicationName} from a document module."); - application = null; // We currently really only use the name anyway. + application = null; } catch (InvalidCastException exception) { _logger.Error(exception, $"Unable to cast the host application object for application {applicationName} acquiered from a document module to its PIA type."); - application = null; //We currently really only use the name anyway. + application = null; } catch (Exception exception) { //note: We catch all exceptions because we currently really do not need application object and there can be exceptions for unexpected system setups. _logger.Error(exception, $"Unexpected exception while acquiring the host application object for application {applicationName} from a document module."); - application = null; //We currently really only use the name anyway. + application = null; } return application; } @@ -89,50 +89,41 @@ private static IProperty ApplicationPropertyFromDocumentModule(IVBE vbe) using (var projects = vbe.VBProjects) { foreach (var project in projects) + using (project) { - try + if (project.Protection == ProjectProtection.Locked) { - if (project.Protection == ProjectProtection.Locked) - { - continue; - } - using (var components = project.VBComponents) + continue; + } + + using (var components = project.VBComponents) + { + foreach (var component in components) + using (component) { - foreach (var component in components) + if (component.Type != ComponentType.Document) { - try + continue; + } + + using (var properties = component.Properties) + { + if (properties.Count <= 1) { - if (component.Type != ComponentType.Document) - { - continue; - } - using (var properties = component.Properties) - { - if (properties.Count <= 1) - { - continue; - } - foreach (var property in properties) - { - if (property.Name == "Application") - { - return property; - } - property.Dispose(); - } - } + continue; } - finally + + foreach (var property in properties) + using(property) { - component.Dispose(); + if (property.Name == "Application") + { + return property; + } } } } } - finally - { - project?.Dispose(); - } } return null; } @@ -142,9 +133,89 @@ private static IProperty ApplicationPropertyFromDocumentModule(IVBE vbe) public string ApplicationName { get; } - public virtual IEnumerable GetDocuments() => null; + private const string ComponentName = "VBIDE.VBComponent"; + + public virtual IEnumerable GetDocuments() + { + var result = new List(); + + foreach (var document in DocumentComponents()) + { + var moduleName = new QualifiedModuleName(document); + var name = GetName(document); + + result.Add(new HostDocument(moduleName, name, ComponentName, DocumentState.DesignView, null)); + } + return result; + } + + public virtual HostDocument GetDocument(QualifiedModuleName moduleName) + { + using (var projects = Vbe.VBProjects) + { + foreach (var project in projects) + using(project) + { + if (moduleName.ProjectName != project.Name || moduleName.ProjectId != project.HelpFile) + { + continue; + } + + using (var components = project.VBComponents) + using (var component = components[moduleName.ComponentName]) + { + var name = GetName(component); + return new HostDocument(moduleName, name, ComponentName, DocumentState.DesignView, null); + } + } + } + + return null; + } + + private static string GetName(IVBComponent component) + { + var name = string.Empty; + try + { + using (var properties = component.Properties) + using (var nameProperty = properties["Name"]) + { + name = nameProperty?.Value.ToString() ?? string.Empty; + } + } + catch (Exception ex) + { + _logger.Trace(ex, "Handled an expection with accessing VBComponent.Properties."); + } - public virtual HostDocument GetDocument(QualifiedModuleName moduleName) => null; + if (string.IsNullOrWhiteSpace(name)) + { + name = component.Name; + } + + return name; + } + + protected IEnumerable DocumentComponents() + { + using (var projects = Vbe.VBProjects) + { + foreach (var project in projects) + using (project) + using (var components = project.VBComponents) + { + foreach (var component in components) + using (component) + { + if (component.Type == ComponentType.Document) + { + yield return component; + } + } + } + } + } public override bool Equals(ISafeComWrapper other) { diff --git a/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs index b9add52e87..42500fd238 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs @@ -38,9 +38,7 @@ public override bool Equals(ISafeComWrapper other) return false; } - var otherPtr = GetPointer(other); - - return IDispatchPointer == otherPtr; + return IDispatchPointer == GetPointer(other); } public override int GetHashCode() diff --git a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs index 8518ea65c6..5181acebeb 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs @@ -17,9 +17,10 @@ namespace Rubberduck.VBEditor.SafeComWrappers.Abstract public enum DocumentState { /// - /// The document is not open and its accompanying is not available. + /// The document is not accessible. It might be closed or otherwise unavailable. In this case + /// it should be presumed it is not safe to use the of that document. /// - Closed, + Inaccessible, /// /// The document is open in design mode. /// @@ -32,7 +33,8 @@ public enum DocumentState public interface IHostDocument { - string Name { get; } + QualifiedModuleName QualifiedName { get; } + string ModuleName { get; } string ClassName { get; } DocumentState State { get; } bool TryGetTarget(out SafeIDispatchWrapper iDispatch); @@ -42,16 +44,18 @@ public class HostDocument : IHostDocument { private readonly Func _getTargetFunc; - public HostDocument(string name, string className, DocumentState state, Func getTargetFunc) + public HostDocument(QualifiedModuleName qualifedName, string name, string className, DocumentState state, Func getTargetFunc) { - Name = name; + QualifiedName = qualifedName; + ModuleName = name; ClassName = className; State = state; _getTargetFunc = getTargetFunc; } - public string Name { get; } + public QualifiedModuleName QualifiedName { get; } + public string ModuleName { get; } public string ClassName { get; } public DocumentState State { get; } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs index 95827cd10e..37ee2b2630 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AccessApp.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using Microsoft.Office.Interop.Access; using Rubberduck.VBEditor.SafeComWrappers.Abstract; @@ -7,31 +8,46 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class AccessApp : HostApplicationBase { - public AccessApp() : base("Access") { } + private const string FormNamePrefix = "Form_"; + private const string FormClassName = "Access.Form"; + private const string ReportNamePrefix = "Report_"; + private const string ReportClassName = "Access.Report"; + + private readonly Lazy _dbcProject; + + public AccessApp(IVBE vbe) : base(vbe, "Access", true) + { + _dbcProject = new Lazy(() => + { + using (var wizHook = new SafeIDispatchWrapper(Application.WizHook)) + { + wizHook.Target.Key = 51488399; + return new VBProject(wizHook.Target.DbcVbProject); + } + }); + } public override HostDocument GetDocument(QualifiedModuleName moduleName) { - if (moduleName.ComponentName.StartsWith("Form_")) + if (moduleName.ComponentName.StartsWith(FormNamePrefix)) { - var name = moduleName.ComponentName.Substring("Form_".Length); + var name = moduleName.ComponentName.Substring(FormNamePrefix.Length); using (var currentProject = new SafeIDispatchWrapper<_CurrentProject>(Application.CurrentProject)) using (var allForms = new SafeIDispatchWrapper(currentProject.Target.AllForms)) - using (var forms = new SafeIDispatchWrapper(Application.Forms)) using (var accessObject = new SafeIDispatchWrapper(allForms.Target[name])) { - return LoadHostDocument("Access.Form", accessObject, forms); + return LoadHostDocument(moduleName, FormClassName, accessObject); } } - if (moduleName.ComponentName.StartsWith("Report_")) + if (moduleName.ComponentName.StartsWith(ReportNamePrefix)) { - var name = moduleName.ComponentName.Substring("Report_".Length); + var name = moduleName.ComponentName.Substring(ReportNamePrefix.Length); using (var currentProject = new SafeIDispatchWrapper<_CurrentProject>(Application.CurrentProject)) using (var allReports = new SafeIDispatchWrapper(currentProject.Target.AllReports)) - using (var reports = new SafeIDispatchWrapper(Application.Reports)) using (var accessObject = new SafeIDispatchWrapper(allReports.Target[name])) { - return LoadHostDocument("Access.Report", accessObject, reports); + return LoadHostDocument(moduleName, name, accessObject); } } @@ -40,42 +56,109 @@ public override HostDocument GetDocument(QualifiedModuleName moduleName) public override IEnumerable GetDocuments() { - var result = new List(); - using (var currentProject = new SafeIDispatchWrapper<_CurrentProject>(Application.CurrentProject)) - using (var allForms = new SafeIDispatchWrapper(currentProject.Target.AllForms)) - using (var allReports = new SafeIDispatchWrapper(currentProject.Target.AllReports)) - using (var forms = new SafeIDispatchWrapper(Application.Forms)) - using (var reports = new SafeIDispatchWrapper(Application.Reports)) + var list = new List(); + + foreach (var document in DocumentComponents()) { - PopulateList(ref result, "Access.Form", allForms, forms); - PopulateList(ref result, "Access.Report", allReports, reports); + var moduleName = new QualifiedModuleName(document); + var name = string.Empty; + var className = string.Empty; + if (document.Name.StartsWith(FormNamePrefix)) + { + className = FormClassName; + name = document.Name.Substring(FormNamePrefix.Length); + } + else if(document.Name.StartsWith(ReportNamePrefix)) + { + className = ReportClassName; + name = document.Name.Substring(ReportNamePrefix.Length); + } + + using (var project = document.ParentProject) + { + var state = GetDocumentState(project, name, className); + list.Add(new HostDocument(moduleName, name, className, state, null)); + } } - return result; + return list; } - private void PopulateList(ref List result, string className, SafeIDispatchWrapper allObjects, dynamic objects) + private DocumentState GetDocumentState(IVBProject project, string name, string className) { - foreach (AccessObject rawAccessObject in allObjects.Target) - using (var accessObject = new SafeIDispatchWrapper(rawAccessObject)) + if (!project.Equals(_dbcProject.Value)) { - var item = LoadHostDocument(className, accessObject, objects); - result.Add(item); + return DocumentState.Inaccessible; } + + using (var currentProject = new SafeIDispatchWrapper<_CurrentProject>(Application.CurrentProject)) + { + switch (className) + { + case FormClassName: + using (var allForms = new SafeIDispatchWrapper(currentProject.Target.AllForms)) + using (var accessObject = new SafeIDispatchWrapper(allForms.Target[name])) + { + if (accessObject.Target.IsLoaded) + { + return DetermineDocumentState(accessObject.Target.CurrentView); + } + } + + break; + case ReportClassName: + using (var allReports = new SafeIDispatchWrapper(currentProject.Target.AllReports)) + using (var accessObject = new SafeIDispatchWrapper(allReports.Target[name])) + { + if (accessObject.Target.IsLoaded) + { + return DetermineDocumentState(accessObject.Target.CurrentView); + } + } + + break; + } + } + + return DocumentState.Inaccessible; } - private HostDocument LoadHostDocument(string className, SafeIDispatchWrapper accessObject, dynamic objects) + private HostDocument LoadHostDocument(QualifiedModuleName moduleName, string className, SafeIDispatchWrapper accessObject) { - var state = DocumentState.Closed; + var state = DocumentState.Inaccessible; if (!accessObject.Target.IsLoaded) { - return new HostDocument(accessObject.Target.Name, className, state, null); + return new HostDocument(moduleName, accessObject.Target.Name, className, state, null); } - state = accessObject.Target.CurrentView == AcCurrentView.acCurViewDesign + if (moduleName.ProjectName == _dbcProject.Value.Name && moduleName.ProjectId == _dbcProject.Value.HelpFile) + { + state = DetermineDocumentState(accessObject.Target.CurrentView); + } + + return new HostDocument(moduleName, accessObject.Target.Name, className, state, null); + } + + private static DocumentState DetermineDocumentState(AcCurrentView CurrentView) + { + return CurrentView == AcCurrentView.acCurViewDesign ? DocumentState.DesignView : DocumentState.ActiveView; - return new HostDocument(accessObject.Target.Name, className, state, null); + } + + private bool _disposed; + protected override void Dispose(bool disposing) + { + if (!_disposed) + { + _disposed = true; + if (_dbcProject.IsValueCreated) + { + _dbcProject.Value.Dispose(); + } + } + + base.Dispose(disposing); } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs index f05211a46c..d32cb0948b 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/AutoCADApp.cs @@ -5,7 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class AutoCADApp : HostApplicationBase { - public AutoCADApp() : base("AutoCAD") { } - + public AutoCADApp(IVBE vbe) : base(vbe, "AutoCAD", true) { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/CorelDRAWApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/CorelDRAWApp.cs index 27d42a2f32..44f5ff080c 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/CorelDRAWApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/CorelDRAWApp.cs @@ -5,10 +5,8 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class CorelDRAWApp : HostApplicationBase { - public CorelDRAWApp() : base("CorelDRAW") { } - public CorelDRAWApp(IVBE vbe) : base(vbe, "CorelDRAW") { } + public CorelDRAWApp(IVBE vbe) : base(vbe, "CorelDRAW", true) { } //TODO:Can only get a CorelDraw application if at least one document is open in CorelDraw. - } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ExcelApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ExcelApp.cs index cd174cf15f..74f2645c6d 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ExcelApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ExcelApp.cs @@ -5,8 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class ExcelApp : HostApplicationBase { - public ExcelApp() : base("Excel") { } - public ExcelApp(IVBE vbe) : base(vbe, "Excel") { } - + public ExcelApp(IVBE vbe) : base(vbe, "Excel", true) { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs index d9779c171a..e1fc9e3333 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/OutlookApp.cs @@ -7,8 +7,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA [ComVisible(false)] public class OutlookApp : HostApplicationBase { - public OutlookApp() : base("Outlook") - { - } + public OutlookApp(IVBE vbe) : base(vbe, "Outlook", true) { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PowerPointApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PowerPointApp.cs index f2f9955121..a1a2af9fd3 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PowerPointApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PowerPointApp.cs @@ -5,11 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class PowerPointApp : HostApplicationBase { - private readonly IVBE _vbe; - - public PowerPointApp(IVBE vbe) : base(vbe, "PowerPoint") - { - _vbe = vbe; - } + public PowerPointApp(IVBE vbe) : base(vbe, "PowerPoint") { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ProjectApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ProjectApp.cs index 321f1a6db2..1d0726d55d 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ProjectApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/ProjectApp.cs @@ -5,7 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class ProjectApp : HostApplicationBase { - public ProjectApp() : base("MSProject") { } - public ProjectApp(IVBE vbe) : base(vbe, "MSProject") { } + public ProjectApp(IVBE vbe) : base(vbe, "MSProject", true) { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PublisherApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PublisherApp.cs index 88c2afcbc1..78efcb029f 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PublisherApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/PublisherApp.cs @@ -5,6 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class PublisherApp : HostApplicationBase { - public PublisherApp() : base("Publisher") { } + public PublisherApp(IVBE vbe) : base(vbe, "Publisher", true) { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs index 3110e13877..90ba9146c2 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/SolidWorksApp.cs @@ -5,7 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class SolidWorksApp : HostApplicationBase { - public SolidWorksApp() : base("SolidWorks") { } public SolidWorksApp(IVBE vbe) : base(vbe, "SolidWorks") { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/Visio.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/Visio.cs index 9c9846e083..bb67e8f5ea 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/Visio.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/Visio.cs @@ -5,7 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class VisioApp : HostApplicationBase { - public VisioApp() : base("Visio") { } - public VisioApp(IVBE vbe) : base(vbe, "Visio") { } + public VisioApp(IVBE vbe) : base(vbe, "Visio", true) { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/WordApp.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/WordApp.cs index 3d1387eb9b..d8ea7d820b 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/WordApp.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/Application/WordApp.cs @@ -5,7 +5,6 @@ namespace Rubberduck.VBEditor.SafeComWrappers.VBA { public class WordApp : HostApplicationBase { - public WordApp() : base("Word") { } - public WordApp(IVBE vbe) : base(vbe, "Word") { } + public WordApp(IVBE vbe) : base(vbe, "Word", true) { } } } diff --git a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs index 42cbe56122..4d17a62ab3 100644 --- a/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs +++ b/Rubberduck.VBEditor.VBA/SafeComWrappers/VB/VBE.cs @@ -188,15 +188,10 @@ public IHostApplication HostApplication() } var host = Path.GetFileName(System.Windows.Forms.Application.ExecutablePath).ToUpperInvariant(); - //These need the VBE as a ctor argument. - if (host.Equals("SLDWORKS.EXE") || host.Equals("POWERPNT.EXE")) - { - return (IHostApplication)Activator.CreateInstance(HostAppMap[host], this); - } - //The rest don't. + if (HostAppMap.ContainsKey(host)) { - return (IHostApplication)Activator.CreateInstance(HostAppMap[host]); + return (IHostApplication)Activator.CreateInstance(HostAppMap[host], this); } //Guessing the above will work like 99.9999% of the time for supported applications. @@ -220,34 +215,34 @@ public IHostApplication HostApplication() switch (hostAppControl.Caption) { case "Microsoft Excel": - result = new ExcelApp(); + result = new ExcelApp(this); break; case "Microsoft Access": - result = new AccessApp(); + result = new AccessApp(this); break; case "Microsoft Word": - result = new WordApp(); + result = new WordApp(this); break; case "Microsoft PowerPoint": result = new PowerPointApp(this); break; case "Microsoft Outlook": - result = new OutlookApp(); + result = new OutlookApp(this); break; case "Microsoft Project": - result = new ProjectApp(); + result = new ProjectApp(this); break; case "Microsoft Publisher": - result = new PublisherApp(); + result = new PublisherApp(this); break; case "Microsoft Visio": - result = new VisioApp(); + result = new VisioApp(this); break; case "AutoCAD": - result = new AutoCADApp(); + result = new AutoCADApp(this); break; case "CorelDRAW": - result = new CorelDRAWApp(); + result = new CorelDRAWApp(this); break; case "SolidWorks": result = new SolidWorksApp(this); @@ -272,21 +267,21 @@ public IHostApplication HostApplication() case "Excel": return new ExcelApp(this); case "Access": - return new AccessApp(); + return new AccessApp(this); case "Word": return new WordApp(this); case "PowerPoint": return new PowerPointApp(this); case "Outlook": - return new OutlookApp(); + return new OutlookApp(this); case "MSProject": - return new ProjectApp(); + return new ProjectApp(this); case "Publisher": - return new PublisherApp(); + return new PublisherApp(this); case "Visio": - return new VisioApp(); + return new VisioApp(this); case "AutoCAD": - return new AutoCADApp(); + return new AutoCADApp(this); case "CorelDRAW": return new CorelDRAWApp(this); case "SolidWorks": From 41d327e38bc90f310e21834e2a32c1e6535cab0d Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 27 Oct 2018 14:14:42 +0200 Subject: [PATCH 014/107] Introduce the IRewriteSession and IRewritingManager These two are meant to build the foundation for a new way to manage rewriting modules in a consistent fashion. When a feature wants to rewrite a module, it needs to have the IRewritingManager injected. Then it can request a IRewriteSession from it, either for code pane rewrites or attributes rewrites. The sessions manage the rewriting of all checked out rewriters and function as a point to perform pre- and post-rewrite actions in a consistent manner. The manager and sessions are set up such that only one active rewrite session may ever perform a successful rewrite: the manager will invalidate all active rewrite sessions on the first rewrite of an active rewrite session. (To coordinate this a callback gets passed to the freshly created sessions.) The current setup of the StateTokenStreamCache is temporary only; a change to only storing ITokenStreams on the RubberduckParserState is envisioned for the future. --- .../Rewriter/AttributesRewriteSession.cs | 41 ++++++++ .../Rewriter/CodePaneRewriteSession.cs | 33 +++++++ .../Rewriter/IRewriteSession.cs | 12 +++ .../Rewriter/IRewriteSessionFactory.cs | 10 ++ .../Rewriter/IRewriterProvider.cs | 10 ++ .../Rewriter/IRewritingManager.cs | 9 ++ .../Rewriter/ITokenStreamCache.cs | 11 +++ .../Rewriter/RewriteSessionBase.cs | 82 ++++++++++++++++ .../Rewriter/RewriteSessionFactory.cs | 27 ++++++ .../Rewriter/RewriterProvider.cs | 29 ++++++ .../Rewriter/RewritingManager.cs | 93 +++++++++++++++++++ .../Rewriter/StateTokenStreamCache.cs | 27 ++++++ 12 files changed, 384 insertions(+) create mode 100644 Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs create mode 100644 Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs create mode 100644 Rubberduck.Parsing/Rewriter/IRewriteSession.cs create mode 100644 Rubberduck.Parsing/Rewriter/IRewriteSessionFactory.cs create mode 100644 Rubberduck.Parsing/Rewriter/IRewriterProvider.cs create mode 100644 Rubberduck.Parsing/Rewriter/IRewritingManager.cs create mode 100644 Rubberduck.Parsing/Rewriter/ITokenStreamCache.cs create mode 100644 Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs create mode 100644 Rubberduck.Parsing/Rewriter/RewriteSessionFactory.cs create mode 100644 Rubberduck.Parsing/Rewriter/RewriterProvider.cs create mode 100644 Rubberduck.Parsing/Rewriter/RewritingManager.cs create mode 100644 Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs diff --git a/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs new file mode 100644 index 0000000000..8719806c9c --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs @@ -0,0 +1,41 @@ +using System; +using Rubberduck.Parsing.VBA; +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public class AttributesRewriteSession : RewriteSessionBase + { + private readonly RubberduckParserState _state; + + public AttributesRewriteSession(RubberduckParserState state, IRewriterProvider rewriterProvider, + Func rewritingAllowed) + : base(rewriterProvider, rewritingAllowed) + { + _state = state; + } + + protected override IExecutableModuleRewriter ModuleRewriter(QualifiedModuleName module) + { + return RewriterProvider.CodePaneModuleRewriter(module); + } + + protected override void RewriteInternal() + { + //The suspension ensures that only one parse gets executed instead of two for each rewritten module. + var result = _state.OnSuspendParser(this, new[] {ParserState.Ready}, RewriteAllRewriters); + if(result != SuspensionResult.Completed) + { + Logger.Warn($"Rewriting attribute modules did not succeed. suspension result = {result}"); + } + } + + private void RewriteAllRewriters() + { + foreach (var rewriter in CheckedOutModuleRewriters.Values) + { + rewriter.Rewrite(); + } + } + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs b/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs new file mode 100644 index 0000000000..4b731d7bc7 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs @@ -0,0 +1,33 @@ +using System; +using Rubberduck.Parsing.VBA; +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public class CodePaneRewriteSession : RewriteSessionBase + { + private readonly RubberduckParserState _state; + + public CodePaneRewriteSession(RubberduckParserState state, IRewriterProvider rewriterProvider, + Func rewritingAllowed) + : base(rewriterProvider, rewritingAllowed) + { + _state = state; + } + + + protected override IExecutableModuleRewriter ModuleRewriter(QualifiedModuleName module) + { + return RewriterProvider.CodePaneModuleRewriter(module); + } + + protected override void RewriteInternal() + { + foreach (var rewriter in CheckedOutModuleRewriters.Values) + { + rewriter.Rewrite(); + } + _state.OnParseRequested(this); + } + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/IRewriteSession.cs b/Rubberduck.Parsing/Rewriter/IRewriteSession.cs new file mode 100644 index 0000000000..b4488592a4 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/IRewriteSession.cs @@ -0,0 +1,12 @@ +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public interface IRewriteSession + { + IModuleRewriter CheckOutModuleRewriter(QualifiedModuleName module); + void Rewrite(); + bool IsInvalidated { get; } + void Invalidate(); + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/IRewriteSessionFactory.cs b/Rubberduck.Parsing/Rewriter/IRewriteSessionFactory.cs new file mode 100644 index 0000000000..d4047a36d2 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/IRewriteSessionFactory.cs @@ -0,0 +1,10 @@ +using System; + +namespace Rubberduck.Parsing.Rewriter +{ + public interface IRewriteSessionFactory + { + IRewriteSession CodePaneSession(Func rewritingAllowed); + IRewriteSession AttributesSession(Func rewritingAllowed); + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/IRewriterProvider.cs b/Rubberduck.Parsing/Rewriter/IRewriterProvider.cs new file mode 100644 index 0000000000..2766c114e5 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/IRewriterProvider.cs @@ -0,0 +1,10 @@ +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public interface IRewriterProvider + { + IExecutableModuleRewriter CodePaneModuleRewriter(QualifiedModuleName module); + IExecutableModuleRewriter AttributesModuleRewriter(QualifiedModuleName module); + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/IRewritingManager.cs b/Rubberduck.Parsing/Rewriter/IRewritingManager.cs new file mode 100644 index 0000000000..150b8adefe --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/IRewritingManager.cs @@ -0,0 +1,9 @@ +namespace Rubberduck.Parsing.Rewriter +{ + public interface IRewritingManager + { + IRewriteSession CheckOutCodePaneSession(); + IRewriteSession CheckOutAttributesSession(); + void InvalidateAllSessions(); + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/ITokenStreamCache.cs b/Rubberduck.Parsing/Rewriter/ITokenStreamCache.cs new file mode 100644 index 0000000000..eedd6b8549 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/ITokenStreamCache.cs @@ -0,0 +1,11 @@ +using Antlr4.Runtime; +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public interface ITokenStreamCache + { + ITokenStream CodePaneTokenStream(QualifiedModuleName module); + ITokenStream AttributesTokenStream(QualifiedModuleName module); + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs b/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs new file mode 100644 index 0000000000..45546a2f75 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using NLog; +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public abstract class RewriteSessionBase : IRewriteSession + { + protected readonly IDictionary CheckedOutModuleRewriters = new Dictionary(); + protected readonly IRewriterProvider RewriterProvider; + + private readonly Func _rewritingAllowed; + + protected readonly Logger Logger = LogManager.GetCurrentClassLogger(); + private readonly object _invalidationLockObject = new object(); + + + protected RewriteSessionBase(IRewriterProvider rewriterProvider, Func rewritingAllowed) + { + RewriterProvider = rewriterProvider; + _rewritingAllowed = rewritingAllowed; + } + + + public IModuleRewriter CheckOutModuleRewriter(QualifiedModuleName module) + { + if (CheckedOutModuleRewriters.TryGetValue(module, out var rewriter)) + { + return rewriter; + } + + rewriter = ModuleRewriter(module); + CheckedOutModuleRewriters.Add(module, rewriter); + return rewriter; + } + + protected abstract IExecutableModuleRewriter ModuleRewriter(QualifiedModuleName module); + + public void Rewrite() + { + lock (_invalidationLockObject) + { + if (_isInvalidated) + { + Logger.Warn("Tried to execute Rewrite on a RewriteSession that was already invalidated."); + return; + } + } + + if (!_rewritingAllowed(this)) + { + Logger.Warn("Tried to execute Rewrite on a RewriteSession when rewriting was no longer allowed."); + return; + } + + RewriteInternal(); + } + + protected abstract void RewriteInternal(); + + private bool _isInvalidated = false; + public bool IsInvalidated + { + get + { + lock (_invalidationLockObject) + { + return _isInvalidated; + } + } + } + + public void Invalidate() + { + lock(_invalidationLockObject) + { + _isInvalidated = true; + } + } + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/RewriteSessionFactory.cs b/Rubberduck.Parsing/Rewriter/RewriteSessionFactory.cs new file mode 100644 index 0000000000..d0f81ddbd1 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/RewriteSessionFactory.cs @@ -0,0 +1,27 @@ +using System; +using Rubberduck.Parsing.VBA; + +namespace Rubberduck.Parsing.Rewriter +{ + public class RewriteSessionFactory : IRewriteSessionFactory + { + private readonly RubberduckParserState _state; + private readonly IRewriterProvider _rewriterProvider; + + public RewriteSessionFactory(RubberduckParserState state, IRewriterProvider rewriterProvider) + { + _state = state; + _rewriterProvider = rewriterProvider; + } + + public IRewriteSession CodePaneSession(Func rewritingAllowed) + { + return new CodePaneRewriteSession(_state, _rewriterProvider, rewritingAllowed); + } + + public IRewriteSession AttributesSession(Func rewritingAllowed) + { + return new AttributesRewriteSession(_state, _rewriterProvider, rewritingAllowed); + } + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/RewriterProvider.cs b/Rubberduck.Parsing/Rewriter/RewriterProvider.cs new file mode 100644 index 0000000000..23df1fb818 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/RewriterProvider.cs @@ -0,0 +1,29 @@ +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public class RewriterProvider : IRewriterProvider + { + private ITokenStreamCache _tokenStreamCache; + private IModuleRewriterFactory _rewriterFactory; + + public RewriterProvider(ITokenStreamCache tokenStreamCache, IModuleRewriterFactory rewriterFactory) + { + _tokenStreamCache = tokenStreamCache; + _rewriterFactory = rewriterFactory; + } + + + public IExecutableModuleRewriter CodePaneModuleRewriter(QualifiedModuleName module) + { + var tokenStream = _tokenStreamCache.CodePaneTokenStream(module); + return _rewriterFactory.CodePaneRewriter(module, tokenStream); + } + + public IExecutableModuleRewriter AttributesModuleRewriter(QualifiedModuleName module) + { + var tokenStream = _tokenStreamCache.AttributesTokenStream(module); + return _rewriterFactory.AttributesRewriter(module, tokenStream); + } + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/RewritingManager.cs b/Rubberduck.Parsing/Rewriter/RewritingManager.cs new file mode 100644 index 0000000000..d8c9e155dd --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/RewritingManager.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; + +namespace Rubberduck.Parsing.Rewriter +{ + public class RewritingManager : IRewritingManager + { + private readonly HashSet _activeCodePaneSessions = new HashSet(); + private readonly HashSet _activeAttributesSessions = new HashSet(); + + private readonly IRewriteSessionFactory _sessionFactory; + + private readonly object _invalidationLockObject = new object(); + + public RewritingManager(IRewriteSessionFactory sessionFactory) + { + _sessionFactory = sessionFactory; + } + + + public IRewriteSession CheckOutCodePaneSession() + { + var newSession = _sessionFactory.CodePaneSession(TryAllowExclusiveRewrite); + lock (_invalidationLockObject) + { + _activeCodePaneSessions.Add(newSession); + } + + return newSession; + } + + public IRewriteSession CheckOutAttributesSession() + { + var newSession = _sessionFactory.AttributesSession(TryAllowExclusiveRewrite); + lock (_invalidationLockObject) + { + _activeAttributesSessions.Add(newSession); + } + + return newSession; + } + + private bool TryAllowExclusiveRewrite(IRewriteSession rewriteSession) + { + lock (_invalidationLockObject) + { + if (!IsCurrentlyActive(rewriteSession)) + { + return false; + } + + InvalidateAllSessionsInternal(); + return true; + } + } + + private bool IsCurrentlyActive(IRewriteSession rewriteSession) + { + switch (rewriteSession) + { + case AttributesRewriteSession attributeSession: + return _activeAttributesSessions.Contains(attributeSession); + case CodePaneRewriteSession codePaneSession: + return _activeAttributesSessions.Contains(codePaneSession); + default: + throw new NotSupportedException(nameof(rewriteSession)); + } + } + + public void InvalidateAllSessions() + { + lock (_invalidationLockObject) + { + InvalidateAllSessionsInternal(); + } + } + + private void InvalidateAllSessionsInternal() + { + foreach (var rewriteSession in _activeCodePaneSessions) + { + rewriteSession.Invalidate(); + } + _activeCodePaneSessions.Clear(); + + foreach (var rewriteSession in _activeAttributesSessions) + { + rewriteSession.Invalidate(); + } + _activeAttributesSessions.Clear(); + } + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs b/Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs new file mode 100644 index 0000000000..7ba464e164 --- /dev/null +++ b/Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs @@ -0,0 +1,27 @@ +using Antlr4.Runtime; +using Rubberduck.Parsing.VBA; +using Rubberduck.VBEditor; + +namespace Rubberduck.Parsing.Rewriter +{ + public class StateTokenStreamCache : ITokenStreamCache + { + private readonly RubberduckParserState _state; + + public StateTokenStreamCache(RubberduckParserState state) + { + _state = state; + } + + + public ITokenStream CodePaneTokenStream(QualifiedModuleName module) + { + return _state.GetRewriter(module).TokenStream; + } + + public ITokenStream AttributesTokenStream(QualifiedModuleName module) + { + return _state.GetAttributeRewriter(module).TokenStream; + } + } +} \ No newline at end of file From 1c2f6ce2a38a1f9655b1d8070b8d46922ac4599e Mon Sep 17 00:00:00 2001 From: bclothier Date: Sat, 27 Oct 2018 08:08:26 -0500 Subject: [PATCH 015/107] Make the generic version of SafeIDispatchWrapper visible only to Rubberduck.VBEditor and Rubberduck.VBEditor.* to ensure raw COM objects will not leak outside those projects. Add comments describing the intended usage of both versions. --- .../Properties/AssemblyInfo.cs | 7 ++-- .../SafeComWrappers/SafeIDispatchWrapper.cs | 36 +++++++++++++++++-- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/Rubberduck.VBEEditor/Properties/AssemblyInfo.cs b/Rubberduck.VBEEditor/Properties/AssemblyInfo.cs index 7d743643ac..149c390a70 100644 --- a/Rubberduck.VBEEditor/Properties/AssemblyInfo.cs +++ b/Rubberduck.VBEEditor/Properties/AssemblyInfo.cs @@ -1,9 +1,12 @@ -using System.Reflection; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("RubberduckTests")] +//Allow Rubberduck.VBEditor.* projects to use internal class +[assembly: InternalsVisibleTo("Rubberduck.VBEditor.VB6")] +[assembly: InternalsVisibleTo("Rubberduck.VBEditor.VBA")] + // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4758424b-266e-4a3a-83c6-4aa50af7ea9e")] [assembly: ComVisible(false)] \ No newline at end of file diff --git a/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs index 42500fd238..71a94ad1d6 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/SafeIDispatchWrapper.cs @@ -4,14 +4,36 @@ namespace Rubberduck.VBEditor.SafeComWrappers { - public class SafeIDispatchWrapper : SafeIDispatchWrapper + /// + /// Creates a new IDispatch-based wrapper for a provided + /// COM interface. This is internal and should be used only + /// within the Rubberduck.VBEditor.* projects. + /// + /// + /// To avoid exposing additional interop libraries to other projects + /// and violating the separation, only the non-generic version of + /// be provided for consumption outside + /// the Rubberduck.VBEditor.* projects. + /// Within those projects, the class is useful for wrapping COM interfaces + /// that do not have a corresponding + /// implementations to ensure those are managed and will not leak. + /// + /// COM interface to wrap + /// + internal class SafeIDispatchWrapper : SafeIDispatchWrapper { - public SafeIDispatchWrapper(TDispatch target, bool rewrapping = false) : base(target, rewrapping) + internal SafeIDispatchWrapper(TDispatch target, bool rewrapping = false) : base(target, rewrapping) { } public new TDispatch Target => (TDispatch) base.Target; } + /// + /// Provide a IDispatch-based (e.g. late-bound) access to a COM object. + /// Use to work with the object. The + /// must be a raw COM object without + /// any wrappers. + /// public class SafeIDispatchWrapper : SafeComWrapper { public SafeIDispatchWrapper(object target, bool rewrapping = false) : base(target, rewrapping) @@ -24,8 +46,18 @@ public SafeIDispatchWrapper(object target, bool rewrapping = false) : base(targe IDispatchPointer = GetPointer(target); } + // ReSharper disable once InconsistentNaming public IntPtr IDispatchPointer { get; } + /// + /// Use the method to encapsulate operations against the late-bound COM object. + /// It is caller's responsibilty to handle any exceptions that may result as part + /// of the operation. + /// + /// + /// A method that perform work against the late-bound COM object provided as the + /// parameter to the function + /// public void Invoke(Action action) { action.Invoke(Target); From 31c4bb010bf230dca24b14d0543628218957703d Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 27 Oct 2018 15:10:59 +0200 Subject: [PATCH 016/107] Wire up the IRewritingManager When parsing, all rewrite sessions get invalidated because any change, like removing components, changing referenced projects or their priority or reparsing components may invalidate the basis for a rewrite or make the underlying component inaccessible. --- Rubberduck.API/VBA/Parser.cs | 2 - .../Root/RubberduckIoCInstaller.cs | 7 +++ Rubberduck.Parsing/VBA/ParseCoordinator.cs | 9 +++- .../VBA/SynchronousParseCoordinator.cs | 18 +++++--- RubberduckTests/Mocks/MockParser.cs | 45 ++++++++++++++----- 5 files changed, 61 insertions(+), 20 deletions(-) diff --git a/Rubberduck.API/VBA/Parser.cs b/Rubberduck.API/VBA/Parser.cs index 727e638298..31495a0ed8 100644 --- a/Rubberduck.API/VBA/Parser.cs +++ b/Rubberduck.API/VBA/Parser.cs @@ -5,13 +5,11 @@ using System.Linq; using System.Runtime.InteropServices; using System.Threading; -using Rubberduck.Common; using Rubberduck.Parsing.ComReflection; using Rubberduck.Parsing.PreProcessing; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols.DeclarationLoaders; using Rubberduck.Parsing.VBA; -using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.UIContext; using Rubberduck.Parsing.VBA.ComReferenceLoading; using Rubberduck.Parsing.VBA.DeclarationCaching; diff --git a/Rubberduck.Main/Root/RubberduckIoCInstaller.cs b/Rubberduck.Main/Root/RubberduckIoCInstaller.cs index 4dda7dbdee..77494ea791 100644 --- a/Rubberduck.Main/Root/RubberduckIoCInstaller.cs +++ b/Rubberduck.Main/Root/RubberduckIoCInstaller.cs @@ -122,6 +122,10 @@ public void Install(IWindsorContainer container, IConfigurationStore store) RegisterParsingEngine(container); RegisterTypeLibApi(container); + container.Register(Component.For() + .ImplementedBy() + .LifestyleSingleton()); + container.Register(Component.For() .LifestyleSingleton()); container.Register(Component.For() @@ -288,6 +292,9 @@ private void RegisterSpecialFactories(IWindsorContainer container) container.Register(Component.For() .ImplementedBy() .LifestyleSingleton()); + container.Register(Component.For() + .ImplementedBy() + .LifestyleSingleton()); } private void RegisterQuickFixes(IWindsorContainer container, Assembly[] assembliesToRegister) diff --git a/Rubberduck.Parsing/VBA/ParseCoordinator.cs b/Rubberduck.Parsing/VBA/ParseCoordinator.cs index e8685888d3..eec03d5602 100644 --- a/Rubberduck.Parsing/VBA/ParseCoordinator.cs +++ b/Rubberduck.Parsing/VBA/ParseCoordinator.cs @@ -8,6 +8,7 @@ using System.Diagnostics; using System.Linq; using NLog; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA.Extensions; using Rubberduck.VBEditor.SafeComWrappers.Abstract; @@ -27,6 +28,7 @@ public class ParseCoordinator : IParseCoordinator private readonly IProjectManager _projectManager; private readonly IParsingCacheService _parsingCacheService; private readonly IParserStateManager _parserStateManager; + private readonly IRewritingManager _rewritingManager; private readonly ConcurrentStack _requestorStack; private bool _isSuspended; @@ -35,7 +37,8 @@ public ParseCoordinator( IParsingStageService parsingStageService, IParsingCacheService parsingCacheService, IProjectManager projectManager, - IParserStateManager parserStateManager) + IParserStateManager parserStateManager, + IRewritingManager rewritingManager = null) { if (state == null) { @@ -63,6 +66,7 @@ public ParseCoordinator( _projectManager = projectManager; _parsingCacheService = parsingCacheService; _parserStateManager = parserStateManager; + _rewritingManager = rewritingManager; state.ParseRequest += ReparseRequested; state.SuspendRequest += SuspendRequested; @@ -433,6 +437,9 @@ protected void ParseAllInternal(object requestor, CancellationToken token) _parserStateManager.SetStatusAndFireStateChanged(requestor, ParserState.Started, token); token.ThrowIfCancellationRequested(); + _rewritingManager?.InvalidateAllSessions(); + token.ThrowIfCancellationRequested(); + _projectManager.RefreshProjects(); token.ThrowIfCancellationRequested(); diff --git a/Rubberduck.Parsing/VBA/SynchronousParseCoordinator.cs b/Rubberduck.Parsing/VBA/SynchronousParseCoordinator.cs index 3bf284076c..ce3d5acd6d 100644 --- a/Rubberduck.Parsing/VBA/SynchronousParseCoordinator.cs +++ b/Rubberduck.Parsing/VBA/SynchronousParseCoordinator.cs @@ -1,5 +1,6 @@ using System; using System.Threading; +using Rubberduck.Parsing.Rewriter; namespace Rubberduck.Parsing.VBA { @@ -10,13 +11,16 @@ public SynchronousParseCoordinator( IParsingStageService parsingStageService, IParsingCacheService parsingCacheService, IProjectManager projectManager, - IParserStateManager parserStateManager) : base( - state, - parsingStageService, - parsingCacheService, - projectManager, - parserStateManager) - { } + IParserStateManager parserStateManager, + IRewritingManager rewritingManager = null) + :base( + state, + parsingStageService, + parsingCacheService, + projectManager, + parserStateManager, + rewritingManager) + {} public override void BeginParse(object sender) { diff --git a/RubberduckTests/Mocks/MockParser.cs b/RubberduckTests/Mocks/MockParser.cs index 2cba9b7e40..779531698a 100644 --- a/RubberduckTests/Mocks/MockParser.cs +++ b/RubberduckTests/Mocks/MockParser.cs @@ -43,22 +43,27 @@ public static RubberduckParserState ParseString(string inputCode, out QualifiedM return parser.State; } - public static SynchronousParseCoordinator Create(IVBE vbe, string serializedDeclarationsPath = null) + public static (SynchronousParseCoordinator parser, IRewritingManager rewritingManager) CreateWithRewriteManager(IVBE vbe, string serializedComProjectsPath = null) { var vbeEvents = MockVbeEvents.CreateMockVbeEvents(new Moq.Mock()); var declarationFinderFactory = new DeclarationFinderFactory(); var projectRepository = new ProjectsRepository(vbe); var state = new RubberduckParserState(vbe, projectRepository, declarationFinderFactory, vbeEvents.Object); - return Create(vbe, state, projectRepository, serializedDeclarationsPath); + return CreateWithRewriteManager(vbe, state, projectRepository, serializedComProjectsPath); + } + + public static SynchronousParseCoordinator Create(IVBE vbe, string serializedDeclarationsPath = null) + { + return CreateWithRewriteManager(vbe, serializedDeclarationsPath).parser; } - public static SynchronousParseCoordinator Create(IVBE vbe, RubberduckParserState state, IProjectsRepository projectRepository, string serializedDeclarationsPath = null) + public static (SynchronousParseCoordinator parser, IRewritingManager rewritingManager) CreateWithRewriteManager(IVBE vbe, RubberduckParserState state, IProjectsRepository projectRepository, string serializedComProjectsPath = null) { var vbeVersion = double.Parse(vbe.Version, CultureInfo.InvariantCulture); var compilationArgumentsProvider = MockCompilationArgumentsProvider(vbeVersion); var compilationsArgumentsCache = new CompilationArgumentsCache(compilationArgumentsProvider); - var path = serializedDeclarationsPath ?? + var path = serializedComProjectsPath ?? Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(MockParser)).Location), "TestFiles", "Resolver"); var preprocessorErrorListenerFactory = new PreprocessingParseErrorListenerFactory(); var preprocessorParser = new VBAPreprocessorParser(preprocessorErrorListenerFactory, preprocessorErrorListenerFactory); @@ -126,13 +131,25 @@ public static SynchronousParseCoordinator Create(IVBE vbe, RubberduckParserState supertypeClearer, compilationsArgumentsCache ); + var tokenStreamCache = new StateTokenStreamCache(state); + var rewriterProvider = new RewriterProvider(tokenStreamCache, moduleRewriterFactory); + var rewriteSessionFactory = new RewriteSessionFactory(state, rewriterProvider); + var rewritingManager = new RewritingManager(rewriteSessionFactory); - return new SynchronousParseCoordinator( + var parser = new SynchronousParseCoordinator( state, parsingStageService, parsingCacheService, projectManager, - parserStateManager); + parserStateManager, + rewritingManager); + + return (parser, rewritingManager); + } + + public static SynchronousParseCoordinator Create(IVBE vbe, RubberduckParserState state, IProjectsRepository projectRepository, string serializedComProjectsPath = null) + { + return CreateWithRewriteManager(vbe, state, projectRepository, serializedComProjectsPath).parser; } private static ICompilationArgumentsProvider MockCompilationArgumentsProvider(double vbeVersion) @@ -147,13 +164,21 @@ private static ICompilationArgumentsProvider MockCompilationArgumentsProvider(do return compilationArgumentsProvider; } - public static RubberduckParserState CreateAndParse(IVBE vbe, string serializedDeclarationsPath = null) + public static (RubberduckParserState state, IRewritingManager rewritingManager) CreateAndParseWithRewritingManager(IVBE vbe, string serializedComProjectsPath = null) { - var parser = Create(vbe, serializedDeclarationsPath); + var (parser, rewritingManager) = CreateWithRewriteManager(vbe, serializedComProjectsPath); parser.Parse(new CancellationTokenSource()); - if (parser.State.Status >= ParserState.Error) { Assert.Inconclusive("Parser Error"); } + if (parser.State.Status >= ParserState.Error) + { + Assert.Inconclusive("Parser Error"); + } - return parser.State; + return (parser.State, rewritingManager); + } + + public static RubberduckParserState CreateAndParse(IVBE vbe, string serializedComProjectsPath = null) + { + return CreateAndParseWithRewritingManager(vbe, serializedComProjectsPath).state; } private static readonly HashSet ProceduralTypes = From 52be1e0358db418cab3d9fa5b206e2d4498d60e3 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 27 Oct 2018 15:20:13 +0200 Subject: [PATCH 017/107] Expose the IRewritingManager on the RubberduckParserState This change is to be reverted later. It allows to decouple the work necessary to change the users of the IModuleRewriter to use the IRewritingManager from the work necessary to constructor inject the IRewritingManager into them. (The latter is a lot of work in the tests.) Here, property injection is used because the construction of the RewritingManager ultimately depends on the RubberduckParserState to be there. --- Rubberduck.Parsing/VBA/ParseCoordinator.cs | 4 ++++ Rubberduck.Parsing/VBA/RubberduckParserState.cs | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Rubberduck.Parsing/VBA/ParseCoordinator.cs b/Rubberduck.Parsing/VBA/ParseCoordinator.cs index eec03d5602..a8a1490cf1 100644 --- a/Rubberduck.Parsing/VBA/ParseCoordinator.cs +++ b/Rubberduck.Parsing/VBA/ParseCoordinator.cs @@ -72,6 +72,10 @@ public ParseCoordinator( state.SuspendRequest += SuspendRequested; _requestorStack = new ConcurrentStack(); + + //todo: Remove this again in favor of injection of the IRewritingManager into the callers RubberduckParserState.RewritingManager. + //This gets property injected here because the construction of the rewritingManager ultimately depend on the RubberduckParserState. + state.RewritingManager = rewritingManager; } // In production, the cancellation token should be accessed inside the CancellationSyncObject diff --git a/Rubberduck.Parsing/VBA/RubberduckParserState.cs b/Rubberduck.Parsing/VBA/RubberduckParserState.cs index 938679b663..254cba8fc8 100644 --- a/Rubberduck.Parsing/VBA/RubberduckParserState.cs +++ b/Rubberduck.Parsing/VBA/RubberduckParserState.cs @@ -1066,13 +1066,16 @@ private void ClearAsTypeDeclarationPointingToReference(QualifiedModuleName refer } } - public void AddAttributesRewriter(QualifiedModuleName module, IExecutableModuleRewriter attributesRewriter) { var key = module; _moduleStates[key].SetAttributesRewriter(attributesRewriter); } + //todo: Remove this again in favor of injection of the IRewritingManager into the callers. + public IRewritingManager RewritingManager { get; internal set; } + + private bool _isDisposed; public void Dispose() { From b0ca35fc780dffa8112ddf444bb34fe1404bb33d Mon Sep 17 00:00:00 2001 From: bclothier Date: Sat, 27 Oct 2018 08:50:56 -0500 Subject: [PATCH 018/107] Clarify the confusing names of the HostDocument's properties --- .../CodeExplorer/CodeExplorerComponentViewModel.cs | 2 +- .../SafeComWrappers/VB/Abstract/HostDocument.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs index c1dbc97079..21316d0a82 100644 --- a/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs +++ b/Rubberduck.Core/Navigation/CodeExplorer/CodeExplorerComponentViewModel.cs @@ -76,7 +76,7 @@ public CodeExplorerComponentViewModel(CodeExplorerItemViewModel parent, Declarat if (app != null) { var document = app.GetDocument(qualifiedModuleName); - parenthesizedName = document?.ModuleName ?? string.Empty; + parenthesizedName = document?.DocumentName ?? string.Empty; state = document?.State ?? DocumentState.Inaccessible; } } diff --git a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs index 5181acebeb..16437efd82 100644 --- a/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs +++ b/Rubberduck.VBEEditor/SafeComWrappers/VB/Abstract/HostDocument.cs @@ -34,7 +34,7 @@ public enum DocumentState public interface IHostDocument { QualifiedModuleName QualifiedName { get; } - string ModuleName { get; } + string DocumentName { get; } string ClassName { get; } DocumentState State { get; } bool TryGetTarget(out SafeIDispatchWrapper iDispatch); @@ -47,7 +47,7 @@ public class HostDocument : IHostDocument public HostDocument(QualifiedModuleName qualifedName, string name, string className, DocumentState state, Func getTargetFunc) { QualifiedName = qualifedName; - ModuleName = name; + DocumentName = name; ClassName = className; State = state; @@ -55,7 +55,7 @@ public HostDocument(QualifiedModuleName qualifedName, string name, string classN } public QualifiedModuleName QualifiedName { get; } - public string ModuleName { get; } + public string DocumentName { get; } public string ClassName { get; } public DocumentState State { get; } From e28fadde094d96f436955b791741099664906f77 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 27 Oct 2018 16:22:06 +0200 Subject: [PATCH 019/107] Optionally pass a IRewriteSession to quickfixes This is a first step to make them use the IRewriteSession model. Passing it is, will allow the QuickFixProvider to pass in the same session for all results when fixing more than one resulte.g. for FixAll. --- Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs | 3 ++- .../QuickFixes/AccessSheetUsingCodeNameQuickFix.cs | 3 ++- .../QuickFixes/AddIdentifierToWhiteListQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs | 2 +- .../QuickFixes/ApplicationWorksheetFunctionQuickFix.cs | 3 ++- .../QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs | 2 +- .../QuickFixes/ChangeDimToPrivateQuickFix.cs | 3 ++- .../QuickFixes/ChangeIntegerToLongQuickFix.cs | 2 +- .../QuickFixes/ChangeProcedureToFunctionQuickFix.cs | 3 ++- .../QuickFixes/ConvertToProcedureQuickFix.cs | 3 ++- .../QuickFixes/DeclareAsExplicitVariantQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs | 3 ++- .../QuickFixes/IntroduceLocalVariableQuickFix.cs | 3 ++- .../QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs | 3 ++- .../QuickFixes/MakeSingleLineParameterQuickFix.cs | 3 ++- .../QuickFixes/MoveFieldCloserToUsageQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs | 3 ++- .../QuickFixes/PassParameterByReferenceQuickFix.cs | 3 ++- .../QuickFixes/PassParameterByValueQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs | 3 ++- .../QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs | 2 +- .../QuickFixes/RemoveEmptyElseBlockQuickFix.cs | 2 +- .../QuickFixes/RemoveEmptyIfBlockQuickFix.cs | 2 +- .../QuickFixes/RemoveExplicitByRefModifierQuickFix.cs | 2 +- .../QuickFixes/RemoveExplicitCallStatmentQuickFix.cs | 3 ++- .../QuickFixes/RemoveExplicitLetStatementQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs | 3 ++- .../QuickFixes/RemoveOptionBaseStatementQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs | 2 +- .../QuickFixes/RemoveStopKeywordQuickFix.cs | 3 ++- Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs | 3 ++- .../QuickFixes/RemoveUnassignedIdentifierQuickFix.cs | 3 ++- .../QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs | 3 ++- .../QuickFixes/RemoveUnusedDeclarationQuickFix.cs | 3 ++- .../QuickFixes/RemoveUnusedParameterQuickFix.cs | 3 ++- .../QuickFixes/RenameDeclarationQuickFix.cs | 3 ++- .../QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs | 3 ++- .../QuickFixes/ReplaceGlobalModifierQuickFix.cs | 3 ++- .../ReplaceIfElseWithConditionalStatementQuickFix.cs | 3 ++- .../QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs | 3 ++- .../QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs | 3 ++- .../QuickFixes/RestoreErrorHandlingQuickFix.cs | 3 ++- .../QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs | 3 ++- .../QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs | 2 +- .../QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs | 3 ++- .../QuickFixes/SplitMultipleDeclarationsQuickFix.cs | 3 ++- .../QuickFixes/UntypedFunctionUsageQuickFix.cs | 3 ++- .../QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs | 3 ++- .../QuickFixes/WriteOnlyPropertyQuickFix.cs | 3 ++- Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs | 3 ++- 51 files changed, 93 insertions(+), 51 deletions(-) diff --git a/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs b/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs index 124c229ec5..9d684db1ec 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs @@ -3,6 +3,7 @@ using System.Linq; using NLog; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; using Rubberduck.Parsing.VBA.Extensions; @@ -39,7 +40,7 @@ public void RemoveInspections(params Type[] inspections) _supportedInspections = _supportedInspections.Except(inspections).ToHashSet(); } - public abstract void Fix(IInspectionResult result); + public abstract void Fix(IInspectionResult result, IRewriteSession rewriteSession = null); public abstract string Description(IInspectionResult result); public abstract bool CanFixInProcedure { get; } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs index ad08179cc5..0669973444 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs @@ -6,6 +6,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -20,7 +21,7 @@ public AccessSheetUsingCodeNameQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var referenceResult = (IdentifierReferenceInspectionResult)result; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs index 5c7dc054fd..a175c4c54d 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Settings; using Rubberduck.SettingsProvider; @@ -17,7 +18,7 @@ public AddIdentifierToWhiteListQuickFix(IPersistanceService()); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs index a83c0499d3..0a6722630b 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -16,7 +17,7 @@ public ChangeDimToPrivateQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs index 1ebcf98399..b537da2d14 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs @@ -23,7 +23,7 @@ public ChangeIntegerToLongQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs index d85ce81c22..fcfd26ea76 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs @@ -5,6 +5,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -20,7 +21,7 @@ public ChangeProcedureToFunctionQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var parameterizedDeclaration = (IParameterizedDeclaration) result.Target; var arg = parameterizedDeclaration.Parameters.Cast().First(p => p.IsByRef || p.IsImplicitByRef); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs index 9b037f0e3a..afd57a0db8 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs @@ -6,6 +6,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -21,7 +22,7 @@ public ConvertToProcedureQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { switch (result.Context) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs index 28a0db45bd..e0bc881be3 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs @@ -3,6 +3,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -17,7 +18,7 @@ public DeclareAsExplicitVariantQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs index 01b8545c1a..919de89b2a 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.EncapsulateField; using Rubberduck.SmartIndenter; @@ -23,7 +24,7 @@ public EncapsulateFieldQuickFix(IVBE vbe, RubberduckParserState state, IIndenter _indenter = indenter; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { using (var view = new EncapsulateFieldDialog(new EncapsulateFieldViewModel(_state, _indenter))) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs index 65ae67fd15..ce7052146a 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs @@ -8,6 +8,7 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -26,7 +27,7 @@ public IgnoreOnceQuickFix(RubberduckParserState state, IEnumerable public override bool CanFixInModule => false; public override bool CanFixInProject => false; - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var annotationText = $"'@Ignore {result.Inspection.AnnotationName}"; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs index eb17717cc4..847e9b30fd 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs @@ -5,6 +5,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -23,7 +24,7 @@ public IntroduceLocalVariableQuickFix(RubberduckParserState state) public override bool CanFixInModule => true; public override bool CanFixInProject => true; - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var identifierContext = result.Target.Context; var enclosingStatmentContext = identifierContext.GetAncestor(); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs index 2b13021482..65fb994536 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs @@ -6,6 +6,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -21,7 +22,7 @@ public IsMissingOnInappropriateArgumentQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { if (!(result.Properties is ParameterDeclaration parameter)) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs index 2bd56531a8..0c0e97956e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; using Rubberduck.Parsing.VBA.Extensions; @@ -16,7 +17,7 @@ public MakeSingleLineParameterQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs index 9a5634222f..7ac6c44185 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Interaction; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.MoveCloserToUsage; using Rubberduck.Resources.Inspections; @@ -23,7 +24,7 @@ public MoveFieldCloserToUsageQuickFix(IVBE vbe, RubberduckParserState state, IMe _messageBox = messageBox; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var refactoring = new MoveCloserToUsageRefactoring(_vbe, _state, _messageBox); refactoring.Refactor(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs index b223170ef9..49135709cc 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs @@ -3,6 +3,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -17,7 +18,7 @@ public OptionExplicitQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.InsertBefore(0, Tokens.Option + ' ' + Tokens.Explicit + Environment.NewLine + Environment.NewLine); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs index 590f81c512..8be2a9860f 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -16,7 +17,7 @@ public PassParameterByReferenceQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs index 0689f17bfd..077a6b7a30 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs @@ -4,6 +4,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.VBEditor; @@ -20,7 +21,7 @@ public PassParameterByValueQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { if (result.Target.ParentDeclaration.DeclarationType == DeclarationType.Event || _state.DeclarationFinder.FindAllInterfaceMembers().Contains(result.Target.ParentDeclaration)) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs index 6f9e55c905..90fea1b043 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -15,7 +16,7 @@ public RemoveCommentQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.Remove(result.Context); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs index 508759ee69..c0f62838d6 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs @@ -21,7 +21,7 @@ public RemoveDuplicatedAnnotationQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs index 2968a5b88b..bcb9ad9b8f 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs @@ -17,7 +17,7 @@ public RemoveEmptyElseBlockQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs index f928ecb161..26bf7c9923 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs @@ -21,7 +21,7 @@ public RemoveEmptyIfBlockQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs index 66a0a0efcb..225582c16e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs @@ -21,7 +21,7 @@ public RemoveExplicitByRefModifierQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var context = (VBAParser.ArgContext) result.Context; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatmentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatmentQuickFix.cs index 09e0a7b902..8aef5ff215 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatmentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatmentQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -16,7 +17,7 @@ public RemoveExplicitCallStatmentQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs index bb891e8a67..4d617dabf2 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs @@ -3,6 +3,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -17,7 +18,7 @@ public RemoveExplicitLetStatementQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs index 1982d006b4..73c19cd37c 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -16,7 +17,7 @@ public RemoveLocalErrorQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var errorStmt = (VBAParser.OnErrorStmtContext)result.Context; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs index 2b202958aa..b946277096 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -15,7 +16,7 @@ public RemoveOptionBaseStatementQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.Remove(result.Context); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs index 88155453a9..0a94043ddb 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs @@ -24,7 +24,7 @@ public RemoveStepOneQuickFix(RubberduckParserState state) public override string Description(IInspectionResult result) => Resources.Inspections.QuickFixes.RemoveStepOneQuickFix; - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { IExecutableModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); var context = result.Context; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs index b4bb155545..bb61ae64fd 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -15,7 +16,7 @@ public RemoveStopKeywordQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.Remove(result.Context); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs index 964837b6c6..ddaa597a4f 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs @@ -3,6 +3,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -18,7 +19,7 @@ public RemoveTypeHintsQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { if (!string.IsNullOrWhiteSpace(result.Target.TypeHint)) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs index e85da40746..4d314052ef 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -15,7 +16,7 @@ public RemoveUnassignedIdentifierQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); rewriter.Remove(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs index 5a2465ac06..d4d3d08ccf 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs @@ -4,6 +4,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -19,7 +20,7 @@ public RemoveUnassignedVariableUsageQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs index 395707237b..0ae3f345f9 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -18,7 +19,7 @@ public RemoveUnusedDeclarationQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); rewriter.Remove(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs index 77017f84c4..0bc2aef419 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Interaction; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.RemoveParameters; using Rubberduck.UI.Refactorings.RemoveParameters; @@ -23,7 +24,7 @@ public RemoveUnusedParameterQuickFix(IVBE vbe, RubberduckParserState state, IMes _messageBox = messageBox; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { using (var dialog = new RemoveParametersDialog(new RemoveParametersViewModel(_state))) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs index ab6c2817a8..75d0ef30ae 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs @@ -3,6 +3,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Interaction; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.Rename; using Rubberduck.Resources; @@ -25,7 +26,7 @@ public RenameDeclarationQuickFix(IVBE vbe, RubberduckParserState state, IMessage _messageBox = messageBox; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { using (var view = new RenameDialog(new RenameViewModel(_state))) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs index cc62ac489b..a2284ebb23 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -15,7 +16,7 @@ public ReplaceEmptyStringLiteralStatementQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(result.Context, "vbNullString"); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs index 2b1da070b5..c99e7e1670 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs @@ -4,6 +4,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -18,7 +19,7 @@ public ReplaceGlobalModifierQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); rewriter.Replace(((ParserRuleContext)result.Context.Parent.Parent).GetDescendent(), Tokens.Public); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs index 502957de05..9e5180b67e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs @@ -3,6 +3,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -18,7 +19,7 @@ public ReplaceIfElseWithConditionalStatementQuickFix(RubberduckParserState state _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var ifContext = (VBAParser.IfStmtContext) result.Context; var letStmt = ifContext.block().GetDescendent(); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs index be1aba443a..56b173af26 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -16,7 +17,7 @@ public ReplaceObsoleteCommentMarkerQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.RemCommentContext) result.Context; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs index 2006d98ab9..36134df642 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -16,7 +17,7 @@ public ReplaceObsoleteErrorStatementQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.ErrorStmtContext) result.Context; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs index 02f053724c..73cb76157e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs @@ -5,6 +5,7 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -20,7 +21,7 @@ public RestoreErrorHandlingQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var exitStatement = "Exit "; VBAParser.BlockContext block; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs index b7247fdfdd..5e046355b8 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs @@ -2,6 +2,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -17,7 +18,7 @@ public SetExplicitVariantReturnTypeQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs index 6c2d5055f9..39d861bee0 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs @@ -21,7 +21,7 @@ public SpecifyExplicitByRefModifierQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var context = (VBAParser.ArgContext)result.Context; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs index 0192284930..7e13182f23 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -15,7 +16,7 @@ public SpecifyExplicitPublicModifierQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.Target); rewriter.InsertBefore(result.Context.Start.TokenIndex, "Public "); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs index b608d712a3..3ca396076f 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs @@ -5,6 +5,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -19,7 +20,7 @@ public SplitMultipleDeclarationsQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var context = result.Context is VBAParser.ConstStmtContext ? result.Context diff --git a/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs index 35f113ef81..ba7e5f92b2 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs @@ -5,6 +5,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -19,7 +20,7 @@ public UntypedFunctionUsageQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.InsertAfter(result.Context.Stop.TokenIndex, "$"); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs index 541d6b361f..332b02e49f 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs @@ -1,6 +1,7 @@ using Rubberduck.Inspections.Abstract; using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes @@ -15,7 +16,7 @@ public UseSetKeywordForObjectAssignmentQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.InsertBefore(result.Context.Start.TokenIndex, "Set "); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs index 00966ef0d6..0d9cc12122 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs @@ -4,6 +4,7 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; @@ -19,7 +20,7 @@ public WriteOnlyPropertyQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { var parameters = ((IParameterizedDeclaration) result.Target).Parameters.Cast().ToList(); diff --git a/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs b/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs index 89f3a91a0e..31134db667 100644 --- a/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs +++ b/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs @@ -1,11 +1,12 @@ using System; using System.Collections.Generic; +using Rubberduck.Parsing.Rewriter; namespace Rubberduck.Parsing.Inspections.Abstract { public interface IQuickFix { - void Fix(IInspectionResult result); + void Fix(IInspectionResult result, IRewriteSession rewriteSession = null); string Description(IInspectionResult result); bool CanFixInProcedure { get; } From ee12ff52a93b6b7d6fa8a93397837ee082bcd15d Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 27 Oct 2018 18:59:33 +0200 Subject: [PATCH 020/107] Provide IRewriteSessions to quickfixes in QuickFixProvider This change ensures that whenever a fix is used for multiple results, the same IRewriteSession is used. --- .../Inspections/Abstract/QuickFixBase.cs | 4 +- .../QuickFixes/QuickFixProvider.cs | 76 ++++++++++++++----- .../Inspections/Abstract/IQuickFix.cs | 2 + .../Rewriter/RewriteSessionBase.cs | 6 ++ 4 files changed, 66 insertions(+), 22 deletions(-) diff --git a/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs b/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs index 9d684db1ec..3c6cfad8e1 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs @@ -4,8 +4,8 @@ using NLog; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; using Rubberduck.Parsing.VBA.Extensions; +using Rubberduck.Parsing.VBA.Parsing; namespace Rubberduck.Inspections.Abstract { @@ -40,6 +40,8 @@ public void RemoveInspections(params Type[] inspections) _supportedInspections = _supportedInspections.Except(inspections).ToHashSet(); } + public virtual CodeKind TargetCodeKind => CodeKind.CodePaneCode; + public abstract void Fix(IInspectionResult result, IRewriteSession rewriteSession = null); public abstract string Description(IInspectionResult result); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs index a69621f420..c27e466d11 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs @@ -4,7 +4,9 @@ using System.Linq; using Microsoft.CSharp.RuntimeBinder; using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; +using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.VBEditor; namespace Rubberduck.Inspections.QuickFixes @@ -74,17 +76,39 @@ public void Fix(IQuickFix fix, IInspectionResult result) return; } - fix.Fix(result); + var rewriteSession = RewriteSession(fix.TargetCodeKind); + fix.Fix(result, rewriteSession); + rewriteSession.Rewrite(); + _state.RewriteAllModules(); _state.OnParseRequested(this); } + private IRewriteSession RewriteSession(CodeKind targetCodeKind) + { + switch (targetCodeKind) + { + case CodeKind.CodePaneCode: + return _state.RewritingManager.CheckOutCodePaneSession(); + case CodeKind.AttributesCode: + return _state.RewritingManager.CheckOutAttributesSession(); + default: + throw new NotSupportedException(nameof(targetCodeKind)); + } + } + public void FixInProcedure(IQuickFix fix, QualifiedMemberName? qualifiedMember, Type inspectionType, IEnumerable results) { Debug.Assert(qualifiedMember.HasValue, "Null qualified member."); var filteredResults = results.Where(result => result.Inspection.GetType() == inspectionType && result.QualifiedMemberName == qualifiedMember).ToList(); + if (!filteredResults.Any()) + { + return; + } + + var rewriteSession = RewriteSession(fix.TargetCodeKind); foreach (var result in filteredResults) { if (!CanFix(fix, result)) @@ -94,18 +118,22 @@ public void FixInProcedure(IQuickFix fix, QualifiedMemberName? qualifiedMember, fix.Fix(result); } + rewriteSession.Rewrite(); - if (filteredResults.Any()) - { - _state.RewriteAllModules(); - _state.OnParseRequested(this); - } + _state.RewriteAllModules(); + _state.OnParseRequested(this); } public void FixInModule(IQuickFix fix, QualifiedSelection selection, Type inspectionType, IEnumerable results) { var filteredResults = results.Where(result => result.Inspection.GetType() == inspectionType && result.QualifiedSelection.QualifiedName == selection.QualifiedName).ToList(); + if (!filteredResults.Any()) + { + return; + } + + var rewriteSession = RewriteSession(fix.TargetCodeKind); foreach (var result in filteredResults) { if (!CanFix(fix, result)) @@ -115,18 +143,22 @@ public void FixInModule(IQuickFix fix, QualifiedSelection selection, Type inspec fix.Fix(result); } + rewriteSession.Rewrite(); - if (filteredResults.Any()) - { - _state.RewriteAllModules(); - _state.OnParseRequested(this); - } + _state.RewriteAllModules(); + _state.OnParseRequested(this); } public void FixInProject(IQuickFix fix, QualifiedSelection selection, Type inspectionType, IEnumerable results) { var filteredResults = results.Where(result => result.Inspection.GetType() == inspectionType && result.QualifiedSelection.QualifiedName.ProjectId == selection.QualifiedName.ProjectId).ToList(); + if (!filteredResults.Any()) + { + return; + } + + var rewriteSession = RewriteSession(fix.TargetCodeKind); foreach (var result in filteredResults) { if (!CanFix(fix, result)) @@ -136,18 +168,22 @@ public void FixInProject(IQuickFix fix, QualifiedSelection selection, Type inspe fix.Fix(result); } + rewriteSession.Rewrite(); - if (filteredResults.Any()) - { - _state.RewriteAllModules(); - _state.OnParseRequested(this); - } + _state.RewriteAllModules(); + _state.OnParseRequested(this); } public void FixAll(IQuickFix fix, Type inspectionType, IEnumerable results) { var filteredResults = results.Where(result => result.Inspection.GetType() == inspectionType).ToArray(); + if (!filteredResults.Any()) + { + return; + } + + var rewriteSession = RewriteSession(fix.TargetCodeKind); foreach (var result in filteredResults) { if (!CanFix(fix, result)) @@ -157,12 +193,10 @@ public void FixAll(IQuickFix fix, Type inspectionType, IEnumerable SupportedInspections { get; } + CodeKind TargetCodeKind { get; } void RegisterInspections(params Type[] inspections); void RemoveInspections(params Type[] inspections); diff --git a/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs b/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs index 45546a2f75..9256d35c22 100644 --- a/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs +++ b/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using NLog; using Rubberduck.VBEditor; @@ -39,6 +40,11 @@ public IModuleRewriter CheckOutModuleRewriter(QualifiedModuleName module) public void Rewrite() { + if (!CheckedOutModuleRewriters.Any()) + { + return; + } + lock (_invalidationLockObject) { if (_isInvalidated) From 4ca6d8ab5658b4744b45ad054311bb79764bc965 Mon Sep 17 00:00:00 2001 From: bclothier Date: Tue, 30 Oct 2018 20:12:42 -0500 Subject: [PATCH 021/107] Fix up the Dispose methods --- Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs | 5 +++-- Rubberduck.VBEEditor/ComManagement/StrongComSafe.cs | 1 + Rubberduck.VBEEditor/ComManagement/WeakComSafe.cs | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs b/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs index cbee17a160..60fe688249 100644 --- a/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs +++ b/Rubberduck.VBEEditor/ComManagement/ComSafeBase.cs @@ -28,7 +28,10 @@ protected int GetComWrapperObjectHashCode(ISafeComWrapper comWrapper) public void Dispose() { Dispose(true); + } + protected virtual void Dispose(bool disposing) + { #if DEBUG if (_disposed) { @@ -67,8 +70,6 @@ public void Dispose() #endif } - protected abstract void Dispose(bool disposing); - #if DEBUG private struct TraceData { diff --git a/Rubberduck.VBEEditor/ComManagement/StrongComSafe.cs b/Rubberduck.VBEEditor/ComManagement/StrongComSafe.cs index 8db80bf1d7..fa1e19b03f 100644 --- a/Rubberduck.VBEEditor/ComManagement/StrongComSafe.cs +++ b/Rubberduck.VBEEditor/ComManagement/StrongComSafe.cs @@ -57,6 +57,7 @@ protected override void Dispose(bool disposing) } _disposed = true; + base.Dispose(disposing); foreach (var comWrapper in _comWrapperCache.Keys) { diff --git a/Rubberduck.VBEEditor/ComManagement/WeakComSafe.cs b/Rubberduck.VBEEditor/ComManagement/WeakComSafe.cs index 3f18fb360e..54200ffb86 100644 --- a/Rubberduck.VBEEditor/ComManagement/WeakComSafe.cs +++ b/Rubberduck.VBEEditor/ComManagement/WeakComSafe.cs @@ -61,6 +61,7 @@ protected override void Dispose(bool disposing) } _disposed = true; + base.Dispose(disposing); foreach (var weakReference in _comWrapperCache.Values) { From 280b1b125f78bb65ac288aacd9fc69f8d3ed5a23 Mon Sep 17 00:00:00 2001 From: bclothier Date: Wed, 31 Oct 2018 00:21:58 -0500 Subject: [PATCH 022/107] Provide a means of locating the VBE for use along COM classes which are not managed by a IoC container. --- Rubberduck.Main/Extension.cs | 2 ++ Rubberduck.Main/VbeProvider.cs | 35 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 Rubberduck.Main/VbeProvider.cs diff --git a/Rubberduck.Main/Extension.cs b/Rubberduck.Main/Extension.cs index 5f2af07210..8587355b24 100644 --- a/Rubberduck.Main/Extension.cs +++ b/Rubberduck.Main/Extension.cs @@ -59,6 +59,7 @@ public void OnConnection(object Application, ext_ConnectMode ConnectMode, object _addin = RootComWrapperFactory.GetAddInWrapper(AddInInst); _addin.Object = this; + VbeProvider.Initialize(_vbe); VBENativeServices.HookEvents(_vbe); #if DEBUG @@ -242,6 +243,7 @@ private void ShutdownAddIn() _logger.Log(LogLevel.Info, "Rubberduck is shutting down."); _logger.Log(LogLevel.Trace, "Unhooking VBENativeServices events..."); VBENativeServices.UnhookEvents(); + VbeProvider.Terminate(); _logger.Log(LogLevel.Trace, "Releasing dockable hosts..."); diff --git a/Rubberduck.Main/VbeProvider.cs b/Rubberduck.Main/VbeProvider.cs new file mode 100644 index 0000000000..45761cfa83 --- /dev/null +++ b/Rubberduck.Main/VbeProvider.cs @@ -0,0 +1,35 @@ +using Rubberduck.VBEditor.SafeComWrappers.Abstract; +using Rubberduck.VBEditor.VBERuntime; + +namespace Rubberduck +{ + /// + /// ANTI-PATTERN: Service locator for COM class. Think carefully before using it, and regret it. + /// + /// + /// This is a hacky workaround to provide support to COM-visible classes without breaking the + /// interface or violating the security settings of the Office host. Because a COM class must + /// have a parameterless constructor if it is to be newed up and because COM class cannot come + /// from the IoC container nor have any dependencies coming out of it, we use the service + /// locator anti-pattern here to provide the necessary functionality for the COM classes' + /// internal implementations. The use should never expand beyond that limited scope. + /// + internal static class VbeProvider + { + internal static void Initialize(IVBE vbe) + { + Vbe = vbe; + VbeRuntime = new VBERuntimeAccessor(vbe); + } + + internal static void Terminate() + { + Vbe.Dispose(); + Vbe = null; + VbeRuntime = null; + } + + internal static IVBE Vbe { get; private set; } + internal static IVBERuntime VbeRuntime { get; private set; } + } +} From c396b40714894b8cdcc8457cedfc6c0503461ded Mon Sep 17 00:00:00 2001 From: bclothier Date: Wed, 31 Oct 2018 00:22:50 -0500 Subject: [PATCH 023/107] Update the VBERuntime implementations to include the needed functions --- .../VBERuntime/IVBERuntime.cs | 17 +++- .../VBERuntime/VBERuntime6.cs | 84 +++++++++++++++++-- .../VBERuntime/VBERuntime7.cs | 84 +++++++++++++++++-- .../VBERuntime/VBERuntimeAccessor.cs | 60 ++++++++++++- 4 files changed, 229 insertions(+), 16 deletions(-) diff --git a/Rubberduck.VBEEditor/VBERuntime/IVBERuntime.cs b/Rubberduck.VBEEditor/VBERuntime/IVBERuntime.cs index e4da23d87a..52fa45f24c 100644 --- a/Rubberduck.VBEEditor/VBERuntime/IVBERuntime.cs +++ b/Rubberduck.VBEEditor/VBERuntime/IVBERuntime.cs @@ -1,8 +1,21 @@ -namespace Rubberduck.VBEditor.VBERuntime +using System; + +namespace Rubberduck.VBEditor.VBERuntime { public interface IVBERuntime { - float Timer(); + string DllName { get; } int DoEvents(); + float GetTimer(); + void GetDateVar(out object retval); + void GetPresentDate(out object retVal); + double Shell(IntPtr pathname, short windowstyle); + void GetTimeVar(out object retVal); + void ChangeDir(IntPtr path); + void ChangeDrive(IntPtr driveletter); + void KillFiles(IntPtr pathname); + void MakeDir(IntPtr path); + void RemoveDir(IntPtr path); + void Beep(); } } diff --git a/Rubberduck.VBEEditor/VBERuntime/VBERuntime6.cs b/Rubberduck.VBEEditor/VBERuntime/VBERuntime6.cs index 75189de516..302d4f9c2f 100644 --- a/Rubberduck.VBEEditor/VBERuntime/VBERuntime6.cs +++ b/Rubberduck.VBEEditor/VBERuntime/VBERuntime6.cs @@ -1,23 +1,97 @@ -using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; namespace Rubberduck.VBEditor.VBERuntime { internal class VBERuntime6 : IVBERuntime { - private const string DllName = "vbe6.dll"; + private const string _dllName = "vbe6.dll"; - [DllImport(DllName)] + public string DllName => _dllName; + + [DllImport(_dllName)] private static extern int rtcDoEvents(); public int DoEvents() { return rtcDoEvents(); } - [DllImport(DllName)] + [DllImport(_dllName, SetLastError = true)] + [return: MarshalAs(UnmanagedType.R4)] private static extern float rtcGetTimer(); - public float Timer() + public float GetTimer() { return rtcGetTimer(); } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcGetDateVar(out object retVal); + public void GetDateVar(out object retval) + { + rtcGetDateVar(out retval); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcGetPresentDate(out object retVal); + public void GetPresentDate(out object retVal) + { + rtcGetPresentDate(out retVal); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern double rtcShell(IntPtr pathname, short windowstyle); + public double Shell(IntPtr pathname, short windowstyle) + { + return rtcShell(pathname, windowstyle); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcGetTimeVar(out object retVal); + public void GetTimeVar(out object retVal) + { + rtcGetTimeVar(out retVal); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcChangeDir(IntPtr path); + public void ChangeDir(IntPtr path) + { + rtcChangeDir(path); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcChangeDrive(IntPtr driveletter); + public void ChangeDrive(IntPtr driveletter) + { + rtcChangeDrive(driveletter); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcKillFiles(IntPtr pathname); + public void KillFiles(IntPtr pathname) + { + rtcKillFiles(pathname); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcMakeDir(IntPtr path); + public void MakeDir(IntPtr path) + { + rtcMakeDir(path); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcRemoveDir(IntPtr path); + public void RemoveDir(IntPtr path) + { + rtcRemoveDir(path); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcBeep(); + public void Beep() + { + rtcBeep(); + } } } diff --git a/Rubberduck.VBEEditor/VBERuntime/VBERuntime7.cs b/Rubberduck.VBEEditor/VBERuntime/VBERuntime7.cs index 4846cead5a..dad602650c 100644 --- a/Rubberduck.VBEEditor/VBERuntime/VBERuntime7.cs +++ b/Rubberduck.VBEEditor/VBERuntime/VBERuntime7.cs @@ -1,23 +1,97 @@ -using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; namespace Rubberduck.VBEditor.VBERuntime { internal class VBERuntime7 : IVBERuntime { - private const string DllName = "vbe7.dll"; + private const string _dllName = "vbe7.dll"; - [DllImport(DllName)] + public string DllName => _dllName; + + [DllImport(_dllName)] private static extern int rtcDoEvents(); public int DoEvents() { return rtcDoEvents(); } - [DllImport(DllName)] + [DllImport(_dllName, SetLastError = true)] + [return: MarshalAs(UnmanagedType.R4)] private static extern float rtcGetTimer(); - public float Timer() + public float GetTimer() { return rtcGetTimer(); } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcGetDateVar(out object retVal); + public void GetDateVar(out object retval) + { + rtcGetDateVar(out retval); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcGetPresentDate(out object retVal); + public void GetPresentDate(out object retVal) + { + rtcGetPresentDate(out retVal); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern double rtcShell(IntPtr pathname, short windowstyle); + public double Shell(IntPtr pathname, short windowstyle) + { + return rtcShell(pathname, windowstyle); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcGetTimeVar(out object retVal); + public void GetTimeVar(out object retVal) + { + rtcGetTimeVar(out retVal); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcChangeDir(IntPtr path); + public void ChangeDir(IntPtr path) + { + rtcChangeDir(path); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcChangeDrive(IntPtr driveletter); + public void ChangeDrive(IntPtr driveletter) + { + rtcChangeDrive(driveletter); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcKillFiles(IntPtr pathname); + public void KillFiles(IntPtr pathname) + { + rtcKillFiles(pathname); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcMakeDir(IntPtr path); + public void MakeDir(IntPtr path) + { + rtcMakeDir(path); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcRemoveDir(IntPtr path); + public void RemoveDir(IntPtr path) + { + rtcRemoveDir(path); + } + + [DllImport(_dllName, SetLastError = true)] + private static extern void rtcBeep(); + public void Beep() + { + rtcBeep(); + } } } diff --git a/Rubberduck.VBEEditor/VBERuntime/VBERuntimeAccessor.cs b/Rubberduck.VBEEditor/VBERuntime/VBERuntimeAccessor.cs index c2e835bf30..9074d42ee4 100644 --- a/Rubberduck.VBEEditor/VBERuntime/VBERuntimeAccessor.cs +++ b/Rubberduck.VBEEditor/VBERuntime/VBERuntimeAccessor.cs @@ -48,7 +48,7 @@ private static IVBERuntime DetermineVersion() try { runtime = new VBERuntime7(); - runtime.Timer(); + runtime.GetTimer(); _version = DllVersion.Vbe7; } catch @@ -56,7 +56,7 @@ private static IVBERuntime DetermineVersion() try { runtime = new VBERuntime6(); - runtime.Timer(); + runtime.GetTimer(); _version = DllVersion.Vbe6; } catch @@ -69,14 +69,66 @@ private static IVBERuntime DetermineVersion() return _version != DllVersion.Unknown ? runtime : null; } - public float Timer() + public string DllName => _runtime.DllName; + + public float GetTimer() + { + return _runtime.GetTimer(); + } + + public void GetDateVar(out object retval) + { + _runtime.GetDateVar(out retval); + } + + public void GetPresentDate(out object retVal) + { + _runtime.GetPresentDate(out retVal); + } + + public double Shell(IntPtr pathname, short windowstyle) + { + return _runtime.Shell(pathname, windowstyle); + } + + public void GetTimeVar(out object retVal) + { + _runtime.GetTimeVar(out retVal); + } + + public void ChangeDir(IntPtr path) { - return _runtime.Timer(); + _runtime.ChangeDir(path); + } + + public void ChangeDrive(IntPtr driveletter) + { + _runtime.ChangeDrive(driveletter); + } + + public void KillFiles(IntPtr pathname) + { + _runtime.KillFiles(pathname); + } + + public void MakeDir(IntPtr path) + { + _runtime.MakeDir(path); + } + + public void RemoveDir(IntPtr path) + { + _runtime.RemoveDir(path); } public int DoEvents() { return _runtime.DoEvents(); } + + public void Beep() + { + _runtime.Beep(); + } } } From c1bd83011bac195c266aa39ee8257dcd6af0f4da Mon Sep 17 00:00:00 2001 From: bclothier Date: Wed, 31 Oct 2018 00:24:13 -0500 Subject: [PATCH 024/107] Update the stubs & fakes to use VBERuntime instead of directly implementing the VBE functions & use the correct DLL name. --- .../ComClientLibrary/UnitTesting/Fakes/CurDir.cs | 10 +++++----- .../ComClientLibrary/UnitTesting/Fakes/Date.cs | 11 ++++------- .../UnitTesting/Fakes/DoEvents.cs | 13 ++++--------- .../UnitTesting/Fakes/Environ.cs | 10 +++++----- .../UnitTesting/Fakes/InputBox.cs | 6 +++--- .../ComClientLibrary/UnitTesting/Fakes/MsgBox.cs | 6 +++--- .../ComClientLibrary/UnitTesting/Fakes/Now.cs | 11 ++++------- .../ComClientLibrary/UnitTesting/Fakes/Shell.cs | 11 ++++------- .../ComClientLibrary/UnitTesting/Fakes/Time.cs | 11 ++++------- .../ComClientLibrary/UnitTesting/Fakes/Timer.cs | 12 ++++-------- .../ComClientLibrary/UnitTesting/StubBase.cs | 1 - .../ComClientLibrary/UnitTesting/Stubs/Beep.cs | 16 ++++++---------- .../ComClientLibrary/UnitTesting/Stubs/ChDir.cs | 11 ++++------- .../UnitTesting/Stubs/ChDrive.cs | 11 ++++------- .../ComClientLibrary/UnitTesting/Stubs/Kill.cs | 11 ++++------- .../ComClientLibrary/UnitTesting/Stubs/MkDir.cs | 11 ++++------- .../ComClientLibrary/UnitTesting/Stubs/RmDir.cs | 11 ++++------- .../UnitTesting/Stubs/SendKeys.cs | 8 ++++---- 18 files changed, 70 insertions(+), 111 deletions(-) diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/CurDir.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/CurDir.cs index 656c91410f..e9777c7de2 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/CurDir.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/CurDir.cs @@ -6,13 +6,13 @@ namespace Rubberduck.UnitTesting.Fakes { internal class CurDir : FakeBase { - private static readonly IntPtr ProcessAddressVariant = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcCurrentDir"); - private static readonly IntPtr ProcessAddressString = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcCurrentDirBstr"); - public CurDir() { - InjectDelegate(new CurDirStringDelegate(CurDirStringCallback), ProcessAddressString); - InjectDelegate(new CurDirVariantDelegate(CurDirVariantCallback), ProcessAddressVariant); + var processAddressVariant = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcCurrentDir"); + var processAddressString = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcCurrentDirBstr"); + + InjectDelegate(new CurDirStringDelegate(CurDirStringCallback), processAddressString); + InjectDelegate(new CurDirVariantDelegate(CurDirVariantCallback), processAddressVariant); } public override bool PassThrough diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Date.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Date.cs index 5753bb4166..aba16c16b6 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Date.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Date.cs @@ -5,15 +5,12 @@ namespace Rubberduck.UnitTesting.Fakes { internal class Date : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcGetDateVar"); - public Date() { - InjectDelegate(new DateDelegate(DateCallback), ProcessAddress); - } + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcGetDateVar"); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcGetDateVar(out object retVal); + InjectDelegate(new DateDelegate(DateCallback), processAddress); + } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void DateDelegate(IntPtr retVal); @@ -28,7 +25,7 @@ public void DateCallback(IntPtr retVal) if (PassThrough) { object result; - rtcGetDateVar(out result); + VbeProvider.VbeRuntime.GetDateVar(out result); Marshal.GetNativeVariantForObject(result, retVal); return; } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/DoEvents.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/DoEvents.cs index e6a19b85b6..683470b537 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/DoEvents.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/DoEvents.cs @@ -1,16 +1,15 @@ using Rubberduck.UnitTesting.ComClientHelpers; -using System; using System.Runtime.InteropServices; namespace Rubberduck.UnitTesting.Fakes { internal class DoEvents : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcDoEvents"); - public DoEvents() { - InjectDelegate(new DoEventsDelegate(DoEventsCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcDoEvents"); + + InjectDelegate(new DoEventsDelegate(DoEventsCallback), processAddress); } private readonly ValueTypeConverter _converter = new ValueTypeConverter(); @@ -20,10 +19,6 @@ public override void Returns(object value, int invocation = FakesProvider.AllInv base.Returns((int)_converter.Value, invocation); } - [DllImport(TargetLibrary, SetLastError = true)] - [return: MarshalAs(UnmanagedType.I4)] - private static extern int rtcDoEvents(); - [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] [return: MarshalAs(UnmanagedType.I4)] private delegate int DoEventsDelegate(); @@ -34,7 +29,7 @@ public int DoEventsCallback() if (PassThrough) { - return rtcDoEvents(); + return VbeProvider.VbeRuntime.DoEvents(); } return (int)(ReturnValue ?? 0); } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Environ.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Environ.cs index 3e389cb1b7..285fd6b5cb 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Environ.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Environ.cs @@ -6,13 +6,13 @@ namespace Rubberduck.UnitTesting.Fakes { internal class Environ : FakeBase { - private static readonly IntPtr ProcessAddressString = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcEnvironBstr"); - private static readonly IntPtr ProcessAddressVariant = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcEnvironVar"); - public Environ() { - InjectDelegate(new EnvironStringDelegate(EnvironStringCallback), ProcessAddressString); - InjectDelegate(new EnvironVariantDelegate(EnvironVariantCallback), ProcessAddressVariant); + var processAddressString = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcEnvironBstr"); + var processAddressVariant = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcEnvironVar"); + + InjectDelegate(new EnvironStringDelegate(EnvironStringCallback), processAddressString); + InjectDelegate(new EnvironVariantDelegate(EnvironVariantCallback), processAddressVariant); } public override bool PassThrough diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/InputBox.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/InputBox.cs index e151df5072..dd00ffc57c 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/InputBox.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/InputBox.cs @@ -6,11 +6,11 @@ namespace Rubberduck.UnitTesting.Fakes { internal class InputBox : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcInputBox"); - public InputBox() { - InjectDelegate(new InputBoxDelegate(InputBoxCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcInputBox"); + + InjectDelegate(new InputBoxDelegate(InputBoxCallback), processAddress); } public override bool PassThrough diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/MsgBox.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/MsgBox.cs index 0257ba2634..eda969650c 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/MsgBox.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/MsgBox.cs @@ -8,11 +8,11 @@ namespace Rubberduck.UnitTesting.Fakes { internal class MsgBox : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcMsgBox"); - public MsgBox() { - InjectDelegate(new MessageBoxDelegate(MsgBoxCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcMsgBox"); + + InjectDelegate(new MessageBoxDelegate(MsgBoxCallback), processAddress); } public override bool PassThrough diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Now.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Now.cs index 2c4c9ec3fa..851ff017df 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Now.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Now.cs @@ -5,15 +5,12 @@ namespace Rubberduck.UnitTesting.Fakes { internal class Now : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcGetPresentDate"); - public Now() { - InjectDelegate(new NowDelegate(NowCallback), ProcessAddress); - } + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcGetPresentDate"); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcGetPresentDate(out object retVal); + InjectDelegate(new NowDelegate(NowCallback), processAddress); + } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void NowDelegate(IntPtr retVal); @@ -28,7 +25,7 @@ public void NowCallback(IntPtr retVal) if (PassThrough) { object result; - rtcGetPresentDate(out result); + VbeProvider.VbeRuntime.GetPresentDate(out result); Marshal.GetNativeVariantForObject(result, retVal); return; } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Shell.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Shell.cs index 44e7e1e379..1baf508aaa 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Shell.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Shell.cs @@ -7,11 +7,11 @@ namespace Rubberduck.UnitTesting.Fakes { internal class Shell : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcShell"); - public Shell() { - InjectDelegate(new ShellDelegate(ShellCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcShell"); + + InjectDelegate(new ShellDelegate(ShellCallback), processAddress); } private readonly ValueTypeConverter _converter = new ValueTypeConverter(); @@ -21,9 +21,6 @@ public override void Returns(object value, int invocation = FakesProvider.AllInv base.Returns((double)_converter.Value, invocation); } - [DllImport(TargetLibrary, SetLastError = true)] - private static extern double rtcShell(IntPtr pathname, short windowstyle); - [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] [return: MarshalAs(UnmanagedType.R8)] private delegate double ShellDelegate(IntPtr pathname, short windowstyle); @@ -39,7 +36,7 @@ public double ShellCallback(IntPtr pathname, short windowstyle) if (PassThrough) { - return Convert.ToDouble(rtcShell(pathname, windowstyle)); + return Convert.ToDouble(VbeProvider.VbeRuntime.Shell(pathname, windowstyle)); } return Convert.ToDouble(ReturnValue ?? 0); } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Time.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Time.cs index 622e844f54..68b80c8898 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Time.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Time.cs @@ -5,15 +5,12 @@ namespace Rubberduck.UnitTesting.Fakes { internal class Time : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcGetTimeVar"); - public Time() { - InjectDelegate(new TimeDelegate(TimeCallback), ProcessAddress); - } + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcGetTimeVar"); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcGetTimeVar(out object retVal); + InjectDelegate(new TimeDelegate(TimeCallback), processAddress); + } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void TimeDelegate(IntPtr retVal); @@ -28,7 +25,7 @@ public void TimeCallback(IntPtr retVal) if (PassThrough) { object result; - rtcGetTimeVar(out result); + VbeProvider.VbeRuntime.GetTimeVar(out result); Marshal.GetNativeVariantForObject(result, retVal); return; } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Timer.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Timer.cs index 199dcf6029..1120e11ea2 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Timer.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Fakes/Timer.cs @@ -6,11 +6,11 @@ namespace Rubberduck.UnitTesting.Fakes { internal class Timer : FakeBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcGetTimer"); - public Timer() { - InjectDelegate(new TimerDelegate(TimerCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcGetTimer"); + + InjectDelegate(new TimerDelegate(TimerCallback), processAddress); } private readonly ValueTypeConverter _converter = new ValueTypeConverter(); @@ -20,10 +20,6 @@ public override void Returns(object value, int invocation = FakesProvider.AllInv base.Returns((float)_converter.Value, invocation); } - [DllImport(TargetLibrary, SetLastError = true)] - [return: MarshalAs(UnmanagedType.R4)] - private static extern float rtcGetTimer(); - [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] [return: MarshalAs(UnmanagedType.R4)] private delegate float TimerDelegate(); @@ -34,7 +30,7 @@ public float TimerCallback() if (PassThrough) { - return rtcGetTimer(); + return VbeProvider.VbeRuntime.GetTimer(); } return Convert.ToSingle(ReturnValue ?? 0); } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/StubBase.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/StubBase.cs index 9e16148906..3f24521613 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/StubBase.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/StubBase.cs @@ -7,7 +7,6 @@ namespace Rubberduck.UnitTesting { internal class StubBase : IStub, IDisposable { - internal const string TargetLibrary = "vbe7.dll"; private readonly List _hooks = new List(); #region Internal diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Beep.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Beep.cs index 7b9a686ca6..6ee16404f6 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Beep.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Beep.cs @@ -1,30 +1,26 @@ -using System; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; namespace Rubberduck.UnitTesting { internal class Beep : StubBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcBeep"); - - public Beep() + public Beep() { - InjectDelegate(new BeepDelegate(BeepCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcBeep"); + + InjectDelegate(new BeepDelegate(BeepCallback), processAddress); } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void BeepDelegate(); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcBeep(); - public void BeepCallback() { OnCallBack(true); if (PassThrough) { - rtcBeep(); + VbeProvider.VbeRuntime.Beep(); } } } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDir.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDir.cs index 888dab64ed..717872dc63 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDir.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDir.cs @@ -6,19 +6,16 @@ namespace Rubberduck.UnitTesting { internal class ChDir : StubBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcChangeDir"); - public ChDir() { - InjectDelegate(new ChDirDelegate(ChDirCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcChangeDir"); + + InjectDelegate(new ChDirDelegate(ChDirCallback), processAddress); } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void ChDirDelegate(IntPtr path); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcChangeDir(IntPtr path); - public void ChDirCallback(IntPtr path) { OnCallBack(true); @@ -28,7 +25,7 @@ public void ChDirCallback(IntPtr path) TrackUsage("path", pathArg, Tokens.String); if (PassThrough) { - rtcChangeDir(path); + VbeProvider.VbeRuntime.ChangeDir(path); } } } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDrive.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDrive.cs index 4bb0f03d43..bdee99b61c 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDrive.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/ChDrive.cs @@ -6,19 +6,16 @@ namespace Rubberduck.UnitTesting { internal class ChDrive : StubBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcChangeDrive"); - public ChDrive() { - InjectDelegate(new ChDriveDelegate(ChDriveCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcChangeDrive"); + + InjectDelegate(new ChDriveDelegate(ChDriveCallback), processAddress); } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void ChDriveDelegate(IntPtr driveletter); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcChangeDrive(IntPtr driveletter); - public void ChDriveCallback(IntPtr driveletter) { OnCallBack(true); @@ -28,7 +25,7 @@ public void ChDriveCallback(IntPtr driveletter) TrackUsage("driveletter", driveletterArg, Tokens.String); if (PassThrough) { - rtcChangeDrive(driveletter); + VbeProvider.VbeRuntime.ChangeDrive(driveletter); } } } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Kill.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Kill.cs index 6392f44c09..69dab0ac75 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Kill.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/Kill.cs @@ -5,19 +5,16 @@ namespace Rubberduck.UnitTesting { internal class Kill : StubBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcKillFiles"); - public Kill() { - InjectDelegate(new KillDelegate(KillCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcKillFiles"); + + InjectDelegate(new KillDelegate(KillCallback), processAddress); } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void KillDelegate(IntPtr pathname); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcKillFiles(IntPtr pathname); - public void KillCallback(IntPtr pathname) { OnCallBack(true); @@ -25,7 +22,7 @@ public void KillCallback(IntPtr pathname) TrackUsage("pathname", pathname); if (PassThrough) { - rtcKillFiles(pathname); + VbeProvider.VbeRuntime.KillFiles(pathname); } } } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/MkDir.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/MkDir.cs index 06c3609c83..968de453ba 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/MkDir.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/MkDir.cs @@ -6,19 +6,16 @@ namespace Rubberduck.UnitTesting { internal class MkDir : StubBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcMakeDir"); - public MkDir() { - InjectDelegate(new MkDirDelegate(MkDirCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcMakeDir"); + + InjectDelegate(new MkDirDelegate(MkDirCallback), processAddress); } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void MkDirDelegate(IntPtr path); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcMakeDir(IntPtr path); - public void MkDirCallback(IntPtr path) { OnCallBack(true); @@ -28,7 +25,7 @@ public void MkDirCallback(IntPtr path) TrackUsage("path", pathArg, Tokens.String); if (PassThrough) { - rtcMakeDir(path); + VbeProvider.VbeRuntime.MakeDir(path); } } } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/RmDir.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/RmDir.cs index 820cac2637..f48a320ee8 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/RmDir.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/RmDir.cs @@ -6,19 +6,16 @@ namespace Rubberduck.UnitTesting { internal class RmDir : StubBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcRemoveDir"); - public RmDir() { - InjectDelegate(new RmDirDelegate(RmDirCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcRemoveDir"); + + InjectDelegate(new RmDirDelegate(RmDirCallback), processAddress); } [UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)] private delegate void RmDirDelegate(IntPtr path); - [DllImport(TargetLibrary, SetLastError = true)] - private static extern void rtcRemoveDir(IntPtr path); - public void RmDirCallback(IntPtr path) { OnCallBack(true); @@ -28,7 +25,7 @@ public void RmDirCallback(IntPtr path) TrackUsage("path", pathArg, Tokens.String); if (PassThrough) { - rtcRemoveDir(path); + VbeProvider.VbeRuntime.RemoveDir(path); } } } diff --git a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/SendKeys.cs b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/SendKeys.cs index 8f92d4f635..0a2cb4da71 100644 --- a/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/SendKeys.cs +++ b/Rubberduck.Main/ComClientLibrary/UnitTesting/Stubs/SendKeys.cs @@ -7,16 +7,16 @@ namespace Rubberduck.UnitTesting { internal class SendKeys : StubBase { - private static readonly IntPtr ProcessAddress = EasyHook.LocalHook.GetProcAddress(TargetLibrary, "rtcSendKeys"); - public SendKeys() { - InjectDelegate(new SendKeysDelegate(SendKeysCallback), ProcessAddress); + var processAddress = EasyHook.LocalHook.GetProcAddress(VbeProvider.VbeRuntime.DllName, "rtcSendKeys"); + + InjectDelegate(new SendKeysDelegate(SendKeysCallback), processAddress); } public override bool PassThrough { - get { return false; } + get => false; // ReSharper disable once ValueParameterNotUsed set { From 0eb245db401149dfc71f9bd313d010d25029b3d8 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Wed, 31 Oct 2018 00:16:58 +0100 Subject: [PATCH 025/107] Make the quickfixes use the IRewritesession (DOES NOT COMPILE) The tests are still pending; that is another undertaking. --- .../Inspections/Abstract/QuickFixBase.cs | 2 +- .../VariableRequiresSetAssignmentEvaluator.cs | 8 +- .../AccessSheetUsingCodeNameQuickFix.cs | 14 ++-- .../QuickFixes/AddStepOneQuickFix.cs | 25 +++---- .../ApplicationWorksheetFunctionQuickFix.cs | 13 +--- ...gnedByValParameterMakeLocalCopyQuickFix.cs | 18 ++--- .../QuickFixes/ChangeDimToPrivateQuickFix.cs | 13 +--- .../QuickFixes/ChangeIntegerToLongQuickFix.cs | 30 ++++---- .../ChangeProcedureToFunctionQuickFix.cs | 25 +++---- .../QuickFixes/ConvertToProcedureQuickFix.cs | 25 +++---- .../DeclareAsExplicitVariantQuickFix.cs | 13 +--- .../QuickFixes/EncapsulateFieldQuickFix.cs | 2 +- .../QuickFixes/IgnoreOnceQuickFix.cs | 6 +- .../IntroduceLocalVariableQuickFix.cs | 14 ++-- ...sMissingOnInappropriateArgumentQuickFix.cs | 14 ++-- .../MakeSingleLineParameterQuickFix.cs | 13 +--- .../MoveFieldCloserToUsageQuickFix.cs | 2 +- .../QuickFixes/OptionExplicitQuickFix.cs | 13 +--- .../PassParameterByReferenceQuickFix.cs | 13 +--- .../PassParameterByValueQuickFix.cs | 26 ++++--- .../QuickFixes/RemoveCommentQuickFix.cs | 13 +--- .../RemoveDuplicatedAnnotationQuickFix.cs | 20 ++--- .../RemoveEmptyElseBlockQuickFix.cs | 20 ++--- .../QuickFixes/RemoveEmptyIfBlockQuickFix.cs | 74 +++++++++++++------ .../RemoveExplicitByRefModifierQuickFix.cs | 22 +++--- ...=> RemoveExplicitCallStatementQuickFix.cs} | 15 ++-- .../RemoveExplicitLetStatementQuickFix.cs | 13 +--- .../QuickFixes/RemoveLocalErrorQuickFix.cs | 13 +--- .../RemoveOptionBaseStatementQuickFix.cs | 13 +--- .../QuickFixes/RemoveStepOneQuickFix.cs | 15 ++-- .../QuickFixes/RemoveStopKeywordQuickFix.cs | 13 +--- .../QuickFixes/RemoveTypeHintsQuickFix.cs | 15 ++-- .../RemoveUnassignedIdentifierQuickFix.cs | 13 +--- .../RemoveUnassignedVariableUsageQuickFix.cs | 14 +--- .../RemoveUnusedDeclarationQuickFix.cs | 13 +--- .../RemoveUnusedParameterQuickFix.cs | 2 +- .../QuickFixes/RenameDeclarationQuickFix.cs | 2 +- ...laceEmptyStringLiteralStatementQuickFix.cs | 13 +--- .../ReplaceGlobalModifierQuickFix.cs | 13 +--- ...eIfElseWithConditionalStatementQuickFix.cs | 14 +--- .../ReplaceObsoleteCommentMarkerQuickFix.cs | 13 +--- .../ReplaceObsoleteErrorStatementQuickFix.cs | 13 +--- .../RestoreErrorHandlingQuickFix.cs | 14 ++-- .../SetExplicitVariantReturnTypeQuickFix.cs | 13 +--- .../SpecifyExplicitByRefModifierQuickFix.cs | 22 +++--- .../SpecifyExplicitPublicModifierQuickFix.cs | 13 +--- .../SplitMultipleDeclarationsQuickFix.cs | 13 +--- .../UntypedFunctionUsageQuickFix.cs | 13 +--- ...seSetKeywordForObjectAssignmentQuickFix.cs | 13 +--- .../QuickFixes/WriteOnlyPropertyQuickFix.cs | 15 ++-- .../Inspections/Abstract/IQuickFix.cs | 2 +- .../Rewriter/AttributesRewriteSession.cs | 4 +- ...emoveExplicitCallStatementQuickFixTests.cs | 2 +- 53 files changed, 312 insertions(+), 457 deletions(-) rename Rubberduck.CodeAnalysis/QuickFixes/{RemoveExplicitCallStatmentQuickFix.cs => RemoveExplicitCallStatementQuickFix.cs} (74%) diff --git a/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs b/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs index 3c6cfad8e1..b4f13d3c09 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Abstract/QuickFixBase.cs @@ -42,7 +42,7 @@ public void RemoveInspections(params Type[] inspections) public virtual CodeKind TargetCodeKind => CodeKind.CodePaneCode; - public abstract void Fix(IInspectionResult result, IRewriteSession rewriteSession = null); + public abstract void Fix(IInspectionResult result, IRewriteSession rewriteSession); public abstract string Description(IInspectionResult result); public abstract bool CanFixInProcedure { get; } diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/VariableRequiresSetAssignmentEvaluator.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/VariableRequiresSetAssignmentEvaluator.cs index 9f4d01922e..7e000bbf67 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Concrete/VariableRequiresSetAssignmentEvaluator.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/VariableRequiresSetAssignmentEvaluator.cs @@ -13,8 +13,8 @@ public static class VariableRequiresSetAssignmentEvaluator /// Determines whether the 'Set' keyword is required (whether it's present or not) for the specified identifier reference. /// /// The identifier reference to analyze - /// The parser state - public static bool RequiresSetAssignment(IdentifierReference reference, RubberduckParserState state) + /// The parser state + public static bool RequiresSetAssignment(IdentifierReference reference, IDeclarationFinderProvider declarationFinderProvider) { if (!reference.IsAssignment) { @@ -89,7 +89,7 @@ public static bool RequiresSetAssignment(IdentifierReference reference, Rubberdu // todo resolve expression return type - var memberRefs = state.DeclarationFinder.IdentifierReferences(reference.ParentScoping.QualifiedName); + var memberRefs = declarationFinderProvider.DeclarationFinder.IdentifierReferences(reference.ParentScoping.QualifiedName); var lastRef = memberRefs.LastOrDefault(r => !Equals(r, reference) && r.Context.GetAncestor() == letStmtContext); if (lastRef?.Declaration.AsTypeDeclaration?.DeclarationType.HasFlag(DeclarationType.ClassModule) ?? false) { @@ -104,7 +104,7 @@ public static bool RequiresSetAssignment(IdentifierReference reference, Rubberdu // is the reference referring to something else in scope that's a object? var project = Declaration.GetProjectParent(reference.ParentScoping); var module = Declaration.GetModuleParent(reference.ParentScoping); - return state.DeclarationFinder.MatchName(expression.GetText().ToLowerInvariant()) + return declarationFinderProvider.DeclarationFinder.MatchName(expression.GetText().ToLowerInvariant()) .Any(decl => (decl.DeclarationType.HasFlag(DeclarationType.ClassModule) || Tokens.Object.Equals(decl.AsTypeName)) && AccessibilityCheck.IsAccessible(project, module, reference.ParentScoping, decl)); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs index 0669973444..ff8b7fdb8e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AccessSheetUsingCodeNameQuickFix.cs @@ -11,21 +11,21 @@ namespace Rubberduck.Inspections.QuickFixes { - public class AccessSheetUsingCodeNameQuickFix : QuickFixBase + public sealed class AccessSheetUsingCodeNameQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; + private readonly IDeclarationFinderProvider _declarationFinderProvider; - public AccessSheetUsingCodeNameQuickFix(RubberduckParserState state) + public AccessSheetUsingCodeNameQuickFix(IDeclarationFinderProvider declarationFinderProvider) : base(typeof(SheetAccessedUsingStringInspection)) { - _state = state; + _declarationFinderProvider = declarationFinderProvider; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var referenceResult = (IdentifierReferenceInspectionResult)result; - var rewriter = _state.GetRewriter(referenceResult.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(referenceResult.QualifiedName); var setStatement = referenceResult.Context.GetAncestor(); if (setStatement == null) @@ -43,7 +43,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio // Sheet assigned to variable var sheetVariableName = setStatement.lExpression().GetText(); - var sheetDeclaration = _state.DeclarationFinder.MatchName(sheetVariableName) + var sheetDeclaration = _declarationFinderProvider.DeclarationFinder.MatchName(sheetVariableName) .First(declaration => { var moduleBodyElement = declaration.Context.GetAncestor(); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs index a077e3b2b4..1eb99baf18 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AddStepOneQuickFix.cs @@ -2,21 +2,16 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; using System; using static Rubberduck.Parsing.Grammar.VBAParser; namespace Rubberduck.Inspections.QuickFixes { - public class AddStepOneQuickFix : QuickFixBase + public sealed class AddStepOneQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public AddStepOneQuickFix(RubberduckParserState state) + public AddStepOneQuickFix() : base(typeof(StepIsNotSpecifiedInspection)) - { - _state = state; - } + {} public override bool CanFixInProcedure => true; @@ -29,20 +24,20 @@ public override string Description(IInspectionResult result) return Resources.Inspections.QuickFixes.AddStepOneQuickFix; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - IExecutableModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); - ForNextStmtContext context = result.Context as ForNextStmtContext; + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); + var context = result.Context as ForNextStmtContext; - int toExpressionEnd = this.GetToExpressionEnd(context); + var toExpressionEnd = GetToExpressionEnd(context); rewriter.InsertAfter(toExpressionEnd, " Step 1"); } - private int GetToExpressionEnd(ForNextStmtContext context) + private static int GetToExpressionEnd(ForNextStmtContext context) { - int toNodeIndex = context.TO().Symbol.TokenIndex; + var toNodeIndex = context.TO().Symbol.TokenIndex; - foreach(ExpressionContext expressionChild in context.expression()) + foreach(var expressionChild in context.expression()) { if (expressionChild.Stop.TokenIndex > toNodeIndex) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ApplicationWorksheetFunctionQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ApplicationWorksheetFunctionQuickFix.cs index 9a0c10333d..d17b552f66 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ApplicationWorksheetFunctionQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ApplicationWorksheetFunctionQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ApplicationWorksheetFunctionQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ApplicationWorksheetFunctionQuickFix(RubberduckParserState state) + public ApplicationWorksheetFunctionQuickFix() : base(typeof(ApplicationWorksheetFunctionInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.InsertBefore(result.Context.Start.TokenIndex, "WorksheetFunction."); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs index b387dff513..bb4a3ed35d 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFix.cs @@ -19,17 +19,17 @@ namespace Rubberduck.Inspections.QuickFixes public sealed class AssignedByValParameterMakeLocalCopyQuickFix : QuickFixBase { private readonly IAssignedByValParameterQuickFixDialogFactory _dialogFactory; - private readonly RubberduckParserState _parserState; + private readonly IDeclarationFinderProvider _declarationFinderProvider; private Declaration _quickFixTarget; - public AssignedByValParameterMakeLocalCopyQuickFix(RubberduckParserState state, IAssignedByValParameterQuickFixDialogFactory dialogFactory) + public AssignedByValParameterMakeLocalCopyQuickFix(IDeclarationFinderProvider declarationFinderProvider, IAssignedByValParameterQuickFixDialogFactory dialogFactory) : base(typeof(AssignedByValParameterInspection)) { _dialogFactory = dialogFactory; - _parserState = state; + _declarationFinderProvider = declarationFinderProvider; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { Debug.Assert(result.Target.Context.Parent is VBAParser.ArgListContext); Debug.Assert(null != ((ParserRuleContext)result.Target.Context.Parent.Parent).GetChild()); @@ -42,7 +42,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio return; } - var rewriter = _parserState.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); ReplaceAssignedByValParameterReferences(rewriter, result.Target, localIdentifier); InsertLocalVariableDeclarationAndAssignment(rewriter, result.Target, localIdentifier); } @@ -76,7 +76,7 @@ private string PromptForLocalVariableName(Declaration target) } private bool IsNameCollision(string newName) - => _parserState.DeclarationFinder.FindNewDeclarationNameConflicts(newName, _quickFixTarget).Any(); + => _declarationFinderProvider.DeclarationFinder.FindNewDeclarationNameConflicts(newName, _quickFixTarget).Any(); private string GetDefaultLocalIdentifier(Declaration target) { @@ -103,7 +103,7 @@ private bool IsValidVariableName(string variableName) && !IsNameCollision(variableName); } - private void ReplaceAssignedByValParameterReferences(IExecutableModuleRewriter rewriter, Declaration target, string localIdentifier) + private void ReplaceAssignedByValParameterReferences(IModuleRewriter rewriter, Declaration target, string localIdentifier) { foreach (var identifierReference in target.References) { @@ -111,12 +111,12 @@ private void ReplaceAssignedByValParameterReferences(IExecutableModuleRewriter r } } - private void InsertLocalVariableDeclarationAndAssignment(IExecutableModuleRewriter rewriter, Declaration target, string localIdentifier) + private void InsertLocalVariableDeclarationAndAssignment(IModuleRewriter rewriter, Declaration target, string localIdentifier) { var localVariableDeclaration = $"{Tokens.Dim} {localIdentifier} {Tokens.As} {target.AsTypeName}"; var requiresAssignmentUsingSet = - target.References.Any(refItem => VariableRequiresSetAssignmentEvaluator.RequiresSetAssignment(refItem, _parserState)); + target.References.Any(refItem => VariableRequiresSetAssignmentEvaluator.RequiresSetAssignment(refItem, _declarationFinderProvider)); var localVariableAssignment = $"{(requiresAssignmentUsingSet ? $"{Tokens.Set} " : string.Empty)}{localIdentifier} = {target.IdentifierName}"; diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs index 0a6722630b..1d9f7e4e2b 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ChangeDimToPrivateQuickFix.cs @@ -3,23 +3,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ChangeDimToPrivateQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ChangeDimToPrivateQuickFix(RubberduckParserState state) + public ChangeDimToPrivateQuickFix() : base(typeof(ModuleScopeDimKeywordInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.VariableStmtContext)result.Context.Parent.Parent; rewriter.Replace(context.DIM(), Tokens.Private); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs index b537da2d14..5bca967550 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ChangeIntegerToLongQuickFix.cs @@ -13,19 +13,19 @@ namespace Rubberduck.Inspections.QuickFixes { - public class ChangeIntegerToLongQuickFix : QuickFixBase + public sealed class ChangeIntegerToLongQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; + private readonly IDeclarationFinderProvider _declarationFinderProvider; - public ChangeIntegerToLongQuickFix(RubberduckParserState state) + public ChangeIntegerToLongQuickFix(IDeclarationFinderProvider declarationFinderProvider) : base(typeof(IntegerDataTypeInspection)) { - _state = state; + _declarationFinderProvider = declarationFinderProvider; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); if (result.Target.HasTypeHint) { @@ -66,7 +66,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio } } - var interfaceMembers = _state.DeclarationFinder.FindAllInterfaceMembers().ToArray(); + var interfaceMembers = _declarationFinderProvider.DeclarationFinder.FindAllInterfaceMembers().ToArray(); ParserRuleContext matchingInterfaceMemberContext; @@ -80,11 +80,11 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio var interfaceParameterIndex = GetParameterIndex((VBAParser.ArgContext)result.Context); var implementationMembers = - _state.DeclarationFinder.FindInterfaceImplementationMembers(interfaceMembers.First( + _declarationFinderProvider.DeclarationFinder.FindInterfaceImplementationMembers(interfaceMembers.First( member => member.Context == matchingInterfaceMemberContext)).ToHashSet(); var parameterDeclarations = - _state.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) + _declarationFinderProvider.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) .Where(p => implementationMembers.Contains(p.ParentDeclaration)) .Cast() .ToArray(); @@ -96,7 +96,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio if (parameterIndex == interfaceParameterIndex) { - var parameterRewriter = _state.GetRewriter(parameter); + var parameterRewriter = rewriteSession.CheckOutModuleRewriter(parameter.QualifiedModuleName); if (parameter.HasTypeHint) { @@ -116,14 +116,14 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio if (matchingInterfaceMemberContext != null) { var functionDeclarations = - _state.DeclarationFinder.FindInterfaceImplementationMembers( + _declarationFinderProvider.DeclarationFinder.FindInterfaceImplementationMembers( interfaceMembers.First(member => member.Context == matchingInterfaceMemberContext)) .Cast() .ToHashSet(); foreach (var function in functionDeclarations) { - var functionRewriter = _state.GetRewriter(function); + var functionRewriter = rewriteSession.CheckOutModuleRewriter(function.QualifiedModuleName); if (function.HasTypeHint) { @@ -143,14 +143,14 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio if (matchingInterfaceMemberContext != null) { var propertyGetDeclarations = - _state.DeclarationFinder.FindInterfaceImplementationMembers( + _declarationFinderProvider.DeclarationFinder.FindInterfaceImplementationMembers( interfaceMembers.First(member => member.Context == matchingInterfaceMemberContext)) .Cast() .ToHashSet(); foreach (var propertyGet in propertyGetDeclarations) { - var propertyGetRewriter = _state.GetRewriter(propertyGet); + var propertyGetRewriter = rewriteSession.CheckOutModuleRewriter(propertyGet.QualifiedModuleName); if (propertyGet.HasTypeHint) { @@ -178,7 +178,7 @@ private static int GetParameterIndex(VBAParser.ArgContext context) return Array.IndexOf(((VBAParser.ArgListContext)context.Parent).arg().ToArray(), context); } - private static void ReplaceTypeHint(RuleContext context, IExecutableModuleRewriter rewriter) + private static void ReplaceTypeHint(RuleContext context, IModuleRewriter rewriter) { var typeHintContext = ((ParserRuleContext)context).GetDescendent(); rewriter.Replace(typeHintContext, "&"); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs index fcfd26ea76..2103a637e4 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ChangeProcedureToFunctionQuickFix.cs @@ -7,41 +7,36 @@ using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ChangeProcedureToFunctionQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ChangeProcedureToFunctionQuickFix(RubberduckParserState state) + public ChangeProcedureToFunctionQuickFix() : base(typeof(ProcedureCanBeWrittenAsFunctionInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var parameterizedDeclaration = (IParameterizedDeclaration) result.Target; - var arg = parameterizedDeclaration.Parameters.Cast().First(p => p.IsByRef || p.IsImplicitByRef); + var arg = parameterizedDeclaration.Parameters.First(p => p.IsByRef || p.IsImplicitByRef); var argIndex = parameterizedDeclaration.Parameters.ToList().IndexOf(arg); - UpdateSignature(result.Target, arg); + UpdateSignature(result.Target, arg, rewriteSession); foreach (var reference in result.Target.References) { - UpdateCall(reference, argIndex); + UpdateCall(reference, argIndex, rewriteSession); } } public override string Description(IInspectionResult result) => Resources.Inspections.QuickFixes.ProcedureShouldBeFunctionInspectionQuickFix; - private void UpdateSignature(Declaration target, ParameterDeclaration arg) + private void UpdateSignature(Declaration target, ParameterDeclaration arg, IRewriteSession rewriteSession) { var subStmt = (VBAParser.SubStmtContext) target.Context; var argContext = (VBAParser.ArgContext)arg.Context; - var rewriter = _state.GetRewriter(target); + var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName); rewriter.Replace(subStmt.SUB(), Tokens.Function); rewriter.Replace(subStmt.END_SUB(), "End Function"); @@ -61,9 +56,9 @@ private void UpdateSignature(Declaration target, ParameterDeclaration arg) rewriter.InsertBefore(subStmt.END_SUB().Symbol.TokenIndex, returnStmt); } - private void UpdateCall(IdentifierReference reference, int argIndex) + private void UpdateCall(IdentifierReference reference, int argIndex, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(reference.QualifiedModuleName); + var rewriter = rewriteSession.CheckOutModuleRewriter(reference.QualifiedModuleName); var callStmtContext = reference.Context.GetAncestor(); var argListContext = callStmtContext.GetChild(); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs index afd57a0db8..bea1f27609 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ConvertToProcedureQuickFix.cs @@ -8,37 +8,32 @@ using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ConvertToProcedureQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ConvertToProcedureQuickFix(RubberduckParserState state) + public ConvertToProcedureQuickFix() : base(typeof(NonReturningFunctionInspection), typeof(FunctionReturnValueNotUsedInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); + switch (result.Context) { case VBAParser.FunctionStmtContext functionContext: - ConvertFunction(result, functionContext); + ConvertFunction(result, functionContext, rewriter); break; case VBAParser.PropertyGetStmtContext propertyGetContext: - ConvertPropertyGet(result, propertyGetContext); + ConvertPropertyGet(result, propertyGetContext, rewriter); break; } } - private void ConvertFunction(IInspectionResult result, VBAParser.FunctionStmtContext functionContext) + private void ConvertFunction(IInspectionResult result, VBAParser.FunctionStmtContext functionContext, IModuleRewriter rewriter) { - var rewriter = _state.GetRewriter(result.Target); - var asTypeContext = functionContext.GetChild(); if (asTypeContext != null) { @@ -60,10 +55,8 @@ private void ConvertFunction(IInspectionResult result, VBAParser.FunctionStmtCon } } - private void ConvertPropertyGet(IInspectionResult result, VBAParser.PropertyGetStmtContext propertyGetContext) + private void ConvertPropertyGet(IInspectionResult result, VBAParser.PropertyGetStmtContext propertyGetContext, IModuleRewriter rewriter) { - var rewriter = _state.GetRewriter(result.Target); - var asTypeContext = propertyGetContext.GetChild(); if (asTypeContext != null) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs index e0bc881be3..fa4beeaa94 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/DeclareAsExplicitVariantQuickFix.cs @@ -4,23 +4,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class DeclareAsExplicitVariantQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public DeclareAsExplicitVariantQuickFix(RubberduckParserState state) + public DeclareAsExplicitVariantQuickFix() : base(typeof(VariableTypeNotDeclaredInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); ParserRuleContext identifierNode = result.Context is VBAParser.VariableSubStmtContext || result.Context is VBAParser.ConstSubStmtContext diff --git a/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs index 919de89b2a..59c6024d8b 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs @@ -24,7 +24,7 @@ public EncapsulateFieldQuickFix(IVBE vbe, RubberduckParserState state, IIndenter _indenter = indenter; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { using (var view = new EncapsulateFieldDialog(new EncapsulateFieldViewModel(_state, _indenter))) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs index ce7052146a..a5aa066e0b 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IgnoreOnceQuickFix.cs @@ -27,12 +27,12 @@ public IgnoreOnceQuickFix(RubberduckParserState state, IEnumerable public override bool CanFixInModule => false; public override bool CanFixInProject => false; - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var annotationText = $"'@Ignore {result.Inspection.AnnotationName}"; int annotationLine; - string codeLine; + //TODO: Make this use the parse tree instead of the code module. var component = _state.ProjectsProvider.Component(result.QualifiedSelection.QualifiedName); using (var module = component.CodeModule) { @@ -54,7 +54,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio var commentContext = listener.Contexts.LastOrDefault(i => i.Stop.TokenIndex <= result.Context.Start.TokenIndex); var commented = commentContext?.Stop.Line + 1 == annotationLine; - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); if (commented) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs index 847e9b30fd..a4fca60ca3 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IntroduceLocalVariableQuickFix.cs @@ -6,30 +6,26 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class IntroduceLocalVariableQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public IntroduceLocalVariableQuickFix(RubberduckParserState state) + public IntroduceLocalVariableQuickFix() : base(typeof(UndeclaredVariableInspection)) - { - _state = state; - } + {} public override bool CanFixInProcedure => true; public override bool CanFixInModule => true; public override bool CanFixInProject => true; - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var identifierContext = result.Target.Context; var enclosingStatmentContext = identifierContext.GetAncestor(); var instruction = IdentifierDeclarationText(result.Target.IdentifierName, EndOfStatementText(enclosingStatmentContext), FrontPadding(enclosingStatmentContext)); - _state.GetRewriter(result.Target).InsertBefore(enclosingStatmentContext.Start.TokenIndex, instruction); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); + rewriter.InsertBefore(enclosingStatmentContext.Start.TokenIndex, instruction); } private string EndOfStatementText(VBAParser.BlockStmtContext context) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs index 65fb994536..8a69d25d85 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/IsMissingOnInappropriateArgumentQuickFix.cs @@ -12,17 +12,17 @@ namespace Rubberduck.Inspections.QuickFixes { - public class IsMissingOnInappropriateArgumentQuickFix : QuickFixBase + public sealed class IsMissingOnInappropriateArgumentQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; + private readonly IDeclarationFinderProvider _declarationFinderProvider; - public IsMissingOnInappropriateArgumentQuickFix(RubberduckParserState state) + public IsMissingOnInappropriateArgumentQuickFix(IDeclarationFinderProvider declarationFinderProvider) : base(typeof(IsMissingOnInappropriateArgumentInspection)) { - _state = state; + _declarationFinderProvider = declarationFinderProvider; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { if (!(result.Properties is ParameterDeclaration parameter)) { @@ -31,7 +31,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio return; } - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); if (!result.Context.TryGetAncestor(out var context)) { Logger.Trace("IsMissingOnInappropriateArgumentQuickFix could not locate containing LExprContext for replacement."); @@ -109,7 +109,7 @@ private string UninitializedComparisonForParameter(ParameterDeclaration paramete case DeclarationType.ClassModule: return $"{parameter.IdentifierName} Is {Tokens.Nothing}"; case DeclarationType.Enumeration: - var members = _state.DeclarationFinder.AllDeclarations.OfType() + var members = _declarationFinderProvider.DeclarationFinder.AllDeclarations.OfType() .FirstOrDefault(decl => ReferenceEquals(decl.ParentDeclaration, parameter.AsTypeDeclaration) && decl.Expression.Equals("0")); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs index 0c0e97956e..a3c79a807e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/MakeSingleLineParameterQuickFix.cs @@ -2,24 +2,19 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; using Rubberduck.Parsing.VBA.Extensions; namespace Rubberduck.Inspections.QuickFixes { public sealed class MakeSingleLineParameterQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public MakeSingleLineParameterQuickFix(RubberduckParserState state) + public MakeSingleLineParameterQuickFix() : base(typeof(MultilineParameterInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var parameter = result.Context.GetText() .Replace("_", "") diff --git a/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs index 7ac6c44185..e3c3528c98 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs @@ -24,7 +24,7 @@ public MoveFieldCloserToUsageQuickFix(IVBE vbe, RubberduckParserState state, IMe _messageBox = messageBox; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var refactoring = new MoveCloserToUsageRefactoring(_vbe, _state, _messageBox); refactoring.Refactor(result.Target); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs index 49135709cc..f5f729013b 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/OptionExplicitQuickFix.cs @@ -4,23 +4,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class OptionExplicitQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public OptionExplicitQuickFix(RubberduckParserState state) + public OptionExplicitQuickFix() : base(typeof(OptionExplicitInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.InsertBefore(0, Tokens.Option + ' ' + Tokens.Explicit + Environment.NewLine + Environment.NewLine); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs index 8be2a9860f..f4debba3f2 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByReferenceQuickFix.cs @@ -3,23 +3,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class PassParameterByReferenceQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public PassParameterByReferenceQuickFix(RubberduckParserState state) + public PassParameterByReferenceQuickFix() : base(typeof(AssignedByValParameterInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); var token = ((VBAParser.ArgContext)result.Target.Context).BYVAL().Symbol; rewriter.Replace(token, Tokens.ByRef); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs index 077a6b7a30..374299fd16 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/PassParameterByValueQuickFix.cs @@ -13,6 +13,7 @@ namespace Rubberduck.Inspections.QuickFixes { public sealed class PassParameterByValueQuickFix : QuickFixBase { + //TODO: Change this to IDeclarationFinderProvider once the FIXME below is handled. private readonly RubberduckParserState _state; public PassParameterByValueQuickFix(RubberduckParserState state) @@ -21,26 +22,26 @@ public PassParameterByValueQuickFix(RubberduckParserState state) _state = state; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { if (result.Target.ParentDeclaration.DeclarationType == DeclarationType.Event || _state.DeclarationFinder.FindAllInterfaceMembers().Contains(result.Target.ParentDeclaration)) { - FixMethods(result.Target); + FixMethods(result.Target, rewriteSession); } else { - FixMethod((VBAParser.ArgContext)result.Target.Context, result.QualifiedSelection); + FixMethod((VBAParser.ArgContext)result.Target.Context, result.QualifiedSelection, rewriteSession); } } public override string Description(IInspectionResult result) => Resources.Inspections.QuickFixes.PassParameterByValueQuickFix; - private void FixMethods(Declaration target) + private void FixMethods(Declaration target, IRewriteSession rewriteSession) { var declarationParameters = - _state.AllUserDeclarations.Where(declaration => declaration.DeclarationType == DeclarationType.Parameter && - Equals(declaration.ParentDeclaration, target.ParentDeclaration)) + _state.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) + .Where(declaration => Equals(declaration.ParentDeclaration, target.ParentDeclaration)) .OrderBy(o => o.Selection.StartLine) .ThenBy(t => t.Selection.StartColumn) .ToList(); @@ -51,6 +52,7 @@ private void FixMethods(Declaration target) return; // should only happen if the parse results are stale; prevents a crash in that case } + //FIXME: Make this use the DeclarationFinder. var members = target.ParentDeclaration.DeclarationType == DeclarationType.Event ? _state.AllUserDeclarations.FindHandlersForEvent(target.ParentDeclaration) .Select(s => s.Item2) @@ -60,23 +62,23 @@ private void FixMethods(Declaration target) foreach (var member in members) { var parameters = - _state.AllUserDeclarations.Where(declaration => declaration.DeclarationType == DeclarationType.Parameter && - Equals(declaration.ParentDeclaration, member)) + _state.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) + .Where(declaration => Equals(declaration.ParentDeclaration, member)) .OrderBy(o => o.Selection.StartLine) .ThenBy(t => t.Selection.StartColumn) .ToList(); FixMethod((VBAParser.ArgContext)parameters[parameterIndex].Context, - parameters[parameterIndex].QualifiedSelection); + parameters[parameterIndex].QualifiedSelection, rewriteSession); } FixMethod((VBAParser.ArgContext)declarationParameters[parameterIndex].Context, - declarationParameters[parameterIndex].QualifiedSelection); + declarationParameters[parameterIndex].QualifiedSelection, rewriteSession); } - private void FixMethod(VBAParser.ArgContext context, QualifiedSelection qualifiedSelection) + private void FixMethod(VBAParser.ArgContext context, QualifiedSelection qualifiedSelection, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(qualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(qualifiedSelection.QualifiedName); if (context.BYREF() != null) { rewriter.Replace(context.BYREF(), Tokens.ByVal); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs index 90fea1b043..e17409f5f0 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveCommentQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveCommentQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveCommentQuickFix(RubberduckParserState state) + public RemoveCommentQuickFix() : base(typeof(ObsoleteCommentSyntaxInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Remove(result.Context); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs index c0f62838d6..f2255c9058 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveDuplicatedAnnotationQuickFix.cs @@ -7,28 +7,24 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { - public class RemoveDuplicatedAnnotationQuickFix : QuickFixBase + public sealed class RemoveDuplicatedAnnotationQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveDuplicatedAnnotationQuickFix(RubberduckParserState state) + public RemoveDuplicatedAnnotationQuickFix() : base(typeof(DuplicatedAnnotationInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var duplicateAnnotations = result.Target.Annotations .Where(annotation => annotation.AnnotationType == result.Properties.AnnotationType) .OrderBy(annotation => annotation.Context.Start.StartIndex) - .Skip(1); + .Skip(1) + .ToList(); var duplicatesPerAnnotationList = duplicateAnnotations .Select(annotation => (VBAParser.AnnotationListContext) annotation.Context.Parent) @@ -64,7 +60,7 @@ public override string Description(IInspectionResult result) => public override bool CanFixInProject => true; private static void RemoveAnnotationMarker(VBAParser.AnnotationListContext annotationList, - IAnnotation annotation, IExecutableModuleRewriter rewriter) + IAnnotation annotation, IModuleRewriter rewriter) { var index = Array.IndexOf(annotationList.annotation(), annotation.Context); rewriter.Remove(annotationList.AT(index)); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs index bcb9ad9b8f..83ace83be6 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyElseBlockQuickFix.cs @@ -3,29 +3,23 @@ using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { - class RemoveEmptyElseBlockQuickFix : QuickFixBase + public sealed class RemoveEmptyElseBlockQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveEmptyElseBlockQuickFix(RubberduckParserState state) + public RemoveEmptyElseBlockQuickFix() : base(typeof(EmptyElseBlockInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); - //dynamic used since it's not known at run-time - UpdateContext((dynamic)result.Context, rewriter); + UpdateContext((VBAParser.ElseBlockContext)result.Context, rewriter); } - private void UpdateContext(VBAParser.ElseBlockContext context, IExecutableModuleRewriter rewriter) + private void UpdateContext(VBAParser.ElseBlockContext context, IModuleRewriter rewriter) { var elseBlock = context.block(); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs index 26bf7c9923..0b3cfa4da6 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveEmptyIfBlockQuickFix.cs @@ -7,28 +7,36 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { - internal sealed class RemoveEmptyIfBlockQuickFix : QuickFixBase + public sealed class RemoveEmptyIfBlockQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveEmptyIfBlockQuickFix(RubberduckParserState state) + public RemoveEmptyIfBlockQuickFix() : base(typeof(EmptyIfBlockInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); - - UpdateContext((dynamic)result.Context, rewriter); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); + + switch (result.Context) + { + case VBAParser.IfStmtContext ifContext: + UpdateContext(ifContext, rewriter); + break; + case VBAParser.IfWithEmptyThenContext ifWithEmtyThenContext: + UpdateContext(ifWithEmtyThenContext, rewriter); + break; + case VBAParser.ElseIfBlockContext elseIfBlockContext: + UpdateContext(elseIfBlockContext, rewriter); + break; + default: + throw new NotSupportedException(nameof(result.Context)); + } } - private void UpdateContext(VBAParser.IfStmtContext context, IExecutableModuleRewriter rewriter) + private void UpdateContext(VBAParser.IfStmtContext context, IModuleRewriter rewriter) { var elseBlock = context.elseBlock(); var elseIfBlock = context.elseIfBlock().FirstOrDefault(); @@ -55,7 +63,7 @@ private void UpdateContext(VBAParser.IfStmtContext context, IExecutableModuleRew } Debug.Assert(context.booleanExpression().children.Count == 1); - UpdateCondition((dynamic)context.booleanExpression().children[0], rewriter); + UpdateConditionDependingOnType((ParserRuleContext)context.booleanExpression().children[0], rewriter); } else { @@ -63,7 +71,7 @@ private void UpdateContext(VBAParser.IfStmtContext context, IExecutableModuleRew } } - private void UpdateContext(VBAParser.IfWithEmptyThenContext context, IExecutableModuleRewriter rewriter) + private void UpdateContext(VBAParser.IfWithEmptyThenContext context, IModuleRewriter rewriter) { var elseClause = context.singleLineElseClause(); if (context.singleLineElseClause().whiteSpace() != null) @@ -76,10 +84,10 @@ private void UpdateContext(VBAParser.IfWithEmptyThenContext context, IExecutable } Debug.Assert(context.booleanExpression().children.Count == 1); - UpdateCondition((dynamic)context.booleanExpression().children[0], rewriter); + UpdateConditionDependingOnType((ParserRuleContext)context.booleanExpression().children[0], rewriter); } - private void UpdateContext(VBAParser.ElseIfBlockContext context, IExecutableModuleRewriter rewriter) + private void UpdateContext(VBAParser.ElseIfBlockContext context, IModuleRewriter rewriter) { if (BlockHasDeclaration(context.block())) { @@ -89,7 +97,29 @@ private void UpdateContext(VBAParser.ElseIfBlockContext context, IExecutableModu rewriter.Remove(context); } - private void UpdateCondition(VBAParser.RelationalOpContext condition, IExecutableModuleRewriter rewriter) + private void UpdateConditionDependingOnType(ParserRuleContext context, IModuleRewriter rewriter) + { + switch (context) + { + case VBAParser.RelationalOpContext condition: + UpdateCondition(condition, rewriter); + break; + case VBAParser.LogicalNotOpContext condition: + UpdateCondition(condition, rewriter); + break; + case VBAParser.LogicalAndOpContext condition: + UpdateCondition(condition, rewriter); + break; + case VBAParser.LogicalOrOpContext condition: + UpdateCondition(condition, rewriter); + break; + default: + UpdateCondition(context, rewriter); + break; + } + } + + private void UpdateCondition(VBAParser.RelationalOpContext condition, IModuleRewriter rewriter) { if (condition.EQ() != null) { @@ -121,7 +151,7 @@ private void UpdateCondition(VBAParser.RelationalOpContext condition, IExecutabl } } - private void UpdateCondition(VBAParser.LogicalNotOpContext condition, IExecutableModuleRewriter rewriter) + private void UpdateCondition(VBAParser.LogicalNotOpContext condition, IModuleRewriter rewriter) { if (condition.whiteSpace() != null) { @@ -133,17 +163,17 @@ private void UpdateCondition(VBAParser.LogicalNotOpContext condition, IExecutabl } } - private void UpdateCondition(VBAParser.LogicalAndOpContext condition, IExecutableModuleRewriter rewriter) + private void UpdateCondition(VBAParser.LogicalAndOpContext condition, IModuleRewriter rewriter) { rewriter.Replace(condition.AND(), "Or"); } - private void UpdateCondition(VBAParser.LogicalOrOpContext condition, IExecutableModuleRewriter rewriter) + private void UpdateCondition(VBAParser.LogicalOrOpContext condition, IModuleRewriter rewriter) { rewriter.Replace(condition.OR(), "And"); } - private void UpdateCondition(ParserRuleContext condition, IExecutableModuleRewriter rewriter) + private void UpdateCondition(ParserRuleContext condition, IModuleRewriter rewriter) { if (condition.GetText().Contains(' ')) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs index 225582c16e..f82e3fd211 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitByRefModifierQuickFix.cs @@ -11,23 +11,23 @@ namespace Rubberduck.Inspections.QuickFixes { - public class RemoveExplicitByRefModifierQuickFix : QuickFixBase + public sealed class RemoveExplicitByRefModifierQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; + private readonly IDeclarationFinderProvider _declarationFinderProvider; - public RemoveExplicitByRefModifierQuickFix(RubberduckParserState state) + public RemoveExplicitByRefModifierQuickFix(IDeclarationFinderProvider declarationFinderProvider) : base(typeof(RedundantByRefModifierInspection)) { - _state = state; + _declarationFinderProvider = declarationFinderProvider; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var context = (VBAParser.ArgContext) result.Context; - RemoveByRefIdentifier(_state.GetRewriter(result.QualifiedSelection.QualifiedName), context); + RemoveByRefIdentifier(rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName), context); - var interfaceMembers = _state.DeclarationFinder.FindAllInterfaceMembers().ToArray(); + var interfaceMembers = _declarationFinderProvider.DeclarationFinder.FindAllInterfaceMembers().ToArray(); var matchingInterfaceMemberContext = interfaceMembers.Select(member => member.Context).FirstOrDefault(c => c == context.Parent.Parent); @@ -36,11 +36,11 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio var interfaceParameterIndex = GetParameterIndex(context); var implementationMembers = - _state.DeclarationFinder.FindInterfaceImplementationMembers(interfaceMembers.First( + _declarationFinderProvider.DeclarationFinder.FindInterfaceImplementationMembers(interfaceMembers.First( member => member.Context == matchingInterfaceMemberContext)).ToHashSet(); var parameters = - _state.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) + _declarationFinderProvider.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) .Where(p => implementationMembers.Contains(p.ParentDeclaration)) .Cast() .ToArray(); @@ -52,7 +52,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio if (parameterIndex == interfaceParameterIndex) { - RemoveByRefIdentifier(_state.GetRewriter(parameter), parameterContext); + RemoveByRefIdentifier(rewriteSession.CheckOutModuleRewriter(parameter.QualifiedModuleName), parameterContext); } } } @@ -69,7 +69,7 @@ private static int GetParameterIndex(VBAParser.ArgContext context) return Array.IndexOf(((VBAParser.ArgListContext)context.Parent).arg().ToArray(), context); } - private static void RemoveByRefIdentifier(IExecutableModuleRewriter rewriter, VBAParser.ArgContext context) + private static void RemoveByRefIdentifier(IModuleRewriter rewriter, VBAParser.ArgContext context) { if (context.BYREF() != null) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatmentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatementQuickFix.cs similarity index 74% rename from Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatmentQuickFix.cs rename to Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatementQuickFix.cs index 8aef5ff215..88601e6c97 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatmentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitCallStatementQuickFix.cs @@ -3,23 +3,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { - public sealed class RemoveExplicitCallStatmentQuickFix : QuickFixBase + public sealed class RemoveExplicitCallStatementQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveExplicitCallStatmentQuickFix(RubberduckParserState state) + public RemoveExplicitCallStatementQuickFix() : base(typeof(ObsoleteCallStatementInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.CallStmtContext)result.Context; rewriter.Remove(context.CALL()); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs index 4d617dabf2..286635fc54 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveExplicitLetStatementQuickFix.cs @@ -4,23 +4,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveExplicitLetStatementQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveExplicitLetStatementQuickFix(RubberduckParserState state) + public RemoveExplicitLetStatementQuickFix() : base(typeof(ObsoleteLetStatementInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.LetStmtContext) result.Context; rewriter.Remove(context.LET()); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs index 73c19cd37c..aedb0bbbe4 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveLocalErrorQuickFix.cs @@ -3,25 +3,20 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveLocalErrorQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveLocalErrorQuickFix(RubberduckParserState state) + public RemoveLocalErrorQuickFix() : base(typeof(OnLocalErrorInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var errorStmt = (VBAParser.OnErrorStmtContext)result.Context; - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(errorStmt.ON_LOCAL_ERROR(), Tokens.On + " " + Tokens.Error); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs index b946277096..a980f9d34c 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveOptionBaseStatementQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveOptionBaseStatementQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveOptionBaseStatementQuickFix(RubberduckParserState state) + public RemoveOptionBaseStatementQuickFix() : base(typeof(RedundantOptionInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Remove(result.Context); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs index 0a94043ddb..676f013f1e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStepOneQuickFix.cs @@ -2,19 +2,14 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { - public class RemoveStepOneQuickFix : QuickFixBase + public sealed class RemoveStepOneQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveStepOneQuickFix(RubberduckParserState state) + public RemoveStepOneQuickFix() : base(typeof(StepOneIsRedundantInspection)) - { - _state = state; - } + {} public override bool CanFixInProcedure => true; @@ -24,9 +19,9 @@ public RemoveStepOneQuickFix(RubberduckParserState state) public override string Description(IInspectionResult result) => Resources.Inspections.QuickFixes.RemoveStepOneQuickFix; - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - IExecutableModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = result.Context; rewriter.Remove(context); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs index bb61ae64fd..18929a6c69 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveStopKeywordQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveStopKeywordQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveStopKeywordQuickFix(RubberduckParserState state) + public RemoveStopKeywordQuickFix() : base(typeof(StopKeywordInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Remove(result.Context); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs index ddaa597a4f..c1ab54b6cf 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveTypeHintsQuickFix.cs @@ -5,25 +5,20 @@ using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveTypeHintsQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveTypeHintsQuickFix(RubberduckParserState state) + public RemoveTypeHintsQuickFix() : base(typeof(ObsoleteTypeHintInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { if (!string.IsNullOrWhiteSpace(result.Target.TypeHint)) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); var typeHintContext = result.Context.GetDescendent(); rewriter.Remove(typeHintContext); @@ -56,11 +51,11 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio foreach (var reference in result.Target.References) { - var rewriter = _state.GetRewriter(reference.QualifiedModuleName); var context = reference.Context.GetDescendent(); if (context != null) { + var rewriter = rewriteSession.CheckOutModuleRewriter(reference.QualifiedModuleName); rewriter.Remove(context); } } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs index 4d314052ef..e2c0ab47fb 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedIdentifierQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveUnassignedIdentifierQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveUnassignedIdentifierQuickFix(RubberduckParserState state) + public RemoveUnassignedIdentifierQuickFix() : base(typeof(VariableNotAssignedInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); rewriter.Remove(result.Target); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs index d4d3d08ccf..20d23aea67 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnassignedVariableUsageQuickFix.cs @@ -5,24 +5,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.Symbols; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class RemoveUnassignedVariableUsageQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveUnassignedVariableUsageQuickFix(RubberduckParserState state) + public RemoveUnassignedVariableUsageQuickFix() : base(typeof(UnassignedVariableUsageInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var assignmentContext = result.Context.GetAncestor() ?? (ParserRuleContext)result.Context.GetAncestor(); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs index 0ae3f345f9..515bf8d2ac 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedDeclarationQuickFix.cs @@ -2,7 +2,6 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { @@ -11,17 +10,13 @@ namespace Rubberduck.Inspections.QuickFixes /// public sealed class RemoveUnusedDeclarationQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public RemoveUnusedDeclarationQuickFix(RubberduckParserState state) + public RemoveUnusedDeclarationQuickFix() : base(typeof(ConstantNotUsedInspection), typeof(ProcedureNotUsedInspection), typeof(VariableNotUsedInspection), typeof(LineLabelNotUsedInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); rewriter.Remove(result.Target); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs index 0bc2aef419..04128d2407 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs @@ -24,7 +24,7 @@ public RemoveUnusedParameterQuickFix(IVBE vbe, RubberduckParserState state, IMes _messageBox = messageBox; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { using (var dialog = new RemoveParametersDialog(new RemoveParametersViewModel(_state))) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs index 75d0ef30ae..877bd29186 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs @@ -26,7 +26,7 @@ public RenameDeclarationQuickFix(IVBE vbe, RubberduckParserState state, IMessage _messageBox = messageBox; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { using (var view = new RenameDialog(new RenameViewModel(_state))) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs index a2284ebb23..27bfec7e25 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ReplaceEmptyStringLiteralStatementQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ReplaceEmptyStringLiteralStatementQuickFix(RubberduckParserState state) + public ReplaceEmptyStringLiteralStatementQuickFix() : base(typeof(EmptyStringLiteralInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(result.Context, "vbNullString"); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs index c99e7e1670..0c31e2fc91 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceGlobalModifierQuickFix.cs @@ -5,23 +5,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ReplaceGlobalModifierQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ReplaceGlobalModifierQuickFix(RubberduckParserState state) + public ReplaceGlobalModifierQuickFix() : base(typeof(ObsoleteGlobalInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); rewriter.Replace(((ParserRuleContext)result.Context.Parent.Parent).GetDescendent(), Tokens.Public); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs index 9e5180b67e..3020fc05bd 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFix.cs @@ -4,22 +4,16 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.Symbols; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ReplaceIfElseWithConditionalStatementQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ReplaceIfElseWithConditionalStatementQuickFix(RubberduckParserState state) + public ReplaceIfElseWithConditionalStatementQuickFix() : base(typeof(BooleanAssignedInIfElseInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var ifContext = (VBAParser.IfStmtContext) result.Context; var letStmt = ifContext.block().GetDescendent(); @@ -31,7 +25,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio conditional = $"Not ({conditional})"; } - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(result.Context, $"{letStmt.lExpression().GetText()} = {conditional}"); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs index 56b173af26..cc9129aef3 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteCommentMarkerQuickFix.cs @@ -3,23 +3,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ReplaceObsoleteCommentMarkerQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ReplaceObsoleteCommentMarkerQuickFix(RubberduckParserState state) + public ReplaceObsoleteCommentMarkerQuickFix() : base(typeof(ObsoleteCommentSyntaxInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.RemCommentContext) result.Context; rewriter.Replace(context.REM(), "'"); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs index 36134df642..35364228a8 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/ReplaceObsoleteErrorStatementQuickFix.cs @@ -3,23 +3,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class ReplaceObsoleteErrorStatementQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public ReplaceObsoleteErrorStatementQuickFix(RubberduckParserState state) + public ReplaceObsoleteErrorStatementQuickFix() : base(typeof(ObsoleteErrorSyntaxInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.ErrorStmtContext) result.Context; rewriter.Replace(context.ERROR(), "Err.Raise"); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs index 73cb76157e..b96dc94f0e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RestoreErrorHandlingQuickFix.cs @@ -6,22 +6,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { - public class RestoreErrorHandlingQuickFix : QuickFixBase + public sealed class RestoreErrorHandlingQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; private const string LabelPrefix = "ErrorHandler"; - public RestoreErrorHandlingQuickFix(RubberduckParserState state) + public RestoreErrorHandlingQuickFix() : base(typeof(UnhandledOnErrorResumeNextInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var exitStatement = "Exit "; VBAParser.BlockContext block; @@ -53,7 +49,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio block = bodyElementContext.subStmt().block(); } - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.OnErrorStmtContext)result.Context; var labels = bodyElementContext.GetDescendents().ToArray(); var maximumExistingLabelIndex = GetMaximumExistingLabelIndex(labels); diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs index 5e046355b8..06c5d27bed 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SetExplicitVariantReturnTypeQuickFix.cs @@ -4,23 +4,18 @@ using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class SetExplicitVariantReturnTypeQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public SetExplicitVariantReturnTypeQuickFix(RubberduckParserState state) + public SetExplicitVariantReturnTypeQuickFix() :base(typeof(ImplicitVariantReturnTypeInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); const string asTypeClause = " As Variant"; switch (result.Target.DeclarationType) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs index 39d861bee0..c6d18d0484 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitByRefModifierQuickFix.cs @@ -11,23 +11,23 @@ namespace Rubberduck.Inspections.QuickFixes { - public class SpecifyExplicitByRefModifierQuickFix : QuickFixBase + public sealed class SpecifyExplicitByRefModifierQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; + private readonly IDeclarationFinderProvider _declarationFinderProvider; - public SpecifyExplicitByRefModifierQuickFix(RubberduckParserState state) + public SpecifyExplicitByRefModifierQuickFix(IDeclarationFinderProvider declarationFinderProvider) : base(typeof(ImplicitByRefModifierInspection)) { - _state = state; + _declarationFinderProvider = declarationFinderProvider; } - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var context = (VBAParser.ArgContext)result.Context; - AddByRefIdentifier(_state.GetRewriter(result.QualifiedSelection.QualifiedName), context); + AddByRefIdentifier(rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName), context); - var interfaceMembers = _state.DeclarationFinder.FindAllInterfaceMembers().ToArray(); + var interfaceMembers = _declarationFinderProvider.DeclarationFinder.FindAllInterfaceMembers().ToArray(); var matchingInterfaceMemberContext = interfaceMembers.Select(member => member.Context).FirstOrDefault(c => c == context.Parent.Parent); @@ -39,11 +39,11 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio var interfaceParameterIndex = GetParameterIndex(context); var implementationMembers = - _state.DeclarationFinder.FindInterfaceImplementationMembers(interfaceMembers.First( + _declarationFinderProvider.DeclarationFinder.FindInterfaceImplementationMembers(interfaceMembers.First( member => member.Context == matchingInterfaceMemberContext)).ToHashSet(); var parameters = - _state.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) + _declarationFinderProvider.DeclarationFinder.UserDeclarations(DeclarationType.Parameter) .Where(p => implementationMembers.Contains(p.ParentDeclaration)) .Cast() .ToArray(); @@ -55,7 +55,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio if (parameterIndex == interfaceParameterIndex) { - AddByRefIdentifier(_state.GetRewriter(parameter), parameterContext); + AddByRefIdentifier(rewriteSession.CheckOutModuleRewriter(parameter.QualifiedModuleName), parameterContext); } } @@ -72,7 +72,7 @@ private static int GetParameterIndex(VBAParser.ArgContext context) return Array.IndexOf(((VBAParser.ArgListContext)context.Parent).arg().ToArray(), context); } - private static void AddByRefIdentifier(IExecutableModuleRewriter rewriter, VBAParser.ArgContext context) + private static void AddByRefIdentifier(IModuleRewriter rewriter, VBAParser.ArgContext context) { if (context.BYREF() == null) { diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs index 7e13182f23..5c95e0e80b 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SpecifyExplicitPublicModifierQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class SpecifyExplicitPublicModifierQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public SpecifyExplicitPublicModifierQuickFix(RubberduckParserState state) + public SpecifyExplicitPublicModifierQuickFix() : base(typeof(ImplicitPublicMemberInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); rewriter.InsertBefore(result.Context.Start.TokenIndex, "Public "); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs index 3ca396076f..fbd2796e6e 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/SplitMultipleDeclarationsQuickFix.cs @@ -6,21 +6,16 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class SplitMultipleDeclarationsQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public SplitMultipleDeclarationsQuickFix(RubberduckParserState state) + public SplitMultipleDeclarationsQuickFix() : base(typeof(MultipleDeclarationsInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var context = result.Context is VBAParser.ConstStmtContext ? result.Context @@ -39,7 +34,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio throw new NotSupportedException(); } - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(context, declarationsText); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs index ba7e5f92b2..5a2da9f884 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/UntypedFunctionUsageQuickFix.cs @@ -6,23 +6,18 @@ using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class UntypedFunctionUsageQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public UntypedFunctionUsageQuickFix(RubberduckParserState state) + public UntypedFunctionUsageQuickFix() : base(typeof(UntypedFunctionUsageInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.InsertAfter(result.Context.Stop.TokenIndex, "$"); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs index 332b02e49f..fa50da1c06 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/UseSetKeywordForObjectAssignmentQuickFix.cs @@ -2,23 +2,18 @@ using Rubberduck.Inspections.Concrete; using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class UseSetKeywordForObjectAssignmentQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public UseSetKeywordForObjectAssignmentQuickFix(RubberduckParserState state) + public UseSetKeywordForObjectAssignmentQuickFix() : base(typeof(ObjectVariableNotSetInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.InsertBefore(result.Context.Start.TokenIndex, "Set "); } diff --git a/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs index 0d9cc12122..05bd4916c6 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/WriteOnlyPropertyQuickFix.cs @@ -6,23 +6,18 @@ using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; -using Rubberduck.Parsing.VBA; namespace Rubberduck.Inspections.QuickFixes { public sealed class WriteOnlyPropertyQuickFix : QuickFixBase { - private readonly RubberduckParserState _state; - - public WriteOnlyPropertyQuickFix(RubberduckParserState state) + public WriteOnlyPropertyQuickFix() : base(typeof(WriteOnlyPropertyInspection)) - { - _state = state; - } + {} - public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) + public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { - var parameters = ((IParameterizedDeclaration) result.Target).Parameters.Cast().ToList(); + var parameters = ((IParameterizedDeclaration) result.Target).Parameters.ToList(); var signatureParams = parameters.Except(new[] {parameters.Last()}).Select(GetParamText); @@ -32,7 +27,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio parameters.Last().AsTypeName, Environment.NewLine); - var rewriter = _state.GetRewriter(result.Target); + var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); rewriter.InsertBefore(result.Target.Context.Start.TokenIndex, propertyGet); } diff --git a/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs b/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs index 635e06386d..f84cc8c814 100644 --- a/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs +++ b/Rubberduck.Parsing/Inspections/Abstract/IQuickFix.cs @@ -7,7 +7,7 @@ namespace Rubberduck.Parsing.Inspections.Abstract { public interface IQuickFix { - void Fix(IInspectionResult result, IRewriteSession rewriteSession = null); + void Fix(IInspectionResult result, IRewriteSession rewriteSession); string Description(IInspectionResult result); bool CanFixInProcedure { get; } diff --git a/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs index 8719806c9c..de94ed5b72 100644 --- a/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs +++ b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs @@ -23,14 +23,14 @@ protected override IExecutableModuleRewriter ModuleRewriter(QualifiedModuleName protected override void RewriteInternal() { //The suspension ensures that only one parse gets executed instead of two for each rewritten module. - var result = _state.OnSuspendParser(this, new[] {ParserState.Ready}, RewriteAllRewriters); + var result = _state.OnSuspendParser(this, new[] {ParserState.Ready}, ExecuteAllRewriters); if(result != SuspensionResult.Completed) { Logger.Warn($"Rewriting attribute modules did not succeed. suspension result = {result}"); } } - private void RewriteAllRewriters() + private void ExecuteAllRewriters() { foreach (var rewriter in CheckedOutModuleRewriters.Values) { diff --git a/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs index 50cc939aa3..fdd4209b2a 100644 --- a/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs @@ -40,7 +40,7 @@ Sub Goo(arg1 As Integer, arg1 As String) var inspector = InspectionsHelper.GetInspector(inspection); var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - var fix = new RemoveExplicitCallStatmentQuickFix(state); + var fix = new RemoveExplicitCallStatementQuickFix(state); foreach (var result in inspectionResults) { fix.Fix(result); From 7523788b08551162cf5473408fcffe12cd30053d Mon Sep 17 00:00:00 2001 From: bclothier Date: Wed, 31 Oct 2018 06:59:54 -0500 Subject: [PATCH 026/107] Make project copy required EasyHook files from contents. --- .../Rubberduck.Deployment.csproj | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/Rubberduck.Deployment/Rubberduck.Deployment.csproj b/Rubberduck.Deployment/Rubberduck.Deployment.csproj index a10dbe493d..eebff5573e 100644 --- a/Rubberduck.Deployment/Rubberduck.Deployment.csproj +++ b/Rubberduck.Deployment/Rubberduck.Deployment.csproj @@ -17,6 +17,7 @@ + @@ -36,7 +37,19 @@ OleWoo\olewoo_interop.dll - + + + + + + + + + + @@ -50,11 +63,4 @@ - - - - - - - \ No newline at end of file From e7e27d409078fe68094d5bdb4cbdd366be6366fe Mon Sep 17 00:00:00 2001 From: bclothier Date: Wed, 31 Oct 2018 18:13:25 -0500 Subject: [PATCH 027/107] Rename VBE* files/types to Vbe* for types we own. --- .../Service/AutoCompleteService.cs | 8 +++--- Rubberduck.Core/UI/Command/ReparseCommand.cs | 7 +++-- Rubberduck.Core/UI/SelectionChangeService.cs | 10 +++---- .../UI/Settings/GeneralSettingsViewModel.cs | 6 ++--- Rubberduck.Core/UI/Settings/SettingsForm.cs | 4 +-- Rubberduck.Main/Extension.cs | 4 +-- Rubberduck.Main/VbeProvider.cs | 6 ++--- .../ComManagement/ComMessagePumper.cs | 7 +++-- .../Events/VBENativeServices.cs | 2 +- .../VBERuntime/Settings/IVBESettings.cs | 4 +-- .../VBERuntime/Settings/VBESettings.cs | 8 +++--- .../VBERuntime/VBEDllVersion.cs | 4 +-- .../IVbeNativeApi.cs} | 4 +-- .../VbeNativeApi6.cs} | 4 +-- .../VbeNativeApi7.cs} | 4 +-- .../VbeNativeApiAccessor.cs} | 26 +++++++++---------- .../WindowsApi/SubclassManager.cs | 2 +- .../Settings/GeneralSettingsTests.cs | 19 +++++++------- RubberduckTests/VBE/VBESettingsTests.cs | 18 ++++++------- 19 files changed, 72 insertions(+), 75 deletions(-) rename Rubberduck.VBEEditor/{VBERuntime/IVBERuntime.cs => VbeRuntime/IVbeNativeApi.cs} (87%) rename Rubberduck.VBEEditor/{VBERuntime/VBERuntime6.cs => VbeRuntime/VbeNativeApi6.cs} (96%) rename Rubberduck.VBEEditor/{VBERuntime/VBERuntime7.cs => VbeRuntime/VbeNativeApi7.cs} (96%) rename Rubberduck.VBEEditor/{VBERuntime/VBERuntimeAccessor.cs => VbeRuntime/VbeNativeApiAccessor.cs} (81%) diff --git a/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs b/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs index a45c93944c..4dc4a5f344 100644 --- a/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs +++ b/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs @@ -57,8 +57,8 @@ private void Enable() if (!_enabled) { - VBENativeServices.KeyDown += HandleKeyDown; - VBENativeServices.IntelliSenseChanged += HandleIntelliSenseChanged; + VbeNativeServices.KeyDown += HandleKeyDown; + VbeNativeServices.IntelliSenseChanged += HandleIntelliSenseChanged; _enabled = true; } } @@ -67,8 +67,8 @@ private void Disable() { if (_enabled && _initialized) { - VBENativeServices.KeyDown -= HandleKeyDown; - VBENativeServices.IntelliSenseChanged -= HandleIntelliSenseChanged; + VbeNativeServices.KeyDown -= HandleKeyDown; + VbeNativeServices.IntelliSenseChanged -= HandleIntelliSenseChanged; _enabled = false; _popupShown = false; } diff --git a/Rubberduck.Core/UI/Command/ReparseCommand.cs b/Rubberduck.Core/UI/Command/ReparseCommand.cs index dc1244ecfe..d25bba7221 100644 --- a/Rubberduck.Core/UI/Command/ReparseCommand.cs +++ b/Rubberduck.Core/UI/Command/ReparseCommand.cs @@ -9,11 +9,10 @@ using Rubberduck.Settings; using Rubberduck.SettingsProvider; using Rubberduck.Resources; -using Rubberduck.UI.CodeExplorer.Commands; using Rubberduck.VBEditor.ComManagement.TypeLibsAPI; using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.VBEditor.SafeComWrappers.Abstract; -using Rubberduck.VBEditor.VBERuntime.Settings; +using Rubberduck.VBEditor.VbeRuntime.Settings; namespace Rubberduck.UI.Command { @@ -22,12 +21,12 @@ public class ReparseCommand : CommandBase { private readonly IVBE _vbe; private readonly IVBETypeLibsAPI _typeLibApi; - private readonly IVBESettings _vbeSettings; + private readonly IVbeSettings _vbeSettings; private readonly IMessageBox _messageBox; private readonly RubberduckParserState _state; private readonly GeneralSettings _settings; - public ReparseCommand(IVBE vbe, IConfigProvider settingsProvider, RubberduckParserState state, IVBETypeLibsAPI typeLibApi, IVBESettings vbeSettings, IMessageBox messageBox) : base(LogManager.GetCurrentClassLogger()) + public ReparseCommand(IVBE vbe, IConfigProvider settingsProvider, RubberduckParserState state, IVBETypeLibsAPI typeLibApi, IVbeSettings vbeSettings, IMessageBox messageBox) : base(LogManager.GetCurrentClassLogger()) { _vbe = vbe; _vbeSettings = vbeSettings; diff --git a/Rubberduck.Core/UI/SelectionChangeService.cs b/Rubberduck.Core/UI/SelectionChangeService.cs index 88e39ef4e7..6919563c19 100644 --- a/Rubberduck.Core/UI/SelectionChangeService.cs +++ b/Rubberduck.Core/UI/SelectionChangeService.cs @@ -30,8 +30,8 @@ public SelectionChangeService(IVBE vbe, IParseCoordinator parser) { _parser = parser; _vbe = vbe; - VBENativeServices.SelectionChanged += OnVbeSelectionChanged; - VBENativeServices.WindowFocusChange += OnVbeFocusChanged; + VbeNativeServices.SelectionChanged += OnVbeSelectionChanged; + VbeNativeServices.WindowFocusChange += OnVbeFocusChanged; } private void OnVbeSelectionChanged(object sender, EventArgs e) @@ -69,7 +69,7 @@ private void OnVbeFocusChanged(object sender, WindowChangedEventArgs e) //Caret changed in a code pane. Task.Run(() => { - using (var pane = VBENativeServices.GetCodePaneFromHwnd(e.Hwnd)) + using (var pane = VbeNativeServices.GetCodePaneFromHwnd(e.Hwnd)) { DispatchSelectedDeclaration( new DeclarationChangedEventArgs(_vbe, _parser.State.FindSelectedDeclaration(pane))); @@ -186,8 +186,8 @@ private bool DeclarationChanged(Declaration current) public void Dispose() { - VBENativeServices.SelectionChanged -= OnVbeSelectionChanged; - VBENativeServices.WindowFocusChange -= OnVbeFocusChanged; + VbeNativeServices.SelectionChanged -= OnVbeSelectionChanged; + VbeNativeServices.WindowFocusChange -= OnVbeFocusChanged; } } diff --git a/Rubberduck.Core/UI/Settings/GeneralSettingsViewModel.cs b/Rubberduck.Core/UI/Settings/GeneralSettingsViewModel.cs index 508071255e..25c0cee70c 100644 --- a/Rubberduck.Core/UI/Settings/GeneralSettingsViewModel.cs +++ b/Rubberduck.Core/UI/Settings/GeneralSettingsViewModel.cs @@ -8,7 +8,7 @@ using NLog; using Rubberduck.SettingsProvider; using Rubberduck.UI.Command; -using Rubberduck.VBEditor.VBERuntime.Settings; +using Rubberduck.VBEditor.VbeRuntime.Settings; using Rubberduck.Resources; namespace Rubberduck.UI.Settings @@ -23,12 +23,12 @@ public class GeneralSettingsViewModel : SettingsViewModelBase, ISettingsViewMode { private readonly IOperatingSystem _operatingSystem; private readonly IMessageBox _messageBox; - private readonly IVBESettings _vbeSettings; + private readonly IVbeSettings _vbeSettings; private bool _indenterPrompted; private readonly ReadOnlyCollection _experimentalFeatureTypes; - public GeneralSettingsViewModel(Configuration config, IOperatingSystem operatingSystem, IMessageBox messageBox, IVBESettings vbeSettings, IEnumerable experimentalFeatureTypes) + public GeneralSettingsViewModel(Configuration config, IOperatingSystem operatingSystem, IMessageBox messageBox, IVbeSettings vbeSettings, IEnumerable experimentalFeatureTypes) { _operatingSystem = operatingSystem; _messageBox = messageBox; diff --git a/Rubberduck.Core/UI/Settings/SettingsForm.cs b/Rubberduck.Core/UI/Settings/SettingsForm.cs index d977665528..63cea3ef66 100644 --- a/Rubberduck.Core/UI/Settings/SettingsForm.cs +++ b/Rubberduck.Core/UI/Settings/SettingsForm.cs @@ -2,7 +2,7 @@ using Rubberduck.Settings; using Rubberduck.Common; using Rubberduck.Interaction; -using Rubberduck.VBEditor.VBERuntime.Settings; +using Rubberduck.VBEditor.VbeRuntime.Settings; using System.Collections.Generic; using System; @@ -21,7 +21,7 @@ public SettingsForm() InitializeComponent(); } - public SettingsForm(IGeneralConfigService configService, IOperatingSystem operatingSystem, IMessageBox messageBox, IVBESettings vbeSettings, SettingsViews activeView = SettingsViews.GeneralSettings) : this() + public SettingsForm(IGeneralConfigService configService, IOperatingSystem operatingSystem, IMessageBox messageBox, IVbeSettings vbeSettings, SettingsViews activeView = SettingsViews.GeneralSettings) : this() { var config = configService.LoadConfiguration(); diff --git a/Rubberduck.Main/Extension.cs b/Rubberduck.Main/Extension.cs index 8587355b24..e1028cdc4b 100644 --- a/Rubberduck.Main/Extension.cs +++ b/Rubberduck.Main/Extension.cs @@ -60,7 +60,7 @@ public void OnConnection(object Application, ext_ConnectMode ConnectMode, object _addin.Object = this; VbeProvider.Initialize(_vbe); - VBENativeServices.HookEvents(_vbe); + VbeNativeServices.HookEvents(_vbe); #if DEBUG // FOR DEBUGGING/DEVELOPMENT PURPOSES, ALLOW ACCESS TO SOME VBETypeLibsAPI FEATURES FROM VBA @@ -242,7 +242,7 @@ private void ShutdownAddIn() { _logger.Log(LogLevel.Info, "Rubberduck is shutting down."); _logger.Log(LogLevel.Trace, "Unhooking VBENativeServices events..."); - VBENativeServices.UnhookEvents(); + VbeNativeServices.UnhookEvents(); VbeProvider.Terminate(); _logger.Log(LogLevel.Trace, "Releasing dockable hosts..."); diff --git a/Rubberduck.Main/VbeProvider.cs b/Rubberduck.Main/VbeProvider.cs index 45761cfa83..c5b8f996e5 100644 --- a/Rubberduck.Main/VbeProvider.cs +++ b/Rubberduck.Main/VbeProvider.cs @@ -1,5 +1,5 @@ using Rubberduck.VBEditor.SafeComWrappers.Abstract; -using Rubberduck.VBEditor.VBERuntime; +using Rubberduck.VBEditor.VbeRuntime; namespace Rubberduck { @@ -19,7 +19,7 @@ internal static class VbeProvider internal static void Initialize(IVBE vbe) { Vbe = vbe; - VbeRuntime = new VBERuntimeAccessor(vbe); + VbeRuntime = new VbeNativeApiAccessor(vbe); } internal static void Terminate() @@ -30,6 +30,6 @@ internal static void Terminate() } internal static IVBE Vbe { get; private set; } - internal static IVBERuntime VbeRuntime { get; private set; } + internal static IVbeNativeApi VbeRuntime { get; private set; } } } diff --git a/Rubberduck.VBEEditor/ComManagement/ComMessagePumper.cs b/Rubberduck.VBEEditor/ComManagement/ComMessagePumper.cs index 4b921af52a..a4db42d78b 100644 --- a/Rubberduck.VBEEditor/ComManagement/ComMessagePumper.cs +++ b/Rubberduck.VBEEditor/ComManagement/ComMessagePumper.cs @@ -1,7 +1,6 @@ using System; -using System.Threading; using Rubberduck.VBEditor.Utility; -using Rubberduck.VBEditor.VBERuntime; +using Rubberduck.VBEditor.VbeRuntime; namespace Rubberduck.VBEditor.ComManagement { @@ -12,10 +11,10 @@ public interface IComMessagePumper public class ComMessagePumper : IComMessagePumper { - private readonly IVBERuntime _runtime; + private readonly IVbeNativeApi _runtime; private readonly IUiContextProvider _uiContext; - public ComMessagePumper(IUiContextProvider uiContext, IVBERuntime runtime) + public ComMessagePumper(IUiContextProvider uiContext, IVbeNativeApi runtime) { _uiContext = uiContext; _runtime = runtime; diff --git a/Rubberduck.VBEEditor/Events/VBENativeServices.cs b/Rubberduck.VBEEditor/Events/VBENativeServices.cs index c2bf5017dc..9b3da6e1b7 100644 --- a/Rubberduck.VBEEditor/Events/VBENativeServices.cs +++ b/Rubberduck.VBEEditor/Events/VBENativeServices.cs @@ -10,7 +10,7 @@ namespace Rubberduck.VBEditor.Events { // ReSharper disable once InconsistentNaming - public static class VBENativeServices + public static class VbeNativeServices { private static User32.WinEventProc _eventProc; private static IntPtr _eventHandle; diff --git a/Rubberduck.VBEEditor/VBERuntime/Settings/IVBESettings.cs b/Rubberduck.VBEEditor/VBERuntime/Settings/IVBESettings.cs index 87591d4a90..6fa43e4c0e 100644 --- a/Rubberduck.VBEEditor/VBERuntime/Settings/IVBESettings.cs +++ b/Rubberduck.VBEEditor/VBERuntime/Settings/IVBESettings.cs @@ -1,6 +1,6 @@ -namespace Rubberduck.VBEditor.VBERuntime.Settings +namespace Rubberduck.VBEditor.VbeRuntime.Settings { - public interface IVBESettings + public interface IVbeSettings { DllVersion Version { get; } bool CompileOnDemand { get; set; } diff --git a/Rubberduck.VBEEditor/VBERuntime/Settings/VBESettings.cs b/Rubberduck.VBEEditor/VBERuntime/Settings/VBESettings.cs index d5ea51b642..572440248e 100644 --- a/Rubberduck.VBEEditor/VBERuntime/Settings/VBESettings.cs +++ b/Rubberduck.VBEEditor/VBERuntime/Settings/VBESettings.cs @@ -3,9 +3,9 @@ using Rubberduck.VBEditor.SafeComWrappers.Abstract; using Rubberduck.VBEditor.Utility; -namespace Rubberduck.VBEditor.VBERuntime.Settings +namespace Rubberduck.VBEditor.VbeRuntime.Settings { - public class VBESettings : IVBESettings + public class VbeSettings : IVbeSettings { private const string Vbe7SettingPath = @"HKEY_CURRENT_USER\Software\Microsoft\VBA\7.0\Common"; private const string Vbe6SettingPath = @"HKEY_CURRENT_USER\Software\Microsoft\VBA\6.0\Common"; @@ -14,11 +14,11 @@ public class VBESettings : IVBESettings private readonly string _activeRegistryRootPath; private readonly string[] _registryRootPaths = { Vbe7SettingPath, Vbe6SettingPath }; - public VBESettings(IVBE vbe, IRegistryWrapper registry) + public VbeSettings(IVBE vbe, IRegistryWrapper registry) { try { - switch (VBEDllVersion.GetCurrentVersion(vbe)) + switch (VbeDllVersion.GetCurrentVersion(vbe)) { case DllVersion.Vbe6: Version = DllVersion.Vbe6; diff --git a/Rubberduck.VBEEditor/VBERuntime/VBEDllVersion.cs b/Rubberduck.VBEEditor/VBERuntime/VBEDllVersion.cs index 995893b0bf..485a57f257 100644 --- a/Rubberduck.VBEEditor/VBERuntime/VBEDllVersion.cs +++ b/Rubberduck.VBEEditor/VBERuntime/VBEDllVersion.cs @@ -1,6 +1,6 @@ using Rubberduck.VBEditor.SafeComWrappers.Abstract; -namespace Rubberduck.VBEditor.VBERuntime +namespace Rubberduck.VBEditor.VbeRuntime { public enum DllVersion { @@ -9,7 +9,7 @@ public enum DllVersion Vbe7 } - public static class VBEDllVersion + public static class VbeDllVersion { public static DllVersion GetCurrentVersion(IVBE vbe) { diff --git a/Rubberduck.VBEEditor/VBERuntime/IVBERuntime.cs b/Rubberduck.VBEEditor/VbeRuntime/IVbeNativeApi.cs similarity index 87% rename from Rubberduck.VBEEditor/VBERuntime/IVBERuntime.cs rename to Rubberduck.VBEEditor/VbeRuntime/IVbeNativeApi.cs index 52fa45f24c..842902cf7e 100644 --- a/Rubberduck.VBEEditor/VBERuntime/IVBERuntime.cs +++ b/Rubberduck.VBEEditor/VbeRuntime/IVbeNativeApi.cs @@ -1,8 +1,8 @@ using System; -namespace Rubberduck.VBEditor.VBERuntime +namespace Rubberduck.VBEditor.VbeRuntime { - public interface IVBERuntime + public interface IVbeNativeApi { string DllName { get; } int DoEvents(); diff --git a/Rubberduck.VBEEditor/VBERuntime/VBERuntime6.cs b/Rubberduck.VBEEditor/VbeRuntime/VbeNativeApi6.cs similarity index 96% rename from Rubberduck.VBEEditor/VBERuntime/VBERuntime6.cs rename to Rubberduck.VBEEditor/VbeRuntime/VbeNativeApi6.cs index 302d4f9c2f..fb7e125150 100644 --- a/Rubberduck.VBEEditor/VBERuntime/VBERuntime6.cs +++ b/Rubberduck.VBEEditor/VbeRuntime/VbeNativeApi6.cs @@ -1,9 +1,9 @@ using System; using System.Runtime.InteropServices; -namespace Rubberduck.VBEditor.VBERuntime +namespace Rubberduck.VBEditor.VbeRuntime { - internal class VBERuntime6 : IVBERuntime + internal class VbeNativeApi6 : IVbeNativeApi { private const string _dllName = "vbe6.dll"; diff --git a/Rubberduck.VBEEditor/VBERuntime/VBERuntime7.cs b/Rubberduck.VBEEditor/VbeRuntime/VbeNativeApi7.cs similarity index 96% rename from Rubberduck.VBEEditor/VBERuntime/VBERuntime7.cs rename to Rubberduck.VBEEditor/VbeRuntime/VbeNativeApi7.cs index dad602650c..16facd9e5c 100644 --- a/Rubberduck.VBEEditor/VBERuntime/VBERuntime7.cs +++ b/Rubberduck.VBEEditor/VbeRuntime/VbeNativeApi7.cs @@ -1,9 +1,9 @@ using System; using System.Runtime.InteropServices; -namespace Rubberduck.VBEditor.VBERuntime +namespace Rubberduck.VBEditor.VbeRuntime { - internal class VBERuntime7 : IVBERuntime + internal class VbeNativeApi7 : IVbeNativeApi { private const string _dllName = "vbe7.dll"; diff --git a/Rubberduck.VBEEditor/VBERuntime/VBERuntimeAccessor.cs b/Rubberduck.VBEEditor/VbeRuntime/VbeNativeApiAccessor.cs similarity index 81% rename from Rubberduck.VBEEditor/VBERuntime/VBERuntimeAccessor.cs rename to Rubberduck.VBEEditor/VbeRuntime/VbeNativeApiAccessor.cs index 9074d42ee4..80434cd93d 100644 --- a/Rubberduck.VBEEditor/VBERuntime/VBERuntimeAccessor.cs +++ b/Rubberduck.VBEEditor/VbeRuntime/VbeNativeApiAccessor.cs @@ -1,25 +1,25 @@ using System; using Rubberduck.VBEditor.SafeComWrappers.Abstract; -namespace Rubberduck.VBEditor.VBERuntime +namespace Rubberduck.VBEditor.VbeRuntime { - public class VBERuntimeAccessor : IVBERuntime + public class VbeNativeApiAccessor : IVbeNativeApi { private static DllVersion _version; - private readonly IVBERuntime _runtime; + private readonly IVbeNativeApi _runtime; - static VBERuntimeAccessor() + static VbeNativeApiAccessor() { _version = DllVersion.Unknown; } - public VBERuntimeAccessor(IVBE vbe) + public VbeNativeApiAccessor(IVBE vbe) { if (_version == DllVersion.Unknown) { try { - _version = VBEDllVersion.GetCurrentVersion(vbe); + _version = VbeDllVersion.GetCurrentVersion(vbe); } catch { @@ -29,25 +29,25 @@ public VBERuntimeAccessor(IVBE vbe) _runtime = InitializeRuntime(); } - private static IVBERuntime InitializeRuntime() + private static IVbeNativeApi InitializeRuntime() { switch (_version) { case DllVersion.Vbe7: - return new VBERuntime7(); + return new VbeNativeApi7(); case DllVersion.Vbe6: - return new VBERuntime6(); + return new VbeNativeApi6(); default: return DetermineVersion(); } } - private static IVBERuntime DetermineVersion() + private static IVbeNativeApi DetermineVersion() { - IVBERuntime runtime; + IVbeNativeApi runtime; try { - runtime = new VBERuntime7(); + runtime = new VbeNativeApi7(); runtime.GetTimer(); _version = DllVersion.Vbe7; } @@ -55,7 +55,7 @@ private static IVBERuntime DetermineVersion() { try { - runtime = new VBERuntime6(); + runtime = new VbeNativeApi6(); runtime.GetTimer(); _version = DllVersion.Vbe6; } diff --git a/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs b/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs index cd69f4ef7e..54a9009e80 100644 --- a/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs +++ b/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs @@ -86,7 +86,7 @@ private void SubclassRemoved(object sender, EventArgs eventArgs) private static void AssociateCodePane(object sender, EventArgs eventArgs) { var subclass = (CodePaneSubclass)sender; - subclass.VbeObject = VBENativeServices.GetCodePaneFromHwnd(subclass.Hwnd); + subclass.VbeObject = VbeNativeServices.GetCodePaneFromHwnd(subclass.Hwnd); SubclassLogger.Trace($"CodePane subclass for hWnd 0x{subclass.Hwnd.ToInt64():X8} associated itself with its VBE object."); } diff --git a/RubberduckTests/Settings/GeneralSettingsTests.cs b/RubberduckTests/Settings/GeneralSettingsTests.cs index aa2fd85beb..c163ebd431 100644 --- a/RubberduckTests/Settings/GeneralSettingsTests.cs +++ b/RubberduckTests/Settings/GeneralSettingsTests.cs @@ -6,8 +6,7 @@ using GeneralSettings = Rubberduck.Settings.GeneralSettings; using Rubberduck.Common; using Moq; -using Rubberduck.UI; -using Rubberduck.VBEditor.VBERuntime.Settings; +using Rubberduck.VBEditor.VbeRuntime.Settings; using System; using Rubberduck.Interaction; @@ -26,9 +25,9 @@ private Mock GetMessageBoxMock() return new Mock(); } - private Mock GetVBESettingsMock() + private Mock GetVbeSettingsMock() { - return new Mock(); + return new Mock(); } private Configuration GetDefaultConfig() @@ -83,7 +82,7 @@ private Configuration GetNondefaultConfig() public void SaveConfigWorks() { var customConfig = GetNondefaultConfig(); - var viewModel = new GeneralSettingsViewModel(customConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVBESettingsMock().Object, new List()); + var viewModel = new GeneralSettingsViewModel(customConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVbeSettingsMock().Object, new List()); var config = GetDefaultConfig(); viewModel.UpdateConfig(config); @@ -101,7 +100,7 @@ public void SaveConfigWorks() [Test] public void SetDefaultsWorks() { - var viewModel = new GeneralSettingsViewModel(GetNondefaultConfig(), GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVBESettingsMock().Object, new List()); + var viewModel = new GeneralSettingsViewModel(GetNondefaultConfig(), GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVbeSettingsMock().Object, new List()); var defaultConfig = GetDefaultConfig(); viewModel.SetToDefaults(defaultConfig); @@ -120,7 +119,7 @@ public void SetDefaultsWorks() public void LanguageIsSetInCtor() { var defaultConfig = GetDefaultConfig(); - var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVBESettingsMock().Object, new List()); + var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVbeSettingsMock().Object, new List()); Assert.AreEqual(defaultConfig.UserSettings.GeneralSettings.Language, viewModel.SelectedLanguage); } @@ -130,7 +129,7 @@ public void LanguageIsSetInCtor() public void HotkeysAreSetInCtor() { var defaultConfig = GetDefaultConfig(); - var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVBESettingsMock().Object, new List()); + var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVbeSettingsMock().Object, new List()); Assert.IsTrue(defaultConfig.UserSettings.HotkeySettings.Settings.SequenceEqual(viewModel.Hotkeys)); } @@ -140,7 +139,7 @@ public void HotkeysAreSetInCtor() public void AutoSaveEnabledIsSetInCtor() { var defaultConfig = GetDefaultConfig(); - var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVBESettingsMock().Object, new List()); + var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVbeSettingsMock().Object, new List()); Assert.AreEqual(defaultConfig.UserSettings.GeneralSettings.IsAutoSaveEnabled, viewModel.AutoSaveEnabled); } @@ -150,7 +149,7 @@ public void AutoSaveEnabledIsSetInCtor() public void AutoSavePeriodIsSetInCtor() { var defaultConfig = GetDefaultConfig(); - var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVBESettingsMock().Object, new List()); + var viewModel = new GeneralSettingsViewModel(defaultConfig, GetOperatingSystemMock().Object, GetMessageBoxMock().Object, GetVbeSettingsMock().Object, new List()); Assert.AreEqual(defaultConfig.UserSettings.GeneralSettings.AutoSavePeriod, viewModel.AutoSavePeriod); } diff --git a/RubberduckTests/VBE/VBESettingsTests.cs b/RubberduckTests/VBE/VBESettingsTests.cs index cbec8d9d88..246ec21b66 100644 --- a/RubberduckTests/VBE/VBESettingsTests.cs +++ b/RubberduckTests/VBE/VBESettingsTests.cs @@ -2,14 +2,14 @@ using Moq; using NUnit.Framework; using Rubberduck.VBEditor.Utility; -using Rubberduck.VBEditor.VBERuntime; -using Rubberduck.VBEditor.VBERuntime.Settings; +using Rubberduck.VBEditor.VbeRuntime; +using Rubberduck.VBEditor.VbeRuntime.Settings; using RubberduckTests.Mocks; namespace RubberduckTests.VBE { [TestFixture] - public class VBESettingsTests + public class VbeSettingsTests { private const string Vbe7SettingPath = @"HKEY_CURRENT_USER\Software\Microsoft\VBA\7.0\Common"; private const string Vbe6SettingPath = @"HKEY_CURRENT_USER\Software\Microsoft\VBA\6.0\Common"; @@ -29,7 +29,7 @@ public void DllVersion_MustBe6() var registry = GetRegistryMock(); vbe.SetupGet(s => s.Version).Returns("6.00"); - var settings = new VBESettings(vbe.Object, registry.Object); + var settings = new VbeSettings(vbe.Object, registry.Object); Assert.AreEqual(DllVersion.Vbe6, settings.Version); } @@ -42,7 +42,7 @@ public void DllVersion_MustBe7() var registry = GetRegistryMock(); vbe.SetupGet(s => s.Version).Returns("7.00"); - var settings = new VBESettings(vbe.Object, registry.Object); + var settings = new VbeSettings(vbe.Object, registry.Object); Assert.AreEqual(DllVersion.Vbe7, settings.Version); } @@ -55,7 +55,7 @@ public void DllVersion_IsBogus() var registry = GetRegistryMock(); vbe.SetupGet(s => s.Version).Returns("foo"); - var settings = new VBESettings(vbe.Object, registry.Object); + var settings = new VbeSettings(vbe.Object, registry.Object); Assert.AreEqual(DllVersion.Unknown, settings.Version); } @@ -68,7 +68,7 @@ public void DllVersion_IsNull() var registry = GetRegistryMock(); vbe.SetupGet(s => s.Version).Returns((string)null); - var settings = new VBESettings(vbe.Object, registry.Object); + var settings = new VbeSettings(vbe.Object, registry.Object); Assert.IsTrue(settings.Version == DllVersion.Unknown); } @@ -84,7 +84,7 @@ public void CompileOnDemand_Write_IsTrue() registry.Setup(s => s.SetValue(Vbe7SettingPath, "CompileOnDemand", true, RegistryValueKind.DWord)); registry.Setup(s => s.GetValue(Vbe7SettingPath, "CompileOnDemand", DWordFalseValue)).Returns(DWordTrueValue); - var settings = new VBESettings(vbe.Object, registry.Object); + var settings = new VbeSettings(vbe.Object, registry.Object); settings.CompileOnDemand = true; Assert.IsTrue(settings.CompileOnDemand); @@ -101,7 +101,7 @@ public void BackGroundCompile_Write_IsFalse() registry.Setup(s => s.SetValue(Vbe7SettingPath, "BackGroundCompile", false, RegistryValueKind.DWord)); registry.Setup(s => s.GetValue(Vbe7SettingPath, "BackGroundCompile", DWordFalseValue)).Returns(DWordFalseValue); - var settings = new VBESettings(vbe.Object, registry.Object); + var settings = new VbeSettings(vbe.Object, registry.Object); settings.BackGroundCompile = false; Assert.IsTrue(settings.BackGroundCompile == false); From 76426be60d75a41f00fadc36a3299f866ecbd7d0 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Thu, 1 Nov 2018 14:19:53 +0100 Subject: [PATCH 028/107] Adjust the quickfix tests to the new setup of rewriting In addition, the tests are streamlined to use methods from a base class in order to reduce code duplication. --- .../QuickFixes/QuickFixProvider.cs | 23 +- .../AccessSheetUsingCodeNameQuickFixTests.cs | 111 +-- .../QuickFixes/AddStepOneQuickFixTests.cs | 34 +- ...plicationWorksheetFunctionQuickFixTests.cs | 85 +-- ...yValParameterMakeLocalCopyQuickFixTests.cs | 16 +- .../ChangeDimToPrivateQuickFixTests.cs | 53 +- .../ChangeIntegerToLongQuickFixTests.cs | 672 +++++------------ .../ChangeProcedureToFunctionQuickFixTests.cs | 104 +-- .../ConvertToProcedureQuickFixTests.cs | 136 +--- .../DeclareAsExplicitVariantQuickFixTests.cs | 67 +- .../QuickFixes/IgnoreOnceQuickFixTests.cs | 694 +++++------------- .../IntroduceLocalVariableQuickFixTests.cs | 41 +- ...ingOnInappropriateArgumentQuickFixTests.cs | 28 +- .../MakeSingleLineParamegerQuickFixTests.cs | 27 +- .../MoveFieldCloserToUsageQuickFixTests.cs | 53 +- .../QuickFixes/OptionExplicitQuickFixTests.cs | 27 +- .../PassParameterByReferenceQuickFixTests.cs | 101 +-- .../PassParameterByValueQuickFixTests.cs | 129 ++-- .../QuickFixes/QuickFixBaseTests.cs | 4 +- .../QuickFixes/QuickFixProviderTests.cs | 5 +- .../QuickFixes/QuickFixTestBase.cs | 176 +++++ .../QuickFixes/RemoveCommentQuickFixTests.cs | 65 +- ...RemoveDuplicatedAnnotationQuickFixTests.cs | 111 +-- .../RemoveEmptyElseBlockQuickFixTests.cs | 27 +- .../RemoveEmptyIfBlockQuickFixTests.cs | 420 ++--------- ...emoveExplicitByRefModifierQuickFixTests.cs | 205 ++---- ...emoveExplicitCallStatementQuickFixTests.cs | 29 +- ...RemoveExplicitLetStatementQuickFixTests.cs | 27 +- .../RemoveLocalErrorQuickFixTests.cs | 26 +- .../RemoveOptionBaseStatementQuickFixTests.cs | 83 +-- .../QuickFixes/RemoveStepOneQuickFixTests.cs | 28 +- .../RemoveStopKeywordQuickFixTests.cs | 40 +- .../RemoveTypeHintsQuickFixTests.cs | 197 +---- ...RemoveUnassignedIdentifierQuickFixTests.cs | 57 +- ...oveUnassignedVariableUsageQuickFixTests.cs | 24 +- .../RemoveUnusedDeclarationQuickFixTests.cs | 149 +--- .../RemoveUnusedParameterQuickFixTests.cs | 8 +- ...mptyStringLiteralStatementQuickFixTests.cs | 27 +- .../ReplaceGlobalModifierQuickFixTests.cs | 25 +- ...seWithConditionalStatementQuickFixTests.cs | 64 +- ...placeObsoleteCommentMarkerQuickFixTests.cs | 64 +- ...laceObsoleteErrorStatementQuickFixTests.cs | 64 +- .../RestoreErrorHandlingQuickFixTests.cs | 144 +--- ...tExplicitVariantReturnTypeQuickFixTests.cs | 62 +- ...ecifyExplicitByRefModifierQuickFixTests.cs | 206 ++---- ...cifyExplicitPublicModifierQuickFixTests.cs | 25 +- .../SplitMultipleDeclarationsQuickFixTests.cs | 52 +- .../UntypedFunctionUsageQuickFixTests.cs | 10 +- ...KeywordForObjectAssignmentQuickFixTests.cs | 54 +- .../WriteOnlyPropertyQuickFixTests.cs | 55 +- 50 files changed, 1431 insertions(+), 3503 deletions(-) create mode 100644 RubberduckTests/QuickFixes/QuickFixTestBase.cs diff --git a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs index c27e466d11..f273a4d5a7 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs @@ -79,9 +79,6 @@ public void Fix(IQuickFix fix, IInspectionResult result) var rewriteSession = RewriteSession(fix.TargetCodeKind); fix.Fix(result, rewriteSession); rewriteSession.Rewrite(); - - _state.RewriteAllModules(); - _state.OnParseRequested(this); } private IRewriteSession RewriteSession(CodeKind targetCodeKind) @@ -116,12 +113,9 @@ public void FixInProcedure(IQuickFix fix, QualifiedMemberName? qualifiedMember, continue; } - fix.Fix(result); + fix.Fix(result, rewriteSession); } rewriteSession.Rewrite(); - - _state.RewriteAllModules(); - _state.OnParseRequested(this); } public void FixInModule(IQuickFix fix, QualifiedSelection selection, Type inspectionType, IEnumerable results) @@ -141,12 +135,9 @@ public void FixInModule(IQuickFix fix, QualifiedSelection selection, Type inspec continue; } - fix.Fix(result); + fix.Fix(result, rewriteSession); } rewriteSession.Rewrite(); - - _state.RewriteAllModules(); - _state.OnParseRequested(this); } public void FixInProject(IQuickFix fix, QualifiedSelection selection, Type inspectionType, IEnumerable results) @@ -166,12 +157,9 @@ public void FixInProject(IQuickFix fix, QualifiedSelection selection, Type inspe continue; } - fix.Fix(result); + fix.Fix(result, rewriteSession); } rewriteSession.Rewrite(); - - _state.RewriteAllModules(); - _state.OnParseRequested(this); } public void FixAll(IQuickFix fix, Type inspectionType, IEnumerable results) @@ -191,12 +179,9 @@ public void FixAll(IQuickFix fix, Type inspectionType, IEnumerable new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -52,14 +45,8 @@ Public Sub Foo() Sheet1.Range(""A1"") = ""foo"" End Sub"; - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -76,14 +63,8 @@ Public Sub Foo() Sheet1.Range(""A1"") = ""foo"" End Sub"; - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -111,15 +92,9 @@ End Sub Public Sub Bar(ws As Worksheet) End Sub"; - - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -138,14 +113,8 @@ Public Sub Foo() End Sub"; - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -166,14 +135,8 @@ Dim s As String Sheet1.Cells(1, 1) = ""foo"" End Sub"; - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -194,14 +157,8 @@ Dim s As String Sheet1.Cells(1, 1) = ""foo"" End Sub"; - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -230,14 +187,8 @@ Public Sub ws() Dim ws As Worksheet End Sub"; - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -266,21 +217,21 @@ Public Sub ws() Dim ws As Worksheet End Sub"; - using (var state = ArrangeParserAndParse(inputCode, out var component)) - { - var inspection = new SheetAccessedUsingStringInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new SheetAccessedUsingStringInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } + - new AccessSheetUsingCodeNameQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new AccessSheetUsingCodeNameQuickFix(state); } - private static RubberduckParserState ArrangeParserAndParse(string inputCode, out IVBComponent component) + protected override IVBE TestVbe(string code, out IVBComponent component) { var builder = new MockVbeBuilder(); var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("Module1", ComponentType.StandardModule, inputCode) + .AddComponent("Module1", ComponentType.StandardModule, code) .AddComponent("Sheet1", ComponentType.Document, "", properties: new[] { @@ -298,9 +249,7 @@ private static RubberduckParserState ArrangeParserAndParse(string inputCode, out component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - return MockParser.CreateAndParse(vbe.Object); + return builder.AddProject(project).Build().Object; } private static Mock CreateVBComponentPropertyMock(string propertyName, string propertyValue) diff --git a/RubberduckTests/QuickFixes/AddStepOneQuickFixTests.cs b/RubberduckTests/QuickFixes/AddStepOneQuickFixTests.cs index a462ac1ef4..2fcb80b433 100644 --- a/RubberduckTests/QuickFixes/AddStepOneQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/AddStepOneQuickFixTests.cs @@ -1,15 +1,13 @@ using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using Rubberduck.Parsing.Inspections; -using RubberduckTests.Inspections; -using RubberduckTests.Mocks; -using System.Threading; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class AddStepOneQuickFixTests + public class AddStepOneQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -27,7 +25,8 @@ public void AddStepOne_QuickFixWorks_Remove() Next End Sub"; - this.TestAddStepOneQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new StepIsNotSpecifiedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -50,7 +49,8 @@ public void AddStepOne_QuickFixWorks_NestedLoops() Next End Sub"; - this.TestAddStepOneQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new StepIsNotSpecifiedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -69,24 +69,14 @@ public void AddStepOne_QuickFixWorks_ComplexExpression() Next End Sub"; - this.TestAddStepOneQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new StepIsNotSpecifiedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } - private void TestAddStepOneQuickFix(string expectedCode, string inputCode) - { - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - var state = MockParser.CreateAndParse(vbe.Object); - - var inspection = new StepIsNotSpecifiedInspection(state) { Severity = CodeInspectionSeverity.Warning }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - foreach (var inspectionResult in inspectionResults) - { - new AddStepOneQuickFix(state).Fix(inspectionResult); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new AddStepOneQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/ApplicationWorksheetFunctionQuickFixTests.cs b/RubberduckTests/QuickFixes/ApplicationWorksheetFunctionQuickFixTests.cs index 624cec7595..d005c6a09c 100644 --- a/RubberduckTests/QuickFixes/ApplicationWorksheetFunctionQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ApplicationWorksheetFunctionQuickFixTests.cs @@ -1,16 +1,16 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; +using Rubberduck.Parsing.Inspections.Abstract; using Rubberduck.Parsing.VBA; using Rubberduck.VBEditor.SafeComWrappers; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; using RubberduckTests.Mocks; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ApplicationWorksheetFunctionQuickFixTests + public class ApplicationWorksheetFunctionQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -30,29 +30,8 @@ Dim foo As Double End Sub "; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("Module1", ComponentType.StandardModule, inputCode) - .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) - .Build(); - - var vbe = builder.AddProject(project).Build(); - - var parser = MockParser.Create(vbe.Object); - using (var state = parser.State) - { - parser.Parse(new CancellationTokenSource()); - if (state.Status >= ParserState.Error) - { - Assert.Inconclusive("Parser Error"); - } - - var inspection = new ApplicationWorksheetFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ApplicationWorksheetFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(project.Object.VBComponents.First()).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ApplicationWorksheetFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -77,29 +56,8 @@ End With End Sub "; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("Module1", ComponentType.StandardModule, inputCode) - .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) - .Build(); - - var vbe = builder.AddProject(project).Build(); - - var parser = MockParser.Create(vbe.Object); - using (var state = parser.State) - { - parser.Parse(new CancellationTokenSource()); - if (state.Status >= ParserState.Error) - { - Assert.Inconclusive("Parser Error"); - } - - var inspection = new ApplicationWorksheetFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ApplicationWorksheetFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(project.Object.VBComponents.First()).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ApplicationWorksheetFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -120,22 +78,27 @@ Dim foo As String End Sub "; + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ApplicationWorksheetFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } + + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ApplicationWorksheetFunctionQuickFix(); + } + + protected override IVBE TestVbe(string code, out IVBComponent component) + { var builder = new MockVbeBuilder(); var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("Module1", ComponentType.StandardModule, inputCode) + .AddComponent("Module1", ComponentType.StandardModule, code) .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) .Build(); - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ApplicationWorksheetFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ApplicationWorksheetFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(project.Object.VBComponents.First()).GetText()); - } + var vbe = builder.AddProject(project).Build().Object; + component = project.Object.VBComponents[0]; + return vbe; } } } diff --git a/RubberduckTests/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFixTests.cs b/RubberduckTests/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFixTests.cs index e63d18be20..60bec95e82 100644 --- a/RubberduckTests/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/AssignedByValParameterMakeLocalCopyQuickFixTests.cs @@ -355,11 +355,12 @@ End Sub" private string ApplyLocalVariableQuickFixToCodeFragment(string inputCode, string userEnteredName = "") { - var vbe = BuildMockVBE(inputCode); + var vbe = BuildMockVBE(inputCode, out var component); var mockDialogFactory = BuildMockDialogFactory(userEnteredName); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new AssignedByValParameterInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); @@ -369,14 +370,17 @@ private string ApplyLocalVariableQuickFixToCodeFragment(string inputCode, string Assert.Inconclusive("Inspection yielded no results."); } - new AssignedByValParameterMakeLocalCopyQuickFix(state, mockDialogFactory.Object).Fix(result); - return state.GetRewriter(vbe.Object.ActiveVBProject.VBComponents[0]).GetText(); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); + + new AssignedByValParameterMakeLocalCopyQuickFix(state, mockDialogFactory.Object).Fix(result, rewriteSession); + + return rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName).GetText(); } } - private Mock BuildMockVBE(string inputCode) + private Mock BuildMockVBE(string inputCode, out IVBComponent component) { - return MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _); + return MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); } private Mock BuildMockDialogFactory(string userEnteredName) diff --git a/RubberduckTests/QuickFixes/ChangeDimToPrivateQuickFixTests.cs b/RubberduckTests/QuickFixes/ChangeDimToPrivateQuickFixTests.cs index 763633b02b..96b4676842 100644 --- a/RubberduckTests/QuickFixes/ChangeDimToPrivateQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ChangeDimToPrivateQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ChangeDimToPrivateQuickFixTests + public class ChangeDimToPrivateQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -21,17 +19,8 @@ public void ModuleScopeDimKeyword_QuickFixWorks() const string expectedCode = @"Private foo As String"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ModuleScopeDimKeywordInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeDimToPrivateQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ModuleScopeDimKeywordInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -46,17 +35,8 @@ public void ModuleScopeDimKeyword_QuickFixWorks_SplitDeclaration() @"Private _ foo As String"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ModuleScopeDimKeywordInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeDimToPrivateQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ModuleScopeDimKeywordInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -71,18 +51,13 @@ public void ModuleScopeDimKeyword_QuickFixWorks_MultipleDeclarations() @"Private foo As String, _ bar As Integer"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ModuleScopeDimKeywordInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeDimToPrivateQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ModuleScopeDimKeywordInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ChangeDimToPrivateQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/ChangeIntegerToLongQuickFixTests.cs b/RubberduckTests/QuickFixes/ChangeIntegerToLongQuickFixTests.cs index 6425c95e39..d3f181af86 100644 --- a/RubberduckTests/QuickFixes/ChangeIntegerToLongQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ChangeIntegerToLongQuickFixTests.cs @@ -1,16 +1,15 @@ -using System.Linq; -using System.Threading; +using System; using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; using Rubberduck.Parsing.Grammar; -using Rubberduck.VBEditor.SafeComWrappers; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ChangeIntegerToLongQuickFixTests + public class ChangeIntegerToLongQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -24,17 +23,8 @@ public void IntegerDataType_QuickFixWorks_Function() @"Function Foo() As Long End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -49,17 +39,8 @@ public void IntegerDataType_QuickFixWorks_FunctionWithTypeHint() @"Function Foo&() End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -74,17 +55,8 @@ public void IntegerDataType_QuickFixWorks_PropertyGet() @"Property Get Foo() As Long End Property"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -99,17 +71,8 @@ public void IntegerDataType_QuickFixWorks_PropertyGetWithTypeHint() @"Property Get Foo&() End Property"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -124,17 +87,8 @@ public void IntegerDataType_QuickFixWorks_Parameter() @"Sub Foo(arg As Long) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -149,17 +103,8 @@ public void IntegerDataType_QuickFixWorks_ParameterWithTypeHint() @"Sub Foo(arg&) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -176,17 +121,8 @@ Dim v As Integer Dim v As Long End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -202,18 +138,8 @@ Dim v% @"Sub Foo() Dim v& End Sub"; - - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -230,17 +156,8 @@ public void IntegerDataType_QuickFixWorks_Constant() Const c As Long = 0 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -257,17 +174,8 @@ public void IntegerDataType_QuickFixWorks_ConstantWithTypeHint() Const c& = 0 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -284,17 +192,8 @@ i as Integer i as Long End Type"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -311,697 +210,454 @@ public void IntegerDataType_QuickFixWorks_UserDefinedTypeUntypedNameMember() i() as Long End Type"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_FunctionInterfaceImplementation() { - const string inputCode1 = + const string interfaceInputCode = @"Function Foo() As Integer End Function"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Function IClass1_Foo() As Integer End Function"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Function Foo() As Long End Function"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Function IClass1_Foo() As Long End Function"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_FunctionInterfaceImplementationWithTypeHints() { - const string inputCode1 = + const string interfaceInputCode = @"Function Foo%() End Function"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Function IClass1_Foo%() End Function"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Function Foo&() End Function"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Function IClass1_Foo&() End Function"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_FunctionInterfaceImplementationWithInterfaceTypeHint() { - const string inputCode1 = + const string interfaceInputCode = @"Function Foo%() End Function"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Function IClass1_Foo() As Integer End Function"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Function Foo&() End Function"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Function IClass1_Foo() As Long End Function"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_FunctionInterfaceImplementationWithImplementationTypeHint() { - const string inputCode1 = + const string interfaceInputCode = @"Function Foo() As Integer End Function"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Function IClass1_Foo%() End Function"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Function Foo() As Long End Function"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Function IClass1_Foo&() End Function"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_PropertyGetInterfaceImplementation() { - const string inputCode1 = + const string interfaceInputCode = @"Property Get Foo() As Integer End Property"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Property Get IClass1_Foo() As Integer End Property"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Property Get Foo() As Long End Property"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Property Get IClass1_Foo() As Long End Property"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_PropertyGetInterfaceImplementationWithTypeHints() { - const string inputCode1 = + const string interfaceInputCode = @"Property Get Foo%() End Property"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Property Get IClass1_Foo%() End Property"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Property Get Foo&() End Property"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Property Get IClass1_Foo&() End Property"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_PropertyGetInterfaceImplementationWithInterfaceTypeHint() { - const string inputCode1 = + const string interfaceInputCode = @"Property Get Foo%() End Property"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Property Get IClass1_Foo() As Integer End Property"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Property Get Foo&() End Property"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Property Get IClass1_Foo() As Long End Property"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_PropertyGetInterfaceImplementationWithImplementationTypeHint() { - const string inputCode1 = + const string interfaceInputCode = @"Property Get Foo() As Integer End Property"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Property Get IClass1_Foo%() End Property"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Property Get Foo() As Long End Property"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Property Get IClass1_Foo&() End Property"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_ParameterInterfaceImplementationWithTypeHints() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1%) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg1%) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1&) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg1&) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_ParameterInterfaceImplementationWithInterfaceTypeHint() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1%) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1&) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Long) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_ParameterInterfaceImplementationWithImplementationTypeHint() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1 As Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg1%) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1 As Long) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg1&) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_ParameterInterfaceImplementation() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1 As Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1 As Long) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Long) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_ParameterInterfaceImplementationWithDifferentName() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1 As Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg2 As Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1 As Long) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg2 As Long) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void IntegerDataType_QuickFixWorks_MultipleParameterInterfaceImplementation() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1 As Integer, arg2 as Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Integer, arg2 as Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1 As Long, arg2 as Integer) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Long, arg2 as Integer) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new IntegerDataTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ChangeIntegerToLongQuickFix(state).Fix( - inspectionResults.First( - result => - ((VBAParser.ArgContext)result.Context).unrestrictedIdentifier() - .identifier() - .untypedIdentifier() - .identifierValue() - .GetText() == "arg1")); + Func conditionOnResultToFix = result => + ((VBAParser.ArgContext)result.Context).unrestrictedIdentifier() + .identifier() + .untypedIdentifier() + .identifierValue() + .GetText() == "arg1"; + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterfaceSatisfyingPredicate(interfaceInputCode, implementationInputCode, + state => new IntegerDataTypeInspection(state), conditionOnResultToFix); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); + } - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ChangeIntegerToLongQuickFix(state); } - } } diff --git a/RubberduckTests/QuickFixes/ChangeProcedureToFunctionQuickFixTests.cs b/RubberduckTests/QuickFixes/ChangeProcedureToFunctionQuickFixTests.cs index a21fc8f549..7c5419071d 100644 --- a/RubberduckTests/QuickFixes/ChangeProcedureToFunctionQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ChangeProcedureToFunctionQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using NUnit.Framework; -using RubberduckTests.Mocks; -using System.Threading; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ChangeProcedureToFunctionQuickFixTests + public class ChangeProcedureToFunctionQuickFixTests : QuickFixTestBase { [Test] @@ -27,17 +25,8 @@ public void ProcedureShouldBeFunction_QuickFixWorks() Foo = arg1 End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeProcedureToFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -55,17 +44,8 @@ public void ProcedureShouldBeFunction_QuickFixWorks_NoAsTypeClauseInParam() Foo = arg1 End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeProcedureToFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -91,17 +71,8 @@ End Function Sub Goo(ByVal a As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeProcedureToFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -121,17 +92,8 @@ End Function Sub Goo(ByVal a As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeProcedureToFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -151,17 +113,8 @@ End Function Sub Goo(ByVal a As String) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeProcedureToFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -189,17 +142,8 @@ Private Function Foo(ByVal arg1 As Integer) As Integer Foo = arg1 End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ChangeProcedureToFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -227,18 +171,14 @@ Dim fizz As Integer fizz = Foo(fizz) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new ChangeProcedureToFunctionQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ChangeProcedureToFunctionQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/ConvertToProcedureQuickFixTests.cs b/RubberduckTests/QuickFixes/ConvertToProcedureQuickFixTests.cs index 9a3ad20c61..5ff6194f77 100644 --- a/RubberduckTests/QuickFixes/ConvertToProcedureQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ConvertToProcedureQuickFixTests.cs @@ -3,13 +3,15 @@ using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; using Rubberduck.VBEditor.SafeComWrappers; using RubberduckTests.Mocks; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ConvertToProcedureQuickFixTests + public class ConvertToProcedureQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -34,16 +36,8 @@ If True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new FunctionReturnValueNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new FunctionReturnValueNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -72,16 +66,8 @@ End Sub Sub goo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new FunctionReturnValueNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new FunctionReturnValueNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -124,16 +110,19 @@ Dim testObj As IFoo .AddComponent("TestModule", ComponentType.StandardModule, callSiteCode) .AddProjectToVbeBuilder().Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new FunctionReturnValueNotUsedInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); + new ConvertToProcedureQuickFix().Fix(inspectionResults.First(), rewriteSession); var component = vbe.Object.VBProjects[0].VBComponents[0]; - Assert.AreEqual(expectedInterfaceCode, state.GetRewriter(component).GetText()); + var actualCode = rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName).GetText(); + Assert.AreEqual(expectedInterfaceCode, actualCode); } } @@ -149,16 +138,8 @@ public void NonReturningFunction_QuickFixWorks_Function() @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -173,16 +154,8 @@ public void GivenFunctionNameWithTypeHint_SubNameHasNoTypeHint() @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -197,16 +170,8 @@ public void NonReturningFunction_QuickFixWorks_FunctionReturnsImplicitVariant() @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -221,16 +186,8 @@ public void NonReturningFunction_QuickFixWorks_FunctionHasVariable() @"Sub Foo(ByVal b As Boolean) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -245,16 +202,8 @@ public void GivenNonReturningPropertyGetter_QuickFixConvertsToSub() @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -269,16 +218,8 @@ public void GivenNonReturningPropertyGetWithTypeHint_QuickFixDropsTypeHint() @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -293,16 +234,8 @@ public void GivenImplicitVariantPropertyGetter_StillConvertsToSub() @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -317,17 +250,14 @@ public void GivenParameterizedPropertyGetter_QuickFixKeepsParameter() @"Sub Foo(ByVal b As Boolean) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new NonReturningFunctionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - new ConvertToProcedureQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ConvertToProcedureQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/DeclareAsExplicitVariantQuickFixTests.cs b/RubberduckTests/QuickFixes/DeclareAsExplicitVariantQuickFixTests.cs index 2111bbce0d..90d4a2cd79 100644 --- a/RubberduckTests/QuickFixes/DeclareAsExplicitVariantQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/DeclareAsExplicitVariantQuickFixTests.cs @@ -1,14 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class DeclareAsExplicitVariantQuickFixTests + public class DeclareAsExplicitVariantQuickFixTests : QuickFixTestBase { [Test] @@ -23,15 +22,8 @@ public void VariableTypeNotDeclared_QuickFixWorks_Parameter() @"Sub Foo(arg1 As Variant) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableTypeNotDeclaredInspection(state); - new DeclareAsExplicitVariantQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableTypeNotDeclaredInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -46,15 +38,8 @@ public void VariableTypeNotDeclared_QuickFixWorks_SubNameContainsParameterName() @"Sub Foo(Foo As Variant) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableTypeNotDeclaredInspection(state); - new DeclareAsExplicitVariantQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableTypeNotDeclaredInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -71,15 +56,8 @@ Dim var1 Dim var1 As Variant End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableTypeNotDeclaredInspection(state); - new DeclareAsExplicitVariantQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableTypeNotDeclaredInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -94,15 +72,8 @@ public void VariableTypeNotDeclared_QuickFixWorks_ParameterWithoutDefaultValue() @"Sub Foo(ByVal Fizz As Variant) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableTypeNotDeclaredInspection(state); - new DeclareAsExplicitVariantQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableTypeNotDeclaredInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -117,16 +88,14 @@ public void VariableTypeNotDeclared_QuickFixWorks_ParameterWithDefaultValue() @"Sub Foo(ByVal Fizz As Variant = False) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableTypeNotDeclaredInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new VariableTypeNotDeclaredInspection(state); - new DeclareAsExplicitVariantQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new DeclareAsExplicitVariantQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/IgnoreOnceQuickFixTests.cs b/RubberduckTests/QuickFixes/IgnoreOnceQuickFixTests.cs index 47a1c9413f..26969b84bf 100644 --- a/RubberduckTests/QuickFixes/IgnoreOnceQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/IgnoreOnceQuickFixTests.cs @@ -1,4 +1,6 @@ -using System.Linq; +using System; +using System.Collections.Generic; +using System.Linq; using System.Threading; using NUnit.Framework; using Rubberduck.Inspections.Concrete; @@ -7,7 +9,9 @@ using Rubberduck.VBEditor.SafeComWrappers; using RubberduckTests.Mocks; using RubberduckTests.Inspections; -using Rubberduck.Parsing.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.VBEditor; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; namespace RubberduckTests.QuickFixes { @@ -31,24 +35,8 @@ Dim foo As Double foo = Application.Pi End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("Module1", ComponentType.StandardModule, inputCode) - .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) - .Build(); - - var vbe = builder.AddProject(project).Build(); - var component = vbe.Object.SelectedVBComponent; - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ApplicationWorksheetFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ApplicationWorksheetFunctionInspection(state), TestStandardModuleInExcelVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -66,16 +54,8 @@ Public Sub Foo(ByVal arg1 As String) Let arg1 = ""test"" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new AssignedByValParameterInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new AssignedByValParameterInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -93,17 +73,8 @@ public void ConstantNotUsed_IgnoreQuickFixWorks() Const const1 As Integer = 9 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ConstantNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ConstantNotUsedInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -121,17 +92,8 @@ public void EmptyStringLiteral_IgnoreQuickFixWorks() arg1 = """" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyStringLiteralInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new EmptyStringLiteralInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -145,16 +107,8 @@ public void EncapsulatePublicField_IgnoreQuickFixWorks() @"'@Ignore EncapsulatePublicField Public fizz As Boolean"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EncapsulatePublicFieldInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new EncapsulatePublicFieldInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -179,16 +133,8 @@ Public Sub Goo() Foo ""test"" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new FunctionReturnValueNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new FunctionReturnValueNotUsedInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -211,16 +157,8 @@ Dim foo End Function "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableTypeNotDeclaredInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new VariableTypeNotDeclaredInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -240,22 +178,8 @@ Dim arr1() As Variant arr1 = Range(""A1:B2"") End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("TestProject1", "TestProject1", ProjectProtection.Unprotected) - .AddComponent("Class1", ComponentType.ClassModule, inputCode) - .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ImplicitActiveSheetReferenceInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ImplicitActiveSheetReferenceInspection(state), TestClassInExcelVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -277,22 +201,8 @@ Dim sheet As Worksheet Set sheet = Worksheets(""Sheet1"") End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("TestProject1", "TestProject1", ProjectProtection.Unprotected) - .AddComponent("Class1", ComponentType.ClassModule, inputCode) - .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ImplicitActiveWorkbookReferenceInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ImplicitActiveWorkbookReferenceInspection(state), TestClassInExcelVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -309,18 +219,8 @@ public void ImplicitByRefModifier_IgnoredQuickFixWorks() Sub Foo(arg1 As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ImplicitByRefModifierInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -342,16 +242,8 @@ Sub Foo(ByVal arg1 as Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitPublicMemberInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ImplicitPublicMemberInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -367,16 +259,8 @@ public void ImplicitVariantReturnType_IgnoreQuickFixWorks() Function Foo() End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitVariantReturnTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ImplicitVariantReturnTypeInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -395,15 +279,8 @@ public void LabelNotUsed_IgnoreQuickFixWorks() label1: End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new LineLabelNotUsedInspection(state); - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new LineLabelNotUsedInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -417,17 +294,8 @@ public void ModuleScopeDimKeyword_IgnoreQuickFixWorks() @"'@Ignore ModuleScopeDimKeyword Dim foo"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ModuleScopeDimKeywordInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ModuleScopeDimKeywordInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -447,16 +315,8 @@ Public Sub Foo() bar = ""test"" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new MoveFieldCloserToUsageInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new MoveFieldCloserToUsageInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -480,17 +340,8 @@ As _ Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new MultilineParameterInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new MultilineParameterInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -509,17 +360,8 @@ public void MultipleDeclarations_IgnoreQuickFixWorks() Dim var1 As Integer, var2 As String End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new MultipleDeclarationsInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new MultipleDeclarationsInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -535,16 +377,8 @@ public void NonReturningFunction_IgnoreQuickFixWorks() Function Foo() As Boolean End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new NonReturningFunctionInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new NonReturningFunctionInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -574,16 +408,8 @@ Dim target As Object End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObjectVariableNotSetInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ObjectVariableNotSetInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -611,22 +437,8 @@ Sub Goo(arg1 As Integer, arg1 As String) Call Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCallStatementInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - var fix = new IgnoreOnceQuickFix(state, new[] { inspection }); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToAllResults(inputCode, state => new ObsoleteCallStatementInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -640,17 +452,8 @@ public void ObsoleteCommentSyntax_IgnoreQuickFixWorks() @"'@Ignore ObsoleteCommentSyntax Rem test1"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -668,17 +471,8 @@ Error 91 Error 91 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteErrorSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ObsoleteErrorSyntaxInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -692,16 +486,8 @@ public void ObsoleteGlobal_IgnoreQuickFixWorks() @"'@Ignore ObsoleteGlobal Global var1 As Integer"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteGlobalInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ObsoleteGlobalInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -726,17 +512,8 @@ Dim var2 As Integer Let var2 = var1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteLetStatementInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ObsoleteLetStatementInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -755,21 +532,8 @@ public void ObsoleteTypeHint_IgnoreQuickFixWorks() Foo = ""test"" End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new IgnoreOnceQuickFix(state, new[] { inspection }); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ObsoleteTypeHintInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -783,17 +547,8 @@ public void OptionBaseOneSpecified_IgnoreQuickFixWorks() @"'@Ignore OptionBase Option Base 1"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new OptionBaseInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new OptionBaseInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -812,15 +567,8 @@ Sub Foo(ByRef _ arg1 As String) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ParameterCanBeByValInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -837,16 +585,8 @@ public void GivenPrivateSub_IgnoreQuickFixWorks() Private Sub Foo(ByVal arg1 as Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ParameterNotUsedInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -863,16 +603,8 @@ public void ProcedureNotUsed_IgnoreQuickFixWorks() Private Sub Foo(ByVal arg1 as Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ProcedureNotUsedInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -891,17 +623,8 @@ Private Sub Foo(ByRef arg1 As Integer) arg1 = 42 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureCanBeWrittenAsFunctionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new ProcedureCanBeWrittenAsFunctionInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -918,18 +641,8 @@ public void RedundantByRefModifier_IgnoredQuickFixWorks() Sub Foo(ByRef arg1 As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new RedundantByRefModifierInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -948,22 +661,8 @@ Dim b As New Collection Dim b As New Collection End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("MyClass", ComponentType.ClassModule, inputCode) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new SelfAssignedDeclarationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new SelfAssignedDeclarationInspection(state), TestClassVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -986,16 +685,8 @@ Dim bb As Boolean bb = b End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new UnassignedVariableUsageInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new UnassignedVariableUsageInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1024,7 +715,7 @@ Dim str As String var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[0]; - var parser = MockParser.Create(vbe.Object); + var (parser, rewritingManager) = MockParser.CreateWithRewriteManager(vbe.Object); using (var state = parser.State) { //FIXME reinstate and unignore tests @@ -1039,9 +730,12 @@ Dim str As String var inspection = new UntypedFunctionUsageInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); + new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First(), rewriteSession); + var actualCode = rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName).GetText(); + + Assert.AreEqual(expectedCode, actualCode); } } @@ -1065,13 +759,17 @@ Sub Ffffff() var component = project.Object.VBComponents[0]; var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new UseMeaningfulNameInspection(state, UseMeaningfulNameInspectionTests.GetInspectionSettings().Object); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); + + new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First(), rewriteSession); + var actualCode = rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName).GetText(); - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); + Assert.AreEqual(expectedCode, actualCode); } } @@ -1091,15 +789,8 @@ Dim var1 as Integer Dim var1 as Integer End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotAssignedInspection(state); - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new VariableNotAssignedInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1117,15 +808,8 @@ Dim var1 As String Dim var1 As String End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotUsedInspection(state); - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new VariableNotUsedInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } @@ -1142,15 +826,8 @@ public void VariableTypeNotDeclared_IgnoreQuickFixWorks() Sub Foo(arg1) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableTypeNotDeclaredInspection(state); - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new VariableTypeNotDeclaredInspection(state), TestStandardModuleVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1166,23 +843,8 @@ public void WriteOnlyProperty_IgnoreQuickFixWorks() Property Let Foo(value) End Property"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("MyClass", ComponentType.ClassModule, inputCode) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new WriteOnlyPropertyInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new WriteOnlyPropertyInspection(state), TestClassVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1210,23 +872,8 @@ If True Then EndIf End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("MyClass", ComponentType.ClassModule, inputCode) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new BooleanAssignedInIfElseInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new BooleanAssignedInIfElseInspection(state), TestClassVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1245,22 +892,8 @@ public void IgnoreQuickFixAppendsToExistingAnnotation() x = 42 End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("MyClass", ComponentType.ClassModule, inputCode) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new UndeclaredVariableInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new UndeclaredVariableInspection(state), TestClassVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1280,22 +913,8 @@ public void IgnoreQuickFixAddsAnnotationAfterComment() x = 42 End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("MyClass", ComponentType.ClassModule, inputCode) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new UndeclaredVariableInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new UndeclaredVariableInspection(state), TestClassVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1315,22 +934,8 @@ Rem comment x = 42 End Sub"; - var builder = new MockVbeBuilder(); - var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) - .AddComponent("MyClass", ComponentType.ClassModule, inputCode) - .Build(); - var component = project.Object.VBComponents[0]; - var vbe = builder.AddProject(project).Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new UndeclaredVariableInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new UndeclaredVariableInspection(state), TestClassVbeSetup); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -1354,6 +959,44 @@ line _ x = 42 End Sub"; + var actualCode = ApplyIgnoreOnceToFirstResult(inputCode, state => new UndeclaredVariableInspection(state), TestClassVbeSetup); + Assert.AreEqual(expectedCode, actualCode); + } + + private string ApplyIgnoreOnceToFirstResult( + string inputCode, + Func inspectionFactory, + Func vbeSetup) + { + var (vbe, moduleName) = vbeSetup(inputCode); + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe); + using (state) + { + var inspection = inspectionFactory(state); + var inspectionResults = InspectionResults(inspection, state); + var resultToFix = inspectionResults.First(); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); + + var quickFix = new IgnoreOnceQuickFix(state, new[] {inspection}); + quickFix.Fix(resultToFix, rewriteSession); + + return rewriteSession.CheckOutModuleRewriter(moduleName).GetText(); + } + } + + private IEnumerable InspectionResults(IInspection inspection, RubberduckParserState state) + { + if (inspection is IParseTreeInspection) + { + var inspector = InspectionsHelper.GetInspector(inspection); + return inspector.FindIssuesAsync(state, CancellationToken.None).Result; + } + + return inspection.GetInspectionResults(CancellationToken.None); + } + + private (IVBE vbe, QualifiedModuleName moduleName) TestClassVbeSetup(string inputCode) + { var builder = new MockVbeBuilder(); var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) .AddComponent("MyClass", ComponentType.ClassModule, inputCode) @@ -1361,14 +1004,63 @@ line _ var component = project.Object.VBComponents[0]; var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + return (vbe.Object, component.QualifiedModuleName); + } + + private (IVBE vbe, QualifiedModuleName moduleName) TestStandardModuleVbeSetup(string inputCode) + { + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); + return (vbe.Object, component.QualifiedModuleName); + } + + private (IVBE vbe, QualifiedModuleName moduleName) TestClassInExcelVbeSetup(string inputCode) + { + var builder = new MockVbeBuilder(); + var project = builder.ProjectBuilder("TestProject1", "TestProject1", ProjectProtection.Unprotected) + .AddComponent("Class1", ComponentType.ClassModule, inputCode) + .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) + .Build(); + var component = project.Object.VBComponents[0]; + var vbe = builder.AddProject(project).Build(); + + return (vbe.Object, component.QualifiedModuleName); + } + + private (IVBE vbe, QualifiedModuleName moduleName) TestStandardModuleInExcelVbeSetup(string inputCode) + { + var builder = new MockVbeBuilder(); + var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) + .AddComponent("Module1", ComponentType.StandardModule, inputCode) + .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) + .Build(); + + var vbe = builder.AddProject(project).Build(); + var component = vbe.Object.SelectedVBComponent; + + return (vbe.Object, component.QualifiedModuleName); + } + + private string ApplyIgnoreOnceToAllResults( + string inputCode, + Func inspectionFactory, + Func vbeSetup) + { + var (vbe, moduleName) = vbeSetup(inputCode); + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe); + using (state) { + var inspection = inspectionFactory(state); + var inspectionResults = InspectionResults(inspection, state); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); - var inspection = new UndeclaredVariableInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var quickFix = new IgnoreOnceQuickFix(state, new[] { inspection }); + + foreach (var resultToFix in inspectionResults) + { + quickFix.Fix(resultToFix, rewriteSession); + } - new IgnoreOnceQuickFix(state, new[] { inspection }).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); + return rewriteSession.CheckOutModuleRewriter(moduleName).GetText(); } } } diff --git a/RubberduckTests/QuickFixes/IntroduceLocalVariableQuickFixTests.cs b/RubberduckTests/QuickFixes/IntroduceLocalVariableQuickFixTests.cs index 3ba43ae5f4..86e48ecc89 100644 --- a/RubberduckTests/QuickFixes/IntroduceLocalVariableQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/IntroduceLocalVariableQuickFixTests.cs @@ -1,16 +1,13 @@ using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using Rubberduck.Parsing.Inspections; -using RubberduckTests.Inspections; -using RubberduckTests.Mocks; -using System.Linq; -using System.Threading; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class IntroduceLocalVariableQuickFixTests + public class IntroduceLocalVariableQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -33,7 +30,8 @@ For Each fooBar In Foo Next End Sub"; - TestInsertLocalVariableQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UndeclaredVariableInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -61,7 +59,8 @@ For Each fooBar In Foo.Items End With End Sub"; - TestInsertLocalVariableQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UndeclaredVariableInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -93,7 +92,8 @@ For Each fooBar In Foo Next End Sub"; - TestInsertLocalVariableQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UndeclaredVariableInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -117,7 +117,8 @@ For Each fooBar In Foo Next End Sub"; - TestInsertLocalVariableQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UndeclaredVariableInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -141,7 +142,8 @@ Dim fooBar As Variant Next End Sub"; - TestInsertLocalVariableQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UndeclaredVariableInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -158,21 +160,14 @@ public void IntroduceLocalVariable_QuickFixWorks_StatementSeperators() Dim bar As Collection : Dim fooBar As Variant : For Each fooBar In Foo : fooBar.Whatever : Next End Sub"; - TestInsertLocalVariableQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UndeclaredVariableInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } - private void TestInsertLocalVariableQuickFix(string expectedCode, string inputCode) - { - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - var state = MockParser.CreateAndParse(vbe.Object); - - var inspection = new UndeclaredVariableInspection(state) { Severity = CodeInspectionSeverity.Warning }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new IntroduceLocalVariableQuickFix(state).Fix(inspectionResults.First()); - var actualCode = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actualCode); + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new IntroduceLocalVariableQuickFix(); } } } \ No newline at end of file diff --git a/RubberduckTests/QuickFixes/IsMissingOnInappropriateArgumentQuickFixTests.cs b/RubberduckTests/QuickFixes/IsMissingOnInappropriateArgumentQuickFixTests.cs index 0dbabd6bab..d65dfb22ef 100644 --- a/RubberduckTests/QuickFixes/IsMissingOnInappropriateArgumentQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/IsMissingOnInappropriateArgumentQuickFixTests.cs @@ -3,14 +3,17 @@ using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; using Rubberduck.VBEditor.SafeComWrappers; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; using RubberduckTests.Inspections; using RubberduckTests.Mocks; namespace RubberduckTests.QuickFixes { [TestFixture] - public class IsMissingOnInappropriateArgumentQuickFixTests + public class IsMissingOnInappropriateArgumentQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -431,6 +434,16 @@ End Sub } private string ArrangeAndApplyQuickFix(string code) + { + return ApplyQuickFixToFirstInspectionResult(code, state => new IsMissingOnInappropriateArgumentInspection(state)); + } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new IsMissingOnInappropriateArgumentQuickFix(state); + } + + protected override IVBE TestVbe(string code, out IVBComponent component) { var builder = new MockVbeBuilder(); var project = builder.ProjectBuilder("TestProject1", "TestProject1", ProjectProtection.Unprotected) @@ -438,17 +451,8 @@ private string ArrangeAndApplyQuickFix(string code) .AddReference("VBA", MockVbeBuilder.LibraryPathVBA, 4, 2, true) .Build(); var vbe = builder.AddProject(project).Build(); - var component = project.Object.VBComponents.FirstOrDefault(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new IsMissingOnInappropriateArgumentInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new IsMissingOnInappropriateArgumentQuickFix(state).Fix(inspectionResults.First()); - return state.GetRewriter(component).GetText(); - } + component = project.Object.VBComponents.First(); + return vbe.Object; } } } diff --git a/RubberduckTests/QuickFixes/MakeSingleLineParamegerQuickFixTests.cs b/RubberduckTests/QuickFixes/MakeSingleLineParamegerQuickFixTests.cs index a7bd271652..49d59d0d3e 100644 --- a/RubberduckTests/QuickFixes/MakeSingleLineParamegerQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/MakeSingleLineParamegerQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class MakeSingleLineParamegerQuickFixTests + public class MakeSingleLineParamegerQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -28,17 +26,14 @@ As _ ByVal Var1 As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new MultilineParameterInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new MakeSingleLineParameterQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new MultilineParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new MakeSingleLineParameterQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs b/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs index b93a489064..21dfce0cdb 100644 --- a/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs @@ -4,7 +4,6 @@ using Moq; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using Rubberduck.UI; using RubberduckTests.Mocks; using Rubberduck.Interaction; @@ -29,15 +28,8 @@ Dim bar As String bar = ""test"" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new MoveFieldCloserToUsageInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new MoveFieldCloserToUsageQuickFix(vbe.Object, state, new Mock().Object).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, component.CodeModule.Content()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -72,20 +64,13 @@ Private Sub FooBar() End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new MoveFieldCloserToUsageInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new MoveFieldCloserToUsageQuickFix(vbe.Object, state, new Mock().Object).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, component.CodeModule.Content()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] - public void MoveFieldCloserToUsage_QuickFixWorks_SingleLineThenStatemente() + public void MoveFieldCloserToUsage_QuickFixWorks_SingleLineThenStatement() { const string inputCode = @"Private bar As String @@ -101,15 +86,8 @@ Dim bar As String If True Then bar = ""test"" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new MoveFieldCloserToUsageInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new MoveFieldCloserToUsageQuickFix(vbe.Object, state, new Mock().Object).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, component.CodeModule.Content()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -130,14 +108,25 @@ Dim bar As String If True Then Else bar = ""test"" End Sub"; + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode); + Assert.AreEqual(expectedCode, actualCode); + } + + private string ApplyQuickFixToFirstInspectionResult(string inputCode) + { var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new MoveFieldCloserToUsageInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var resultToFix = inspectionResults.First(); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); + var quickFix = new MoveFieldCloserToUsageQuickFix(vbe.Object, state, new Mock().Object); + + quickFix.Fix(resultToFix, rewriteSession); - new MoveFieldCloserToUsageQuickFix(vbe.Object, state, new Mock().Object).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, component.CodeModule.Content()); + return component.CodeModule.Content(); } } } diff --git a/RubberduckTests/QuickFixes/OptionExplicitQuickFixTests.cs b/RubberduckTests/QuickFixes/OptionExplicitQuickFixTests.cs index 40d3ff85e9..7ca6ee3025 100644 --- a/RubberduckTests/QuickFixes/OptionExplicitQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/OptionExplicitQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class OptionExplicitQuickFixTests + public class OptionExplicitQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -21,17 +19,14 @@ public void NotAlreadySpecified_QuickFixWorks() "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new OptionExplicitInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new OptionExplicitQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new OptionExplicitInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new OptionExplicitQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/PassParameterByReferenceQuickFixTests.cs b/RubberduckTests/QuickFixes/PassParameterByReferenceQuickFixTests.cs index bc014e453d..58f2bc0a90 100644 --- a/RubberduckTests/QuickFixes/PassParameterByReferenceQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/PassParameterByReferenceQuickFixTests.cs @@ -1,58 +1,50 @@ -using System.Linq; -using System.Threading; using NUnit.Framework; -using Moq; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using Rubberduck.VBEditor.SafeComWrappers.Abstract; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class PassParameterByReferenceQuickFixTests + public class PassParameterByReferenceQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] public void AssignedByValParameter_PassByReferenceQuickFixWorks() { - string inputCode = - @"Public Sub Foo(Optional ByVal barByVal As String = ""XYZ"") + const string inputCode = @"Public Sub Foo(Optional ByVal barByVal As String = ""XYZ"") Let barByVal = ""test"" End Sub"; - string expectedCode = - @"Public Sub Foo(Optional ByRef barByVal As String = ""XYZ"") + const string expectedCode = @"Public Sub Foo(Optional ByRef barByVal As String = ""XYZ"") Let barByVal = ""test"" End Sub"; - var quickFixResult = ApplyPassParameterByReferenceQuickFixToVBAFragment(inputCode); - Assert.AreEqual(expectedCode, quickFixResult); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new AssignedByValParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void AssignedByValParameter_PassByReferenceQuickFixWorks_ByValParameterIsOneOfSeveral() { - var inputCode = - @"Public Sub Foo(ByRef firstArg As Long, Optional ByVal barByVal As String = """", secondArg as Double) + const string inputCode = @"Public Sub Foo(ByRef firstArg As Long, Optional ByVal barByVal As String = """", secondArg as Double) Let barByVal = ""test"" End Sub"; - var expectedCode = - @"Public Sub Foo(ByRef firstArg As Long, Optional ByRef barByVal As String = """", secondArg as Double) + const string expectedCode = @"Public Sub Foo(ByRef firstArg As Long, Optional ByRef barByVal As String = """", secondArg as Double) Let barByVal = ""test"" End Sub"; - var quickFixResult = ApplyPassParameterByReferenceQuickFixToVBAFragment(inputCode); - Assert.AreEqual(expectedCode, quickFixResult); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new AssignedByValParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void AssignedByValParameter_PassByReferenceQuickFixWorks_LineContinued1() { - var inputCode = - @" + const string inputCode = @" Private Sub Foo(Optional ByVal _ bar _ As _ @@ -63,10 +55,8 @@ As _ Long) bar = 42 End Sub -" - ; - var expectedCode = - @" +"; + const string expectedCode = @" Private Sub Foo(Optional ByRef _ bar _ As _ @@ -77,26 +67,23 @@ As _ Long) bar = 42 End Sub -" - ; - var quickFixResult = ApplyPassParameterByReferenceQuickFixToVBAFragment(inputCode); - Assert.AreEqual(expectedCode, quickFixResult); +"; + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new AssignedByValParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void AssignedByValParameter_PassByReferenceQuickFixWorks_LineContinued2() { - var inputCode = - @"Private Sub Foo(ByVal barByVal As Long, ByVal _xByValbar As Long, ByVal _ + const string inputCode = @"Private Sub Foo(ByVal barByVal As Long, ByVal _xByValbar As Long, ByVal _ barTwo _ As _ Long) barTwo = 42 End Sub "; - var expectedCode = - @"Private Sub Foo(ByVal barByVal As Long, ByVal _xByValbar As Long, ByRef _ + const string expectedCode = @"Private Sub Foo(ByVal barByVal As Long, ByVal _xByValbar As Long, ByRef _ barTwo _ As _ Long) @@ -104,24 +91,22 @@ As _ End Sub "; - var quickFixResult = ApplyPassParameterByReferenceQuickFixToVBAFragment(inputCode); - Assert.AreEqual(expectedCode, quickFixResult); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new AssignedByValParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void AssignedByValParameter_PassByReferenceQuickFixWorks_LineContinued3() { - var inputCode = - @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByVal _ + const string inputCode = @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByVal _ barTwo _ As _ Long) barTwo = 42 End Sub "; - var expectedCode = - @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByRef _ + const string expectedCode = @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByRef _ barTwo _ As _ Long) @@ -129,23 +114,21 @@ As _ End Sub "; - var quickFixResult = ApplyPassParameterByReferenceQuickFixToVBAFragment(inputCode); - Assert.AreEqual(expectedCode, quickFixResult); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new AssignedByValParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void AssignedByValParameter_PassByReferenceQuickFixWorks_LineContinued4() { - var inputCode = - @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByVal barTwo _ + const string inputCode = @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByVal barTwo _ As _ Long) barTwo = 42 End Sub "; - var expectedCode = - @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByRef barTwo _ + const string expectedCode = @"Private Sub Foo(ByVal barByVal As Long, ByVal barTwoon As Long, ByRef barTwo _ As _ Long) barTwo = 42 @@ -153,8 +136,8 @@ End Sub "; - var quickFixResult = ApplyPassParameterByReferenceQuickFixToVBAFragment(inputCode); - Assert.AreEqual(expectedCode, quickFixResult); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new AssignedByValParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -162,8 +145,7 @@ End Sub public void AssignedByValParameter_PassByReferenceQuickFixWorks_LineContinued5() { //weaponized code test - var inputCode = -@"Sub DoSomething( _ + const string inputCode = @"Sub DoSomething( _ ByVal foo As Long, _ ByRef _ bar, _ @@ -175,8 +157,7 @@ ByRef barbecue _ End Sub "; - var expectedCode = -@"Sub DoSomething( _ + const string expectedCode = @"Sub DoSomething( _ ByRef foo As Long, _ ByRef _ bar, _ @@ -187,26 +168,14 @@ ByRef barbecue _ bar + foo / barbecue End Sub "; - var quickFixResult = ApplyPassParameterByReferenceQuickFixToVBAFragment(inputCode); - Assert.AreEqual(expectedCode, quickFixResult); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new AssignedByValParameterInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } - private string ApplyPassParameterByReferenceQuickFixToVBAFragment(string inputCode) - { - var vbe = BuildMockVBEStandardModuleForVBAFragment(inputCode); - using(var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new AssignedByValParameterInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new PassParameterByReferenceQuickFix(state).Fix(inspectionResults.First()); - return state.GetRewriter(vbe.Object.ActiveVBProject.VBComponents[0]).GetText(); - } - } - private Mock BuildMockVBEStandardModuleForVBAFragment(string inputCode) + protected override IQuickFix QuickFix(RubberduckParserState state) { - return MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _); + return new PassParameterByReferenceQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/PassParameterByValueQuickFixTests.cs b/RubberduckTests/QuickFixes/PassParameterByValueQuickFixTests.cs index 01b41f76f2..5b4ab08207 100644 --- a/RubberduckTests/QuickFixes/PassParameterByValueQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/PassParameterByValueQuickFixTests.cs @@ -3,13 +3,15 @@ using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; using Rubberduck.VBEditor.SafeComWrappers; using RubberduckTests.Mocks; namespace RubberduckTests.QuickFixes { [TestFixture] - public class PassParameterByValueQuickFixTests + public class PassParameterByValueQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -23,15 +25,8 @@ public void ParameterCanBeByVal_QuickFixWorks_SubNameStartsWithParamName() @"Sub foo(ByVal f) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -46,15 +41,8 @@ public void ParameterCanBeByVal_QuickFixWorks_PassedByUnspecified() @"Sub Foo(ByVal arg1 As String) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -69,15 +57,8 @@ public void ParameterCanBeByVal_QuickFixWorks_PassedByRef() @"Sub Foo(ByVal arg1 As String) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -94,15 +75,8 @@ public void ParameterCanBeByVal_QuickFixWorks_PassedByUnspecified_MultilineParam ByVal arg1 As String) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -119,15 +93,8 @@ public void ParameterCanBeByVal_QuickFixWorks_PassedByRef_MultilineParameter() arg1 As String) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -178,15 +145,22 @@ Private Sub IClass1_DoSomething(ByVal a As Integer, ByRef b As Integer) var component3 = project.Object.VBComponents["Class2"]; var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewriteManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); + var rewriteSession = rewriteManager.CheckOutCodePaneSession(); + + new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First(), rewriteSession); - Assert.AreEqual(expectedCode1, state.GetRewriter(component1).GetText()); - Assert.AreEqual(expectedCode2, state.GetRewriter(component2).GetText()); - Assert.AreEqual(expectedCode3, state.GetRewriter(component3).GetText()); + var actualCode1 = rewriteSession.CheckOutModuleRewriter(component1.QualifiedModuleName).GetText(); + var actualCode2 = rewriteSession.CheckOutModuleRewriter(component2.QualifiedModuleName).GetText(); + var actualCode3 = rewriteSession.CheckOutModuleRewriter(component3.QualifiedModuleName).GetText(); + + Assert.AreEqual(expectedCode1, actualCode1); + Assert.AreEqual(expectedCode2, actualCode2); + Assert.AreEqual(expectedCode3, actualCode3); } } @@ -236,15 +210,22 @@ Private Sub abc_Foo(ByRef a As Integer, ByVal b As Integer) var component3 = project.Object.VBComponents["Class3"]; var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewriteManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); + var rewriteSession = rewriteManager.CheckOutCodePaneSession(); + + new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First(), rewriteSession); + + var actualCode1 = rewriteSession.CheckOutModuleRewriter(component1.QualifiedModuleName).GetText(); + var actualCode2 = rewriteSession.CheckOutModuleRewriter(component2.QualifiedModuleName).GetText(); + var actualCode3 = rewriteSession.CheckOutModuleRewriter(component3.QualifiedModuleName).GetText(); - Assert.AreEqual(expectedCode1, state.GetRewriter(component1).GetText()); - Assert.AreEqual(expectedCode2, state.GetRewriter(component2).GetText()); - Assert.AreEqual(expectedCode3, state.GetRewriter(component3).GetText()); + Assert.AreEqual(expectedCode1, actualCode1); + Assert.AreEqual(expectedCode2, actualCode2); + Assert.AreEqual(expectedCode3, actualCode3); } } @@ -263,15 +244,8 @@ Debug.Print foo Debug.Print foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } //https://github.com/rubberduck-vba/Rubberduck/issues/2408 @@ -289,15 +263,8 @@ Debug.Print foo Debug.Print foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } //https://github.com/rubberduck-vba/Rubberduck/issues/2408 @@ -325,16 +292,14 @@ Byte _ Debug.Print foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ParameterCanBeByValInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new ParameterCanBeByValInspection(state); - new PassParameterByValueQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new PassParameterByValueQuickFix(state); } - } } diff --git a/RubberduckTests/QuickFixes/QuickFixBaseTests.cs b/RubberduckTests/QuickFixes/QuickFixBaseTests.cs index f277002bb1..e44e242864 100644 --- a/RubberduckTests/QuickFixes/QuickFixBaseTests.cs +++ b/RubberduckTests/QuickFixes/QuickFixBaseTests.cs @@ -16,7 +16,7 @@ public void QuickFixBase_Register() var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); using (var state = MockParser.CreateAndParse(vbe.Object)) { - var quickFix = new RemoveCommentQuickFix(state); + var quickFix = new RemoveCommentQuickFix(); quickFix.RegisterInspections(typeof(EmptyStringLiteralInspection)); Assert.IsTrue(quickFix.SupportedInspections.Contains(typeof(EmptyStringLiteralInspection))); @@ -30,7 +30,7 @@ public void QuickFixBase_Unregister() var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); using (var state = MockParser.CreateAndParse(vbe.Object)) { - var quickFix = new RemoveCommentQuickFix(state); + var quickFix = new RemoveCommentQuickFix(); quickFix.RemoveInspections(quickFix.SupportedInspections.ToArray()); Assert.IsFalse(quickFix.SupportedInspections.Any()); diff --git a/RubberduckTests/QuickFixes/QuickFixProviderTests.cs b/RubberduckTests/QuickFixes/QuickFixProviderTests.cs index 5c78ae2a9a..e746937caf 100644 --- a/RubberduckTests/QuickFixes/QuickFixProviderTests.cs +++ b/RubberduckTests/QuickFixes/QuickFixProviderTests.cs @@ -1,7 +1,6 @@ using System.Linq; using System.Threading; using NUnit.Framework; -using Rubberduck.Inspections; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; using Rubberduck.Parsing.Inspections.Abstract; @@ -52,7 +51,7 @@ Dim str As String var inspector = InspectionsHelper.GetInspector(inspection); var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - var quickFixProvider = new QuickFixProvider(state, new IQuickFix[] { new ReplaceEmptyStringLiteralStatementQuickFix(state) }); + var quickFixProvider = new QuickFixProvider(state, new IQuickFix[] { new ReplaceEmptyStringLiteralStatementQuickFix() }); Assert.AreEqual(1, quickFixProvider.QuickFixes(inspectionResults.First()).Count()); } } @@ -73,7 +72,7 @@ public void ResultDisablesFix() var inspection = new ConstantNotUsedInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - var quickFixProvider = new QuickFixProvider(state, new IQuickFix[] { new RemoveUnusedDeclarationQuickFix(state) }); + var quickFixProvider = new QuickFixProvider(state, new IQuickFix[] { new RemoveUnusedDeclarationQuickFix() }); var result = inspectionResults.First(); result.Properties.DisableFixes = nameof(RemoveUnusedDeclarationQuickFix); diff --git a/RubberduckTests/QuickFixes/QuickFixTestBase.cs b/RubberduckTests/QuickFixes/QuickFixTestBase.cs new file mode 100644 index 0000000000..13cf392308 --- /dev/null +++ b/RubberduckTests/QuickFixes/QuickFixTestBase.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Rewriter; +using Rubberduck.Parsing.VBA; +using Rubberduck.VBEditor; +using Rubberduck.VBEditor.SafeComWrappers; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; +using RubberduckTests.Inspections; +using RubberduckTests.Mocks; + +namespace RubberduckTests.QuickFixes +{ + public abstract class QuickFixTestBase + { + protected abstract IQuickFix QuickFix(RubberduckParserState state); + + protected virtual IVBE TestVbe(string code, out IVBComponent component) + { + return MockVbeBuilder.BuildFromSingleStandardModule(code, out component).Object; + } + + protected string ApplyQuickFixToFirstInspectionResult(string inputCode, + Func inspectionFactory) + { + return ApplyQuickFixToAppropriateInspectionResults( + inputCode, + inspectionFactory, + ApplyToFirstResult); + } + + private string ApplyQuickFixToAppropriateInspectionResults(string inputCode, + Func inspectionFactory, + Action, IRewriteSession> applyQuickFix) + { + var vbe = TestVbe(inputCode, out var component); + var (state, rewriteManager) = MockParser.CreateAndParseWithRewritingManager(vbe); + using (state) + { + var inspection = inspectionFactory(state); + var inspectionResults = InspectionResults(inspection, state); + var rewriteSession = rewriteManager.CheckOutCodePaneSession(); + + var quickFix = QuickFix(state); + + applyQuickFix(quickFix, inspectionResults, rewriteSession); + + return rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName).GetText(); + } + } + + private IEnumerable InspectionResults(IInspection inspection, RubberduckParserState state) + { + if (inspection is IParseTreeInspection) + { + var inspector = InspectionsHelper.GetInspector(inspection); + return inspector.FindIssuesAsync(state, CancellationToken.None).Result; + } + + return inspection.GetInspectionResults(CancellationToken.None); + } + + private void ApplyToFirstResult(IQuickFix quickFix, IEnumerable inspectionResults, IRewriteSession rewriteSession) + { + var resultToFix = inspectionResults.First(); + quickFix.Fix(resultToFix, rewriteSession); + } + + protected string ApplyQuickFixToAllInspectionResults(string inputCode, + Func inspectionFactory) + { + return ApplyQuickFixToAppropriateInspectionResults( + inputCode, + inspectionFactory, + ApplyToAllResults); + } + + private void ApplyToAllResults(IQuickFix quickFix, IEnumerable inspectionResults, IRewriteSession rewriteSession) + { + foreach (var inspectionResult in inspectionResults) + { + quickFix.Fix(inspectionResult, rewriteSession); + } + } + + + + protected (string interfaceCode, string implementationCode) ApplyQuickFixToFirstInspectionResultForImplementedInterface( + string interfaceInputCode, + string implementationInputCode, + Func inspectionFactory) + { + return ApplyQuickFixToAppropriateInspectionResultsForImplementedInterface( + interfaceInputCode, + implementationInputCode, + inspectionFactory, + ApplyToFirstResult); + } + + private (string interfaceCode, string implementationCode) ApplyQuickFixToAppropriateInspectionResultsForImplementedInterface( + string interfaceCode, + string implementationCode, + Func inspectionFactory, + Action, IRewriteSession> applyQuickFix) + { + var (vbe, interfaceModuleName, implementationModuleName) = TestVbeForImplementedInterface(interfaceCode, implementationCode); + + var (state, rewriteManager) = MockParser.CreateAndParseWithRewritingManager(vbe); + using (state) + { + var inspection = inspectionFactory(state); + var inspectionResults = InspectionResults(inspection, state); + var rewriteSession = rewriteManager.CheckOutCodePaneSession(); + + var quickFix = QuickFix(state); + + applyQuickFix(quickFix, inspectionResults, rewriteSession); + + var actualInterfaceCode = rewriteSession.CheckOutModuleRewriter(interfaceModuleName).GetText(); + var actualImplementationCode = rewriteSession.CheckOutModuleRewriter(implementationModuleName).GetText(); + + return (actualInterfaceCode, actualImplementationCode); + } + } + + protected virtual (IVBE vbe, QualifiedModuleName interfaceModuleName, QualifiedModuleName implemetingModuleName) TestVbeForImplementedInterface(string interfaceCode, string implementationCode) + { + var builder = new MockVbeBuilder(); + var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) + .AddComponent("IClass1", ComponentType.ClassModule, interfaceCode) + .AddComponent("Class1", ComponentType.ClassModule, implementationCode) + .AddProjectToVbeBuilder() + .Build().Object; + + var project = vbe.VBProjects[0]; + var interfaceComponent = project.VBComponents[0]; + var implementationComponent = project.VBComponents[1]; + + return (vbe, interfaceComponent.QualifiedModuleName, implementationComponent.QualifiedModuleName); + } + + protected (string interfaceCode, string implementationCode) ApplyQuickFixToFirstInspectionResultForImplementedInterfaceSatisfyingPredicate( + string interfaceInputCode, + string implementationInputCode, + Func inspectionFactory, + Func predicate) + { + var applyQuickFix = ApplyToFirstResultSatisfyingPredicateAction(predicate); + return ApplyQuickFixToAppropriateInspectionResultsForImplementedInterface( + interfaceInputCode, + implementationInputCode, + inspectionFactory, + applyQuickFix); + } + + private Action, IRewriteSession> ApplyToFirstResultSatisfyingPredicateAction(Func predicate) + { + return (quickFix, inspectionResults, rewriteSession) => + quickFix.Fix(inspectionResults.First(predicate), rewriteSession); + } + + protected string ApplyQuickFixToFirstInspectionResultSatisfyingPredicate( + string code, + Func inspectionFactory, + Func predicate) + { + var applyQuickFix = ApplyToFirstResultSatisfyingPredicateAction(predicate); + return ApplyQuickFixToAppropriateInspectionResults( + code, + inspectionFactory, + applyQuickFix); + } + } +} \ No newline at end of file diff --git a/RubberduckTests/QuickFixes/RemoveCommentQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveCommentQuickFixTests.cs index 8427b3b566..9d5481e0df 100644 --- a/RubberduckTests/QuickFixes/RemoveCommentQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveCommentQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveCommentQuickFixTests + public class RemoveCommentQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -21,17 +19,8 @@ public void ObsoleteCommentSyntax_QuickFixWorks_RemoveComment() const string expectedCode = @""; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveCommentQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -45,17 +34,8 @@ public void ObsoleteCommentSyntax_QuickFixWorks_RemoveCommentHasContinuation() const string expectedCode = @""; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveCommentQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -68,17 +48,8 @@ public void ObsoleteCommentSyntax_QuickFixWorks_RemoveComment_LineHasCode() const string expectedCode = @"Dim Foo As Integer: "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveCommentQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -92,18 +63,14 @@ public void ObsoleteCommentSyntax_QuickFixWorks_RemoveComment_LineHasCodeAndCont const string expectedCode = @"Dim Foo As Integer: "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new RemoveCommentQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveCommentQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/RemoveDuplicatedAnnotationQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveDuplicatedAnnotationQuickFixTests.cs index 3ad52cdb6d..7241bc155b 100644 --- a/RubberduckTests/QuickFixes/RemoveDuplicatedAnnotationQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveDuplicatedAnnotationQuickFixTests.cs @@ -1,15 +1,15 @@ -using System.Linq; -using System.Threading; +using System; using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; using Rubberduck.Parsing.Annotations; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveDuplicatedAnnotationQuickFixTests + public class RemoveDuplicatedAnnotationQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -26,15 +26,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -53,15 +46,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -80,15 +66,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -105,15 +84,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -130,15 +102,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -157,15 +122,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -184,15 +142,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -209,15 +160,8 @@ Public Sub Foo Public Sub Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new DuplicatedAnnotationInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -238,16 +182,15 @@ Public Sub Foo '@TestMethod Public Sub Foo End Sub"; + Func conditionToFix = result => result.Properties.AnnotationType == AnnotationType.Obsolete; + var actualCode = ApplyQuickFixToFirstInspectionResultSatisfyingPredicate(inputCode, state => new DuplicatedAnnotationInspection(state), conditionToFix); + Assert.AreEqual(expectedCode, actualCode); + } - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new DuplicatedAnnotationInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - new RemoveDuplicatedAnnotationQuickFix(state).Fix(inspectionResults.First(result => result.Properties.AnnotationType == AnnotationType.Obsolete)); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveDuplicatedAnnotationQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RemoveEmptyElseBlockQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveEmptyElseBlockQuickFixTests.cs index cfb0f2965d..6f74ae03b4 100644 --- a/RubberduckTests/QuickFixes/RemoveEmptyElseBlockQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveEmptyElseBlockQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; -using RubberduckTests.Mocks; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveEmptyElseBlockQuickFixTests + public class RemoveEmptyElseBlockQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -28,19 +26,14 @@ If True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new EmptyElseBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var actualResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyElseBlockQuickFix(state).Fix(actualResults.First()); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyElseBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - string actualRewrite = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actualRewrite); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveEmptyElseBlockQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RemoveEmptyIfBlockQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveEmptyIfBlockQuickFixTests.cs index d45ba2750f..dce1c00c4f 100644 --- a/RubberduckTests/QuickFixes/RemoveEmptyIfBlockQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveEmptyIfBlockQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveEmptyIfBlockQuickFixTests + public class RemoveEmptyIfBlockQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -25,18 +23,8 @@ End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -59,18 +47,8 @@ End Sub Sub Bar() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -88,18 +66,8 @@ End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -128,18 +96,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -168,18 +126,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -209,18 +157,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -246,18 +184,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -285,18 +213,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -327,19 +245,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - var rewrittenCode = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, rewrittenCode); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -365,19 +272,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - var rewrittenCode = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, rewrittenCode); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -402,18 +298,8 @@ Dim d End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -438,18 +324,8 @@ Dim b End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -472,18 +348,8 @@ Dim d End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -503,18 +369,8 @@ If Not True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -534,18 +390,8 @@ If True <> True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -565,18 +411,8 @@ End If End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -596,18 +432,8 @@ End If End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -627,18 +453,8 @@ If True > True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -658,18 +474,8 @@ End If End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -689,18 +495,8 @@ If True < True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -720,18 +516,8 @@ If True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -751,18 +537,8 @@ End If End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -782,18 +558,8 @@ If True Or True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -813,18 +579,8 @@ If True And True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -844,18 +600,8 @@ If Not (True Xor True) Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -875,18 +621,8 @@ If True Or True And True And True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -906,18 +642,8 @@ If True And True And True And True Then End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -937,18 +663,8 @@ End If End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -968,18 +684,14 @@ End If End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new EmptyIfBlockInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyIfBlockInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - new RemoveEmptyIfBlockQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveEmptyIfBlockQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RemoveExplicitByRefModifierQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveExplicitByRefModifierQuickFixTests.cs index 31befc14ce..d14c9df093 100644 --- a/RubberduckTests/QuickFixes/RemoveExplicitByRefModifierQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveExplicitByRefModifierQuickFixTests.cs @@ -1,18 +1,15 @@ -using System.Linq; -using System.Threading; +using System; using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; using Rubberduck.Parsing.Grammar; -using Rubberduck.VBEditor.SafeComWrappers; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; -using Rubberduck.Parsing.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveExplicitByRefModifierQuickFixTests + public class RemoveExplicitByRefModifierQuickFixTests : QuickFixTestBase { [Test] @@ -27,18 +24,8 @@ public void RedundantByRefModifier_QuickFixWorks_OptionalParameter() @"Sub Foo(Optional arg1 As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -59,18 +46,8 @@ bar _ bar = 1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -89,18 +66,8 @@ public void RedundantByRefModifier_QuickFixWorks_LineContinuation() bar = 1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -121,172 +88,107 @@ bar _ bar = 1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void RedundantByRefModifier_QuickFixWorks_InterfaceImplementation() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(ByRef arg1 As Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(ByRef arg1 As Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1 As Integer) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Integer) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new RedundantByRefModifierInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void RedundantByRefModifier_QuickFixWorks_InterfaceImplementationDiffrentParameterName() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(ByRef arg1 As Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(ByRef arg2 As Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1 As Integer) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg2 As Integer) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new RedundantByRefModifierInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void RedundantByRefModifier_QuickFixWorks_InterfaceImplementationWithMultipleParameters() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(ByRef arg1 As Integer, ByRef arg2 as Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(ByRef arg1 As Integer, ByRef arg2 as Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(arg1 As Integer, ByRef arg2 as Integer) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Integer, ByRef arg2 as Integer) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitByRefModifierQuickFix(state).Fix( - inspectionResults.First( - result => - ((VBAParser.ArgContext)result.Context).unrestrictedIdentifier() - .identifier() - .untypedIdentifier() - .identifierValue() - .GetText() == "arg1")); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + Func conditionOnResultToFix = result => + ((VBAParser.ArgContext)result.Context).unrestrictedIdentifier() + .identifier() + .untypedIdentifier() + .identifierValue() + .GetText() == "arg1"; + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterfaceSatisfyingPredicate(interfaceInputCode, implementationInputCode, + state => new RedundantByRefModifierInspection(state), conditionOnResultToFix); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] @@ -301,19 +203,14 @@ public void RedundantByRefModifier_QuickFixWorks_PassByRef() @"Sub Foo(arg1 As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantByRefModifierInspection(state) { Severity = CodeInspectionSeverity.Hint }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - new RemoveExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveExplicitByRefModifierQuickFix(state); } - } } diff --git a/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs index fdd4209b2a..b50d2ba040 100644 --- a/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveExplicitCallStatementQuickFixTests.cs @@ -1,14 +1,13 @@ using NUnit.Framework; -using RubberduckTests.Mocks; -using System.Threading; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveExplicitCallStatementQuickFixTests + public class RemoveExplicitCallStatementQuickFixTests : QuickFixTestBase { [Test] @@ -33,22 +32,14 @@ Sub Goo(arg1 As Integer, arg1 As String) Foo End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ObsoleteCallStatementInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - var fix = new RemoveExplicitCallStatementQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteCallStatementInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveExplicitCallStatementQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/RemoveExplicitLetStatementQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveExplicitLetStatementQuickFixTests.cs index 982045b730..c90fe12f6e 100644 --- a/RubberduckTests/QuickFixes/RemoveExplicitLetStatementQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveExplicitLetStatementQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using NUnit.Framework; -using RubberduckTests.Mocks; -using System.Threading; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveExplicitLetStatementQuickFixTests + public class RemoveExplicitLetStatementQuickFixTests : QuickFixTestBase { [Test] @@ -32,17 +30,14 @@ Dim var2 As Integer var2 = var1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ObsoleteLetStatementInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveExplicitLetStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteLetStatementInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveExplicitLetStatementQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/RemoveLocalErrorQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveLocalErrorQuickFixTests.cs index e76341f226..d5529316df 100644 --- a/RubberduckTests/QuickFixes/RemoveLocalErrorQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveLocalErrorQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using NUnit.Framework; -using RubberduckTests.Mocks; -using System.Threading; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveLocalErrorQuickFixTests + public class RemoveLocalErrorQuickFixTests : QuickFixTestBase { [TestCase("On Local Error GoTo 0")] [TestCase("On Local Error GoTo 1")] @@ -26,16 +24,14 @@ public void OptionBaseZeroStatement_QuickFixWorks_RemoveStatement(string stmt) {stmt.Replace("Local ", "")} End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new OnLocalErrorInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new OnLocalErrorInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } + - new RemoveLocalErrorQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveLocalErrorQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RemoveOptionBaseStatementQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveOptionBaseStatementQuickFixTests.cs index dd924378fa..7e0082f69e 100644 --- a/RubberduckTests/QuickFixes/RemoveOptionBaseStatementQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveOptionBaseStatementQuickFixTests.cs @@ -1,104 +1,69 @@ -using System.Linq; -using NUnit.Framework; -using RubberduckTests.Mocks; -using System.Threading; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveOptionBaseStatementQuickFixTests + public class RemoveOptionBaseStatementQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] public void OptionBaseZeroStatement_QuickFixWorks_RemoveStatement() { - var inputCode = "Option Base 0"; - var expectedCode = string.Empty; + const string inputCode = "Option Base 0"; + const string expectedCode = ""; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new RedundantOptionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveOptionBaseStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantOptionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void OptionBaseZeroStatement_QuickFixWorks_RemoveStatement_MultipleLines() { - var inputCode = - @"Option _ + const string inputCode = @"Option _ Base _ 0"; - var expectedCode = string.Empty; - - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + const string expectedCode = ""; - var inspection = new RedundantOptionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveOptionBaseStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantOptionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void OptionBaseZeroStatement_QuickFixWorks_RemoveStatement_InstructionSeparator() { - var inputCode = "Option Explicit: Option Base 0: Option Base 1"; - - var expectedCode = "Option Explicit: : Option Base 1"; + const string inputCode = "Option Explicit: Option Base 0: Option Base 1"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + const string expectedCode = "Option Explicit: : Option Base 1"; - var inspection = new RedundantOptionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveOptionBaseStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantOptionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void OptionBaseZeroStatement_QuickFixWorks_RemoveStatement_InstructionSeparatorAndMultipleLines() { - var inputCode = - @"Option Explicit: Option _ + const string inputCode = @"Option Explicit: Option _ Base _ 0: Option Base 1"; - var expectedCode = "Option Explicit: : Option Base 1"; + const string expectedCode = "Option Explicit: : Option Base 1"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new RedundantOptionInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new RedundantOptionInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new RemoveOptionBaseStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveOptionBaseStatementQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/RemoveStepOneQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveStepOneQuickFixTests.cs index b7a1d55c2a..b91c78038c 100644 --- a/RubberduckTests/QuickFixes/RemoveStepOneQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveStepOneQuickFixTests.cs @@ -1,16 +1,13 @@ using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using Rubberduck.Parsing.Inspections; -using RubberduckTests.Inspections; -using RubberduckTests.Mocks; -using System.Linq; -using System.Threading; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveStepOneQuickFixTests + public class RemoveStepOneQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -28,7 +25,8 @@ public void StepOne_QuickFixWorks_Remove() Next End Sub"; - TestStepOneQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new StepOneIsRedundantInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -51,20 +49,14 @@ public void StepOne_QuickFixWorks_NestedLoops() Next End Sub"; - TestStepOneQuickFix(expectedCode, inputCode); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new StepOneIsRedundantInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } - private void TestStepOneQuickFix(string expectedCode, string inputCode) - { - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - var state = MockParser.CreateAndParse(vbe.Object); - - var inspection = new StepOneIsRedundantInspection(state) { Severity = CodeInspectionSeverity.Warning }; - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new RemoveStepOneQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveStepOneQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RemoveStopKeywordQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveStopKeywordQuickFixTests.cs index f230f6b4b4..6b6a14b434 100644 --- a/RubberduckTests/QuickFixes/RemoveStopKeywordQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveStopKeywordQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using NUnit.Framework; -using RubberduckTests.Mocks; -using System.Threading; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveStopKeywordQuickFixTests + public class RemoveStopKeywordQuickFixTests : QuickFixTestBase { [Test] @@ -26,17 +24,8 @@ public void StopKeyword_QuickFixWorks_RemoveKeyword() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new StopKeywordInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveStopKeywordQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new StopKeywordInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -47,18 +36,13 @@ public void StopKeyword_QuickFixWorks_RemoveKeyword_InstructionSeparator() var expectedCode = "Sub Foo(): : End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new StopKeywordInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RemoveStopKeywordQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new StopKeywordInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveStopKeywordQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/RemoveTypeHintsQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveTypeHintsQuickFixTests.cs index 1f6e30fe10..ba47d4dce1 100644 --- a/RubberduckTests/QuickFixes/RemoveTypeHintsQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveTypeHintsQuickFixTests.cs @@ -1,14 +1,15 @@ -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; using RubberduckTests.Mocks; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveTypeHintsQuickFixTests + public class RemoveTypeHintsQuickFixTests : QuickFixTestBase { [Test] @@ -21,21 +22,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Field_LongTypeHint() const string expectedCode = @"Public Foo As Long"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -48,21 +36,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Field_IntegerTypeHint() const string expectedCode = @"Public Foo As Integer"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -75,21 +50,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Field_DoubleTypeHint() const string expectedCode = @"Public Foo As Double"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -102,21 +64,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Field_SingleTypeHint() const string expectedCode = @"Public Foo As Single"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -129,21 +78,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Field_DecimalTypeHint() const string expectedCode = @"Public Foo As Currency"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -156,21 +92,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Field_StringTypeHint() const string expectedCode = @"Public Foo As String"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -187,21 +110,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Function_StringTypeHint() Foo = ""test"" End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -218,21 +128,8 @@ public void ObsoleteTypeHint_QuickFixWorks_PropertyGet_StringTypeHint() Foo = ""test"" End Property"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -249,21 +146,8 @@ public void ObsoleteTypeHint_QuickFixWorks_Parameter_StringTypeHint() Foo = ""test"" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -280,21 +164,8 @@ Dim buzz$ Dim buzz As String End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -311,22 +182,14 @@ public void ObsoleteTypeHint_QuickFixWorks_Constant_StringTypeHint() Const buzz As String = """" End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteTypeHintInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObsoleteTypeHintInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var fix = new RemoveTypeHintsQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveTypeHintsQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs index c5e18d5f81..824745fec6 100644 --- a/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs @@ -1,14 +1,14 @@ -using System.Linq; -using System.Threading; +using System; using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveUnassignedIdentifierQuickFixTests + public class RemoveUnassignedIdentifierQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -23,15 +23,8 @@ Dim var1 as Integer @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotAssignedInspection(state); - new RemoveUnassignedIdentifierQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotAssignedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -50,15 +43,8 @@ as _ @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotAssignedInspection(state); - new RemoveUnassignedIdentifierQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotAssignedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -75,16 +61,8 @@ public void UnassignedVariable_MultipleVariablesOnSingleLine_QuickFixWorks() Dim var1 As Integer End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotAssignedInspection(state); - new RemoveUnassignedIdentifierQuickFix(state).Fix( - inspection.GetInspectionResults(CancellationToken.None).Single(s => s.Target.IdentifierName == "var2")); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotAssignedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -102,16 +80,15 @@ var2 As Boolean Dim var1 As Integer End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + Func conditionToFix = result => result.Target.IdentifierName == "var2"; + var actualCode = ApplyQuickFixToFirstInspectionResultSatisfyingPredicate(inputCode, state => new VariableNotAssignedInspection(state), conditionToFix); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new VariableNotAssignedInspection(state); - new RemoveUnassignedIdentifierQuickFix(state).Fix( - inspection.GetInspectionResults(CancellationToken.None).Single(s => s.Target.IdentifierName == "var2")); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveUnassignedIdentifierQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RemoveUnassignedVariableUsageQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveUnassignedVariableUsageQuickFixTests.cs index 63c15f433a..f0b90d7d6c 100644 --- a/RubberduckTests/QuickFixes/RemoveUnassignedVariableUsageQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveUnassignedVariableUsageQuickFixTests.cs @@ -1,14 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveUnassignedVariableUsageQuickFixTests + public class RemoveUnassignedVariableUsageQuickFixTests : QuickFixTestBase { [Test] @@ -29,15 +28,14 @@ Dim bb As Boolean End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnassignedVariableUsageInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UnassignedVariableUsageInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } + - new RemoveUnassignedVariableUsageQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveUnassignedVariableUsageQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RemoveUnusedDeclarationQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveUnusedDeclarationQuickFixTests.cs index 1b9915ec24..5638bee38d 100644 --- a/RubberduckTests/QuickFixes/RemoveUnusedDeclarationQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveUnusedDeclarationQuickFixTests.cs @@ -1,14 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RemoveUnusedDeclarationQuickFixTests + public class RemoveUnusedDeclarationQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -23,19 +22,8 @@ public void ConstantNotUsed_QuickFixWorks() @"Public Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ConstantNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveUnusedDeclarationQuickFix(state).Fix(inspectionResults.First()); - - var rewriter = state.GetRewriter(component); - var rewrittenCode = rewriter.GetText(); - Assert.AreEqual(expectedCode, rewrittenCode); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ConstantNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } @@ -53,16 +41,8 @@ public void LabelNotUsed_QuickFixWorks() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new LineLabelNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new LineLabelNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -85,16 +65,8 @@ dim var1 as variant goto label1: End Sub"; ; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new LineLabelNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new LineLabelNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -107,18 +79,8 @@ public void ProcedureNotUsed_QuickFixWorks() const string expectedCode = @""; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ProcedureNotUsedInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new RemoveUnusedDeclarationQuickFix(state).Fix(inspectionResults.First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ProcedureNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -134,16 +96,8 @@ Dim var1 As String @"Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } @@ -162,16 +116,8 @@ Dim var1 As String End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -188,16 +134,8 @@ Dim var1 As String ' Comment ' Comment End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -220,16 +158,8 @@ Dim var2 As String Foo = var2 End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } @@ -249,16 +179,8 @@ Dim var1 As String ' Comment End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -281,16 +203,8 @@ Dim var2 As String Foo = var2 End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new VariableNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -313,17 +227,14 @@ Dim var2 As String Foo = var2 End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotUsedInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new VariableNotUsedInspection(state); - new RemoveUnusedDeclarationQuickFix(state).Fix(inspection.GetInspectionResults(CancellationToken.None).First()); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RemoveUnusedDeclarationQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs index 3f39c47ad9..3440580bbd 100644 --- a/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs @@ -4,7 +4,6 @@ using Moq; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using Rubberduck.UI; using RubberduckTests.Mocks; using Rubberduck.Interaction; @@ -28,13 +27,16 @@ Private Sub Foo() End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using(var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new ParameterNotUsedInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); new RemoveUnusedParameterQuickFix(vbe.Object, state, new Mock().Object).Fix( - inspectionResults.First()); + inspectionResults.First(), rewriteSession); + Assert.AreEqual(expectedCode, component.CodeModule.Content()); } } diff --git a/RubberduckTests/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFixTests.cs b/RubberduckTests/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFixTests.cs index 7b2f1595a4..05fb6f3c73 100644 --- a/RubberduckTests/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ReplaceEmptyStringLiteralStatementQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using NUnit.Framework; -using RubberduckTests.Mocks; -using System.Threading; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ReplaceEmptyStringLiteralStatementQuickFixTests + public class ReplaceEmptyStringLiteralStatementQuickFixTests : QuickFixTestBase { [Test] [Category("Inspections")] @@ -25,18 +23,13 @@ public void EmptyStringLiteral_QuickFixWorks() arg1 = vbNullString End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new EmptyStringLiteralInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceEmptyStringLiteralStatementQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new EmptyStringLiteralInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ReplaceEmptyStringLiteralStatementQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/ReplaceGlobalModifierQuickFixTests.cs b/RubberduckTests/QuickFixes/ReplaceGlobalModifierQuickFixTests.cs index 3d7181b4a0..3918ff935e 100644 --- a/RubberduckTests/QuickFixes/ReplaceGlobalModifierQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ReplaceGlobalModifierQuickFixTests.cs @@ -1,15 +1,14 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ReplaceGlobalModifierQuickFixTests + public class ReplaceGlobalModifierQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -21,16 +20,14 @@ public void ObsoleteGlobal_QuickFixWorks() const string expectedCode = @"Public var1 As Integer"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ObsoleteGlobalInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new ReplaceGlobalModifierQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteGlobalInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ReplaceGlobalModifierQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFixTests.cs b/RubberduckTests/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFixTests.cs index 5c4e7c8258..24e21709b4 100644 --- a/RubberduckTests/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ReplaceIfElseWithConditionalStatementQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ReplaceIfElseWithConditionalStatementQuickFixTests + public class ReplaceIfElseWithConditionalStatementQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -31,17 +29,8 @@ Dim d As Boolean d = True End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new BooleanAssignedInIfElseInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceIfElseWithConditionalStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new BooleanAssignedInIfElseInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -64,17 +53,8 @@ Dim d As Boolean d = True Or False And False Xor True End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new BooleanAssignedInIfElseInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceIfElseWithConditionalStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new BooleanAssignedInIfElseInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -97,17 +77,8 @@ Dim d As Boolean d = Not (True) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new BooleanAssignedInIfElseInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceIfElseWithConditionalStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new BooleanAssignedInIfElseInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -128,17 +99,14 @@ If True Then Fizz.Buzz = True End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new BooleanAssignedInIfElseInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new BooleanAssignedInIfElseInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new ReplaceIfElseWithConditionalStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ReplaceIfElseWithConditionalStatementQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/ReplaceObsoleteCommentMarkerQuickFixTests.cs b/RubberduckTests/QuickFixes/ReplaceObsoleteCommentMarkerQuickFixTests.cs index 6aaa16560a..262fff29a1 100644 --- a/RubberduckTests/QuickFixes/ReplaceObsoleteCommentMarkerQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ReplaceObsoleteCommentMarkerQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ReplaceObsoleteCommentMarkerQuickFixTests + public class ReplaceObsoleteCommentMarkerQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -21,17 +19,8 @@ public void ObsoleteCommentSyntax_QuickFixWorks_UpdateComment() const string expectedCode = @"' test1"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceObsoleteCommentMarkerQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -46,17 +35,8 @@ public void ObsoleteCommentSyntax_QuickFixWorks_UpdateCommentHasContinuation() @"' this is _ a comment"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceObsoleteCommentMarkerQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } @@ -70,17 +50,8 @@ public void ObsoleteCommentSyntax_QuickFixWorks_UpdateComment_LineHasCode() const string expectedCode = @"Dim Foo As Integer: ' This is a comment"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceObsoleteCommentMarkerQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -95,17 +66,14 @@ public void ObsoleteCommentSyntax_QuickFixWorks_UpdateComment_LineHasCodeAndCont @"Dim Foo As Integer: ' This is _ a comment"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteCommentSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new ObsoleteCommentSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new ReplaceObsoleteCommentMarkerQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ReplaceObsoleteCommentMarkerQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/ReplaceObsoleteErrorStatementQuickFixTests.cs b/RubberduckTests/QuickFixes/ReplaceObsoleteErrorStatementQuickFixTests.cs index d176e0aede..5e60805765 100644 --- a/RubberduckTests/QuickFixes/ReplaceObsoleteErrorStatementQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/ReplaceObsoleteErrorStatementQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class ReplaceObsoleteErrorStatementQuickFixTests + public class ReplaceObsoleteErrorStatementQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -25,17 +23,8 @@ Error 91 Err.Raise 91 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteErrorSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceObsoleteErrorStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteErrorSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] @@ -57,17 +46,8 @@ Sub Foo() Err.Raise 91 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteErrorSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceObsoleteErrorStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteErrorSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -86,17 +66,8 @@ Err.Raise _ 91 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObsoleteErrorSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new ReplaceObsoleteErrorStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteErrorSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } @@ -114,17 +85,14 @@ public void ObsoleteCommentSyntax_QuickFixWorks_UpdateComment_LineHasCode() Dim foo: Err.Raise 91 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObsoleteErrorSyntaxInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new ObsoleteErrorSyntaxInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new ReplaceObsoleteErrorStatementQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new ReplaceObsoleteErrorStatementQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/RestoreErrorHandlingQuickFixTests.cs b/RubberduckTests/QuickFixes/RestoreErrorHandlingQuickFixTests.cs index a067f4b1f8..7d8f7b325b 100644 --- a/RubberduckTests/QuickFixes/RestoreErrorHandlingQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RestoreErrorHandlingQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Inspections; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class RestoreErrorHandlingQuickFixTests + public class RestoreErrorHandlingQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -32,17 +30,8 @@ Resume Next End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RestoreErrorHandlingQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -66,17 +55,8 @@ Resume Next End If End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RestoreErrorHandlingQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -100,17 +80,8 @@ Resume Next End If End Property"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RestoreErrorHandlingQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -138,17 +109,8 @@ Resume Next End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new RestoreErrorHandlingQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -181,20 +143,8 @@ Resume Next End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var quickFix = new RestoreErrorHandlingQuickFix(state); - - foreach (var result in inspector.FindIssuesAsync(state, CancellationToken.None).Result) - { - quickFix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -231,20 +181,8 @@ Resume Next End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var quickFix = new RestoreErrorHandlingQuickFix(state); - - foreach (var result in inspector.FindIssuesAsync(state, CancellationToken.None).Result) - { - quickFix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -283,20 +221,8 @@ Resume Next End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var quickFix = new RestoreErrorHandlingQuickFix(state); - - foreach (var result in inspector.FindIssuesAsync(state, CancellationToken.None).Result) - { - quickFix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -324,20 +250,8 @@ Resume Next End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var quickFix = new RestoreErrorHandlingQuickFix(state); - - foreach (var result in inspector.FindIssuesAsync(state, CancellationToken.None).Result) - { - quickFix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -365,20 +279,14 @@ Resume Next End If End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new UnhandledOnErrorResumeNextInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var quickFix = new RestoreErrorHandlingQuickFix(state); + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new UnhandledOnErrorResumeNextInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - foreach (var result in inspector.FindIssuesAsync(state, CancellationToken.None).Result) - { - quickFix.Fix(result); - } - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new RestoreErrorHandlingQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/SetExplicitVariantReturnTypeQuickFixTests.cs b/RubberduckTests/QuickFixes/SetExplicitVariantReturnTypeQuickFixTests.cs index a64f037b6c..dad7d8ebf4 100644 --- a/RubberduckTests/QuickFixes/SetExplicitVariantReturnTypeQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/SetExplicitVariantReturnTypeQuickFixTests.cs @@ -1,14 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class SetExplicitVariantReturnTypeQuickFixTests + public class SetExplicitVariantReturnTypeQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -22,16 +21,8 @@ public void ImplicitVariantReturnType_QuickFixWorks_Function() @"Function Foo() As Variant End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitVariantReturnTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new SetExplicitVariantReturnTypeQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitVariantReturnTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -46,17 +37,8 @@ public void ImplicitVariantReturnType_QuickFixWorks_PropertyGet() @"Property Get Foo() As Variant End Property"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitVariantReturnTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new SetExplicitVariantReturnTypeQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitVariantReturnTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -89,17 +71,8 @@ public void ImplicitVariantReturnType_QuickFixWorks_LibraryFunction() lpStartupInfo As STARTUPINFO, _ lpProcessInformation As PROCESS_INFORMATION) As Variant"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitVariantReturnTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new SetExplicitVariantReturnTypeQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitVariantReturnTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -114,17 +87,14 @@ public void ImplicitVariantReturnType_QuickFixWorks_Function_HasComment() @"Function Foo() As Variant ' comment End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitVariantReturnTypeInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitVariantReturnTypeInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - new SetExplicitVariantReturnTypeQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new SetExplicitVariantReturnTypeQuickFix(); } } } diff --git a/RubberduckTests/QuickFixes/SpecifyExplicitByRefModifierQuickFixTests.cs b/RubberduckTests/QuickFixes/SpecifyExplicitByRefModifierQuickFixTests.cs index d9c920353c..86e06cb435 100644 --- a/RubberduckTests/QuickFixes/SpecifyExplicitByRefModifierQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/SpecifyExplicitByRefModifierQuickFixTests.cs @@ -1,17 +1,15 @@ -using System.Linq; -using System.Threading; +using System; using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; -using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.Parsing.Grammar; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class SpecifyExplicitByRefModifierQuickFixTests + public class SpecifyExplicitByRefModifierQuickFixTests : QuickFixTestBase { [Test] @@ -26,18 +24,8 @@ public void ImplicitByRefModifier_QuickFixWorks_ImplicitByRefParameter() @"Sub Foo(ByRef arg1 As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -52,18 +40,8 @@ public void ImplicitByRefModifier_QuickFixWorks_OptionalParameter() @"Sub Foo(Optional ByRef arg1 As Integer) End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -84,18 +62,8 @@ ByRef bar _ bar = 1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -114,18 +82,8 @@ public void ImplicitByRefModifier_QuickFixWorks_LineContinuation() bar = 1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -146,173 +104,113 @@ ByRef bar _ bar = 1 End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitByRefModifierInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void ImplicitByRefModifier_QuickFixWorks_InterfaceImplementation() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1 As Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(ByRef arg1 As Integer) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(ByRef arg1 As Integer) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new ImplicitByRefModifierInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void ImplicitByRefModifier_QuickFixWorks_InterfaceImplementationDifferentParameterName() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1 As Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg2 As Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(ByRef arg1 As Integer) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(ByRef arg2 As Integer) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix(inspectionResults.First()); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterface(interfaceInputCode, implementationInputCode, + state => new ImplicitByRefModifierInspection(state)); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } [Test] [Category("QuickFixes")] public void ImplicitByRefModifier_QuickFixWorks_InterfaceImplementationWithMultipleParameters() { - const string inputCode1 = + const string interfaceInputCode = @"Sub Foo(arg1 As Integer, arg2 as Integer) End Sub"; - const string inputCode2 = + const string implementationInputCode = @"Implements IClass1 Sub IClass1_Foo(arg1 As Integer, arg2 as Integer) End Sub"; - const string expectedCode1 = + const string expectedInterfaceCode = @"Sub Foo(ByRef arg1 As Integer, arg2 as Integer) End Sub"; - const string expectedCode2 = + const string expectedImplementationCode = @"Implements IClass1 Sub IClass1_Foo(ByRef arg1 As Integer, arg2 as Integer) End Sub"; - var builder = new MockVbeBuilder(); - var vbe = builder.ProjectBuilder("TestProject1", ProjectProtection.Unprotected) - .AddComponent("IClass1", ComponentType.ClassModule, inputCode1) - .AddComponent("Class1", ComponentType.ClassModule, inputCode2) - .AddProjectToVbeBuilder() - .Build(); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ImplicitByRefModifierInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SpecifyExplicitByRefModifierQuickFix(state).Fix( - inspectionResults.First( - result => - ((VBAParser.ArgContext)result.Context).unrestrictedIdentifier() - .identifier() - .untypedIdentifier() - .identifierValue() - .GetText() == "arg1")); - - var project = vbe.Object.VBProjects[0]; - var interfaceComponent = project.VBComponents[0]; - var implementationComponent = project.VBComponents[1]; - - Assert.AreEqual(expectedCode1, state.GetRewriter(interfaceComponent).GetText(), "Wrong code in interface"); - Assert.AreEqual(expectedCode2, state.GetRewriter(implementationComponent).GetText(), "Wrong code in implementation"); - } + Func conditionOnResultToFix = result => + ((VBAParser.ArgContext)result.Context).unrestrictedIdentifier() + .identifier() + .untypedIdentifier() + .identifierValue() + .GetText() == "arg1"; + var (actualInterfaceCode, actualImplementationCode) = + ApplyQuickFixToFirstInspectionResultForImplementedInterfaceSatisfyingPredicate(interfaceInputCode, implementationInputCode, + state => new ImplicitByRefModifierInspection(state), conditionOnResultToFix); + Assert.AreEqual(expectedInterfaceCode, actualInterfaceCode, "Wrong code in interface"); + Assert.AreEqual(expectedImplementationCode, actualImplementationCode, "Wrong code in implementation"); } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new SpecifyExplicitByRefModifierQuickFix(state); + } } } diff --git a/RubberduckTests/QuickFixes/SpecifyExplicitPublicModifierQuickFixTests.cs b/RubberduckTests/QuickFixes/SpecifyExplicitPublicModifierQuickFixTests.cs index 176346311a..9a3f6c7c97 100644 --- a/RubberduckTests/QuickFixes/SpecifyExplicitPublicModifierQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/SpecifyExplicitPublicModifierQuickFixTests.cs @@ -1,15 +1,14 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class SpecifyExplicitPublicModifierQuickFixTests + public class SpecifyExplicitPublicModifierQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -27,16 +26,14 @@ public void ImplicitPublicMember_QuickFixWorks() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - var inspection = new ImplicitPublicMemberInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new SpecifyExplicitPublicModifierQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ImplicitPublicMemberInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } + + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new SpecifyExplicitPublicModifierQuickFix(); + } } } diff --git a/RubberduckTests/QuickFixes/SplitMultipleDeclarationsQuickFixTests.cs b/RubberduckTests/QuickFixes/SplitMultipleDeclarationsQuickFixTests.cs index 21fd6a9688..19e9f103be 100644 --- a/RubberduckTests/QuickFixes/SplitMultipleDeclarationsQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/SplitMultipleDeclarationsQuickFixTests.cs @@ -1,15 +1,13 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; -using RubberduckTests.Inspections; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class SplitMultipleDeclarationsQuickFixTests + public class SplitMultipleDeclarationsQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -27,17 +25,8 @@ Dim var2 As String End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new MultipleDeclarationsInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SplitMultipleDeclarationsQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new MultipleDeclarationsInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -56,17 +45,8 @@ public void MultipleDeclarations_QuickFixWorks_Constants() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new MultipleDeclarationsInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - - new SplitMultipleDeclarationsQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new MultipleDeclarationsInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -85,18 +65,14 @@ Static var2 As String End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new MultipleDeclarationsInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new MultipleDeclarationsInspection(state); - var inspector = InspectionsHelper.GetInspector(inspection); - var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - new SplitMultipleDeclarationsQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new SplitMultipleDeclarationsQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/UntypedFunctionUsageQuickFixTests.cs b/RubberduckTests/QuickFixes/UntypedFunctionUsageQuickFixTests.cs index 560bed5297..bce200ed5c 100644 --- a/RubberduckTests/QuickFixes/UntypedFunctionUsageQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/UntypedFunctionUsageQuickFixTests.cs @@ -38,7 +38,7 @@ Dim str As String var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[0]; - var parser = MockParser.Create(vbe.Object); + var (parser, rewriteManager) = MockParser.CreateWithRewriteManager(vbe.Object); using (var state = parser.State) { // FIXME reinstate and unignore tests @@ -54,11 +54,13 @@ Dim str As String var inspection = new UntypedFunctionUsageInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - new UntypedFunctionUsageQuickFix(state).Fix(inspectionResults.First()); + var rewriteSession = rewriteManager.CheckOutCodePaneSession(); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); + new UntypedFunctionUsageQuickFix().Fix(inspectionResults.First(), rewriteSession); + + var actualCode = rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName).GetText(); + Assert.AreEqual(expectedCode, actualCode); } } - } } diff --git a/RubberduckTests/QuickFixes/UseSetKeywordForObjectAssignmentQuickFixTests.cs b/RubberduckTests/QuickFixes/UseSetKeywordForObjectAssignmentQuickFixTests.cs index d64bbdf68c..4afe818867 100644 --- a/RubberduckTests/QuickFixes/UseSetKeywordForObjectAssignmentQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/UseSetKeywordForObjectAssignmentQuickFixTests.cs @@ -1,21 +1,19 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; -using RubberduckTests.Mocks; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; namespace RubberduckTests.QuickFixes { [TestFixture] - public class UseSetKeywordForObjectAssignmentQuickFixTests + public class UseSetKeywordForObjectAssignmentQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] public void ObjectVariableNotSet_ForFunctionAssignment_ReturnsResult() { - var expectedResultCount = 2; - var input = + var inputCode = @" Private Function CombineRanges(ByVal source As Range, ByVal toCombine As Range) As Range If source Is Nothing Then @@ -34,30 +32,15 @@ If source Is Nothing Then End If End Function"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObjectVariableNotSetInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None).ToList(); - - Assert.AreEqual(expectedResultCount, inspectionResults.Count); - var fix = new UseSetKeywordForObjectAssignmentQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToAllInspectionResults(inputCode, state => new ObjectVariableNotSetInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] [Category("QuickFixes")] public void ObjectVariableNotSet_ForPropertyGetAssignment_ReturnsResults() { - var expectedResultCount = 1; - var input = @" + var inputCode = @" Private m_example As MyObject Public Property Get Example() As MyObject Example = m_example @@ -71,23 +54,14 @@ Public Property Get Example() As MyObject End Property "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new ObjectVariableNotSetInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None).ToList(); + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new ObjectVariableNotSetInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - Assert.AreEqual(expectedResultCount, inspectionResults.Count); - var fix = new UseSetKeywordForObjectAssignmentQuickFix(state); - foreach (var result in inspectionResults) - { - fix.Fix(result); - } - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new UseSetKeywordForObjectAssignmentQuickFix(); } - } } diff --git a/RubberduckTests/QuickFixes/WriteOnlyPropertyQuickFixTests.cs b/RubberduckTests/QuickFixes/WriteOnlyPropertyQuickFixTests.cs index e81ca02c78..d07b1d1f6d 100644 --- a/RubberduckTests/QuickFixes/WriteOnlyPropertyQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/WriteOnlyPropertyQuickFixTests.cs @@ -1,15 +1,16 @@ -using System.Linq; -using System.Threading; -using NUnit.Framework; +using NUnit.Framework; using Rubberduck.Inspections.Concrete; using Rubberduck.Inspections.QuickFixes; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.VBA; using Rubberduck.VBEditor.SafeComWrappers; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; using RubberduckTests.Mocks; namespace RubberduckTests.QuickFixes { [TestFixture] - public class WriteOnlyPropertyQuickFixTests + public class WriteOnlyPropertyQuickFixTests : QuickFixTestBase { [Test] [Category("QuickFixes")] @@ -26,18 +27,8 @@ End Property Property Let Foo(value) End Property"; - - var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out var component); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new WriteOnlyPropertyInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new WriteOnlyPropertyQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new WriteOnlyPropertyInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -55,17 +46,8 @@ End Property Public Property Let Foo(ByVal value As Integer) End Property"; - var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out var component); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { - - var inspection = new WriteOnlyPropertyInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - - new WriteOnlyPropertyQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new WriteOnlyPropertyInspection(state)); + Assert.AreEqual(expectedCode, actualCode); } [Test] @@ -83,18 +65,19 @@ End Property Public Property Let Foo(value1, ByVal value2 As Integer, ByRef value3 As Long, value4 As Date, ByVal value5, value6 As String) End Property"; - var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out var component); - - using (var state = MockParser.CreateAndParse(vbe.Object)) - { + var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new WriteOnlyPropertyInspection(state)); + Assert.AreEqual(expectedCode, actualCode); + } - var inspection = new WriteOnlyPropertyInspection(state); - var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - new WriteOnlyPropertyQuickFix(state).Fix(inspectionResults.First()); - Assert.AreEqual(expectedCode, state.GetRewriter(component).GetText()); - } + protected override IQuickFix QuickFix(RubberduckParserState state) + { + return new WriteOnlyPropertyQuickFix(); } + protected override IVBE TestVbe(string code, out IVBComponent component) + { + return MockVbeBuilder.BuildFromSingleModule(code, ComponentType.ClassModule, out component).Object; + } } } From 13f7f41204dc5248d3ea78fc054accf74c121283 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Thu, 1 Nov 2018 21:43:26 +0100 Subject: [PATCH 029/107] Remove RewriteAllModules from RubberduckParserState This is now handled via IRewriteSessions. --- .../QuickFixes/QuickFixProvider.cs | 10 +++++----- Rubberduck.Parsing/VBA/RubberduckParserState.cs | 8 -------- .../QuickFixes/QuickFixProviderTests.cs | 15 +++++++++------ 3 files changed, 14 insertions(+), 19 deletions(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs index f273a4d5a7..8f9bd99fee 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs @@ -13,12 +13,12 @@ namespace Rubberduck.Inspections.QuickFixes { public class QuickFixProvider : IQuickFixProvider { - private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly Dictionary> _quickFixes = new Dictionary>(); - public QuickFixProvider(RubberduckParserState state, IEnumerable quickFixes) + public QuickFixProvider(IRewritingManager rewritingManager, IEnumerable quickFixes) { - _state = state; + _rewritingManager = rewritingManager; foreach (var quickFix in quickFixes) { foreach (var supportedInspection in quickFix.SupportedInspections) @@ -86,9 +86,9 @@ private IRewriteSession RewriteSession(CodeKind targetCodeKind) switch (targetCodeKind) { case CodeKind.CodePaneCode: - return _state.RewritingManager.CheckOutCodePaneSession(); + return _rewritingManager.CheckOutCodePaneSession(); case CodeKind.AttributesCode: - return _state.RewritingManager.CheckOutAttributesSession(); + return _rewritingManager.CheckOutAttributesSession(); default: throw new NotSupportedException(nameof(targetCodeKind)); } diff --git a/Rubberduck.Parsing/VBA/RubberduckParserState.cs b/Rubberduck.Parsing/VBA/RubberduckParserState.cs index 254cba8fc8..734a034ba6 100644 --- a/Rubberduck.Parsing/VBA/RubberduckParserState.cs +++ b/Rubberduck.Parsing/VBA/RubberduckParserState.cs @@ -951,14 +951,6 @@ public IExecutableModuleRewriter GetAttributeRewriter(QualifiedModuleName qualif return _moduleStates[qualifiedModuleName].AttributesRewriter; } - public void RewriteAllModules() - { - foreach (var module in _moduleStates.Where(s => ProjectsProvider.Component(s.Key) != null)) - { - module.Value.ModuleRewriter.Rewrite(); - } - } - /// /// Removes the specified from the collection. /// diff --git a/RubberduckTests/QuickFixes/QuickFixProviderTests.cs b/RubberduckTests/QuickFixes/QuickFixProviderTests.cs index e746937caf..0cd08e2415 100644 --- a/RubberduckTests/QuickFixes/QuickFixProviderTests.cs +++ b/RubberduckTests/QuickFixes/QuickFixProviderTests.cs @@ -22,13 +22,14 @@ public void ProviderDoesNotKnowAboutInspection() End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new ConstantNotUsedInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - var quickFixProvider = new QuickFixProvider(state, new IQuickFix[] { }); + var quickFixProvider = new QuickFixProvider(rewritingManager, new IQuickFix[] { }); Assert.AreEqual(0, quickFixProvider.QuickFixes(inspectionResults.First()).Count()); } } @@ -44,14 +45,15 @@ Dim str As String End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new EmptyStringLiteralInspection(state); var inspector = InspectionsHelper.GetInspector(inspection); var inspectionResults = inspector.FindIssuesAsync(state, CancellationToken.None).Result; - var quickFixProvider = new QuickFixProvider(state, new IQuickFix[] { new ReplaceEmptyStringLiteralStatementQuickFix() }); + var quickFixProvider = new QuickFixProvider(rewritingManager, new IQuickFix[] { new ReplaceEmptyStringLiteralStatementQuickFix() }); Assert.AreEqual(1, quickFixProvider.QuickFixes(inspectionResults.First()).Count()); } } @@ -66,13 +68,14 @@ public void ResultDisablesFix() End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var inspection = new ConstantNotUsedInspection(state); var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); - var quickFixProvider = new QuickFixProvider(state, new IQuickFix[] { new RemoveUnusedDeclarationQuickFix() }); + var quickFixProvider = new QuickFixProvider(rewritingManager, new IQuickFix[] { new RemoveUnusedDeclarationQuickFix() }); var result = inspectionResults.First(); result.Properties.DisableFixes = nameof(RemoveUnusedDeclarationQuickFix); From 3deccdbc2f7c5f9e4ca985e8dd614b93aa3d6657 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Thu, 1 Nov 2018 23:02:57 +0100 Subject: [PATCH 030/107] Move creating ModuleRewriters out of the parser This is only a first step. The rewriters are still stored on the ModuleStates because providing a new one each time a rewriter is requested from the RubberduckParserState breaks the refactoring tests. Ultimately, the rewriters should only be created via the IRewriteSession. --- Rubberduck.API/VBA/Parser.cs | 20 +- .../Rewriter/StateTokenStreamCache.cs | 4 +- Rubberduck.Parsing/VBA/ModuleState.cs | 25 +- .../VBA/Parsing/IModuleParser.cs | 12 +- .../VBA/Parsing/ModuleParser.cs | 11 +- .../VBA/Parsing/ParseRunnerBase.cs | 8 +- .../VBA/RubberduckParserState.cs | 43 ++- .../CodeExplorer/CodeExplorerTests.cs | 291 +++++++++--------- RubberduckTests/Mocks/MockParser.cs | 22 +- ...RemoveUnassignedIdentifierQuickFixTests.cs | 4 +- 10 files changed, 242 insertions(+), 198 deletions(-) diff --git a/Rubberduck.API/VBA/Parser.cs b/Rubberduck.API/VBA/Parser.cs index 31495a0ed8..9c6f52ec1e 100644 --- a/Rubberduck.API/VBA/Parser.cs +++ b/Rubberduck.API/VBA/Parser.cs @@ -94,10 +94,17 @@ internal Parser(object vbe) : this() _vbeEvents = VBEEvents.Initialize(_vbe); var declarationFinderFactory = new ConcurrentlyConstructedDeclarationFinderFactory(); var projectRepository = new ProjectsRepository(_vbe); - _state = new RubberduckParserState(_vbe, projectRepository, declarationFinderFactory, _vbeEvents); - _state.StateChanged += _state_StateChanged; + var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); var sourceFileHandler = _vbe.TempSourceFileHandler; + var attributesSourceCodeHandler = new SourceFileHandlerSourceCodeHandlerAdapter(sourceFileHandler, projectRepository); + var moduleRewriterFactory = new ModuleRewriterFactory( + codePaneSourceCodeHandler, + attributesSourceCodeHandler); + + _state = new RubberduckParserState(_vbe, projectRepository, declarationFinderFactory, _vbeEvents, moduleRewriterFactory); + _state.StateChanged += _state_StateChanged; + var vbeVersion = double.Parse(_vbe.Version, CultureInfo.InvariantCulture); var predefinedCompilationConstants = new VBAPredefinedCompilationConstants(vbeVersion); var typeLibProvider = new TypeLibWrapperProvider(projectRepository); @@ -110,7 +117,6 @@ internal Parser(object vbe) : this() var mainTokenStreamParser = new VBATokenStreamParser(mainParseErrorListenerFactory, mainParseErrorListenerFactory); var tokenStreamProvider = new SimpleVBAModuleTokenStreamProvider(); var stringParser = new TokenStreamParserStringParserAdapterWithPreprocessing(tokenStreamProvider, mainTokenStreamParser, preprocessor); - var attributesSourceCodeHandler = new SourceFileHandlerSourceCodeHandlerAdapter(sourceFileHandler, projectRepository); var projectManager = new RepositoryProjectManager(projectRepository); var moduleToModuleReferenceManager = new ModuleToModuleReferenceManager(); var parserStateManager = new ParserStateManager(_state); @@ -130,15 +136,11 @@ internal Parser(object vbe) : this() //new RubberduckApiDeclarations(_state) } ); - var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); - var moduleRewriterFactory = new ModuleRewriterFactory( - codePaneSourceCodeHandler, - attributesSourceCodeHandler); + var moduleParser = new ModuleParser( codePaneSourceCodeHandler, attributesSourceCodeHandler, - stringParser, - moduleRewriterFactory); + stringParser); var parseRunner = new ParseRunner( _state, parserStateManager, diff --git a/Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs b/Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs index 7ba464e164..80e1b939a8 100644 --- a/Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs +++ b/Rubberduck.Parsing/Rewriter/StateTokenStreamCache.cs @@ -16,12 +16,12 @@ public StateTokenStreamCache(RubberduckParserState state) public ITokenStream CodePaneTokenStream(QualifiedModuleName module) { - return _state.GetRewriter(module).TokenStream; + return _state.GetCodePaneTokenStream(module); } public ITokenStream AttributesTokenStream(QualifiedModuleName module) { - return _state.GetAttributeRewriter(module).TokenStream; + return _state.GetAttributesTokenStream(module); } } } \ No newline at end of file diff --git a/Rubberduck.Parsing/VBA/ModuleState.cs b/Rubberduck.Parsing/VBA/ModuleState.cs index 2b4918e019..3762f665bf 100644 --- a/Rubberduck.Parsing/VBA/ModuleState.cs +++ b/Rubberduck.Parsing/VBA/ModuleState.cs @@ -8,7 +8,6 @@ using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.Parsing.VBA.Parsing.ParsingExceptions; -using Rubberduck.VBEditor; namespace Rubberduck.Parsing.VBA { @@ -16,7 +15,9 @@ public class ModuleState { public ConcurrentDictionary Declarations { get; private set; } public ConcurrentDictionary UnresolvedMemberDeclarations { get; private set; } - public IExecutableModuleRewriter ModuleRewriter { get; private set; } + public ITokenStream CodePaneTokenStream { get; private set; } + public ITokenStream AttributesTokenStream { get; private set; } + public IExecutableModuleRewriter CodePaneRewriter { get; private set; } public IExecutableModuleRewriter AttributesRewriter { get; private set; } public IParseTree ParseTree { get; private set; } public IParseTree AttributesPassParseTree { get; private set; } @@ -79,9 +80,15 @@ public ModuleState(SyntaxErrorException moduleException) IsNew = true; } - public ModuleState SetCodePaneRewriter(QualifiedModuleName module, IExecutableModuleRewriter codePaneRewriter) + public ModuleState SetCodePaneTokenStream(ITokenStream codePaneTokenStream) { - ModuleRewriter = codePaneRewriter; + CodePaneTokenStream = codePaneTokenStream; + return this; + } + + public ModuleState SetCodePaneRewriter(IExecutableModuleRewriter codePaneRewriter) + { + CodePaneRewriter = codePaneRewriter; return this; } @@ -144,9 +151,15 @@ public ModuleState SetMembersAllowingAttributes(IDictionary<(string scopeIdentif return this; } - public ModuleState SetAttributesRewriter(IExecutableModuleRewriter rewriter) + public ModuleState SetAttributesTokenStream(ITokenStream attributesTokenStream) + { + AttributesTokenStream = attributesTokenStream; + return this; + } + + public ModuleState SetAttributesRewriter(IExecutableModuleRewriter attributesRewriter) { - AttributesRewriter = rewriter; + AttributesRewriter = attributesRewriter; return this; } diff --git a/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs b/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs index 776e919e2b..84e99308e4 100644 --- a/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs +++ b/Rubberduck.Parsing/VBA/Parsing/IModuleParser.cs @@ -18,8 +18,8 @@ public ModuleParseResults( IEnumerable annotations, IDictionary<(string scopeIdentifier, DeclarationType scopeType), Attributes> attributes, IDictionary<(string scopeIdentifier, DeclarationType scopeType), ParserRuleContext> membersAllowingAttributes, - IExecutableModuleRewriter codePaneRewriter, - IExecutableModuleRewriter attributesRewriter + ITokenStream codePaneTokenStream, + ITokenStream attributesTokenStream ) { CodePaneParseTree = codePaneParseTree; @@ -28,8 +28,8 @@ IExecutableModuleRewriter attributesRewriter Annotations = annotations; Attributes = attributes; MembersAllowingAttributes = membersAllowingAttributes; - CodePaneRewriter = codePaneRewriter; - AttributesRewriter = attributesRewriter; + CodePaneTokenStream = codePaneTokenStream; + AttributesTokenStream = attributesTokenStream; } public IParseTree CodePaneParseTree { get; } @@ -38,8 +38,8 @@ IExecutableModuleRewriter attributesRewriter public IEnumerable Annotations { get; } public IDictionary<(string scopeIdentifier, DeclarationType scopeType), Attributes> Attributes { get; } public IDictionary<(string scopeIdentifier, DeclarationType scopeType), ParserRuleContext> MembersAllowingAttributes { get; } - public IExecutableModuleRewriter CodePaneRewriter { get; } - public IExecutableModuleRewriter AttributesRewriter { get; } + public ITokenStream CodePaneTokenStream { get; } + public ITokenStream AttributesTokenStream { get; } } public interface IModuleParser diff --git a/Rubberduck.Parsing/VBA/Parsing/ModuleParser.cs b/Rubberduck.Parsing/VBA/Parsing/ModuleParser.cs index 73fe692afa..79021eecbd 100644 --- a/Rubberduck.Parsing/VBA/Parsing/ModuleParser.cs +++ b/Rubberduck.Parsing/VBA/Parsing/ModuleParser.cs @@ -9,7 +9,6 @@ using NLog; using Rubberduck.Parsing.Annotations; using Rubberduck.Parsing.Grammar; -using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA.Parsing.ParsingExceptions; using Rubberduck.VBEditor; @@ -23,13 +22,11 @@ public class ModuleParser : IModuleParser private readonly ISourceCodeProvider _codePaneSourceCodeProvider; private readonly ISourceCodeProvider _attributesSourceCodeProvider; private readonly IStringParser _parser; - private readonly IModuleRewriterFactory _moduleRewriterFactory; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - public ModuleParser(ISourceCodeProvider codePaneSourceCodeProvider, ISourceCodeProvider attributesSourceCodeProvider, IStringParser parser, IModuleRewriterFactory moduleRewriterFactory) + public ModuleParser(ISourceCodeProvider codePaneSourceCodeProvider, ISourceCodeProvider attributesSourceCodeProvider, IStringParser parser) { - _moduleRewriterFactory = moduleRewriterFactory; _codePaneSourceCodeProvider = codePaneSourceCodeProvider; _attributesSourceCodeProvider = attributesSourceCodeProvider; _parser = parser; @@ -86,7 +83,6 @@ private ModuleParseResults ParseInternal(QualifiedModuleName module, Cancellatio Logger.Trace($"ParseTaskID {taskId} begins code pane pass."); var (codePaneParseTree, codePaneTokenStream) = CodePanePassResults(module, cancellationToken, rewriter); - var codePaneRewriter = _moduleRewriterFactory.CodePaneRewriter(module, codePaneTokenStream); Logger.Trace($"ParseTaskID {taskId} finished code pane pass."); cancellationToken.ThrowIfCancellationRequested(); @@ -99,7 +95,6 @@ private ModuleParseResults ParseInternal(QualifiedModuleName module, Cancellatio Logger.Trace($"ParseTaskID {taskId} begins attributes pass."); var (attributesParseTree, attributesTokenStream) = AttributesPassResults(module, cancellationToken); - var attributesRewriter = _moduleRewriterFactory.AttributesRewriter(module, attributesTokenStream); Logger.Trace($"ParseTaskID {taskId} finished attributes pass."); cancellationToken.ThrowIfCancellationRequested(); @@ -115,8 +110,8 @@ private ModuleParseResults ParseInternal(QualifiedModuleName module, Cancellatio annotations, attributes, membersAllowingAttributes, - codePaneRewriter, - attributesRewriter + codePaneTokenStream, + attributesTokenStream ); diff --git a/Rubberduck.Parsing/VBA/Parsing/ParseRunnerBase.cs b/Rubberduck.Parsing/VBA/Parsing/ParseRunnerBase.cs index a2f54c925b..64dc7247b6 100644 --- a/Rubberduck.Parsing/VBA/Parsing/ParseRunnerBase.cs +++ b/Rubberduck.Parsing/VBA/Parsing/ParseRunnerBase.cs @@ -1,12 +1,8 @@ using System; using System.Collections.Generic; using System.Threading; -using System.Threading.Tasks; -using Antlr4.Runtime; -using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA.Parsing.ParsingExceptions; using Rubberduck.VBEditor; -using Rubberduck.VBEditor.SourceCodeHandling; namespace Rubberduck.Parsing.VBA.Parsing { @@ -81,8 +77,8 @@ private void SaveModuleParseResultsOnState(QualifiedModuleName module, ModulePar _state.SetModuleAnnotations(module, results.Annotations); _state.SetModuleAttributes(module, results.Attributes); _state.SetMembersAllowingAttributes(module, results.MembersAllowingAttributes); - _state.SetCodePaneRewriter(module, results.CodePaneRewriter); - _state.AddAttributesRewriter(module, results.AttributesRewriter); + _state.SetCodePaneTokenStream(module, results.CodePaneTokenStream); + _state.SetAttributesTokenStream(module, results.AttributesTokenStream); // This really needs to go last //It does not reevaluate the overall parer state to avoid concurrent evaluation of all module states and for performance reasons. diff --git a/Rubberduck.Parsing/VBA/RubberduckParserState.cs b/Rubberduck.Parsing/VBA/RubberduckParserState.cs index 734a034ba6..7457b85d12 100644 --- a/Rubberduck.Parsing/VBA/RubberduckParserState.cs +++ b/Rubberduck.Parsing/VBA/RubberduckParserState.cs @@ -18,7 +18,6 @@ using Rubberduck.VBEditor.Events; using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.VBEditor.SafeComWrappers.Abstract; -using Antlr4.Runtime; using Rubberduck.Parsing.VBA.DeclarationCaching; using Rubberduck.Parsing.VBA.Parsing.ParsingExceptions; @@ -145,10 +144,12 @@ public sealed class RubberduckParserState : IDisposable, IDeclarationFinderProvi private readonly IVBEEvents _vbeEvents; private readonly IHostApplication _hostApp; private readonly IDeclarationFinderFactory _declarationFinderFactory; - + //TODO: Remove this again in a later PR when all rewriters get acquired via IRewriteSessions. + private readonly IModuleRewriterFactory _moduleRewriterFactory; + /// Provides event handling from the VBE. Static method must be already called prior to constructing the method. [SuppressMessage("ReSharper", "JoinNullCheckWithUsage")] - public RubberduckParserState(IVBE vbe, IProjectsRepository projectRepository, IDeclarationFinderFactory declarationFinderFactory, IVBEEvents vbeEvents) + public RubberduckParserState(IVBE vbe, IProjectsRepository projectRepository, IDeclarationFinderFactory declarationFinderFactory, IVBEEvents vbeEvents, IModuleRewriterFactory moduleRewriterFactory) { if (vbe == null) { @@ -170,9 +171,15 @@ public RubberduckParserState(IVBE vbe, IProjectsRepository projectRepository, ID throw new ArgumentNullException(nameof(vbeEvents)); } + if (moduleRewriterFactory == null) + { + throw new ArgumentNullException(nameof(moduleRewriterFactory)); + } + _vbe = vbe; _projectRepository = projectRepository; _declarationFinderFactory = declarationFinderFactory; + _moduleRewriterFactory = moduleRewriterFactory; _vbeEvents = vbeEvents; var values = Enum.GetValues(typeof(ParserState)); @@ -844,9 +851,12 @@ private bool RemoveKeysFromCollections(IEnumerable keys) return success; } - public void SetCodePaneRewriter(QualifiedModuleName module, IExecutableModuleRewriter codePaneRewriter) + public void SetCodePaneTokenStream(QualifiedModuleName module, ITokenStream codePaneTokenStream) { - _moduleStates[module].SetCodePaneRewriter(module, codePaneRewriter); + _moduleStates[module].SetCodePaneTokenStream(codePaneTokenStream); + + var rewriter = _moduleRewriterFactory.CodePaneRewriter(module, codePaneTokenStream); + _moduleStates[module].SetCodePaneRewriter(rewriter); } public void SaveContentHash(QualifiedModuleName module) @@ -931,13 +941,12 @@ public bool IsDirty() public IExecutableModuleRewriter GetRewriter(IVBComponent component) { - var qualifiedModuleName = new QualifiedModuleName(component); - return GetRewriter(qualifiedModuleName); + return GetRewriter(component.QualifiedModuleName); } public IExecutableModuleRewriter GetRewriter(QualifiedModuleName qualifiedModuleName) { - return _moduleStates[qualifiedModuleName].ModuleRewriter; + return _moduleStates[qualifiedModuleName].CodePaneRewriter; } public IExecutableModuleRewriter GetRewriter(Declaration declaration) @@ -951,6 +960,16 @@ public IExecutableModuleRewriter GetAttributeRewriter(QualifiedModuleName qualif return _moduleStates[qualifiedModuleName].AttributesRewriter; } + public ITokenStream GetCodePaneTokenStream(QualifiedModuleName qualifiedModuleName) + { + return _moduleStates[qualifiedModuleName].CodePaneTokenStream; + } + + public ITokenStream GetAttributesTokenStream(QualifiedModuleName qualifiedModuleName) + { + return _moduleStates[qualifiedModuleName].AttributesTokenStream; + } + /// /// Removes the specified from the collection. /// @@ -1058,10 +1077,12 @@ private void ClearAsTypeDeclarationPointingToReference(QualifiedModuleName refer } } - public void AddAttributesRewriter(QualifiedModuleName module, IExecutableModuleRewriter attributesRewriter) + public void SetAttributesTokenStream(QualifiedModuleName module, ITokenStream attributesTokenStream) { - var key = module; - _moduleStates[key].SetAttributesRewriter(attributesRewriter); + _moduleStates[module].SetAttributesTokenStream(attributesTokenStream); + + var rewriter = _moduleRewriterFactory.AttributesRewriter(module, attributesTokenStream); + _moduleStates[module].SetAttributesRewriter(rewriter); } //todo: Remove this again in favor of injection of the IRewritingManager into the callers. diff --git a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs index 7e2211e59f..16b82c6378 100644 --- a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs +++ b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs @@ -15,14 +15,15 @@ using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.VBEditor.SafeComWrappers.Abstract; using RubberduckTests.Mocks; -using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.UIContext; using Rubberduck.SettingsProvider; using Rubberduck.VBEditor.ComManagement; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA.DeclarationCaching; using Rubberduck.UI.UnitTesting.Commands; using Rubberduck.UnitTesting; +using Rubberduck.VBEditor.SourceCodeHandling; namespace RubberduckTests.CodeExplorer { @@ -59,11 +60,10 @@ public void AddStdModule() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var messageBox = new Mock(); var saveFileDialog = new Mock(); @@ -98,13 +98,12 @@ public bool AddStdModule_CanExecuteBasedOnProjectType(ProjectType projectType) var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); - + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddStdModuleCommand = new AddStdModuleCommand(new AddComponentCommand(vbe.Object)); @@ -130,14 +129,13 @@ public void AddClassModule() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); @@ -170,13 +168,12 @@ public bool AddClassModule_CanExecuteBasedOnProjectType(ProjectType projectType) var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddClassModuleCommand = new AddClassModuleCommand(new AddComponentCommand(vbe.Object)); @@ -202,14 +199,13 @@ public void AddUserForm() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var vm = new CodeExplorerViewModel(new FolderHelper(state), state, removeCommand, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); @@ -241,13 +237,12 @@ public bool AddUserForm_CanExecuteBasedOnProjectType(ProjectType projectType) .AddComponent("Module1", ComponentType.StandardModule, ""); - var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var vbe = builder.AddProject(project.Build()).Build(); var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserFormCommand = new AddUserFormCommand(new AddComponentCommand(vbe.Object)); @@ -273,12 +268,11 @@ public void AddVBForm() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddVBFormCommand = new AddVBFormCommand(new AddComponentCommand(vbe.Object)); @@ -310,12 +304,12 @@ public bool AddVBForm_CanExecuteBasedOnProjectType(ProjectType projectType) var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddVBFormCommand = new AddVBFormCommand(new AddComponentCommand(vbe.Object)); @@ -341,12 +335,12 @@ public void AddMDIForm() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddMDIFormCommand = new AddMDIFormCommand(vbe.Object, new AddComponentCommand(vbe.Object)); @@ -378,12 +372,12 @@ public bool AddMDIForm_CanExecuteBasedOnProjectType(ProjectType projectType) var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddMDIFormCommand = new AddMDIFormCommand(vbe.Object, new AddComponentCommand(vbe.Object)); @@ -408,12 +402,12 @@ public void AddMDIForm_CannotExecuteIfProjectAlreadyHasMDIForm() var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddMDIFormCommand = new AddMDIFormCommand(vbe.Object, new AddComponentCommand(vbe.Object)); @@ -439,12 +433,12 @@ public void AddUserControlForm() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserControlCommand = new AddUserControlCommand(new AddComponentCommand(vbe.Object)); @@ -476,12 +470,12 @@ public bool AddUserControl_CanExecuteBasedOnProjectType(ProjectType projectType) var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserControlCommand = new AddUserControlCommand(new AddComponentCommand(vbe.Object)); @@ -507,12 +501,12 @@ public void AddPropertyPage() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddPropertyPageCommand = new AddPropertyPageCommand(new AddComponentCommand(vbe.Object)); @@ -543,12 +537,12 @@ public bool AddPropertyPage_CanExecuteBasedOnProjectType(ProjectType projectType .AddComponent("Module1", ComponentType.StandardModule, ""); var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddPropertyPageCommand = new AddPropertyPageCommand(new AddComponentCommand(vbe.Object)); @@ -574,12 +568,12 @@ public void AddUserDocument() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserDocumentCommand = new AddUserDocumentCommand(new AddComponentCommand(vbe.Object)); @@ -610,12 +604,12 @@ public bool AddUserDocument_CanExecuteBasedOnProjectType(ProjectType projectType .AddComponent("Module1", ComponentType.StandardModule, ""); var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var uiDispatcher = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vm = new CodeExplorerViewModel(new FolderHelper(state), state, null, _generalSettingsProvider.Object, _windowSettingsProvider.Object, uiDispatcher.Object, vbe.Object); vm.AddUserDocumentCommand = new AddUserDocumentCommand(new AddComponentCommand(vbe.Object)); @@ -641,7 +635,7 @@ public void AddTestModule() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var configLoader = new Mock(null, null, null, null, null, null, null, null); configLoader.Setup(c => c.LoadConfiguration()).Returns(GetDefaultUnitTestConfig()); @@ -649,7 +643,7 @@ public void AddTestModule() var saveFileDialog = new Mock(); var projectRepository = new ProjectsRepository(vbe.Object); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); var vbeWrapper = vbe.Object; @@ -681,7 +675,7 @@ public void AddTestModuleWithStubs() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var configLoader = new Mock(null, null, null, null, null, null, null, null); configLoader.Setup(c => c.LoadConfiguration()).Returns(GetDefaultUnitTestConfig()); @@ -690,7 +684,7 @@ public void AddTestModuleWithStubs() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vbeWrapper = vbe.Object; var uiDispatcher = new Mock(); @@ -720,7 +714,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsProject() .AddComponent("Module1", ComponentType.StandardModule, ""); var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var configLoader = new Mock(null, null, null, null, null, null, null, null); configLoader.Setup(c => c.LoadConfiguration()).Returns(GetDefaultUnitTestConfig()); @@ -729,7 +723,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsProject() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vbeWrapper = vbe.Object; var uiDispatcher = new Mock(); @@ -758,7 +752,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsFolder() .AddComponent("Module1", ComponentType.StandardModule, ""); var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var configLoader = new Mock(null, null, null, null, null, null, null, null); configLoader.Setup(c => c.LoadConfiguration()).Returns(GetDefaultUnitTestConfig()); @@ -768,7 +762,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsFolder() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vbeWrapper = vbe.Object; var interaction = new Mock(); @@ -796,7 +790,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsModuleMember() .AddComponent("Module1", ComponentType.StandardModule, "Public Sub S()\r\nEnd Sub"); var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var configLoader = new Mock(null, null, null, null, null, null, null, null); configLoader.Setup(c => c.LoadConfiguration()).Returns(GetDefaultUnitTestConfig()); @@ -805,7 +799,7 @@ public void AddTestModuleWithStubs_DisabledWhenParameterIsModuleMember() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var vbeWrapper = vbe.Object; var uiDispatcher = new Mock(); @@ -836,7 +830,7 @@ public void ImportModule() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var openFileDialog = new Mock(); openFileDialog.Setup(o => o.AddExtension); @@ -853,7 +847,7 @@ public void ImportModule() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -883,7 +877,7 @@ public void ImportMultipleModules() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var openFileDialog = new Mock(); openFileDialog.Setup(o => o.AddExtension); @@ -900,7 +894,7 @@ public void ImportMultipleModules() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -931,7 +925,7 @@ public void ImportModule_Cancel() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var openFileDialog = new Mock(); openFileDialog.Setup(o => o.AddExtension); @@ -948,7 +942,7 @@ public void ImportModule_Cancel() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -977,7 +971,7 @@ public void ExportModule_ExpectExecution() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component = projectMock.MockComponents.First(); var saveFileDialog = new Mock(); @@ -988,7 +982,7 @@ public void ExportModule_ExpectExecution() var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1017,7 +1011,7 @@ public void ExportModule_CancelPressed_ExpectNoExecution() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component = projectMock.MockComponents.First(); var saveFileDialog = new Mock(); @@ -1028,7 +1022,7 @@ public void ExportModule_CancelPressed_ExpectNoExecution() var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1059,7 +1053,7 @@ public void ExportProject_TestCanExecute_ExpectTrue() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component1 = project.Object.VBComponents[0]; var module1 = component1.CodeModule; @@ -1071,7 +1065,7 @@ public void ExportProject_TestCanExecute_ExpectTrue() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1111,7 +1105,7 @@ public void ExportProject_TestExecute_OKPressed_ExpectExecution() project.SetupGet(m => m.FileName).Returns(projectFullPath); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component1 = project.Object.VBComponents[0]; var module1 = component1.CodeModule; @@ -1129,7 +1123,7 @@ public void ExportProject_TestExecute_OKPressed_ExpectExecution() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1169,7 +1163,7 @@ public void ExportProject_TestExecute_CancelPressed_ExpectExecution() project.SetupGet(m => m.FileName).Returns(projectFullPath); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component1 = project.Object.VBComponents[0]; var module1 = component1.CodeModule; @@ -1187,7 +1181,7 @@ public void ExportProject_TestExecute_CancelPressed_ExpectExecution() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1216,14 +1210,14 @@ public void OpenDesigner() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component = projectMock.MockComponents.First(); var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1256,7 +1250,7 @@ public void RemoveCommand_RemovesModuleWhenPromptOk() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component = project.Object.VBComponents[0]; @@ -1269,7 +1263,7 @@ public void RemoveCommand_RemovesModuleWhenPromptOk() messageBox.Setup(m => m.Confirm(It.IsAny(), It.IsAny(), It.IsAny())).Returns(ConfirmationOutcome.Yes); var projectRepository = new ProjectsRepository(vbe.Object); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1299,7 +1293,7 @@ public void RemoveCommand_CancelsWhenFilePromptCancels() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component = project.Object.VBComponents[0]; var saveFileDialog = new Mock(); @@ -1309,7 +1303,7 @@ public void RemoveCommand_CancelsWhenFilePromptCancels() messageBox.Setup(m => m.ConfirmYesNo(It.IsAny(), It.IsAny(), It.IsAny())).Returns(true); var projectRepository = new ProjectsRepository(vbe.Object); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var commands = new List { @@ -1343,7 +1337,7 @@ public void RemoveCommand_GivenMsgBoxNO_RemovesModuleNoExport() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component = project.Object.VBComponents[0]; var saveFileDialog = new Mock(); @@ -1353,7 +1347,7 @@ public void RemoveCommand_GivenMsgBoxNO_RemovesModuleNoExport() messageBox.Setup(m => m.Confirm(It.IsAny(), It.IsAny(), It.IsAny())).Returns(ConfirmationOutcome.No); var projectRepository = new ProjectsRepository(vbe.Object); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1383,7 +1377,7 @@ public void RemoveModule_Cancel() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component = project.Object.VBComponents[0]; var saveFileDialog = new Mock(); @@ -1393,7 +1387,7 @@ public void RemoveModule_Cancel() messageBox.Setup(m => m.Confirm(It.IsAny(), It.IsAny(), It.IsAny())).Returns(ConfirmationOutcome.Cancel); var projectRepository = new ProjectsRepository(vbe.Object); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var commands = new List { @@ -1434,13 +1428,13 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1473,13 +1467,13 @@ Dim d As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1521,7 +1515,7 @@ End Sub var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component1 = project.Object.VBComponents[0]; var module1 = component1.CodeModule; @@ -1532,7 +1526,7 @@ End Sub var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1584,7 +1578,7 @@ End Sub var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component1 = project.Object.VBComponents[0]; var module1 = component1.CodeModule; @@ -1595,7 +1589,7 @@ End Sub var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1634,13 +1628,13 @@ Dim d As Boolean var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1687,7 +1681,7 @@ End Sub var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component1 = project.Object.VBComponents[0]; var module1 = component1.CodeModule; @@ -1698,7 +1692,7 @@ End Sub var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1755,7 +1749,7 @@ End Sub var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var component1 = project.Object.VBComponents[0]; var module1 = component1.CodeModule; @@ -1766,7 +1760,7 @@ End Sub var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1806,13 +1800,13 @@ Dim d As Boolean var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1839,13 +1833,13 @@ public void ExpandAllNodes() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1875,13 +1869,13 @@ public void ExpandAllNodes_StartingWithSubnode() .AddComponent("Comp2", ComponentType.ClassModule, @"'@Folder ""Bar""") .Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1911,13 +1905,13 @@ public void CollapseAllNodes() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1947,13 +1941,13 @@ public void CollapseAllNodes_StartingWithSubnode() .AddComponent("Comp2", ComponentType.ClassModule, @"'@Folder ""Bar""") .Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -1984,7 +1978,7 @@ public void SetSortByName_NotAlreadySelectedInMenu_ExpectTrue() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -1992,7 +1986,7 @@ public void SetSortByName_NotAlreadySelectedInMenu_ExpectTrue() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2029,7 +2023,7 @@ public void SetSortByName_AlreadySelectedInMenu_ExpectTrue() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -2037,7 +2031,7 @@ public void SetSortByName_AlreadySelectedInMenu_ExpectTrue() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2074,7 +2068,7 @@ public void SetSortByName_BothSortOptionsFalse_ExpectTrueOnlyForSortByName() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -2082,7 +2076,7 @@ public void SetSortByName_BothSortOptionsFalse_ExpectTrueOnlyForSortByName() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2119,7 +2113,7 @@ public void SetSortByName_BothSortOptionsTrue_ExpectTrueOnlyForSortByName() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -2129,7 +2123,7 @@ public void SetSortByName_BothSortOptionsTrue_ExpectTrueOnlyForSortByName() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2165,7 +2159,7 @@ public void SetSortByCodeOrder_NotAlreadySelectedInMenu_ExpectTrue() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -2173,7 +2167,7 @@ public void SetSortByCodeOrder_NotAlreadySelectedInMenu_ExpectTrue() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2210,7 +2204,7 @@ public void SetSortByCodeOrder_AlreadySelectedInMenu_ExpectTrue() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -2218,7 +2212,7 @@ public void SetSortByCodeOrder_AlreadySelectedInMenu_ExpectTrue() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2255,7 +2249,7 @@ public void SetSortByCodeOrder_BothSortOptionsFalse_ExpectCorrectSortPair() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -2263,7 +2257,7 @@ public void SetSortByCodeOrder_BothSortOptionsFalse_ExpectCorrectSortPair() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2300,7 +2294,7 @@ public void SetSortByCodeOrder_BothSortOptionsTrue_ExpectCorrectSortPair() var components = project.MockVBComponents; var vbe = builder.AddProject(project.Build()).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var commands = new List { new AddStdModuleCommand(new AddComponentCommand(vbe.Object)) }; @@ -2308,7 +2302,7 @@ public void SetSortByCodeOrder_BothSortOptionsTrue_ExpectCorrectSortPair() var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var windowSettings = new WindowSettings @@ -2382,13 +2376,13 @@ public void CompareByType_ReturnsEventAboveConst() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2414,13 +2408,13 @@ public void CompareByType_ReturnsConstAboveField() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2449,13 +2443,13 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2485,13 +2479,13 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2521,13 +2515,13 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2557,13 +2551,13 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2593,13 +2587,13 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2629,13 +2623,13 @@ End Function IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2665,13 +2659,13 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2701,13 +2695,13 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2734,13 +2728,13 @@ public void CompareByType_ReturnsClassModuleBelowDocument() var project = projectMock.Build(); var vbe = builder.AddProject(project).Build(); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2774,13 +2768,13 @@ Sub Bar() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2810,13 +2804,13 @@ Sub Bar() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2846,13 +2840,13 @@ Sub Bar() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + var projectRepository = new ProjectsRepository(vbe.Object); var messageBox = new Mock(); var saveFileDialog = new Mock(); - using (var state = new RubberduckParserState(vbe.Object, projectRepository, new DeclarationFinderFactory(), vbeEvents.Object)) + using (var state = TestParserState(vbe, projectRepository)) { var uiDispatcher = new Mock(); var removeCommand = new RemoveCommand(saveFileDialog.Object, messageBox.Object, state.ProjectsProvider); @@ -2879,6 +2873,21 @@ public void CompareByNodeType_FoldersAreSortedByName() } #region Helpers + + private RubberduckParserState TestParserState(Mock vbe, IProjectsRepository projectsRepository) + { + var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); + + var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectsRepository); + //We use the same handler because to achieve consistency between the return values. + var attributesSourceCodeHandler = codePaneSourceCodeHandler; + var moduleRewriterFactory = new ModuleRewriterFactory( + codePaneSourceCodeHandler, + attributesSourceCodeHandler); + + return new RubberduckParserState(vbe.Object, projectsRepository, new DeclarationFinderFactory(), vbeEvents.Object, moduleRewriterFactory); + } + private Configuration GetDefaultUnitTestConfig() { var unitTestSettings = new UnitTestSettings(BindingMode.LateBinding, AssertMode.StrictAssert, true, true, false); diff --git a/RubberduckTests/Mocks/MockParser.cs b/RubberduckTests/Mocks/MockParser.cs index 779531698a..5080ca337d 100644 --- a/RubberduckTests/Mocks/MockParser.cs +++ b/RubberduckTests/Mocks/MockParser.cs @@ -48,7 +48,15 @@ public static (SynchronousParseCoordinator parser, IRewritingManager rewritingMa var vbeEvents = MockVbeEvents.CreateMockVbeEvents(new Moq.Mock()); var declarationFinderFactory = new DeclarationFinderFactory(); var projectRepository = new ProjectsRepository(vbe); - var state = new RubberduckParserState(vbe, projectRepository, declarationFinderFactory, vbeEvents.Object); + + var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); + //We use the same handler because to achieve consistency between the return values. + var attributesSourceCodeHandler = codePaneSourceCodeHandler; + var moduleRewriterFactory = new ModuleRewriterFactory( + codePaneSourceCodeHandler, + attributesSourceCodeHandler); + + var state = new RubberduckParserState(vbe, projectRepository, declarationFinderFactory, vbeEvents.Object, moduleRewriterFactory); return CreateWithRewriteManager(vbe, state, projectRepository, serializedComProjectsPath); } @@ -93,17 +101,14 @@ public static (SynchronousParseCoordinator parser, IRewritingManager rewritingMa new SpecialFormDeclarations(state), new FormEventDeclarations(state), new AliasDeclarations(state), - }); var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); + }); + var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); //We use the same handler because to achieve consistency between the return values. var attributesSourceCodeHandler = codePaneSourceCodeHandler; - var moduleRewriterFactory = new ModuleRewriterFactory( - codePaneSourceCodeHandler, - attributesSourceCodeHandler); var moduleParser = new ModuleParser( codePaneSourceCodeHandler, attributesSourceCodeHandler, - stringParser, - moduleRewriterFactory); + stringParser); var parseRunner = new SynchronousParseRunner( state, parserStateManager, @@ -132,6 +137,9 @@ public static (SynchronousParseCoordinator parser, IRewritingManager rewritingMa compilationsArgumentsCache ); var tokenStreamCache = new StateTokenStreamCache(state); + var moduleRewriterFactory = new ModuleRewriterFactory( + codePaneSourceCodeHandler, + attributesSourceCodeHandler); var rewriterProvider = new RewriterProvider(tokenStreamCache, moduleRewriterFactory); var rewriteSessionFactory = new RewriteSessionFactory(state, rewriterProvider); var rewritingManager = new RewritingManager(rewriteSessionFactory); diff --git a/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs index 824745fec6..30279f6190 100644 --- a/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveUnassignedIdentifierQuickFixTests.cs @@ -60,8 +60,8 @@ public void UnassignedVariable_MultipleVariablesOnSingleLine_QuickFixWorks() @"Sub Foo() Dim var1 As Integer End Sub"; - - var actualCode = ApplyQuickFixToFirstInspectionResult(inputCode, state => new VariableNotAssignedInspection(state)); + Func conditionToFix = s => s.Target.IdentifierName == "var2"; + var actualCode = ApplyQuickFixToFirstInspectionResultSatisfyingPredicate(inputCode, state => new VariableNotAssignedInspection(state), conditionToFix); Assert.AreEqual(expectedCode, actualCode); } From 67561cb1eba01e6d63dbeffa1952526e57d6619c Mon Sep 17 00:00:00 2001 From: comintern Date: Thu, 1 Nov 2018 19:49:06 -0500 Subject: [PATCH 031/107] Refactor to use common base class, track context. --- .../Extensions/NodeExtensions.cs | 30 +++++++++++++++++++ .../Nodes/Abstract/NodeBase.cs | 23 ++++++++++++++ .../CodePathAnalysis/Nodes/INode.cs | 3 +- .../Nodes/Implementations/AssignmentNode.cs | 18 ++--------- .../Nodes/Implementations/BlockNode.cs | 18 ++--------- .../Nodes/Implementations/BranchNode.cs | 18 ++--------- .../Nodes/Implementations/DeclarationNode.cs | 18 ++--------- .../Nodes/Implementations/GenericNode.cs | 18 ++--------- .../Nodes/Implementations/LoopNode.cs | 18 ++--------- .../Nodes/Implementations/ReferenceNode.cs | 18 ++--------- .../CodePathAnalysis/Walker.cs | 15 +++++----- 11 files changed, 84 insertions(+), 113 deletions(-) create mode 100644 Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Abstract/NodeBase.cs diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Extensions/NodeExtensions.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Extensions/NodeExtensions.cs index 9ddfe2f42c..f9c66e5622 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Extensions/NodeExtensions.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Extensions/NodeExtensions.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Rubberduck.Parsing.Symbols; namespace Rubberduck.Inspections.CodePathAnalysis.Extensions { @@ -50,5 +51,34 @@ public static INode GetFirstNode(this INode node, IEnumerable excludedType return GetFirstNode(node.Children[0], excludedTypes); } + + public static List GetIdentifierReferences(this INode node) + { + var nodes = new List(); + + var blockNodes = node.GetNodes(new[] { typeof(BlockNode) }); + foreach (var block in blockNodes) + { + INode lastNode = default; + foreach (var flattenedNode in block.GetFlattenedNodes(new[] { typeof(GenericNode), typeof(BlockNode) })) + { + if (flattenedNode is AssignmentNode && + lastNode is AssignmentNode) + { + nodes.Add(lastNode.Reference); + } + + lastNode = flattenedNode; + } + + if (lastNode is AssignmentNode && + block.Children[0].GetFirstNode(new[] { typeof(GenericNode) }) is DeclarationNode) + { + nodes.Add(lastNode.Reference); + } + } + + return nodes; + } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Abstract/NodeBase.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Abstract/NodeBase.cs new file mode 100644 index 0000000000..826ff1fb61 --- /dev/null +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Abstract/NodeBase.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using Antlr4.Runtime.Tree; +using Rubberduck.Parsing.Symbols; + +namespace Rubberduck.Inspections.CodePathAnalysis.Nodes +{ + public abstract class NodeBase : INode + { + protected NodeBase(IParseTree tree) + { + Children = new List().ToImmutableList(); + ParseTree = tree; + } + + public int SortOrder { get; set; } + public ImmutableList Children { get; set; } + public INode Parent { get; set; } + public IParseTree ParseTree { get; } + public Declaration Declaration { get; set; } + public IdentifierReference Reference { get; set; } + } +} diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/INode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/INode.cs index 6a11f7ff6a..e771fa8c7c 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/INode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/INode.cs @@ -1,5 +1,6 @@ using Rubberduck.Parsing.Symbols; using System.Collections.Immutable; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { @@ -8,7 +9,7 @@ public interface INode int SortOrder { get; set; } ImmutableList Children { get; set; } INode Parent { get; set; } - + IParseTree ParseTree { get; } Declaration Declaration { get; set; } IdentifierReference Reference { get; set; } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/AssignmentNode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/AssignmentNode.cs index 5203bfa6ef..a4437ef0da 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/AssignmentNode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/AssignmentNode.cs @@ -1,21 +1,9 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using Rubberduck.Parsing.Symbols; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { - public class AssignmentNode : INode + public class AssignmentNode : NodeBase { - public AssignmentNode() - { - Children = new List().ToImmutableList(); - } - - public int SortOrder { get; set; } - public ImmutableList Children { get; set; } - public INode Parent { get; set; } - - public Declaration Declaration { get; set; } - public IdentifierReference Reference { get; set; } + public AssignmentNode(IParseTree tree) : base(tree) { } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BlockNode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BlockNode.cs index 353add1db7..035052bb52 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BlockNode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BlockNode.cs @@ -1,21 +1,9 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using Rubberduck.Parsing.Symbols; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { - public class BlockNode : INode + public class BlockNode : NodeBase { - public BlockNode() - { - Children = new List().ToImmutableList(); - } - - public int SortOrder { get; set; } - public ImmutableList Children { get; set; } - public INode Parent { get; set; } - - public Declaration Declaration { get; set; } - public IdentifierReference Reference { get; set; } + public BlockNode(IParseTree tree) : base(tree) { } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BranchNode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BranchNode.cs index bef1687b54..fbc40de824 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BranchNode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/BranchNode.cs @@ -1,21 +1,9 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using Rubberduck.Parsing.Symbols; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { - public class BranchNode : IBranchNode + public class BranchNode : NodeBase, IBranchNode { - public BranchNode() - { - Children = new List().ToImmutableList(); - } - - public int SortOrder { get; set; } - public ImmutableList Children { get; set; } - public INode Parent { get; set; } - - public Declaration Declaration { get; set; } - public IdentifierReference Reference { get; set; } + public BranchNode(IParseTree tree) : base(tree) { } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/DeclarationNode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/DeclarationNode.cs index f7173b13e9..dbf0ae2d49 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/DeclarationNode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/DeclarationNode.cs @@ -1,21 +1,9 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using Rubberduck.Parsing.Symbols; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { - public class DeclarationNode : INode + public class DeclarationNode : NodeBase { - public DeclarationNode() - { - Children = new List().ToImmutableList(); - } - - public int SortOrder { get; set; } - public ImmutableList Children { get; set; } - public INode Parent { get; set; } - - public Declaration Declaration { get; set; } - public IdentifierReference Reference { get; set; } + public DeclarationNode(IParseTree tree) : base(tree) { } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/GenericNode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/GenericNode.cs index e8fb1db965..3906d4a6e5 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/GenericNode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/GenericNode.cs @@ -1,21 +1,9 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using Rubberduck.Parsing.Symbols; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { - public class GenericNode : INode + public class GenericNode : NodeBase { - public GenericNode() - { - Children = new List().ToImmutableList(); - } - - public int SortOrder { get; set; } - public ImmutableList Children { get; set; } - public INode Parent { get; set; } - - public Declaration Declaration { get; set; } - public IdentifierReference Reference { get; set; } + public GenericNode(IParseTree tree) : base(tree) { } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/LoopNode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/LoopNode.cs index 56fd6b2d89..8f6d011e59 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/LoopNode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/LoopNode.cs @@ -1,21 +1,9 @@ -using Rubberduck.Parsing.Symbols; -using System.Collections.Generic; -using System.Collections.Immutable; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { - public class LoopNode : ILoopNode + public class LoopNode : NodeBase, ILoopNode { - public LoopNode() - { - Children = new List().ToImmutableList(); - } - - public int SortOrder { get; set; } - public ImmutableList Children { get; set; } - public INode Parent { get; set; } - - public Declaration Declaration { get; set; } - public IdentifierReference Reference { get; set; } + public LoopNode(IParseTree tree) : base(tree) { } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/ReferenceNode.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/ReferenceNode.cs index 538fa01798..f1a1d66ed6 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/ReferenceNode.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Nodes/Implementations/ReferenceNode.cs @@ -1,21 +1,9 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using Rubberduck.Parsing.Symbols; +using Antlr4.Runtime.Tree; namespace Rubberduck.Inspections.CodePathAnalysis.Nodes { - public class ReferenceNode : INode + public class ReferenceNode : NodeBase { - public ReferenceNode() - { - Children = new List().ToImmutableList(); - } - - public int SortOrder { get; set; } - public ImmutableList Children { get; set; } - public INode Parent { get; set; } - - public Declaration Declaration { get; set; } - public IdentifierReference Reference { get; set; } + public ReferenceNode(IParseTree tree) : base(tree) { } } } diff --git a/Rubberduck.CodeAnalysis/CodePathAnalysis/Walker.cs b/Rubberduck.CodeAnalysis/CodePathAnalysis/Walker.cs index 080ecbdf5d..a9c2ba6522 100644 --- a/Rubberduck.CodeAnalysis/CodePathAnalysis/Walker.cs +++ b/Rubberduck.CodeAnalysis/CodePathAnalysis/Walker.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Antlr4.Runtime; namespace Rubberduck.Inspections.CodePathAnalysis { @@ -19,7 +20,7 @@ public INode GenerateTree(IParseTree tree, Declaration declaration) case VBAParser.ForEachStmtContext _: case VBAParser.WhileWendStmtContext _: case VBAParser.DoLoopStmtContext _: - node = new LoopNode(); + node = new LoopNode(tree); break; case VBAParser.IfStmtContext _: case VBAParser.ElseBlockContext _: @@ -28,16 +29,16 @@ public INode GenerateTree(IParseTree tree, Declaration declaration) case VBAParser.SingleLineElseClauseContext _: case VBAParser.CaseClauseContext _: case VBAParser.CaseElseClauseContext _: - node = new BranchNode(); + node = new BranchNode(tree); break; case VBAParser.BlockContext _: - node = new BlockNode(); + node = new BlockNode(tree); break; } if (declaration.Context == tree) { - node = new DeclarationNode + node = new DeclarationNode(tree) { Declaration = declaration }; @@ -48,14 +49,14 @@ public INode GenerateTree(IParseTree tree, Declaration declaration) { if (reference.IsAssignment) { - node = new AssignmentNode + node = new AssignmentNode(tree) { Reference = reference }; } else { - node = new ReferenceNode + node = new ReferenceNode(tree) { Reference = reference }; @@ -64,7 +65,7 @@ public INode GenerateTree(IParseTree tree, Declaration declaration) if (node == null) { - node = new GenericNode(); + node = new GenericNode(tree); } var children = new List(); From 1af96a9ad3f80052e7c0ac8e566ba4cfe5f79fcc Mon Sep 17 00:00:00 2001 From: comintern Date: Thu, 1 Nov 2018 21:11:37 -0500 Subject: [PATCH 032/107] Switch to extension method for GetIdentifierReferences. --- .../Concrete/AssignmentNotUsedInspection.cs | 32 +------------------ 1 file changed, 1 insertion(+), 31 deletions(-) diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/AssignmentNotUsedInspection.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/AssignmentNotUsedInspection.cs index 47f0d0be62..d3e42e68fd 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Concrete/AssignmentNotUsedInspection.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/AssignmentNotUsedInspection.cs @@ -4,7 +4,6 @@ using Rubberduck.Parsing.VBA; using Rubberduck.Inspections.CodePathAnalysis; using Rubberduck.Parsing.Symbols; -using Rubberduck.Inspections.CodePathAnalysis.Nodes; using Rubberduck.Inspections.CodePathAnalysis.Extensions; using System.Linq; using Rubberduck.Inspections.Results; @@ -29,41 +28,12 @@ protected override IEnumerable DoGetInspectionResults() { var tree = _walker.GenerateTree(variable.ParentScopeDeclaration.Context, variable); - nodes.AddRange(GetIdentifierReferences(tree, variable)); + nodes.AddRange(tree.GetIdentifierReferences()); } return nodes .Select(issue => new IdentifierReferenceInspectionResult(this, Description, State, issue)) .ToList(); } - - private List GetIdentifierReferences(INode node, Declaration declaration) - { - var nodes = new List(); - - var blockNodes = node.GetNodes(new[] { typeof(BlockNode) }); - foreach (var block in blockNodes) - { - INode lastNode = default; - foreach (var flattenedNode in block.GetFlattenedNodes(new[] { typeof(GenericNode), typeof(BlockNode) })) - { - if (flattenedNode is AssignmentNode && - lastNode is AssignmentNode) - { - nodes.Add(lastNode.Reference); - } - - lastNode = flattenedNode; - } - - if (lastNode is AssignmentNode && - block.Children[0].GetFirstNode(new[] { typeof(GenericNode) }) is DeclarationNode) - { - nodes.Add(lastNode.Reference); - } - } - - return nodes; - } } } From c0b51aa8aa61618091cceb3b4a2c90500a2671cf Mon Sep 17 00:00:00 2001 From: comintern Date: Thu, 1 Nov 2018 21:12:21 -0500 Subject: [PATCH 033/107] Add member access may be Nothing inspection. --- ...berAccessMayReturnNothingInspectionBase.cs | 101 ++++++ .../ExcelMemberMayReturnNothingInspection.cs | 30 ++ ...elMemberMayReturnNothingInspectionTests.cs | 298 ++++++++++++++++++ 3 files changed, 429 insertions(+) create mode 100644 Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs create mode 100644 Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs create mode 100644 RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs diff --git a/Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs b/Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs new file mode 100644 index 0000000000..1754f33449 --- /dev/null +++ b/Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs @@ -0,0 +1,101 @@ +using System.Collections.Generic; +using System.Linq; +using Antlr4.Runtime.Tree; +using Rubberduck.Inspections.CodePathAnalysis; +using Rubberduck.Inspections.CodePathAnalysis.Nodes; +using Rubberduck.Inspections.Results; +using Rubberduck.Parsing; +using Rubberduck.Parsing.Grammar; +using Rubberduck.Parsing.Inspections.Abstract; +using Rubberduck.Parsing.Symbols; +using Rubberduck.Parsing.VBA; + +namespace Rubberduck.Inspections.Abstract +{ + public abstract class MemberAccessMayReturnNothingInspectionBase : InspectionBase + { + protected MemberAccessMayReturnNothingInspectionBase(RubberduckParserState state) : base(state) { } + + public abstract List MembersUnderTest { get; } + public abstract string ResultTemplate { get; } + + protected override IEnumerable DoGetInspectionResults() + { + var interesting = MembersUnderTest.SelectMany(member => member.References).ToList(); + if (!interesting.Any()) + { + return Enumerable.Empty(); + } + + var output = new List(); + foreach (var reference in interesting) + { + var access = reference.Context.GetAncestor(); + var usageContext = access.Parent is VBAParser.IndexExprContext + ? access.Parent.Parent + : access.Parent; + + var setter = usageContext is VBAParser.LExprContext lexpr && lexpr.Parent is VBAParser.SetStmtContext + ? lexpr.Parent + : null; + + if (setter is null) + { + if (usageContext is VBAParser.MemberAccessExprContext || !ContextIsNothingTest(usageContext)) + { + output.Add(new IdentifierReferenceInspectionResult(this, + string.Format(ResultTemplate, + $"{reference.Declaration.ParentDeclaration.IdentifierName}.{reference.IdentifierName}"), + State, reference)); + } + continue; + } + + var assignedTo = Declarations.SelectMany(decl => decl.References).SingleOrDefault(assign => + assign.IsAssignment && (assign.Context.GetAncestor()?.Equals(setter) ?? false)); + if (assignedTo is null) + { + continue; + } + + var tree = new Walker().GenerateTree(assignedTo.Declaration.ParentScopeDeclaration.Context, assignedTo.Declaration); + var firstUse = GetReferenceNodes(tree).FirstOrDefault(); + if (firstUse is null || ContextIsNothingTest(firstUse.Reference.Context.Parent)) + { + continue; + } + + output.Add(new IdentifierReferenceInspectionResult(this, + string.Format(ResultTemplate, + $"{reference.Declaration.ParentDeclaration.IdentifierName}.{reference.IdentifierName}"), + State, reference)); + } + + return output; + } + + private bool ContextIsNothingTest(IParseTree context) + { + return context is VBAParser.LExprContext && + context.Parent is VBAParser.RelationalOpContext comparison && + comparison.IS() != null + && comparison.GetDescendent() != null; + } + + private IEnumerable GetReferenceNodes(INode node) + { + if (node is ReferenceNode && node.Reference != null) + { + yield return node; + } + + foreach (var child in node.Children) + { + foreach (var childNode in GetReferenceNodes(child)) + { + yield return childNode; + } + } + } + } +} diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs new file mode 100644 index 0000000000..965d30837c --- /dev/null +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Rubberduck.Inspections.Abstract; +using Rubberduck.Parsing.Inspections; +using Rubberduck.Parsing.Symbols; +using Rubberduck.Parsing.VBA; +using Rubberduck.Resources.Inspections; + +namespace Rubberduck.Inspections.Concrete +{ + [RequiredLibrary("Excel")] + public class ExcelMemberMayReturnNothingInspection : MemberAccessMayReturnNothingInspectionBase + { + public ExcelMemberMayReturnNothingInspection(RubberduckParserState state) : base(state) { } + + private static readonly List ExcelMembers = new List + { + "Range.Find", + "Range.FindNext", + "Range.FindPrevious" + }; + + public override List MembersUnderTest => BuiltInDeclarations + .Where(decl => decl.ProjectName.Equals("Excel") && ExcelMembers.Any(member => decl.QualifiedName.ToString().EndsWith(member))) + .ToList(); + + public override string ResultTemplate => Description; //InspectionResults.ExcelMemberMayReturnNothingInspection; + } +} diff --git a/RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs b/RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs new file mode 100644 index 0000000000..f797dc1610 --- /dev/null +++ b/RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs @@ -0,0 +1,298 @@ +using System.Linq; +using System.Threading; +using NUnit.Framework; +using Rubberduck.Inspections.Concrete; +using Rubberduck.Parsing.VBA; +using Rubberduck.VBEditor.SafeComWrappers; +using RubberduckTests.Mocks; + +namespace RubberduckTests.Inspections +{ + [TestFixture] + public class ExcelMemberMayReturnNothingInspectionTests + { + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_FindWithMemberAccess() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + foo = ws.UsedRange.Find(""foo"").Row +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsNoResult_ResultIsNothingInAssignment() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + Dim foo As Boolean + foo = ws.UsedRange.Find(""foo"") Is Nothing +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.IsFalse(inspectionResults.Any()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsNoResult_TransientAccessIsNothing() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + If ws.UsedRange.Find(""foo"") Is Nothing Then + Debug.Print ""Not found"" + End If +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.IsFalse(inspectionResults.Any()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsNoResult_AssignedToVariableIsNothing() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + Dim result As Range + Set result = ws.UsedRange.Find(""foo"") + If result Is Nothing Then + Debug.Print ""Not found"" + End If +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.IsFalse(inspectionResults.Any()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_AssignedAndNotTested() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + Dim result As Range + Set result = ws.UsedRange.Find(""foo"") + result.Value = ""bar"" +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_ResultIsSomethingElse() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + Dim result As Range + Set result = ws.Range(""A1"") + If ws.UsedRange.Find(""foo"") Is result Then + Debug.Print ""Found it the dumb way"" + End If +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_FindNext() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + Dim foo As Range + Set foo = ws.UsedRange.Find(""foo"") + If Not foo Is Nothing Then + bar = ws.UsedRange.FindNext(foo).Row + End If +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_FindPrevious() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + Dim foo As Range + Set foo = ws.UsedRange.Find(""foo"") + If Not foo Is Nothing Then + bar = ws.UsedRange.FindPrevious(foo).Row + End If +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_DefaultAccessExpression() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + If ws.Range(""B:B"").Find(""bar"") = 1 Then + Debug.Print ""bar"" + End If +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_FindAsWithBlockVariable() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + With ws.UsedRange.Find(""foo"") + foo = .Row + End With +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_ReturnsResult_AssignedToWithBlockVariable() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + Dim result As Range + Set result = ws.UsedRange.Find(""foo"") + With result + .Value = ""bar"" + End With +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.AreEqual(1, inspectionResults.Count()); + } + } + + private static RubberduckParserState ArrangeParserAndParse(string inputCode) + { + var builder = new MockVbeBuilder(); + var project = builder.ProjectBuilder("VBAProject", ProjectProtection.Unprotected) + .AddComponent("Module1", ComponentType.StandardModule, inputCode) + .AddReference("Excel", MockVbeBuilder.LibraryPathMsExcel, 1, 8, true) + .Build(); + + var vbe = builder.AddProject(project).Build(); + + return MockParser.CreateAndParse(vbe.Object); ; + } + } +} From 6284ead1a354844270984f30bbc43ea811e4d241 Mon Sep 17 00:00:00 2001 From: comintern Date: Thu, 1 Nov 2018 22:40:26 -0500 Subject: [PATCH 034/107] Fix Designer generation from .resx files. --- Rubberduck.Resources/Rubberduck.Resources.csproj | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Rubberduck.Resources/Rubberduck.Resources.csproj b/Rubberduck.Resources/Rubberduck.Resources.csproj index 88e5eb41a0..5e05ae3570 100644 --- a/Rubberduck.Resources/Rubberduck.Resources.csproj +++ b/Rubberduck.Resources/Rubberduck.Resources.csproj @@ -12,12 +12,20 @@ - - PublicResXFileCodeGenerator - $([System.String]::Copy('%(FileName)')).Designer.cs - + + + + True + True $([System.String]::Copy('%(Filename)').Replace('.Designer', '')).resx + + + + ResXFileCodeGenerator + $([System.String]::Copy('%(FileName)')).Designer.cs + + \ No newline at end of file From 56c43dcf10ac10b9d7de929d893d184863cabb80 Mon Sep 17 00:00:00 2001 From: comintern Date: Thu, 1 Nov 2018 22:41:21 -0500 Subject: [PATCH 035/107] Add resources for ExcelMemberMayReturnNothingInspection. --- .../Inspections/InspectionInfo.Designer.cs | 169 +++++++++-------- .../Inspections/InspectionInfo.resx | 3 + .../Inspections/InspectionNames.Designer.cs | 169 +++++++++-------- .../Inspections/InspectionNames.resx | 3 + .../Inspections/InspectionResults.Designer.cs | 179 +++++++++--------- .../Inspections/InspectionResults.resx | 4 + 6 files changed, 282 insertions(+), 245 deletions(-) diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs index e399928601..4c5b082e00 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs @@ -22,7 +22,7 @@ namespace Rubberduck.Resources.Inspections { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class InspectionInfo { + internal class InspectionInfo { private static global::System.Resources.ResourceManager resourceMan; @@ -36,7 +36,7 @@ internal InspectionInfo() { /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Resources.ResourceManager ResourceManager { + internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Rubberduck.Resources.Inspections.InspectionInfo", typeof(InspectionInfo).Assembly); @@ -51,7 +51,7 @@ internal InspectionInfo() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Globalization.CultureInfo Culture { + internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -63,7 +63,7 @@ internal InspectionInfo() { /// /// Looks up a localized string similar to The Excel Application object does not implement the WorksheetFunction interface directly. All calls made to WorksheetFunction members are handled as late bound and errors in the called member will be returned wrapped in a Variant of VbVarType.vbError. This makes errors un-trappable with error handlers and adds a performance penalty in comparison to early bound calls. Consider calling Application.WorksheetFunction explicitly. Note: If this call generated errors in the past, those errors were ignored. If appl [rest of string was truncated]";. /// - public static string ApplicationWorksheetFunctionInspection { + internal static string ApplicationWorksheetFunctionInspection { get { return ResourceManager.GetString("ApplicationWorksheetFunctionInspection", resourceCulture); } @@ -72,7 +72,7 @@ public static string ApplicationWorksheetFunctionInspection { /// /// Looks up a localized string similar to Parameter is passed by value, but is assigned a new value/reference. Consider making a local copy instead if the caller isn't supposed to know the new value. If the caller should see the new value, the parameter should be passed ByRef instead, and you have a bug.. /// - public static string AssignedByValParameterInspection { + internal static string AssignedByValParameterInspection { get { return ResourceManager.GetString("AssignedByValParameterInspection", resourceCulture); } @@ -81,7 +81,7 @@ public static string AssignedByValParameterInspection { /// /// Looks up a localized string similar to An assignment is immediately overridden by another assignment or is never referenced.. /// - public static string AssignmentNotUsedInspection { + internal static string AssignmentNotUsedInspection { get { return ResourceManager.GetString("AssignmentNotUsedInspection", resourceCulture); } @@ -90,7 +90,7 @@ public static string AssignmentNotUsedInspection { /// /// Looks up a localized string similar to A member is assigned True/False in different branches of an if statement with no other statements in the conditional. Use the condition directly to the member instead.. /// - public static string BooleanAssignedInIfElseInspection { + internal static string BooleanAssignedInIfElseInspection { get { return ResourceManager.GetString("BooleanAssignedInIfElseInspection", resourceCulture); } @@ -99,7 +99,7 @@ public static string BooleanAssignedInIfElseInspection { /// /// Looks up a localized string similar to Rubberduck could not find any reference to constant. Consider removing the unused declaration.. /// - public static string ConstantNotUsedInspection { + internal static string ConstantNotUsedInspection { get { return ResourceManager.GetString("ConstantNotUsedInspection", resourceCulture); } @@ -108,7 +108,7 @@ public static string ConstantNotUsedInspection { /// /// Looks up a localized string similar to Consider naming your VBA project.. /// - public static string DefaultProjectNameInspection { + internal static string DefaultProjectNameInspection { get { return ResourceManager.GetString("DefaultProjectNameInspection", resourceCulture); } @@ -117,7 +117,7 @@ public static string DefaultProjectNameInspection { /// /// Looks up a localized string similar to Using the 'Def[Type]' statement leads to specifying types by using a prefix. This style of naming is heavily discouraged and should be avoided.. /// - public static string DefTypeStatementInspection { + internal static string DefTypeStatementInspection { get { return ResourceManager.GetString("DefTypeStatementInspection", resourceCulture); } @@ -126,7 +126,7 @@ public static string DefTypeStatementInspection { /// /// Looks up a localized string similar to An annotation is specified multiple times, but is intended to be specified only once.. /// - public static string DuplicatedAnnotationInspection { + internal static string DuplicatedAnnotationInspection { get { return ResourceManager.GetString("DuplicatedAnnotationInspection", resourceCulture); } @@ -135,7 +135,7 @@ public static string DuplicatedAnnotationInspection { /// /// Looks up a localized string similar to An empty 'Case' block without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - public static string EmptyCaseBlockInspection { + internal static string EmptyCaseBlockInspection { get { return ResourceManager.GetString("EmptyCaseBlockInspection", resourceCulture); } @@ -144,7 +144,7 @@ public static string EmptyCaseBlockInspection { /// /// Looks up a localized string similar to An empty 'Do...While' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - public static string EmptyDoWhileBlockInspection { + internal static string EmptyDoWhileBlockInspection { get { return ResourceManager.GetString("EmptyDoWhileBlockInspection", resourceCulture); } @@ -153,7 +153,7 @@ public static string EmptyDoWhileBlockInspection { /// /// Looks up a localized string similar to An empty 'Else' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - public static string EmptyElseBlockInspection { + internal static string EmptyElseBlockInspection { get { return ResourceManager.GetString("EmptyElseBlockInspection", resourceCulture); } @@ -162,7 +162,7 @@ public static string EmptyElseBlockInspection { /// /// Looks up a localized string similar to An empty 'For Each...Next' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - public static string EmptyForEachBlockInspection { + internal static string EmptyForEachBlockInspection { get { return ResourceManager.GetString("EmptyForEachBlockInspection", resourceCulture); } @@ -171,7 +171,7 @@ public static string EmptyForEachBlockInspection { /// /// Looks up a localized string similar to An empty 'For...Next' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - public static string EmptyForLoopBlockInspection { + internal static string EmptyForLoopBlockInspection { get { return ResourceManager.GetString("EmptyForLoopBlockInspection", resourceCulture); } @@ -180,7 +180,7 @@ public static string EmptyForLoopBlockInspection { /// /// Looks up a localized string similar to An empty conditional branch without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - public static string EmptyIfBlockInspection { + internal static string EmptyIfBlockInspection { get { return ResourceManager.GetString("EmptyIfBlockInspection", resourceCulture); } @@ -189,7 +189,7 @@ public static string EmptyIfBlockInspection { /// /// Looks up a localized string similar to Empty modules and classes either point to not yet implemented functionality or represent unnecessary baggage that can hurt the maintainability of a project.. /// - public static string EmptyModuleInspection { + internal static string EmptyModuleInspection { get { return ResourceManager.GetString("EmptyModuleInspection", resourceCulture); } @@ -198,7 +198,7 @@ public static string EmptyModuleInspection { /// /// Looks up a localized string similar to The built-in constant 'vbNullString' is a null string pointer taking up 0 bytes of memory, that unambiguously conveys the intent of an empty string.. /// - public static string EmptyStringLiteralInspection { + internal static string EmptyStringLiteralInspection { get { return ResourceManager.GetString("EmptyStringLiteralInspection", resourceCulture); } @@ -207,7 +207,7 @@ public static string EmptyStringLiteralInspection { /// /// Looks up a localized string similar to An empty 'Loop' block without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - public static string EmptyWhileWendBlockInspection { + internal static string EmptyWhileWendBlockInspection { get { return ResourceManager.GetString("EmptyWhileWendBlockInspection", resourceCulture); } @@ -216,16 +216,25 @@ public static string EmptyWhileWendBlockInspection { /// /// Looks up a localized string similar to Consider exposing a property instead.. /// - public static string EncapsulatePublicFieldInspection { + internal static string EncapsulatePublicFieldInspection { get { return ResourceManager.GetString("EncapsulatePublicFieldInspection", resourceCulture); } } + /// + /// Looks up a localized string similar to A Function or Property returning a reference type that can be 'Nothing' should not have the return value used with a test for 'Is Nothing'. If the member does not return a valid object, attempting to use the return value will result in a run-time error 91 - "Object variable or With block variable not set".. + /// + internal static string ExcelMemberMayReturnNothingInspection { + get { + return ResourceManager.GetString("ExcelMemberMayReturnNothingInspection", resourceCulture); + } + } + /// /// Looks up a localized string similar to A member is written as a function, but used as a procedure. Unless the function is recursive, consider converting the 'Function' into a 'Sub'. If the function is recursive, none of its external callers are using the returned value.. /// - public static string FunctionReturnValueNotUsedInspection { + internal static string FunctionReturnValueNotUsedInspection { get { return ResourceManager.GetString("FunctionReturnValueNotUsedInspection", resourceCulture); } @@ -234,7 +243,7 @@ public static string FunctionReturnValueNotUsedInspection { /// /// Looks up a localized string similar to Bracketed expressions are evaluated by the host application at runtime, which means VBA can't validate the expression at compile-time. Consider using the host application's object model instead.. /// - public static string HostSpecificExpressionInspection { + internal static string HostSpecificExpressionInspection { get { return ResourceManager.GetString("HostSpecificExpressionInspection", resourceCulture); } @@ -243,7 +252,7 @@ public static string HostSpecificExpressionInspection { /// /// Looks up a localized string similar to Hungarian notation makes code less readable, and is redundant when strongly typed variables and meaningful names are used.. /// - public static string HungarianNotationInspection { + internal static string HungarianNotationInspection { get { return ResourceManager.GetString("HungarianNotationInspection", resourceCulture); } @@ -252,7 +261,7 @@ public static string HungarianNotationInspection { /// /// Looks up a localized string similar to An annotation meant to be specified at module level cannot be used to annotate members; annotations meant to be annotate members cannot be used at module level.. /// - public static string IllegalAnnotationInspection { + internal static string IllegalAnnotationInspection { get { return ResourceManager.GetString("IllegalAnnotationInspection", resourceCulture); } @@ -261,7 +270,7 @@ public static string IllegalAnnotationInspection { /// /// Looks up a localized string similar to Implicit references to the active sheet make the code frail and harder to debug. Consider making these references explicit when they're intended, and prefer working off object references. Ignore if the member call is referring to a type Rubberduck can't resolve.. /// - public static string ImplicitActiveSheetReferenceInspection { + internal static string ImplicitActiveSheetReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveSheetReferenceInspection", resourceCulture); } @@ -270,7 +279,7 @@ public static string ImplicitActiveSheetReferenceInspection { /// /// Looks up a localized string similar to Implicit references to the active workbook make the code frail and harder to debug. Consider making these references explicit when they're intended, and prefer working off object references. Ignore if the member call is referring to a type Rubberduck can't resolve.. /// - public static string ImplicitActiveWorkbookReferenceInspection { + internal static string ImplicitActiveWorkbookReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveWorkbookReferenceInspection", resourceCulture); } @@ -279,7 +288,7 @@ public static string ImplicitActiveWorkbookReferenceInspection { /// /// Looks up a localized string similar to Parameters are passed by reference unless specified otherwise, which can be confusing and bug-prone. Prefer passing parameters by value, and specify ByRef explicitly when passing parameters by reference.. /// - public static string ImplicitByRefModifierInspection { + internal static string ImplicitByRefModifierInspection { get { return ResourceManager.GetString("ImplicitByRefModifierInspection", resourceCulture); } @@ -288,7 +297,7 @@ public static string ImplicitByRefModifierInspection { /// /// Looks up a localized string similar to Such assignments look like they are assigning an object variable to a value type on the surface, but they are actually assigning that object's default member, implicitly. Consider referring to the default member explicitly, for improved readability.. /// - public static string ImplicitDefaultMemberAssignmentInspection { + internal static string ImplicitDefaultMemberAssignmentInspection { get { return ResourceManager.GetString("ImplicitDefaultMemberAssignmentInspection", resourceCulture); } @@ -297,7 +306,7 @@ public static string ImplicitDefaultMemberAssignmentInspection { /// /// Looks up a localized string similar to Module members are public by default, which can be counter-intuitive. Consider specifying explicit access modifiers to avoid ambiguity.. /// - public static string ImplicitPublicMemberInspection { + internal static string ImplicitPublicMemberInspection { get { return ResourceManager.GetString("ImplicitPublicMemberInspection", resourceCulture); } @@ -306,7 +315,7 @@ public static string ImplicitPublicMemberInspection { /// /// Looks up a localized string similar to Members with a return value implicitly return a 'Variant' unless specified otherwise. Consider returning an explicit 'Variant' when the return type isn't known, or specify it explicitly.. /// - public static string ImplicitVariantReturnTypeInspection { + internal static string ImplicitVariantReturnTypeInspection { get { return ResourceManager.GetString("ImplicitVariantReturnTypeInspection", resourceCulture); } @@ -315,7 +324,7 @@ public static string ImplicitVariantReturnTypeInspection { /// /// Looks up a localized string similar to The maximum value of a 16-bit signed integer is 32,767 - using a 32-bit (Long) integer data type where possible can help prevent 'Overflow' run-time errors, and is better handled by modern CPUs.. /// - public static string IntegerDataTypeInspection { + internal static string IntegerDataTypeInspection { get { return ResourceManager.GetString("IntegerDataTypeInspection", resourceCulture); } @@ -324,7 +333,7 @@ public static string IntegerDataTypeInspection { /// /// Looks up a localized string similar to IsMissing is only intended to be called on optional arguments, and will only return correct results if the type of the argument is 'Variant' with no explicit default value. All other uses will return 'False'.. /// - public static string IsMissingOnInappropriateArgumentInspection { + internal static string IsMissingOnInappropriateArgumentInspection { get { return ResourceManager.GetString("IsMissingOnInappropriateArgumentInspection", resourceCulture); } @@ -333,7 +342,7 @@ public static string IsMissingOnInappropriateArgumentInspection { /// /// Looks up a localized string similar to IsMissing is only intended to be called on arguments of the containing procedure, and almost all other usages will return 'False'. Passing any other expression to the function is the equivalent to 'VarType({expression}) = vbError', and in rare circumstances can cause the host application to crash.. /// - public static string IsMissingWithNonArgumentParameterInspection { + internal static string IsMissingWithNonArgumentParameterInspection { get { return ResourceManager.GetString("IsMissingWithNonArgumentParameterInspection", resourceCulture); } @@ -342,7 +351,7 @@ public static string IsMissingWithNonArgumentParameterInspection { /// /// Looks up a localized string similar to A line label that is never jumpted to ('GoTo', 'Resume', ...), serves no purpose. Consider removing it.. /// - public static string LineLabelNotUsedInspection { + internal static string LineLabelNotUsedInspection { get { return ResourceManager.GetString("LineLabelNotUsedInspection", resourceCulture); } @@ -351,7 +360,7 @@ public static string LineLabelNotUsedInspection { /// /// Looks up a localized string similar to A member access call is made against an extended interface that Rubberduck couldn't resolve, or the member couldn't be found. If VBA cannot resolve the type at run-time, error 438 will be raised. If an equivalent, non-extended interface that Rubberduck can resolve is available, consider using it instead.. /// - public static string MemberNotOnInterfaceInspection { + internal static string MemberNotOnInterfaceInspection { get { return ResourceManager.GetString("MemberNotOnInterfaceInspection", resourceCulture); } @@ -360,7 +369,7 @@ public static string MemberNotOnInterfaceInspection { /// /// Looks up a localized string similar to An annotation parameter is missing or incorrectly specified. The correct syntax is : '@Annotation([parameter])\nExample: '@Folder("Parent.Child"). /// - public static string MissingAnnotationArgumentInspection { + internal static string MissingAnnotationArgumentInspection { get { return ResourceManager.GetString("MissingAnnotationArgumentInspection", resourceCulture); } @@ -369,7 +378,7 @@ public static string MissingAnnotationArgumentInspection { /// /// Looks up a localized string similar to Module and member attributes are not displayed in the VBE. By adding an annotation, you make these attributes more explicit, and Rubberduck can keep annotations and attributes synchronized.. /// - public static string MissingAnnotationInspection { + internal static string MissingAnnotationInspection { get { return ResourceManager.GetString("MissingAnnotationInspection", resourceCulture); } @@ -378,7 +387,7 @@ public static string MissingAnnotationInspection { /// /// Looks up a localized string similar to A Rubberduck annotation is specified for a module or member, but the corresponding attribute isn't present. Module attributes and annotations need to be synchronized.. /// - public static string MissingAttributeInspection { + internal static string MissingAttributeInspection { get { return ResourceManager.GetString("MissingAttributeInspection", resourceCulture); } @@ -387,7 +396,7 @@ public static string MissingAttributeInspection { /// /// Looks up a localized string similar to The 'Public' keyword can only be used at module level; its counterpart 'Private' can also only be used at module level. 'Dim' however, can be used to declare both procedure and module scope variables. For consistency, it would be preferable to reserve 'Dim' for locals, and thus to use 'Private' instead of 'Dim' at module level.. /// - public static string ModuleScopeDimKeywordInspection { + internal static string ModuleScopeDimKeywordInspection { get { return ResourceManager.GetString("ModuleScopeDimKeywordInspection", resourceCulture); } @@ -396,7 +405,7 @@ public static string ModuleScopeDimKeywordInspection { /// /// Looks up a localized string similar to Modules without the '@Folder' annotation cannot receive custom groupings in the Code Explorer. . /// - public static string ModuleWithoutFolderInspection { + internal static string ModuleWithoutFolderInspection { get { return ResourceManager.GetString("ModuleWithoutFolderInspection", resourceCulture); } @@ -405,7 +414,7 @@ public static string ModuleWithoutFolderInspection { /// /// Looks up a localized string similar to A module-level variable used only in one procedure should be declared in that procedure.. /// - public static string MoveFieldCloserToUsageInspection { + internal static string MoveFieldCloserToUsageInspection { get { return ResourceManager.GetString("MoveFieldCloserToUsageInspection", resourceCulture); } @@ -414,7 +423,7 @@ public static string MoveFieldCloserToUsageInspection { /// /// Looks up a localized string similar to Consider continuing long signatures between parameters. Splitting a parameter declaration across multiple lines arguably hurts readability.. /// - public static string MultilineParameterInspection { + internal static string MultilineParameterInspection { get { return ResourceManager.GetString("MultilineParameterInspection", resourceCulture); } @@ -423,7 +432,7 @@ public static string MultilineParameterInspection { /// /// Looks up a localized string similar to Declaring multiple variables in the same instruction is legal, but should be used sparingly. Consider declaring variables closer to their usage, in a single instruction per declaration.. /// - public static string MultipleDeclarationsInspection { + internal static string MultipleDeclarationsInspection { get { return ResourceManager.GetString("MultipleDeclarationsInspection", resourceCulture); } @@ -432,7 +441,7 @@ public static string MultipleDeclarationsInspection { /// /// Looks up a localized string similar to This is likely a bug. The return value of a function or property getter must be assigned before exiting, otherwise the program will not be working with expected results. If a function has no meaningful return value, consider declaring it as a 'Sub' procedure instead.. /// - public static string NonReturningFunctionInspection { + internal static string NonReturningFunctionInspection { get { return ResourceManager.GetString("NonReturningFunctionInspection", resourceCulture); } @@ -441,7 +450,7 @@ public static string NonReturningFunctionInspection { /// /// Looks up a localized string similar to As far as Rubberduck can tell, this variable is an object variable, assigned without the 'Set' keyword. This causes run-time error 91 'Object or With block variable not set'.. /// - public static string ObjectVariableNotSetInspection { + internal static string ObjectVariableNotSetInspection { get { return ResourceManager.GetString("ObjectVariableNotSetInspection", resourceCulture); } @@ -450,7 +459,7 @@ public static string ObjectVariableNotSetInspection { /// /// Looks up a localized string similar to Windows implementations of Visual Basic only support the StdCall calling convention, and use of of the CDecl calling convention is only supported in Macintosh versions of VBA. Use of this keyword in Windows will result in runtime error 49 - 'Bad DLL calling convention'. If this procedure is only intended to be used on Macintosh hosts, it should be conditionally compiled.. /// - public static string ObsoleteCallingConventionInspection { + internal static string ObsoleteCallingConventionInspection { get { return ResourceManager.GetString("ObsoleteCallingConventionInspection", resourceCulture); } @@ -459,7 +468,7 @@ public static string ObsoleteCallingConventionInspection { /// /// Looks up a localized string similar to The 'Call' statement is no longer required to call procedures, and only exists in the language to support legacy code that required it; it can be safely rewritten to an implicit call.. /// - public static string ObsoleteCallStatementInspection { + internal static string ObsoleteCallStatementInspection { get { return ResourceManager.GetString("ObsoleteCallStatementInspection", resourceCulture); } @@ -468,7 +477,7 @@ public static string ObsoleteCallStatementInspection { /// /// Looks up a localized string similar to The 'Rem' statement only exists in the language to support legacy code that required it; it can be safely replaced with an apostrophe / single-quote comment.. /// - public static string ObsoleteCommentSyntaxInspection { + internal static string ObsoleteCommentSyntaxInspection { get { return ResourceManager.GetString("ObsoleteCommentSyntaxInspection", resourceCulture); } @@ -477,7 +486,7 @@ public static string ObsoleteCommentSyntaxInspection { /// /// Looks up a localized string similar to The 'Error' statement only exists in the language to support legacy code that required it; prefer using 'Err.Raise' instead.. /// - public static string ObsoleteErrorSyntaxInspection { + internal static string ObsoleteErrorSyntaxInspection { get { return ResourceManager.GetString("ObsoleteErrorSyntaxInspection", resourceCulture); } @@ -486,7 +495,7 @@ public static string ObsoleteErrorSyntaxInspection { /// /// Looks up a localized string similar to The 'Global' keyword only exists in the language to support legacy code that required it; it can be safely replaced with the 'Public' modifier.. /// - public static string ObsoleteGlobalInspection { + internal static string ObsoleteGlobalInspection { get { return ResourceManager.GetString("ObsoleteGlobalInspection", resourceCulture); } @@ -495,7 +504,7 @@ public static string ObsoleteGlobalInspection { /// /// Looks up a localized string similar to The 'Let' statement only exists in the language to support legacy code that required it; it can be safely removed, since modern VBA does not require that keyword for value assignments.. /// - public static string ObsoleteLetStatementInspection { + internal static string ObsoleteLetStatementInspection { get { return ResourceManager.GetString("ObsoleteLetStatementInspection", resourceCulture); } @@ -504,7 +513,7 @@ public static string ObsoleteLetStatementInspection { /// /// Looks up a localized string similar to This member is marked '@Obsolete'. It should no longer be used, there should be a better alternative.. /// - public static string ObsoleteMemberUsageInspection { + internal static string ObsoleteMemberUsageInspection { get { return ResourceManager.GetString("ObsoleteMemberUsageInspection", resourceCulture); } @@ -513,7 +522,7 @@ public static string ObsoleteMemberUsageInspection { /// /// Looks up a localized string similar to Type hint characters only exist in the language to support legacy code that required it; they can be safely replaced in declarations with an "As" type clause that specifies the type explicitly, and they can be omitted in other identifier references.. /// - public static string ObsoleteTypeHintInspection { + internal static string ObsoleteTypeHintInspection { get { return ResourceManager.GetString("ObsoleteTypeHintInspection", resourceCulture); } @@ -522,7 +531,7 @@ public static string ObsoleteTypeHintInspection { /// /// Looks up a localized string similar to On Local Error exists only for compatibility with previous versions of Visual Basic, and all Errors are treated as Local regardless of the Error statement. Use of this keyword inaccurately gives the impression that there is a distinction between types of error handling when there is not.. /// - public static string OnLocalErrorInspection { + internal static string OnLocalErrorInspection { get { return ResourceManager.GetString("OnLocalErrorInspection", resourceCulture); } @@ -531,7 +540,7 @@ public static string OnLocalErrorInspection { /// /// Looks up a localized string similar to Arrays are typically zero-based. This option changes the default lower boundary for implicitly-sized arrays, which can introduce off-by-one errors if one isn't cautious.. /// - public static string OptionBaseInspection { + internal static string OptionBaseInspection { get { return ResourceManager.GetString("OptionBaseInspection", resourceCulture); } @@ -540,7 +549,7 @@ public static string OptionBaseInspection { /// /// Looks up a localized string similar to This is the default setting, it does not need to be specified.. /// - public static string OptionBaseZeroInspection { + internal static string OptionBaseZeroInspection { get { return ResourceManager.GetString("OptionBaseZeroInspection", resourceCulture); } @@ -549,7 +558,7 @@ public static string OptionBaseZeroInspection { /// /// Looks up a localized string similar to VBA will happily compile a typo: use 'Option Explicit' to prevent successfully compiling an erroneous program.. /// - public static string OptionExplicitInspection { + internal static string OptionExplicitInspection { get { return ResourceManager.GetString("OptionExplicitInspection", resourceCulture); } @@ -558,7 +567,7 @@ public static string OptionExplicitInspection { /// /// Looks up a localized string similar to A parameter that is passed by reference and isn't assigned a new value/reference, could be passed by value instead.. /// - public static string ParameterCanBeByValInspection { + internal static string ParameterCanBeByValInspection { get { return ResourceManager.GetString("ParameterCanBeByValInspection", resourceCulture); } @@ -567,7 +576,7 @@ public static string ParameterCanBeByValInspection { /// /// Looks up a localized string similar to A parameter is passed into a member that does not use it. Consider removing that parameter.. /// - public static string ParameterNotUsedInspection { + internal static string ParameterNotUsedInspection { get { return ResourceManager.GetString("ParameterNotUsedInspection", resourceCulture); } @@ -576,7 +585,7 @@ public static string ParameterNotUsedInspection { /// /// Looks up a localized string similar to A procedure that only has one parameter passed by reference that is assigned a new value/reference before the procedure exits, is using a ByRef parameter as a return value: consider making it a function instead.. /// - public static string ProcedureCanBeWrittenAsFunctionInspection { + internal static string ProcedureCanBeWrittenAsFunctionInspection { get { return ResourceManager.GetString("ProcedureCanBeWrittenAsFunctionInspection", resourceCulture); } @@ -585,7 +594,7 @@ public static string ProcedureCanBeWrittenAsFunctionInspection { /// /// Looks up a localized string similar to Rubberduck could not find any caller for a procedure. If the procedure is hooked to a macro-button, used as a user-defined function (UDF) or handles an application event that Rubberduck didn't know of you can safely ignore this inspection result; otherwise, consider removing it.. /// - public static string ProcedureNotUsedInspection { + internal static string ProcedureNotUsedInspection { get { return ResourceManager.GetString("ProcedureNotUsedInspection", resourceCulture); } @@ -594,7 +603,7 @@ public static string ProcedureNotUsedInspection { /// /// Looks up a localized string similar to By default, all parameters are passed by reference, so it is not necessary to include the 'ByRef' modifier.. /// - public static string RedundantByRefModifierInspection { + internal static string RedundantByRefModifierInspection { get { return ResourceManager.GetString("RedundantByRefModifierInspection", resourceCulture); } @@ -603,7 +612,7 @@ public static string RedundantByRefModifierInspection { /// /// Looks up a localized string similar to Being the default/implicit setting for this option, this instruction can be safely omitted.. /// - public static string RedundantOptionInspection { + internal static string RedundantOptionInspection { get { return ResourceManager.GetString("RedundantOptionInspection", resourceCulture); } @@ -612,7 +621,7 @@ public static string RedundantOptionInspection { /// /// Looks up a localized string similar to An auto-instantiated object variable declaration at procedure scope changes how nulling the reference works, which can lead to unexpected behavior.. /// - public static string SelfAssignedDeclarationInspection { + internal static string SelfAssignedDeclarationInspection { get { return ResourceManager.GetString("SelfAssignedDeclarationInspection", resourceCulture); } @@ -621,7 +630,7 @@ public static string SelfAssignedDeclarationInspection { /// /// Looks up a localized string similar to Two declarations are in scope and have the same identifier name. This means that only one of them will be available to use.. /// - public static string ShadowedDeclarationInspection { + internal static string ShadowedDeclarationInspection { get { return ResourceManager.GetString("ShadowedDeclarationInspection", resourceCulture); } @@ -630,7 +639,7 @@ public static string ShadowedDeclarationInspection { /// /// Looks up a localized string similar to Excel already defines a globally scoped object variable with this reference. Consider using the sheet's 'CodeName' property.. /// - public static string SheetAccessedUsingStringInspection { + internal static string SheetAccessedUsingStringInspection { get { return ResourceManager.GetString("SheetAccessedUsingStringInspection", resourceCulture); } @@ -639,7 +648,7 @@ public static string SheetAccessedUsingStringInspection { /// /// Looks up a localized string similar to Step of the for-next loop is not specified. This might be unintentional.. /// - public static string StepIsNotSpecifiedInspection { + internal static string StepIsNotSpecifiedInspection { get { return ResourceManager.GetString("StepIsNotSpecifiedInspection", resourceCulture); } @@ -648,7 +657,7 @@ public static string StepIsNotSpecifiedInspection { /// /// Looks up a localized string similar to 1 is the default step in a for-next loop and therefore is redundant.. /// - public static string StepOneIsRedundantInspection { + internal static string StepOneIsRedundantInspection { get { return ResourceManager.GetString("StepOneIsRedundantInspection", resourceCulture); } @@ -657,7 +666,7 @@ public static string StepOneIsRedundantInspection { /// /// Looks up a localized string similar to The 'Stop' keyword halts execution and brings up the debugger. Avoid its use in distributed code.. /// - public static string StopKeywordInspection { + internal static string StopKeywordInspection { get { return ResourceManager.GetString("StopKeywordInspection", resourceCulture); } @@ -666,7 +675,7 @@ public static string StopKeywordInspection { /// /// Looks up a localized string similar to This is likely a bug. A variable is being referred to, but is never assigned.. /// - public static string UnassignedVariableUsageInspection { + internal static string UnassignedVariableUsageInspection { get { return ResourceManager.GetString("UnassignedVariableUsageInspection", resourceCulture); } @@ -675,7 +684,7 @@ public static string UnassignedVariableUsageInspection { /// /// Looks up a localized string similar to Code that uses undeclared variables does not compile when Option Explicit is specified. Undeclared variables are always Variant, a data type that incurs unnecessary overhead and storage.. /// - public static string UndeclaredVariableInspection { + internal static string UndeclaredVariableInspection { get { return ResourceManager.GetString("UndeclaredVariableInspection", resourceCulture); } @@ -684,7 +693,7 @@ public static string UndeclaredVariableInspection { /// /// Looks up a localized string similar to Error handling should be restored after using 'On Error Resume Next'.. /// - public static string UnhandledOnErrorResumeNextInspection { + internal static string UnhandledOnErrorResumeNextInspection { get { return ResourceManager.GetString("UnhandledOnErrorResumeNextInspection", resourceCulture); } @@ -693,7 +702,7 @@ public static string UnhandledOnErrorResumeNextInspection { /// /// Looks up a localized string similar to Detects Case Clauses that will never execute. . /// - public static string UnreachableCaseInspection { + internal static string UnreachableCaseInspection { get { return ResourceManager.GetString("UnreachableCaseInspection", resourceCulture); } @@ -703,7 +712,7 @@ public static string UnreachableCaseInspection { /// Looks up a localized string similar to A string-returning equivalent function exists and should preferably be used to avoid implicit type conversions. ///If the parameter can be null, ignore this inspection result; passing a null value to a function expecting a string would raise a type mismatch runtime error.. /// - public static string UntypedFunctionUsageInspection { + internal static string UntypedFunctionUsageInspection { get { return ResourceManager.GetString("UntypedFunctionUsageInspection", resourceCulture); } @@ -712,7 +721,7 @@ public static string UntypedFunctionUsageInspection { /// /// Looks up a localized string similar to Identifier names should indicate what they're used for and should be readable; avoid disemvoweling, numeric suffixes, and 1-2 character names.. /// - public static string UseMeaningfulNameInspection { + internal static string UseMeaningfulNameInspection { get { return ResourceManager.GetString("UseMeaningfulNameInspection", resourceCulture); } @@ -721,7 +730,7 @@ public static string UseMeaningfulNameInspection { /// /// Looks up a localized string similar to Variable is not assigned. If this isn't intended, there's probably a bug. Ignore this inspection result if the variable is assigned in another procedure via a ByRef parameter.. /// - public static string VariableNotAssignedInspection { + internal static string VariableNotAssignedInspection { get { return ResourceManager.GetString("VariableNotAssignedInspection", resourceCulture); } @@ -730,7 +739,7 @@ public static string VariableNotAssignedInspection { /// /// Looks up a localized string similar to Variable is not referred to. /// - public static string VariableNotUsedInspection { + internal static string VariableNotUsedInspection { get { return ResourceManager.GetString("VariableNotUsedInspection", resourceCulture); } @@ -739,7 +748,7 @@ public static string VariableNotUsedInspection { /// /// Looks up a localized string similar to A variable whose type isn't explicitly declared, is implicitly 'Variant'. Consider making it an explicit 'Variant' if that's intended, or declare a more specific type.. /// - public static string VariableTypeNotDeclaredInspection { + internal static string VariableTypeNotDeclaredInspection { get { return ResourceManager.GetString("VariableTypeNotDeclaredInspection", resourceCulture); } @@ -748,7 +757,7 @@ public static string VariableTypeNotDeclaredInspection { /// /// Looks up a localized string similar to A property that exposes a mutator but no accessor is a design smell and makes a confusing API. Consider exposing a getter, or converting the mutator to a method.. /// - public static string WriteOnlyPropertyInspection { + internal static string WriteOnlyPropertyInspection { get { return ResourceManager.GetString("WriteOnlyPropertyInspection", resourceCulture); } diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.resx b/Rubberduck.Resources/Inspections/InspectionInfo.resx index b06e89193b..3958388d8a 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.resx +++ b/Rubberduck.Resources/Inspections/InspectionInfo.resx @@ -349,4 +349,7 @@ If the parameter can be null, ignore this inspection result; passing a null valu An assignment is immediately overridden by another assignment or is never referenced. + + A Function or Property returning a reference type that can be 'Nothing' should not have the return value used with a test for 'Is Nothing'. If the member does not return a valid object, attempting to use the return value will result in a run-time error 91 - "Object variable or With block variable not set". + \ No newline at end of file diff --git a/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs b/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs index f13cc181ab..a0111fba23 100644 --- a/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs @@ -22,7 +22,7 @@ namespace Rubberduck.Resources.Inspections { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class InspectionNames { + internal class InspectionNames { private static global::System.Resources.ResourceManager resourceMan; @@ -36,7 +36,7 @@ internal InspectionNames() { /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Resources.ResourceManager ResourceManager { + internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Rubberduck.Resources.Inspections.InspectionNames", typeof(InspectionNames).Assembly); @@ -51,7 +51,7 @@ internal InspectionNames() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Globalization.CultureInfo Culture { + internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -63,7 +63,7 @@ internal InspectionNames() { /// /// Looks up a localized string similar to Late bound WorksheetFunction call.. /// - public static string ApplicationWorksheetFunctionInspection { + internal static string ApplicationWorksheetFunctionInspection { get { return ResourceManager.GetString("ApplicationWorksheetFunctionInspection", resourceCulture); } @@ -72,7 +72,7 @@ public static string ApplicationWorksheetFunctionInspection { /// /// Looks up a localized string similar to ByVal parameter is assigned. /// - public static string AssignedByValParameterInspection { + internal static string AssignedByValParameterInspection { get { return ResourceManager.GetString("AssignedByValParameterInspection", resourceCulture); } @@ -81,7 +81,7 @@ public static string AssignedByValParameterInspection { /// /// Looks up a localized string similar to Assignment is not used. /// - public static string AssignmentNotUsedInspection { + internal static string AssignmentNotUsedInspection { get { return ResourceManager.GetString("AssignmentNotUsedInspection", resourceCulture); } @@ -90,7 +90,7 @@ public static string AssignmentNotUsedInspection { /// /// Looks up a localized string similar to Boolean literal assignment in conditional. /// - public static string BooleanAssignedInIfElseInspection { + internal static string BooleanAssignedInIfElseInspection { get { return ResourceManager.GetString("BooleanAssignedInIfElseInspection", resourceCulture); } @@ -99,7 +99,7 @@ public static string BooleanAssignedInIfElseInspection { /// /// Looks up a localized string similar to Constant is not used. /// - public static string ConstantNotUsedInspection { + internal static string ConstantNotUsedInspection { get { return ResourceManager.GetString("ConstantNotUsedInspection", resourceCulture); } @@ -108,7 +108,7 @@ public static string ConstantNotUsedInspection { /// /// Looks up a localized string similar to Project name is not specified. /// - public static string DefaultProjectNameInspection { + internal static string DefaultProjectNameInspection { get { return ResourceManager.GetString("DefaultProjectNameInspection", resourceCulture); } @@ -117,7 +117,7 @@ public static string DefaultProjectNameInspection { /// /// Looks up a localized string similar to Usage of 'Def[Type]' statement. /// - public static string DefTypeStatementInspection { + internal static string DefTypeStatementInspection { get { return ResourceManager.GetString("DefTypeStatementInspection", resourceCulture); } @@ -126,7 +126,7 @@ public static string DefTypeStatementInspection { /// /// Looks up a localized string similar to Annotation is duplicated. /// - public static string DuplicatedAnnotationInspection { + internal static string DuplicatedAnnotationInspection { get { return ResourceManager.GetString("DuplicatedAnnotationInspection", resourceCulture); } @@ -135,7 +135,7 @@ public static string DuplicatedAnnotationInspection { /// /// Looks up a localized string similar to Empty 'Case' block. /// - public static string EmptyCaseBlockInspection { + internal static string EmptyCaseBlockInspection { get { return ResourceManager.GetString("EmptyCaseBlockInspection", resourceCulture); } @@ -144,7 +144,7 @@ public static string EmptyCaseBlockInspection { /// /// Looks up a localized string similar to Empty 'Do...While' Loop. /// - public static string EmptyDoWhileBlockInspection { + internal static string EmptyDoWhileBlockInspection { get { return ResourceManager.GetString("EmptyDoWhileBlockInspection", resourceCulture); } @@ -153,7 +153,7 @@ public static string EmptyDoWhileBlockInspection { /// /// Looks up a localized string similar to Empty 'Else' block. /// - public static string EmptyElseBlockInspection { + internal static string EmptyElseBlockInspection { get { return ResourceManager.GetString("EmptyElseBlockInspection", resourceCulture); } @@ -162,7 +162,7 @@ public static string EmptyElseBlockInspection { /// /// Looks up a localized string similar to Empty 'For Each...Next' Loop. /// - public static string EmptyForEachBlockInspection { + internal static string EmptyForEachBlockInspection { get { return ResourceManager.GetString("EmptyForEachBlockInspection", resourceCulture); } @@ -171,7 +171,7 @@ public static string EmptyForEachBlockInspection { /// /// Looks up a localized string similar to Empty 'For...Next' Loop. /// - public static string EmptyForLoopBlockInspection { + internal static string EmptyForLoopBlockInspection { get { return ResourceManager.GetString("EmptyForLoopBlockInspection", resourceCulture); } @@ -180,7 +180,7 @@ public static string EmptyForLoopBlockInspection { /// /// Looks up a localized string similar to Empty conditional branch. /// - public static string EmptyIfBlockInspection { + internal static string EmptyIfBlockInspection { get { return ResourceManager.GetString("EmptyIfBlockInspection", resourceCulture); } @@ -189,7 +189,7 @@ public static string EmptyIfBlockInspection { /// /// Looks up a localized string similar to Empty module. /// - public static string EmptyModuleInspection { + internal static string EmptyModuleInspection { get { return ResourceManager.GetString("EmptyModuleInspection", resourceCulture); } @@ -198,7 +198,7 @@ public static string EmptyModuleInspection { /// /// Looks up a localized string similar to Empty string literal. /// - public static string EmptyStringLiteralInspection { + internal static string EmptyStringLiteralInspection { get { return ResourceManager.GetString("EmptyStringLiteralInspection", resourceCulture); } @@ -207,7 +207,7 @@ public static string EmptyStringLiteralInspection { /// /// Looks up a localized string similar to Empty 'While...Wend' loop. /// - public static string EmptyWhileWendBlockInspection { + internal static string EmptyWhileWendBlockInspection { get { return ResourceManager.GetString("EmptyWhileWendBlockInspection", resourceCulture); } @@ -216,16 +216,25 @@ public static string EmptyWhileWendBlockInspection { /// /// Looks up a localized string similar to Public field breaks encapsulation. /// - public static string EncapsulatePublicFieldInspection { + internal static string EncapsulatePublicFieldInspection { get { return ResourceManager.GetString("EncapsulatePublicFieldInspection", resourceCulture); } } + /// + /// Looks up a localized string similar to Member access may return 'Nothing'. + /// + internal static string ExcelMemberMayReturnNothingInspection { + get { + return ResourceManager.GetString("ExcelMemberMayReturnNothingInspection", resourceCulture); + } + } + /// /// Looks up a localized string similar to Function return value is never used. /// - public static string FunctionReturnValueNotUsedInspection { + internal static string FunctionReturnValueNotUsedInspection { get { return ResourceManager.GetString("FunctionReturnValueNotUsedInspection", resourceCulture); } @@ -234,7 +243,7 @@ public static string FunctionReturnValueNotUsedInspection { /// /// Looks up a localized string similar to Host-specific bracketed expression is only evaluated at runtime. /// - public static string HostSpecificExpressionInspection { + internal static string HostSpecificExpressionInspection { get { return ResourceManager.GetString("HostSpecificExpressionInspection", resourceCulture); } @@ -243,7 +252,7 @@ public static string HostSpecificExpressionInspection { /// /// Looks up a localized string similar to Variable uses Hungarian notation.. /// - public static string HungarianNotationInspection { + internal static string HungarianNotationInspection { get { return ResourceManager.GetString("HungarianNotationInspection", resourceCulture); } @@ -252,7 +261,7 @@ public static string HungarianNotationInspection { /// /// Looks up a localized string similar to Illegal annotation. /// - public static string IllegalAnnotationInspection { + internal static string IllegalAnnotationInspection { get { return ResourceManager.GetString("IllegalAnnotationInspection", resourceCulture); } @@ -261,7 +270,7 @@ public static string IllegalAnnotationInspection { /// /// Looks up a localized string similar to Implicit reference to ActiveSheet. /// - public static string ImplicitActiveSheetReferenceInspection { + internal static string ImplicitActiveSheetReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveSheetReferenceInspection", resourceCulture); } @@ -270,7 +279,7 @@ public static string ImplicitActiveSheetReferenceInspection { /// /// Looks up a localized string similar to Implicit reference to ActiveWorkbook. /// - public static string ImplicitActiveWorkbookReferenceInspection { + internal static string ImplicitActiveWorkbookReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveWorkbookReferenceInspection", resourceCulture); } @@ -279,7 +288,7 @@ public static string ImplicitActiveWorkbookReferenceInspection { /// /// Looks up a localized string similar to Implicit ByRef parameter. /// - public static string ImplicitByRefModifierInspection { + internal static string ImplicitByRefModifierInspection { get { return ResourceManager.GetString("ImplicitByRefModifierInspection", resourceCulture); } @@ -288,7 +297,7 @@ public static string ImplicitByRefModifierInspection { /// /// Looks up a localized string similar to Implicit default member assignment. /// - public static string ImplicitDefaultMemberAssignmentInspection { + internal static string ImplicitDefaultMemberAssignmentInspection { get { return ResourceManager.GetString("ImplicitDefaultMemberAssignmentInspection", resourceCulture); } @@ -297,7 +306,7 @@ public static string ImplicitDefaultMemberAssignmentInspection { /// /// Looks up a localized string similar to Implicitly public member. /// - public static string ImplicitPublicMemberInspection { + internal static string ImplicitPublicMemberInspection { get { return ResourceManager.GetString("ImplicitPublicMemberInspection", resourceCulture); } @@ -306,7 +315,7 @@ public static string ImplicitPublicMemberInspection { /// /// Looks up a localized string similar to Member return type is implicitly 'Variant'. /// - public static string ImplicitVariantReturnTypeInspection { + internal static string ImplicitVariantReturnTypeInspection { get { return ResourceManager.GetString("ImplicitVariantReturnTypeInspection", resourceCulture); } @@ -315,7 +324,7 @@ public static string ImplicitVariantReturnTypeInspection { /// /// Looks up a localized string similar to Use of 16-bit integer type. /// - public static string IntegerDataTypeInspection { + internal static string IntegerDataTypeInspection { get { return ResourceManager.GetString("IntegerDataTypeInspection", resourceCulture); } @@ -324,7 +333,7 @@ public static string IntegerDataTypeInspection { /// /// Looks up a localized string similar to Inappropriate use of 'IsMissing' function. /// - public static string IsMissingOnInappropriateArgumentInspection { + internal static string IsMissingOnInappropriateArgumentInspection { get { return ResourceManager.GetString("IsMissingOnInappropriateArgumentInspection", resourceCulture); } @@ -333,7 +342,7 @@ public static string IsMissingOnInappropriateArgumentInspection { /// /// Looks up a localized string similar to Inappropriate use of 'IsMissing' function. /// - public static string IsMissingWithNonArgumentParameterInspection { + internal static string IsMissingWithNonArgumentParameterInspection { get { return ResourceManager.GetString("IsMissingWithNonArgumentParameterInspection", resourceCulture); } @@ -342,7 +351,7 @@ public static string IsMissingWithNonArgumentParameterInspection { /// /// Looks up a localized string similar to Line label is not used. /// - public static string LineLabelNotUsedInspection { + internal static string LineLabelNotUsedInspection { get { return ResourceManager.GetString("LineLabelNotUsedInspection", resourceCulture); } @@ -351,7 +360,7 @@ public static string LineLabelNotUsedInspection { /// /// Looks up a localized string similar to Member not found. /// - public static string MemberNotOnInterfaceInspection { + internal static string MemberNotOnInterfaceInspection { get { return ResourceManager.GetString("MemberNotOnInterfaceInspection", resourceCulture); } @@ -360,7 +369,7 @@ public static string MemberNotOnInterfaceInspection { /// /// Looks up a localized string similar to Missing annotation parameter. /// - public static string MissingAnnotationArgumentInspection { + internal static string MissingAnnotationArgumentInspection { get { return ResourceManager.GetString("MissingAnnotationArgumentInspection", resourceCulture); } @@ -369,7 +378,7 @@ public static string MissingAnnotationArgumentInspection { /// /// Looks up a localized string similar to Missing annotation. /// - public static string MissingAnnotationInspection { + internal static string MissingAnnotationInspection { get { return ResourceManager.GetString("MissingAnnotationInspection", resourceCulture); } @@ -378,7 +387,7 @@ public static string MissingAnnotationInspection { /// /// Looks up a localized string similar to Missing attribute. /// - public static string MissingAttributeInspection { + internal static string MissingAttributeInspection { get { return ResourceManager.GetString("MissingAttributeInspection", resourceCulture); } @@ -387,7 +396,7 @@ public static string MissingAttributeInspection { /// /// Looks up a localized string similar to Use of 'Dim' keyword at module level. /// - public static string ModuleScopeDimKeywordInspection { + internal static string ModuleScopeDimKeywordInspection { get { return ResourceManager.GetString("ModuleScopeDimKeywordInspection", resourceCulture); } @@ -396,7 +405,7 @@ public static string ModuleScopeDimKeywordInspection { /// /// Looks up a localized string similar to Module without '@Folder' annotation. /// - public static string ModuleWithoutFolderInspection { + internal static string ModuleWithoutFolderInspection { get { return ResourceManager.GetString("ModuleWithoutFolderInspection", resourceCulture); } @@ -405,7 +414,7 @@ public static string ModuleWithoutFolderInspection { /// /// Looks up a localized string similar to Scope of variable is broader than it needs to be. /// - public static string MoveFieldCloserToUsageInspection { + internal static string MoveFieldCloserToUsageInspection { get { return ResourceManager.GetString("MoveFieldCloserToUsageInspection", resourceCulture); } @@ -414,7 +423,7 @@ public static string MoveFieldCloserToUsageInspection { /// /// Looks up a localized string similar to Parameter declaration is split on multiple lines. /// - public static string MultilineParameterInspection { + internal static string MultilineParameterInspection { get { return ResourceManager.GetString("MultilineParameterInspection", resourceCulture); } @@ -423,7 +432,7 @@ public static string MultilineParameterInspection { /// /// Looks up a localized string similar to Multiple declarations in single instruction. /// - public static string MultipleDeclarationsInspection { + internal static string MultipleDeclarationsInspection { get { return ResourceManager.GetString("MultipleDeclarationsInspection", resourceCulture); } @@ -432,7 +441,7 @@ public static string MultipleDeclarationsInspection { /// /// Looks up a localized string similar to Non-returning function or property getter. /// - public static string NonReturningFunctionInspection { + internal static string NonReturningFunctionInspection { get { return ResourceManager.GetString("NonReturningFunctionInspection", resourceCulture); } @@ -441,7 +450,7 @@ public static string NonReturningFunctionInspection { /// /// Looks up a localized string similar to Object variable assignment requires 'Set' keyword. /// - public static string ObjectVariableNotSetInspection { + internal static string ObjectVariableNotSetInspection { get { return ResourceManager.GetString("ObjectVariableNotSetInspection", resourceCulture); } @@ -450,7 +459,7 @@ public static string ObjectVariableNotSetInspection { /// /// Looks up a localized string similar to Use of obsolete 'CDecl' calling convention. /// - public static string ObsoleteCallingConventionInspection { + internal static string ObsoleteCallingConventionInspection { get { return ResourceManager.GetString("ObsoleteCallingConventionInspection", resourceCulture); } @@ -459,7 +468,7 @@ public static string ObsoleteCallingConventionInspection { /// /// Looks up a localized string similar to Use of obsolete 'Call' statement. /// - public static string ObsoleteCallStatementInspection { + internal static string ObsoleteCallStatementInspection { get { return ResourceManager.GetString("ObsoleteCallStatementInspection", resourceCulture); } @@ -468,7 +477,7 @@ public static string ObsoleteCallStatementInspection { /// /// Looks up a localized string similar to Use of obsolete 'Rem' statement. /// - public static string ObsoleteCommentSyntaxInspection { + internal static string ObsoleteCommentSyntaxInspection { get { return ResourceManager.GetString("ObsoleteCommentSyntaxInspection", resourceCulture); } @@ -477,7 +486,7 @@ public static string ObsoleteCommentSyntaxInspection { /// /// Looks up a localized string similar to Use of obsolete 'Error' statement. /// - public static string ObsoleteErrorSyntaxInspection { + internal static string ObsoleteErrorSyntaxInspection { get { return ResourceManager.GetString("ObsoleteErrorSyntaxInspection", resourceCulture); } @@ -486,7 +495,7 @@ public static string ObsoleteErrorSyntaxInspection { /// /// Looks up a localized string similar to Use of obsolete 'Global' access modifier. /// - public static string ObsoleteGlobalInspection { + internal static string ObsoleteGlobalInspection { get { return ResourceManager.GetString("ObsoleteGlobalInspection", resourceCulture); } @@ -495,7 +504,7 @@ public static string ObsoleteGlobalInspection { /// /// Looks up a localized string similar to Use of obsolete explicit 'Let' statement. /// - public static string ObsoleteLetStatementInspection { + internal static string ObsoleteLetStatementInspection { get { return ResourceManager.GetString("ObsoleteLetStatementInspection", resourceCulture); } @@ -504,7 +513,7 @@ public static string ObsoleteLetStatementInspection { /// /// Looks up a localized string similar to Member marked as '@Obsolete' is used. /// - public static string ObsoleteMemberUsageInspection { + internal static string ObsoleteMemberUsageInspection { get { return ResourceManager.GetString("ObsoleteMemberUsageInspection", resourceCulture); } @@ -513,7 +522,7 @@ public static string ObsoleteMemberUsageInspection { /// /// Looks up a localized string similar to Obsolete Type hint usage. /// - public static string ObsoleteTypeHintInspection { + internal static string ObsoleteTypeHintInspection { get { return ResourceManager.GetString("ObsoleteTypeHintInspection", resourceCulture); } @@ -522,7 +531,7 @@ public static string ObsoleteTypeHintInspection { /// /// Looks up a localized string similar to On Local Error statement. /// - public static string OnLocalErrorInspection { + internal static string OnLocalErrorInspection { get { return ResourceManager.GetString("OnLocalErrorInspection", resourceCulture); } @@ -531,7 +540,7 @@ public static string OnLocalErrorInspection { /// /// Looks up a localized string similar to 'Option Base 1' is specified. /// - public static string OptionBaseInspection { + internal static string OptionBaseInspection { get { return ResourceManager.GetString("OptionBaseInspection", resourceCulture); } @@ -540,7 +549,7 @@ public static string OptionBaseInspection { /// /// Looks up a localized string similar to 'Option Base 0' is redundant. /// - public static string OptionBaseZeroInspection { + internal static string OptionBaseZeroInspection { get { return ResourceManager.GetString("OptionBaseZeroInspection", resourceCulture); } @@ -549,7 +558,7 @@ public static string OptionBaseZeroInspection { /// /// Looks up a localized string similar to 'Option Explicit' is not specified. /// - public static string OptionExplicitInspection { + internal static string OptionExplicitInspection { get { return ResourceManager.GetString("OptionExplicitInspection", resourceCulture); } @@ -558,7 +567,7 @@ public static string OptionExplicitInspection { /// /// Looks up a localized string similar to Parameter can be passed by value. /// - public static string ParameterCanBeByValInspection { + internal static string ParameterCanBeByValInspection { get { return ResourceManager.GetString("ParameterCanBeByValInspection", resourceCulture); } @@ -567,7 +576,7 @@ public static string ParameterCanBeByValInspection { /// /// Looks up a localized string similar to Parameter is not referred to. /// - public static string ParameterNotUsedInspection { + internal static string ParameterNotUsedInspection { get { return ResourceManager.GetString("ParameterNotUsedInspection", resourceCulture); } @@ -576,7 +585,7 @@ public static string ParameterNotUsedInspection { /// /// Looks up a localized string similar to Procedure can be written as a function. /// - public static string ProcedureCanBeWrittenAsFunctionInspection { + internal static string ProcedureCanBeWrittenAsFunctionInspection { get { return ResourceManager.GetString("ProcedureCanBeWrittenAsFunctionInspection", resourceCulture); } @@ -585,7 +594,7 @@ public static string ProcedureCanBeWrittenAsFunctionInspection { /// /// Looks up a localized string similar to Procedure is not referred to. /// - public static string ProcedureNotUsedInspection { + internal static string ProcedureNotUsedInspection { get { return ResourceManager.GetString("ProcedureNotUsedInspection", resourceCulture); } @@ -594,7 +603,7 @@ public static string ProcedureNotUsedInspection { /// /// Looks up a localized string similar to Redundant 'ByRef' modifier. /// - public static string RedundantByRefModifierInspection { + internal static string RedundantByRefModifierInspection { get { return ResourceManager.GetString("RedundantByRefModifierInspection", resourceCulture); } @@ -603,7 +612,7 @@ public static string RedundantByRefModifierInspection { /// /// Looks up a localized string similar to Redundant module option. /// - public static string RedundantOptionInspection { + internal static string RedundantOptionInspection { get { return ResourceManager.GetString("RedundantOptionInspection", resourceCulture); } @@ -612,7 +621,7 @@ public static string RedundantOptionInspection { /// /// Looks up a localized string similar to Object variable reference is auto-instantiated. /// - public static string SelfAssignedDeclarationInspection { + internal static string SelfAssignedDeclarationInspection { get { return ResourceManager.GetString("SelfAssignedDeclarationInspection", resourceCulture); } @@ -621,7 +630,7 @@ public static string SelfAssignedDeclarationInspection { /// /// Looks up a localized string similar to Shadowed declaration. /// - public static string ShadowedDeclarationInspection { + internal static string ShadowedDeclarationInspection { get { return ResourceManager.GetString("ShadowedDeclarationInspection", resourceCulture); } @@ -630,7 +639,7 @@ public static string ShadowedDeclarationInspection { /// /// Looks up a localized string similar to Statically accessible sheet accessed using string. /// - public static string SheetAccessedUsingStringInspection { + internal static string SheetAccessedUsingStringInspection { get { return ResourceManager.GetString("SheetAccessedUsingStringInspection", resourceCulture); } @@ -639,7 +648,7 @@ public static string SheetAccessedUsingStringInspection { /// /// Looks up a localized string similar to 'For...Next' loop step is not specified. /// - public static string StepIsNotSpecifiedInspection { + internal static string StepIsNotSpecifiedInspection { get { return ResourceManager.GetString("StepIsNotSpecifiedInspection", resourceCulture); } @@ -648,7 +657,7 @@ public static string StepIsNotSpecifiedInspection { /// /// Looks up a localized string similar to 'For...Next' loop step 1 is redundant. /// - public static string StepOneIsRedundantInspection { + internal static string StepOneIsRedundantInspection { get { return ResourceManager.GetString("StepOneIsRedundantInspection", resourceCulture); } @@ -657,7 +666,7 @@ public static string StepOneIsRedundantInspection { /// /// Looks up a localized string similar to 'Stop' keyword. /// - public static string StopKeywordInspection { + internal static string StopKeywordInspection { get { return ResourceManager.GetString("StopKeywordInspection", resourceCulture); } @@ -666,7 +675,7 @@ public static string StopKeywordInspection { /// /// Looks up a localized string similar to Variable is used but not assigned. /// - public static string UnassignedVariableUsageInspection { + internal static string UnassignedVariableUsageInspection { get { return ResourceManager.GetString("UnassignedVariableUsageInspection", resourceCulture); } @@ -675,7 +684,7 @@ public static string UnassignedVariableUsageInspection { /// /// Looks up a localized string similar to Undeclared variable. /// - public static string UndeclaredVariableInspection { + internal static string UndeclaredVariableInspection { get { return ResourceManager.GetString("UndeclaredVariableInspection", resourceCulture); } @@ -684,7 +693,7 @@ public static string UndeclaredVariableInspection { /// /// Looks up a localized string similar to Unhandled 'On Error Resume Next'. /// - public static string UnhandledOnErrorResumeNextInspection { + internal static string UnhandledOnErrorResumeNextInspection { get { return ResourceManager.GetString("UnhandledOnErrorResumeNextInspection", resourceCulture); } @@ -693,7 +702,7 @@ public static string UnhandledOnErrorResumeNextInspection { /// /// Looks up a localized string similar to Case Clause(s) cannot be reached. /// - public static string UnreachableCaseInspection { + internal static string UnreachableCaseInspection { get { return ResourceManager.GetString("UnreachableCaseInspection", resourceCulture); } @@ -702,7 +711,7 @@ public static string UnreachableCaseInspection { /// /// Looks up a localized string similar to Use of variant-returning string function. /// - public static string UntypedFunctionUsageInspection { + internal static string UntypedFunctionUsageInspection { get { return ResourceManager.GetString("UntypedFunctionUsageInspection", resourceCulture); } @@ -711,7 +720,7 @@ public static string UntypedFunctionUsageInspection { /// /// Looks up a localized string similar to Use meaningful names. /// - public static string UseMeaningfulNameInspection { + internal static string UseMeaningfulNameInspection { get { return ResourceManager.GetString("UseMeaningfulNameInspection", resourceCulture); } @@ -720,7 +729,7 @@ public static string UseMeaningfulNameInspection { /// /// Looks up a localized string similar to Variable is not assigned. /// - public static string VariableNotAssignedInspection { + internal static string VariableNotAssignedInspection { get { return ResourceManager.GetString("VariableNotAssignedInspection", resourceCulture); } @@ -729,7 +738,7 @@ public static string VariableNotAssignedInspection { /// /// Looks up a localized string similar to Variable is not referred to. /// - public static string VariableNotUsedInspection { + internal static string VariableNotUsedInspection { get { return ResourceManager.GetString("VariableNotUsedInspection", resourceCulture); } @@ -738,7 +747,7 @@ public static string VariableNotUsedInspection { /// /// Looks up a localized string similar to Implicitly 'Variant' variable. /// - public static string VariableTypeNotDeclaredInspection { + internal static string VariableTypeNotDeclaredInspection { get { return ResourceManager.GetString("VariableTypeNotDeclaredInspection", resourceCulture); } @@ -747,7 +756,7 @@ public static string VariableTypeNotDeclaredInspection { /// /// Looks up a localized string similar to Write-only property. /// - public static string WriteOnlyPropertyInspection { + internal static string WriteOnlyPropertyInspection { get { return ResourceManager.GetString("WriteOnlyPropertyInspection", resourceCulture); } diff --git a/Rubberduck.Resources/Inspections/InspectionNames.resx b/Rubberduck.Resources/Inspections/InspectionNames.resx index 619f5ddbb9..f505a7b740 100644 --- a/Rubberduck.Resources/Inspections/InspectionNames.resx +++ b/Rubberduck.Resources/Inspections/InspectionNames.resx @@ -348,4 +348,7 @@ Assignment is not used + + Member access may return 'Nothing' + \ No newline at end of file diff --git a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs index 02946f951a..ec61bb7a7d 100644 --- a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs @@ -22,7 +22,7 @@ namespace Rubberduck.Resources.Inspections { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class InspectionResults { + internal class InspectionResults { private static global::System.Resources.ResourceManager resourceMan; @@ -36,7 +36,7 @@ internal InspectionResults() { /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Resources.ResourceManager ResourceManager { + internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Rubberduck.Resources.Inspections.InspectionResults", typeof(InspectionResults).Assembly); @@ -51,7 +51,7 @@ internal InspectionResults() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Globalization.CultureInfo Culture { + internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -63,7 +63,7 @@ internal InspectionResults() { /// /// Looks up a localized string similar to {0} ({1} results).. /// - public static string AggregateInspection { + internal static string AggregateInspection { get { return ResourceManager.GetString("AggregateInspection", resourceCulture); } @@ -72,7 +72,7 @@ public static string AggregateInspection { /// /// Looks up a localized string similar to Use of late bound 'Application.{0}' member.. /// - public static string ApplicationWorksheetFunctionInspection { + internal static string ApplicationWorksheetFunctionInspection { get { return ResourceManager.GetString("ApplicationWorksheetFunctionInspection", resourceCulture); } @@ -81,7 +81,7 @@ public static string ApplicationWorksheetFunctionInspection { /// /// Looks up a localized string similar to Parameter '{0}' is passed 'ByVal' and assigned a value.. /// - public static string AssignedByValParameterInspection { + internal static string AssignedByValParameterInspection { get { return ResourceManager.GetString("AssignedByValParameterInspection", resourceCulture); } @@ -90,7 +90,7 @@ public static string AssignedByValParameterInspection { /// /// Looks up a localized string similar to An assignment is immediately overridden by another assignment or is never referenced.. /// - public static string AssignmentNotUsedInspection { + internal static string AssignmentNotUsedInspection { get { return ResourceManager.GetString("AssignmentNotUsedInspection", resourceCulture); } @@ -99,7 +99,7 @@ public static string AssignmentNotUsedInspection { /// /// Looks up a localized string similar to Boolean literal '{0}' assigned in conditional.. /// - public static string BooleanAssignedInIfElseInspection { + internal static string BooleanAssignedInIfElseInspection { get { return ResourceManager.GetString("BooleanAssignedInIfElseInspection", resourceCulture); } @@ -108,7 +108,7 @@ public static string BooleanAssignedInIfElseInspection { /// /// Looks up a localized string similar to Project '{0}' has default name.. /// - public static string DefaultProjectNameInspection { + internal static string DefaultProjectNameInspection { get { return ResourceManager.GetString("DefaultProjectNameInspection", resourceCulture); } @@ -117,7 +117,7 @@ public static string DefaultProjectNameInspection { /// /// Looks up a localized string similar to Consider the explicit use of 'As {0}' instead of '{1}'.. /// - public static string DefTypeStatementInspection { + internal static string DefTypeStatementInspection { get { return ResourceManager.GetString("DefTypeStatementInspection", resourceCulture); } @@ -126,7 +126,7 @@ public static string DefTypeStatementInspection { /// /// Looks up a localized string similar to Annotation '{0}' is duplicated.. /// - public static string DuplicatedAnnotationInspection { + internal static string DuplicatedAnnotationInspection { get { return ResourceManager.GetString("DuplicatedAnnotationInspection", resourceCulture); } @@ -135,7 +135,7 @@ public static string DuplicatedAnnotationInspection { /// /// Looks up a localized string similar to 'Case' block contains no executable statements.. /// - public static string EmptyCaseBlockInspection { + internal static string EmptyCaseBlockInspection { get { return ResourceManager.GetString("EmptyCaseBlockInspection", resourceCulture); } @@ -144,7 +144,7 @@ public static string EmptyCaseBlockInspection { /// /// Looks up a localized string similar to 'Do...While' loop contains no executable statements.. /// - public static string EmptyDoWhileBlockInspection { + internal static string EmptyDoWhileBlockInspection { get { return ResourceManager.GetString("EmptyDoWhileBlockInspection", resourceCulture); } @@ -153,7 +153,7 @@ public static string EmptyDoWhileBlockInspection { /// /// Looks up a localized string similar to 'Else' block contains no executable statements.. /// - public static string EmptyElseBlockInspection { + internal static string EmptyElseBlockInspection { get { return ResourceManager.GetString("EmptyElseBlockInspection", resourceCulture); } @@ -162,7 +162,7 @@ public static string EmptyElseBlockInspection { /// /// Looks up a localized string similar to 'For...Each' loop contains no executable statements.. /// - public static string EmptyForEachBlockInspection { + internal static string EmptyForEachBlockInspection { get { return ResourceManager.GetString("EmptyForEachBlockInspection", resourceCulture); } @@ -171,7 +171,7 @@ public static string EmptyForEachBlockInspection { /// /// Looks up a localized string similar to 'For...Next' loop contains no executable statements.. /// - public static string EmptyForLoopBlockInspection { + internal static string EmptyForLoopBlockInspection { get { return ResourceManager.GetString("EmptyForLoopBlockInspection", resourceCulture); } @@ -180,7 +180,7 @@ public static string EmptyForLoopBlockInspection { /// /// Looks up a localized string similar to 'If' block contains no executable statements.. /// - public static string EmptyIfBlockInspection { + internal static string EmptyIfBlockInspection { get { return ResourceManager.GetString("EmptyIfBlockInspection", resourceCulture); } @@ -189,7 +189,7 @@ public static string EmptyIfBlockInspection { /// /// Looks up a localized string similar to Module/class '{0}' is empty.. /// - public static string EmptyModuleInspection { + internal static string EmptyModuleInspection { get { return ResourceManager.GetString("EmptyModuleInspection", resourceCulture); } @@ -198,7 +198,7 @@ public static string EmptyModuleInspection { /// /// Looks up a localized string similar to 'vbNullString' preferred to empty string literals.. /// - public static string EmptyStringLiteralInspection { + internal static string EmptyStringLiteralInspection { get { return ResourceManager.GetString("EmptyStringLiteralInspection", resourceCulture); } @@ -207,7 +207,7 @@ public static string EmptyStringLiteralInspection { /// /// Looks up a localized string similar to 'While...Wend' loop contains no executable statements.. /// - public static string EmptyWhileWendBlockInspection { + internal static string EmptyWhileWendBlockInspection { get { return ResourceManager.GetString("EmptyWhileWendBlockInspection", resourceCulture); } @@ -216,16 +216,25 @@ public static string EmptyWhileWendBlockInspection { /// /// Looks up a localized string similar to Public field '{0}' breaks encapsulation.. /// - public static string EncapsulatePublicFieldInspection { + internal static string EncapsulatePublicFieldInspection { get { return ResourceManager.GetString("EncapsulatePublicFieldInspection", resourceCulture); } } + /// + /// Looks up a localized string similar to Result of '{0}' call is not tested for 'Nothing'.. + /// + internal static string ExcelMemberMayReturnNothingInspection { + get { + return ResourceManager.GetString("ExcelMemberMayReturnNothingInspection", resourceCulture); + } + } + /// /// Looks up a localized string similar to Return value of function '{0}' is never used.. /// - public static string FunctionReturnValueNotUsedInspection { + internal static string FunctionReturnValueNotUsedInspection { get { return ResourceManager.GetString("FunctionReturnValueNotUsedInspection", resourceCulture); } @@ -234,7 +243,7 @@ public static string FunctionReturnValueNotUsedInspection { /// /// Looks up a localized string similar to Expression '{0}' cannot be validated at compile-time.. /// - public static string HostSpecificExpressionInspection { + internal static string HostSpecificExpressionInspection { get { return ResourceManager.GetString("HostSpecificExpressionInspection", resourceCulture); } @@ -243,7 +252,7 @@ public static string HostSpecificExpressionInspection { /// /// Looks up a localized string similar to Consider renaming {0} '{1}'.. /// - public static string IdentifierNameInspection { + internal static string IdentifierNameInspection { get { return ResourceManager.GetString("IdentifierNameInspection", resourceCulture); } @@ -252,7 +261,7 @@ public static string IdentifierNameInspection { /// /// Looks up a localized string similar to {0} '{1}' is not used.. /// - public static string IdentifierNotUsedInspection { + internal static string IdentifierNotUsedInspection { get { return ResourceManager.GetString("IdentifierNotUsedInspection", resourceCulture); } @@ -261,7 +270,7 @@ public static string IdentifierNotUsedInspection { /// /// Looks up a localized string similar to Annotation '{0}' is illegal in this context.. /// - public static string IllegalAnnotationInspection { + internal static string IllegalAnnotationInspection { get { return ResourceManager.GetString("IllegalAnnotationInspection", resourceCulture); } @@ -270,7 +279,7 @@ public static string IllegalAnnotationInspection { /// /// Looks up a localized string similar to Member '{0}' implicitly references 'ActiveSheet'.. /// - public static string ImplicitActiveSheetReferenceInspection { + internal static string ImplicitActiveSheetReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveSheetReferenceInspection", resourceCulture); } @@ -279,7 +288,7 @@ public static string ImplicitActiveSheetReferenceInspection { /// /// Looks up a localized string similar to Member '{0}' implicitly references 'ActiveWorkbook'.. /// - public static string ImplicitActiveWorkbookReferenceInspection { + internal static string ImplicitActiveWorkbookReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveWorkbookReferenceInspection", resourceCulture); } @@ -288,7 +297,7 @@ public static string ImplicitActiveWorkbookReferenceInspection { /// /// Looks up a localized string similar to Parameter '{0}' is implicitly passed by reference.. /// - public static string ImplicitByRefModifierInspection { + internal static string ImplicitByRefModifierInspection { get { return ResourceManager.GetString("ImplicitByRefModifierInspection", resourceCulture); } @@ -297,7 +306,7 @@ public static string ImplicitByRefModifierInspection { /// /// Looks up a localized string similar to Assignment to '{0}' implicitly assigns default member of class '{1}'.. /// - public static string ImplicitDefaultMemberAssignmentInspection { + internal static string ImplicitDefaultMemberAssignmentInspection { get { return ResourceManager.GetString("ImplicitDefaultMemberAssignmentInspection", resourceCulture); } @@ -306,7 +315,7 @@ public static string ImplicitDefaultMemberAssignmentInspection { /// /// Looks up a localized string similar to Member '{0}' is implicitly public.. /// - public static string ImplicitPublicMemberInspection { + internal static string ImplicitPublicMemberInspection { get { return ResourceManager.GetString("ImplicitPublicMemberInspection", resourceCulture); } @@ -315,7 +324,7 @@ public static string ImplicitPublicMemberInspection { /// /// Looks up a localized string similar to {0} '{1}' is implicitly 'Variant'.. /// - public static string ImplicitVariantDeclarationInspection { + internal static string ImplicitVariantDeclarationInspection { get { return ResourceManager.GetString("ImplicitVariantDeclarationInspection", resourceCulture); } @@ -324,7 +333,7 @@ public static string ImplicitVariantDeclarationInspection { /// /// Looks up a localized string similar to Return type of member '{0}' is implicitly 'Variant'.. /// - public static string ImplicitVariantReturnTypeInspection { + internal static string ImplicitVariantReturnTypeInspection { get { return ResourceManager.GetString("ImplicitVariantReturnTypeInspection", resourceCulture); } @@ -333,7 +342,7 @@ public static string ImplicitVariantReturnTypeInspection { /// /// Looks up a localized string similar to {0} '{1}' is declared as 'Integer'.. /// - public static string IntegerDataTypeInspection { + internal static string IntegerDataTypeInspection { get { return ResourceManager.GetString("IntegerDataTypeInspection", resourceCulture); } @@ -342,7 +351,7 @@ public static string IntegerDataTypeInspection { /// /// Looks up a localized string similar to 'IsMissing' will always return false with the passed argument.. /// - public static string IsMissingOnInappropriateArgumentInspection { + internal static string IsMissingOnInappropriateArgumentInspection { get { return ResourceManager.GetString("IsMissingOnInappropriateArgumentInspection", resourceCulture); } @@ -351,7 +360,7 @@ public static string IsMissingOnInappropriateArgumentInspection { /// /// Looks up a localized string similar to 'IsMissing' is passed an expresssion that is not an argument to the enclosing procedure.. /// - public static string IsMissingWithNonArgumentParameterInspection { + internal static string IsMissingWithNonArgumentParameterInspection { get { return ResourceManager.GetString("IsMissingWithNonArgumentParameterInspection", resourceCulture); } @@ -360,7 +369,7 @@ public static string IsMissingWithNonArgumentParameterInspection { /// /// Looks up a localized string similar to Line label '{0}' is not used.. /// - public static string LineLabelNotUsedInspection { + internal static string LineLabelNotUsedInspection { get { return ResourceManager.GetString("LineLabelNotUsedInspection", resourceCulture); } @@ -369,7 +378,7 @@ public static string LineLabelNotUsedInspection { /// /// Looks up a localized string similar to Member '{0}' was not found on the compile-time interface for type '{1}'.. /// - public static string MemberNotOnInterfaceInspection { + internal static string MemberNotOnInterfaceInspection { get { return ResourceManager.GetString("MemberNotOnInterfaceInspection", resourceCulture); } @@ -378,7 +387,7 @@ public static string MemberNotOnInterfaceInspection { /// /// Looks up a localized string similar to Expression '{0}' was expected to contain a parameter, but none was specified.. /// - public static string MissingAnnotationArgumentInspection { + internal static string MissingAnnotationArgumentInspection { get { return ResourceManager.GetString("MissingAnnotationArgumentInspection", resourceCulture); } @@ -387,7 +396,7 @@ public static string MissingAnnotationArgumentInspection { /// /// Looks up a localized string similar to Module or member '{0}' has a '{1}' attribute, but no corresponding annotation.. /// - public static string MissingAnnotationInspection { + internal static string MissingAnnotationInspection { get { return ResourceManager.GetString("MissingAnnotationInspection", resourceCulture); } @@ -396,7 +405,7 @@ public static string MissingAnnotationInspection { /// /// Looks up a localized string similar to Module or member '{0}' has a '{1}' annotation, but no corresponding attribute.. /// - public static string MissingAttributeInspection { + internal static string MissingAttributeInspection { get { return ResourceManager.GetString("MissingAttributeInspection", resourceCulture); } @@ -405,7 +414,7 @@ public static string MissingAttributeInspection { /// /// Looks up a localized string similar to Module-level variable '{0}' is declared with the 'Dim' keyword.. /// - public static string ModuleScopeDimKeywordInspection { + internal static string ModuleScopeDimKeywordInspection { get { return ResourceManager.GetString("ModuleScopeDimKeywordInspection", resourceCulture); } @@ -414,7 +423,7 @@ public static string ModuleScopeDimKeywordInspection { /// /// Looks up a localized string similar to Module '{0}' has no '@Folder' annotation. /// - public static string ModuleWithoutFolderInspection { + internal static string ModuleWithoutFolderInspection { get { return ResourceManager.GetString("ModuleWithoutFolderInspection", resourceCulture); } @@ -423,7 +432,7 @@ public static string ModuleWithoutFolderInspection { /// /// Looks up a localized string similar to Move module-level variable '{0}' to a smaller scope.. /// - public static string MoveFieldCloserToUsageInspection { + internal static string MoveFieldCloserToUsageInspection { get { return ResourceManager.GetString("MoveFieldCloserToUsageInspection", resourceCulture); } @@ -432,7 +441,7 @@ public static string MoveFieldCloserToUsageInspection { /// /// Looks up a localized string similar to Parameter '{0}' is specified on multiple lines.. /// - public static string MultilineParameterInspection { + internal static string MultilineParameterInspection { get { return ResourceManager.GetString("MultilineParameterInspection", resourceCulture); } @@ -441,7 +450,7 @@ public static string MultilineParameterInspection { /// /// Looks up a localized string similar to Instruction contains multiple declarations.. /// - public static string MultipleDeclarationsInspection { + internal static string MultipleDeclarationsInspection { get { return ResourceManager.GetString("MultipleDeclarationsInspection", resourceCulture); } @@ -450,7 +459,7 @@ public static string MultipleDeclarationsInspection { /// /// Looks up a localized string similar to Return value for member '{0}' is never assigned.. /// - public static string NonReturningFunctionInspection { + internal static string NonReturningFunctionInspection { get { return ResourceManager.GetString("NonReturningFunctionInspection", resourceCulture); } @@ -459,7 +468,7 @@ public static string NonReturningFunctionInspection { /// /// Looks up a localized string similar to Object variable '{0}' is assigned without the 'Set' keyword.. /// - public static string ObjectVariableNotSetInspection { + internal static string ObjectVariableNotSetInspection { get { return ResourceManager.GetString("ObjectVariableNotSetInspection", resourceCulture); } @@ -468,7 +477,7 @@ public static string ObjectVariableNotSetInspection { /// /// Looks up a localized string similar to '{0}' is declared using the obsolete 'CDecl' calling convention.. /// - public static string ObsoleteCallingConventionInspection { + internal static string ObsoleteCallingConventionInspection { get { return ResourceManager.GetString("ObsoleteCallingConventionInspection", resourceCulture); } @@ -477,7 +486,7 @@ public static string ObsoleteCallingConventionInspection { /// /// Looks up a localized string similar to Assignment uses obsolete 'Call' modifier.. /// - public static string ObsoleteCallStatementInspection { + internal static string ObsoleteCallStatementInspection { get { return ResourceManager.GetString("ObsoleteCallStatementInspection", resourceCulture); } @@ -486,7 +495,7 @@ public static string ObsoleteCallStatementInspection { /// /// Looks up a localized string similar to Comment uses obsolete 'Rem' marker.. /// - public static string ObsoleteCommentSyntaxInspection { + internal static string ObsoleteCommentSyntaxInspection { get { return ResourceManager.GetString("ObsoleteCommentSyntaxInspection", resourceCulture); } @@ -495,7 +504,7 @@ public static string ObsoleteCommentSyntaxInspection { /// /// Looks up a localized string similar to A run-time error is raised using the obsolete 'Error' statement.. /// - public static string ObsoleteErrorSyntaxInspection { + internal static string ObsoleteErrorSyntaxInspection { get { return ResourceManager.GetString("ObsoleteErrorSyntaxInspection", resourceCulture); } @@ -504,7 +513,7 @@ public static string ObsoleteErrorSyntaxInspection { /// /// Looks up a localized string similar to {0} '{1}' uses obsolete 'Global' access modifier.. /// - public static string ObsoleteGlobalInspection { + internal static string ObsoleteGlobalInspection { get { return ResourceManager.GetString("ObsoleteGlobalInspection", resourceCulture); } @@ -513,7 +522,7 @@ public static string ObsoleteGlobalInspection { /// /// Looks up a localized string similar to Assignment uses obsolete 'Let' modifier.. /// - public static string ObsoleteLetStatementInspection { + internal static string ObsoleteLetStatementInspection { get { return ResourceManager.GetString("ObsoleteLetStatementInspection", resourceCulture); } @@ -522,7 +531,7 @@ public static string ObsoleteLetStatementInspection { /// /// Looks up a localized string similar to Consider replacing the call to '{0}'. {1}. /// - public static string ObsoleteMemberUsageInspection { + internal static string ObsoleteMemberUsageInspection { get { return ResourceManager.GetString("ObsoleteMemberUsageInspection", resourceCulture); } @@ -531,7 +540,7 @@ public static string ObsoleteMemberUsageInspection { /// /// Looks up a localized string similar to {0} of {1} '{2}' uses an obsolete type hint.. /// - public static string ObsoleteTypeHintInspection { + internal static string ObsoleteTypeHintInspection { get { return ResourceManager.GetString("ObsoleteTypeHintInspection", resourceCulture); } @@ -540,7 +549,7 @@ public static string ObsoleteTypeHintInspection { /// /// Looks up a localized string similar to 'On Local Error' statement detected.. /// - public static string OnLocalErrorInspection { + internal static string OnLocalErrorInspection { get { return ResourceManager.GetString("OnLocalErrorInspection", resourceCulture); } @@ -549,7 +558,7 @@ public static string OnLocalErrorInspection { /// /// Looks up a localized string similar to Component '{0}' uses 'Option Base 1'.. /// - public static string OptionBaseInspection { + internal static string OptionBaseInspection { get { return ResourceManager.GetString("OptionBaseInspection", resourceCulture); } @@ -558,7 +567,7 @@ public static string OptionBaseInspection { /// /// Looks up a localized string similar to Component '{0}' uses 'Option Base 0'.. /// - public static string OptionBaseZeroInspection { + internal static string OptionBaseZeroInspection { get { return ResourceManager.GetString("OptionBaseZeroInspection", resourceCulture); } @@ -567,7 +576,7 @@ public static string OptionBaseZeroInspection { /// /// Looks up a localized string similar to 'Option Explicit' is not specified in '{0}'.. /// - public static string OptionExplicitInspection { + internal static string OptionExplicitInspection { get { return ResourceManager.GetString("OptionExplicitInspection", resourceCulture); } @@ -576,7 +585,7 @@ public static string OptionExplicitInspection { /// /// Looks up a localized string similar to Parameter '{0}' can be passed by value.. /// - public static string ParameterCanBeByValInspection { + internal static string ParameterCanBeByValInspection { get { return ResourceManager.GetString("ParameterCanBeByValInspection", resourceCulture); } @@ -585,7 +594,7 @@ public static string ParameterCanBeByValInspection { /// /// Looks up a localized string similar to Parameter '{0}' is never used.. /// - public static string ParameterNotUsedInspection { + internal static string ParameterNotUsedInspection { get { return ResourceManager.GetString("ParameterNotUsedInspection", resourceCulture); } @@ -594,7 +603,7 @@ public static string ParameterNotUsedInspection { /// /// Looks up a localized string similar to Procedure '{0}' can be written as a function.. /// - public static string ProcedureCanBeWrittenAsFunctionInspection { + internal static string ProcedureCanBeWrittenAsFunctionInspection { get { return ResourceManager.GetString("ProcedureCanBeWrittenAsFunctionInspection", resourceCulture); } @@ -603,7 +612,7 @@ public static string ProcedureCanBeWrittenAsFunctionInspection { /// /// Looks up a localized string similar to Procedure '{0}' can be written as a function.. /// - public static string ProcedureShouldBeFunctionInspection { + internal static string ProcedureShouldBeFunctionInspection { get { return ResourceManager.GetString("ProcedureShouldBeFunctionInspection", resourceCulture); } @@ -612,7 +621,7 @@ public static string ProcedureShouldBeFunctionInspection { /// /// Looks up a localized string similar to Parameter '{0}' has a redundant 'ByRef' modifier.. /// - public static string RedundantByRefModifierInspection { + internal static string RedundantByRefModifierInspection { get { return ResourceManager.GetString("RedundantByRefModifierInspection", resourceCulture); } @@ -621,7 +630,7 @@ public static string RedundantByRefModifierInspection { /// /// Looks up a localized string similar to '{0}' has no effect.. /// - public static string RedundantOptionInspection { + internal static string RedundantOptionInspection { get { return ResourceManager.GetString("RedundantOptionInspection", resourceCulture); } @@ -630,7 +639,7 @@ public static string RedundantOptionInspection { /// /// Looks up a localized string similar to Object reference '{0}' is auto-instantiated.. /// - public static string SelfAssignedDeclarationInspection { + internal static string SelfAssignedDeclarationInspection { get { return ResourceManager.GetString("SelfAssignedDeclarationInspection", resourceCulture); } @@ -639,7 +648,7 @@ public static string SelfAssignedDeclarationInspection { /// /// Looks up a localized string similar to {0} '{1}' hides {2} '{3}'.. /// - public static string ShadowedDeclarationInspection { + internal static string ShadowedDeclarationInspection { get { return ResourceManager.GetString("ShadowedDeclarationInspection", resourceCulture); } @@ -648,7 +657,7 @@ public static string ShadowedDeclarationInspection { /// /// Looks up a localized string similar to Statically accessible sheet can be referred to by its code name.. /// - public static string SheetAccessedUsingStringInspection { + internal static string SheetAccessedUsingStringInspection { get { return ResourceManager.GetString("SheetAccessedUsingStringInspection", resourceCulture); } @@ -657,7 +666,7 @@ public static string SheetAccessedUsingStringInspection { /// /// Looks up a localized string similar to 'Step' not specified.. /// - public static string StepIsNotSpecifiedInspection { + internal static string StepIsNotSpecifiedInspection { get { return ResourceManager.GetString("StepIsNotSpecifiedInspection", resourceCulture); } @@ -666,7 +675,7 @@ public static string StepIsNotSpecifiedInspection { /// /// Looks up a localized string similar to 1 is the default step in a 'For...Next' loop and therefore is redundant.. /// - public static string StepOneIsRedundantInspection { + internal static string StepOneIsRedundantInspection { get { return ResourceManager.GetString("StepOneIsRedundantInspection", resourceCulture); } @@ -675,7 +684,7 @@ public static string StepOneIsRedundantInspection { /// /// Looks up a localized string similar to 'Stop' keyword halts execution.. /// - public static string StopKeywordInspection { + internal static string StopKeywordInspection { get { return ResourceManager.GetString("StopKeywordInspection", resourceCulture); } @@ -684,7 +693,7 @@ public static string StopKeywordInspection { /// /// Looks up a localized string similar to Variable '{0}' is used but not assigned.. /// - public static string UnassignedVariableUsageInspection { + internal static string UnassignedVariableUsageInspection { get { return ResourceManager.GetString("UnassignedVariableUsageInspection", resourceCulture); } @@ -693,7 +702,7 @@ public static string UnassignedVariableUsageInspection { /// /// Looks up a localized string similar to Local variable '{0}' is not declared.. /// - public static string UndeclaredVariableInspection { + internal static string UndeclaredVariableInspection { get { return ResourceManager.GetString("UndeclaredVariableInspection", resourceCulture); } @@ -702,7 +711,7 @@ public static string UndeclaredVariableInspection { /// /// Looks up a localized string similar to Errors are ignored but never handled again.. /// - public static string UnhandledOnErrorResumeNextInspection { + internal static string UnhandledOnErrorResumeNextInspection { get { return ResourceManager.GetString("UnhandledOnErrorResumeNextInspection", resourceCulture); } @@ -711,7 +720,7 @@ public static string UnhandledOnErrorResumeNextInspection { /// /// Looks up a localized string similar to Case clause '{0}' cannot be reached.. /// - public static string UnreachableCaseInspection { + internal static string UnreachableCaseInspection { get { return ResourceManager.GetString("UnreachableCaseInspection", resourceCulture); } @@ -720,7 +729,7 @@ public static string UnreachableCaseInspection { /// /// Looks up a localized string similar to Unreachable Case Else: all matches exist within prior Case statement(s).. /// - public static string UnreachableCaseInspection_CaseElse { + internal static string UnreachableCaseInspection_CaseElse { get { return ResourceManager.GetString("UnreachableCaseInspection_CaseElse", resourceCulture); } @@ -729,7 +738,7 @@ public static string UnreachableCaseInspection_CaseElse { /// /// Looks up a localized string similar to Unreachable: Case Statement contains invalid range clause(s).. /// - public static string UnreachableCaseInspection_InherentlyUnreachable { + internal static string UnreachableCaseInspection_InherentlyUnreachable { get { return ResourceManager.GetString("UnreachableCaseInspection_InherentlyUnreachable", resourceCulture); } @@ -738,7 +747,7 @@ public static string UnreachableCaseInspection_InherentlyUnreachable { /// /// Looks up a localized string similar to Unreachable: Case Statement will cause a Run-time error 6 (Overflow).. /// - public static string UnreachableCaseInspection_Overflow { + internal static string UnreachableCaseInspection_Overflow { get { return ResourceManager.GetString("UnreachableCaseInspection_Overflow", resourceCulture); } @@ -747,7 +756,7 @@ public static string UnreachableCaseInspection_Overflow { /// /// Looks up a localized string similar to Unreachable: Case Statement will cause a Run-time error 13 (Mismatch).. /// - public static string UnreachableCaseInspection_TypeMismatch { + internal static string UnreachableCaseInspection_TypeMismatch { get { return ResourceManager.GetString("UnreachableCaseInspection_TypeMismatch", resourceCulture); } @@ -756,7 +765,7 @@ public static string UnreachableCaseInspection_TypeMismatch { /// /// Looks up a localized string similar to Unreachable: Never matches or is equivalent to a prior Case statement.. /// - public static string UnreachableCaseInspection_Unreachable { + internal static string UnreachableCaseInspection_Unreachable { get { return ResourceManager.GetString("UnreachableCaseInspection_Unreachable", resourceCulture); } @@ -765,7 +774,7 @@ public static string UnreachableCaseInspection_Unreachable { /// /// Looks up a localized string similar to Replace function '{0}' with existing typed function.. /// - public static string UntypedFunctionUsageInspection { + internal static string UntypedFunctionUsageInspection { get { return ResourceManager.GetString("UntypedFunctionUsageInspection", resourceCulture); } @@ -774,7 +783,7 @@ public static string UntypedFunctionUsageInspection { /// /// Looks up a localized string similar to Variable '{0}' is not assigned.. /// - public static string VariableNotAssignedInspection { + internal static string VariableNotAssignedInspection { get { return ResourceManager.GetString("VariableNotAssignedInspection", resourceCulture); } @@ -783,7 +792,7 @@ public static string VariableNotAssignedInspection { /// /// Looks up a localized string similar to {0} '{1}' is implicitly 'Variant'.. /// - public static string VariableTypeNotDeclaredInspection { + internal static string VariableTypeNotDeclaredInspection { get { return ResourceManager.GetString("VariableTypeNotDeclaredInspection", resourceCulture); } @@ -792,7 +801,7 @@ public static string VariableTypeNotDeclaredInspection { /// /// Looks up a localized string similar to Property '{0}' has no getter.. /// - public static string WriteOnlyPropertyInspection { + internal static string WriteOnlyPropertyInspection { get { return ResourceManager.GetString("WriteOnlyPropertyInspection", resourceCulture); } diff --git a/Rubberduck.Resources/Inspections/InspectionResults.resx b/Rubberduck.Resources/Inspections/InspectionResults.resx index 36ac7d58cb..6ea624bad1 100644 --- a/Rubberduck.Resources/Inspections/InspectionResults.resx +++ b/Rubberduck.Resources/Inspections/InspectionResults.resx @@ -378,4 +378,8 @@ An assignment is immediately overridden by another assignment or is never referenced. + + Result of '{0}' call is not tested for 'Nothing'. + {0} Member identifier + \ No newline at end of file From 74f6aa32861487b3207909d0e6138b1a40071442 Mon Sep 17 00:00:00 2001 From: IvenBach Date: Thu, 1 Nov 2018 20:51:40 -0700 Subject: [PATCH 036/107] Update README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7707a5b45f..4be14947cb 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ If you like this project and would like to thank its contributors, you are welco [![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/rubberduck-vba/Rubberduck.svg)](http://isitmaintained.com/project/rubberduck-vba/Rubberduck "Average time to resolve an issue") [![Percentage of issues still open](http://isitmaintained.com/badge/open/rubberduck-vba/Rubberduck.svg)](http://isitmaintained.com/project/rubberduck-vba/Rubberduck "Percentage of issues still open") -> **[rubberduckvba.com](http://rubberduckvba.com)** [Wiki](https://github.com/retailcoder/Rubberduck/wiki) [Rubberduck News](https://rubberduckvba.wordpress.com/) +> **[rubberduckvba.com](http://rubberduckvba.com)** [Wiki](https://github.com/rubberduck-vba/Rubberduck/wiki) [Rubberduck News](https://rubberduckvba.wordpress.com/) > devs@rubberduckvba.com > Follow [@rubberduckvba](https://twitter.com/rubberduckvba) on Twitter From 2fbb7d64bbd1ff85f0f8dc03c7108c77fcb4c121 Mon Sep 17 00:00:00 2001 From: comintern Date: Thu, 1 Nov 2018 22:57:55 -0500 Subject: [PATCH 037/107] Update autogenerated files that were unscrewed with the csproj fix. --- .../Inspections/InspectionInfo.Designer.cs | 162 ++++++++--------- .../Inspections/InspectionNames.Designer.cs | 162 ++++++++--------- .../Inspections/InspectionResults.Designer.cs | 172 +++++++++--------- .../Rubberduck.Resources.csproj | 2 +- .../Settings/AutoCompletesPage.Designer.cs | 158 ++++------------ .../Settings/SettingsUI.Designer.cs | 9 - 6 files changed, 283 insertions(+), 382 deletions(-) diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs index 4c5b082e00..16e73ced43 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs @@ -22,7 +22,7 @@ namespace Rubberduck.Resources.Inspections { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class InspectionInfo { + public class InspectionInfo { private static global::System.Resources.ResourceManager resourceMan; @@ -36,7 +36,7 @@ internal InspectionInfo() { /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Rubberduck.Resources.Inspections.InspectionInfo", typeof(InspectionInfo).Assembly); @@ -51,7 +51,7 @@ internal InspectionInfo() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -63,7 +63,7 @@ internal InspectionInfo() { /// /// Looks up a localized string similar to The Excel Application object does not implement the WorksheetFunction interface directly. All calls made to WorksheetFunction members are handled as late bound and errors in the called member will be returned wrapped in a Variant of VbVarType.vbError. This makes errors un-trappable with error handlers and adds a performance penalty in comparison to early bound calls. Consider calling Application.WorksheetFunction explicitly. Note: If this call generated errors in the past, those errors were ignored. If appl [rest of string was truncated]";. /// - internal static string ApplicationWorksheetFunctionInspection { + public static string ApplicationWorksheetFunctionInspection { get { return ResourceManager.GetString("ApplicationWorksheetFunctionInspection", resourceCulture); } @@ -72,7 +72,7 @@ internal static string ApplicationWorksheetFunctionInspection { /// /// Looks up a localized string similar to Parameter is passed by value, but is assigned a new value/reference. Consider making a local copy instead if the caller isn't supposed to know the new value. If the caller should see the new value, the parameter should be passed ByRef instead, and you have a bug.. /// - internal static string AssignedByValParameterInspection { + public static string AssignedByValParameterInspection { get { return ResourceManager.GetString("AssignedByValParameterInspection", resourceCulture); } @@ -81,7 +81,7 @@ internal static string AssignedByValParameterInspection { /// /// Looks up a localized string similar to An assignment is immediately overridden by another assignment or is never referenced.. /// - internal static string AssignmentNotUsedInspection { + public static string AssignmentNotUsedInspection { get { return ResourceManager.GetString("AssignmentNotUsedInspection", resourceCulture); } @@ -90,7 +90,7 @@ internal static string AssignmentNotUsedInspection { /// /// Looks up a localized string similar to A member is assigned True/False in different branches of an if statement with no other statements in the conditional. Use the condition directly to the member instead.. /// - internal static string BooleanAssignedInIfElseInspection { + public static string BooleanAssignedInIfElseInspection { get { return ResourceManager.GetString("BooleanAssignedInIfElseInspection", resourceCulture); } @@ -99,7 +99,7 @@ internal static string BooleanAssignedInIfElseInspection { /// /// Looks up a localized string similar to Rubberduck could not find any reference to constant. Consider removing the unused declaration.. /// - internal static string ConstantNotUsedInspection { + public static string ConstantNotUsedInspection { get { return ResourceManager.GetString("ConstantNotUsedInspection", resourceCulture); } @@ -108,7 +108,7 @@ internal static string ConstantNotUsedInspection { /// /// Looks up a localized string similar to Consider naming your VBA project.. /// - internal static string DefaultProjectNameInspection { + public static string DefaultProjectNameInspection { get { return ResourceManager.GetString("DefaultProjectNameInspection", resourceCulture); } @@ -117,7 +117,7 @@ internal static string DefaultProjectNameInspection { /// /// Looks up a localized string similar to Using the 'Def[Type]' statement leads to specifying types by using a prefix. This style of naming is heavily discouraged and should be avoided.. /// - internal static string DefTypeStatementInspection { + public static string DefTypeStatementInspection { get { return ResourceManager.GetString("DefTypeStatementInspection", resourceCulture); } @@ -126,7 +126,7 @@ internal static string DefTypeStatementInspection { /// /// Looks up a localized string similar to An annotation is specified multiple times, but is intended to be specified only once.. /// - internal static string DuplicatedAnnotationInspection { + public static string DuplicatedAnnotationInspection { get { return ResourceManager.GetString("DuplicatedAnnotationInspection", resourceCulture); } @@ -135,7 +135,7 @@ internal static string DuplicatedAnnotationInspection { /// /// Looks up a localized string similar to An empty 'Case' block without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - internal static string EmptyCaseBlockInspection { + public static string EmptyCaseBlockInspection { get { return ResourceManager.GetString("EmptyCaseBlockInspection", resourceCulture); } @@ -144,7 +144,7 @@ internal static string EmptyCaseBlockInspection { /// /// Looks up a localized string similar to An empty 'Do...While' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - internal static string EmptyDoWhileBlockInspection { + public static string EmptyDoWhileBlockInspection { get { return ResourceManager.GetString("EmptyDoWhileBlockInspection", resourceCulture); } @@ -153,7 +153,7 @@ internal static string EmptyDoWhileBlockInspection { /// /// Looks up a localized string similar to An empty 'Else' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - internal static string EmptyElseBlockInspection { + public static string EmptyElseBlockInspection { get { return ResourceManager.GetString("EmptyElseBlockInspection", resourceCulture); } @@ -162,7 +162,7 @@ internal static string EmptyElseBlockInspection { /// /// Looks up a localized string similar to An empty 'For Each...Next' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - internal static string EmptyForEachBlockInspection { + public static string EmptyForEachBlockInspection { get { return ResourceManager.GetString("EmptyForEachBlockInspection", resourceCulture); } @@ -171,7 +171,7 @@ internal static string EmptyForEachBlockInspection { /// /// Looks up a localized string similar to An empty 'For...Next' loop without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - internal static string EmptyForLoopBlockInspection { + public static string EmptyForLoopBlockInspection { get { return ResourceManager.GetString("EmptyForLoopBlockInspection", resourceCulture); } @@ -180,7 +180,7 @@ internal static string EmptyForLoopBlockInspection { /// /// Looks up a localized string similar to An empty conditional branch without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - internal static string EmptyIfBlockInspection { + public static string EmptyIfBlockInspection { get { return ResourceManager.GetString("EmptyIfBlockInspection", resourceCulture); } @@ -189,7 +189,7 @@ internal static string EmptyIfBlockInspection { /// /// Looks up a localized string similar to Empty modules and classes either point to not yet implemented functionality or represent unnecessary baggage that can hurt the maintainability of a project.. /// - internal static string EmptyModuleInspection { + public static string EmptyModuleInspection { get { return ResourceManager.GetString("EmptyModuleInspection", resourceCulture); } @@ -198,7 +198,7 @@ internal static string EmptyModuleInspection { /// /// Looks up a localized string similar to The built-in constant 'vbNullString' is a null string pointer taking up 0 bytes of memory, that unambiguously conveys the intent of an empty string.. /// - internal static string EmptyStringLiteralInspection { + public static string EmptyStringLiteralInspection { get { return ResourceManager.GetString("EmptyStringLiteralInspection", resourceCulture); } @@ -207,7 +207,7 @@ internal static string EmptyStringLiteralInspection { /// /// Looks up a localized string similar to An empty 'Loop' block without any executable statements, leaves a maintainer wondering about the intent of the code. Avoid writing code that doesn't need to be written.. /// - internal static string EmptyWhileWendBlockInspection { + public static string EmptyWhileWendBlockInspection { get { return ResourceManager.GetString("EmptyWhileWendBlockInspection", resourceCulture); } @@ -216,7 +216,7 @@ internal static string EmptyWhileWendBlockInspection { /// /// Looks up a localized string similar to Consider exposing a property instead.. /// - internal static string EncapsulatePublicFieldInspection { + public static string EncapsulatePublicFieldInspection { get { return ResourceManager.GetString("EncapsulatePublicFieldInspection", resourceCulture); } @@ -225,7 +225,7 @@ internal static string EncapsulatePublicFieldInspection { /// /// Looks up a localized string similar to A Function or Property returning a reference type that can be 'Nothing' should not have the return value used with a test for 'Is Nothing'. If the member does not return a valid object, attempting to use the return value will result in a run-time error 91 - "Object variable or With block variable not set".. /// - internal static string ExcelMemberMayReturnNothingInspection { + public static string ExcelMemberMayReturnNothingInspection { get { return ResourceManager.GetString("ExcelMemberMayReturnNothingInspection", resourceCulture); } @@ -234,7 +234,7 @@ internal static string ExcelMemberMayReturnNothingInspection { /// /// Looks up a localized string similar to A member is written as a function, but used as a procedure. Unless the function is recursive, consider converting the 'Function' into a 'Sub'. If the function is recursive, none of its external callers are using the returned value.. /// - internal static string FunctionReturnValueNotUsedInspection { + public static string FunctionReturnValueNotUsedInspection { get { return ResourceManager.GetString("FunctionReturnValueNotUsedInspection", resourceCulture); } @@ -243,7 +243,7 @@ internal static string FunctionReturnValueNotUsedInspection { /// /// Looks up a localized string similar to Bracketed expressions are evaluated by the host application at runtime, which means VBA can't validate the expression at compile-time. Consider using the host application's object model instead.. /// - internal static string HostSpecificExpressionInspection { + public static string HostSpecificExpressionInspection { get { return ResourceManager.GetString("HostSpecificExpressionInspection", resourceCulture); } @@ -252,7 +252,7 @@ internal static string HostSpecificExpressionInspection { /// /// Looks up a localized string similar to Hungarian notation makes code less readable, and is redundant when strongly typed variables and meaningful names are used.. /// - internal static string HungarianNotationInspection { + public static string HungarianNotationInspection { get { return ResourceManager.GetString("HungarianNotationInspection", resourceCulture); } @@ -261,7 +261,7 @@ internal static string HungarianNotationInspection { /// /// Looks up a localized string similar to An annotation meant to be specified at module level cannot be used to annotate members; annotations meant to be annotate members cannot be used at module level.. /// - internal static string IllegalAnnotationInspection { + public static string IllegalAnnotationInspection { get { return ResourceManager.GetString("IllegalAnnotationInspection", resourceCulture); } @@ -270,7 +270,7 @@ internal static string IllegalAnnotationInspection { /// /// Looks up a localized string similar to Implicit references to the active sheet make the code frail and harder to debug. Consider making these references explicit when they're intended, and prefer working off object references. Ignore if the member call is referring to a type Rubberduck can't resolve.. /// - internal static string ImplicitActiveSheetReferenceInspection { + public static string ImplicitActiveSheetReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveSheetReferenceInspection", resourceCulture); } @@ -279,7 +279,7 @@ internal static string ImplicitActiveSheetReferenceInspection { /// /// Looks up a localized string similar to Implicit references to the active workbook make the code frail and harder to debug. Consider making these references explicit when they're intended, and prefer working off object references. Ignore if the member call is referring to a type Rubberduck can't resolve.. /// - internal static string ImplicitActiveWorkbookReferenceInspection { + public static string ImplicitActiveWorkbookReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveWorkbookReferenceInspection", resourceCulture); } @@ -288,7 +288,7 @@ internal static string ImplicitActiveWorkbookReferenceInspection { /// /// Looks up a localized string similar to Parameters are passed by reference unless specified otherwise, which can be confusing and bug-prone. Prefer passing parameters by value, and specify ByRef explicitly when passing parameters by reference.. /// - internal static string ImplicitByRefModifierInspection { + public static string ImplicitByRefModifierInspection { get { return ResourceManager.GetString("ImplicitByRefModifierInspection", resourceCulture); } @@ -297,7 +297,7 @@ internal static string ImplicitByRefModifierInspection { /// /// Looks up a localized string similar to Such assignments look like they are assigning an object variable to a value type on the surface, but they are actually assigning that object's default member, implicitly. Consider referring to the default member explicitly, for improved readability.. /// - internal static string ImplicitDefaultMemberAssignmentInspection { + public static string ImplicitDefaultMemberAssignmentInspection { get { return ResourceManager.GetString("ImplicitDefaultMemberAssignmentInspection", resourceCulture); } @@ -306,7 +306,7 @@ internal static string ImplicitDefaultMemberAssignmentInspection { /// /// Looks up a localized string similar to Module members are public by default, which can be counter-intuitive. Consider specifying explicit access modifiers to avoid ambiguity.. /// - internal static string ImplicitPublicMemberInspection { + public static string ImplicitPublicMemberInspection { get { return ResourceManager.GetString("ImplicitPublicMemberInspection", resourceCulture); } @@ -315,7 +315,7 @@ internal static string ImplicitPublicMemberInspection { /// /// Looks up a localized string similar to Members with a return value implicitly return a 'Variant' unless specified otherwise. Consider returning an explicit 'Variant' when the return type isn't known, or specify it explicitly.. /// - internal static string ImplicitVariantReturnTypeInspection { + public static string ImplicitVariantReturnTypeInspection { get { return ResourceManager.GetString("ImplicitVariantReturnTypeInspection", resourceCulture); } @@ -324,7 +324,7 @@ internal static string ImplicitVariantReturnTypeInspection { /// /// Looks up a localized string similar to The maximum value of a 16-bit signed integer is 32,767 - using a 32-bit (Long) integer data type where possible can help prevent 'Overflow' run-time errors, and is better handled by modern CPUs.. /// - internal static string IntegerDataTypeInspection { + public static string IntegerDataTypeInspection { get { return ResourceManager.GetString("IntegerDataTypeInspection", resourceCulture); } @@ -333,7 +333,7 @@ internal static string IntegerDataTypeInspection { /// /// Looks up a localized string similar to IsMissing is only intended to be called on optional arguments, and will only return correct results if the type of the argument is 'Variant' with no explicit default value. All other uses will return 'False'.. /// - internal static string IsMissingOnInappropriateArgumentInspection { + public static string IsMissingOnInappropriateArgumentInspection { get { return ResourceManager.GetString("IsMissingOnInappropriateArgumentInspection", resourceCulture); } @@ -342,7 +342,7 @@ internal static string IsMissingOnInappropriateArgumentInspection { /// /// Looks up a localized string similar to IsMissing is only intended to be called on arguments of the containing procedure, and almost all other usages will return 'False'. Passing any other expression to the function is the equivalent to 'VarType({expression}) = vbError', and in rare circumstances can cause the host application to crash.. /// - internal static string IsMissingWithNonArgumentParameterInspection { + public static string IsMissingWithNonArgumentParameterInspection { get { return ResourceManager.GetString("IsMissingWithNonArgumentParameterInspection", resourceCulture); } @@ -351,7 +351,7 @@ internal static string IsMissingWithNonArgumentParameterInspection { /// /// Looks up a localized string similar to A line label that is never jumpted to ('GoTo', 'Resume', ...), serves no purpose. Consider removing it.. /// - internal static string LineLabelNotUsedInspection { + public static string LineLabelNotUsedInspection { get { return ResourceManager.GetString("LineLabelNotUsedInspection", resourceCulture); } @@ -360,7 +360,7 @@ internal static string LineLabelNotUsedInspection { /// /// Looks up a localized string similar to A member access call is made against an extended interface that Rubberduck couldn't resolve, or the member couldn't be found. If VBA cannot resolve the type at run-time, error 438 will be raised. If an equivalent, non-extended interface that Rubberduck can resolve is available, consider using it instead.. /// - internal static string MemberNotOnInterfaceInspection { + public static string MemberNotOnInterfaceInspection { get { return ResourceManager.GetString("MemberNotOnInterfaceInspection", resourceCulture); } @@ -369,7 +369,7 @@ internal static string MemberNotOnInterfaceInspection { /// /// Looks up a localized string similar to An annotation parameter is missing or incorrectly specified. The correct syntax is : '@Annotation([parameter])\nExample: '@Folder("Parent.Child"). /// - internal static string MissingAnnotationArgumentInspection { + public static string MissingAnnotationArgumentInspection { get { return ResourceManager.GetString("MissingAnnotationArgumentInspection", resourceCulture); } @@ -378,7 +378,7 @@ internal static string MissingAnnotationArgumentInspection { /// /// Looks up a localized string similar to Module and member attributes are not displayed in the VBE. By adding an annotation, you make these attributes more explicit, and Rubberduck can keep annotations and attributes synchronized.. /// - internal static string MissingAnnotationInspection { + public static string MissingAnnotationInspection { get { return ResourceManager.GetString("MissingAnnotationInspection", resourceCulture); } @@ -387,7 +387,7 @@ internal static string MissingAnnotationInspection { /// /// Looks up a localized string similar to A Rubberduck annotation is specified for a module or member, but the corresponding attribute isn't present. Module attributes and annotations need to be synchronized.. /// - internal static string MissingAttributeInspection { + public static string MissingAttributeInspection { get { return ResourceManager.GetString("MissingAttributeInspection", resourceCulture); } @@ -396,7 +396,7 @@ internal static string MissingAttributeInspection { /// /// Looks up a localized string similar to The 'Public' keyword can only be used at module level; its counterpart 'Private' can also only be used at module level. 'Dim' however, can be used to declare both procedure and module scope variables. For consistency, it would be preferable to reserve 'Dim' for locals, and thus to use 'Private' instead of 'Dim' at module level.. /// - internal static string ModuleScopeDimKeywordInspection { + public static string ModuleScopeDimKeywordInspection { get { return ResourceManager.GetString("ModuleScopeDimKeywordInspection", resourceCulture); } @@ -405,7 +405,7 @@ internal static string ModuleScopeDimKeywordInspection { /// /// Looks up a localized string similar to Modules without the '@Folder' annotation cannot receive custom groupings in the Code Explorer. . /// - internal static string ModuleWithoutFolderInspection { + public static string ModuleWithoutFolderInspection { get { return ResourceManager.GetString("ModuleWithoutFolderInspection", resourceCulture); } @@ -414,7 +414,7 @@ internal static string ModuleWithoutFolderInspection { /// /// Looks up a localized string similar to A module-level variable used only in one procedure should be declared in that procedure.. /// - internal static string MoveFieldCloserToUsageInspection { + public static string MoveFieldCloserToUsageInspection { get { return ResourceManager.GetString("MoveFieldCloserToUsageInspection", resourceCulture); } @@ -423,7 +423,7 @@ internal static string MoveFieldCloserToUsageInspection { /// /// Looks up a localized string similar to Consider continuing long signatures between parameters. Splitting a parameter declaration across multiple lines arguably hurts readability.. /// - internal static string MultilineParameterInspection { + public static string MultilineParameterInspection { get { return ResourceManager.GetString("MultilineParameterInspection", resourceCulture); } @@ -432,7 +432,7 @@ internal static string MultilineParameterInspection { /// /// Looks up a localized string similar to Declaring multiple variables in the same instruction is legal, but should be used sparingly. Consider declaring variables closer to their usage, in a single instruction per declaration.. /// - internal static string MultipleDeclarationsInspection { + public static string MultipleDeclarationsInspection { get { return ResourceManager.GetString("MultipleDeclarationsInspection", resourceCulture); } @@ -441,7 +441,7 @@ internal static string MultipleDeclarationsInspection { /// /// Looks up a localized string similar to This is likely a bug. The return value of a function or property getter must be assigned before exiting, otherwise the program will not be working with expected results. If a function has no meaningful return value, consider declaring it as a 'Sub' procedure instead.. /// - internal static string NonReturningFunctionInspection { + public static string NonReturningFunctionInspection { get { return ResourceManager.GetString("NonReturningFunctionInspection", resourceCulture); } @@ -450,7 +450,7 @@ internal static string NonReturningFunctionInspection { /// /// Looks up a localized string similar to As far as Rubberduck can tell, this variable is an object variable, assigned without the 'Set' keyword. This causes run-time error 91 'Object or With block variable not set'.. /// - internal static string ObjectVariableNotSetInspection { + public static string ObjectVariableNotSetInspection { get { return ResourceManager.GetString("ObjectVariableNotSetInspection", resourceCulture); } @@ -459,7 +459,7 @@ internal static string ObjectVariableNotSetInspection { /// /// Looks up a localized string similar to Windows implementations of Visual Basic only support the StdCall calling convention, and use of of the CDecl calling convention is only supported in Macintosh versions of VBA. Use of this keyword in Windows will result in runtime error 49 - 'Bad DLL calling convention'. If this procedure is only intended to be used on Macintosh hosts, it should be conditionally compiled.. /// - internal static string ObsoleteCallingConventionInspection { + public static string ObsoleteCallingConventionInspection { get { return ResourceManager.GetString("ObsoleteCallingConventionInspection", resourceCulture); } @@ -468,7 +468,7 @@ internal static string ObsoleteCallingConventionInspection { /// /// Looks up a localized string similar to The 'Call' statement is no longer required to call procedures, and only exists in the language to support legacy code that required it; it can be safely rewritten to an implicit call.. /// - internal static string ObsoleteCallStatementInspection { + public static string ObsoleteCallStatementInspection { get { return ResourceManager.GetString("ObsoleteCallStatementInspection", resourceCulture); } @@ -477,7 +477,7 @@ internal static string ObsoleteCallStatementInspection { /// /// Looks up a localized string similar to The 'Rem' statement only exists in the language to support legacy code that required it; it can be safely replaced with an apostrophe / single-quote comment.. /// - internal static string ObsoleteCommentSyntaxInspection { + public static string ObsoleteCommentSyntaxInspection { get { return ResourceManager.GetString("ObsoleteCommentSyntaxInspection", resourceCulture); } @@ -486,7 +486,7 @@ internal static string ObsoleteCommentSyntaxInspection { /// /// Looks up a localized string similar to The 'Error' statement only exists in the language to support legacy code that required it; prefer using 'Err.Raise' instead.. /// - internal static string ObsoleteErrorSyntaxInspection { + public static string ObsoleteErrorSyntaxInspection { get { return ResourceManager.GetString("ObsoleteErrorSyntaxInspection", resourceCulture); } @@ -495,7 +495,7 @@ internal static string ObsoleteErrorSyntaxInspection { /// /// Looks up a localized string similar to The 'Global' keyword only exists in the language to support legacy code that required it; it can be safely replaced with the 'Public' modifier.. /// - internal static string ObsoleteGlobalInspection { + public static string ObsoleteGlobalInspection { get { return ResourceManager.GetString("ObsoleteGlobalInspection", resourceCulture); } @@ -504,7 +504,7 @@ internal static string ObsoleteGlobalInspection { /// /// Looks up a localized string similar to The 'Let' statement only exists in the language to support legacy code that required it; it can be safely removed, since modern VBA does not require that keyword for value assignments.. /// - internal static string ObsoleteLetStatementInspection { + public static string ObsoleteLetStatementInspection { get { return ResourceManager.GetString("ObsoleteLetStatementInspection", resourceCulture); } @@ -513,7 +513,7 @@ internal static string ObsoleteLetStatementInspection { /// /// Looks up a localized string similar to This member is marked '@Obsolete'. It should no longer be used, there should be a better alternative.. /// - internal static string ObsoleteMemberUsageInspection { + public static string ObsoleteMemberUsageInspection { get { return ResourceManager.GetString("ObsoleteMemberUsageInspection", resourceCulture); } @@ -522,7 +522,7 @@ internal static string ObsoleteMemberUsageInspection { /// /// Looks up a localized string similar to Type hint characters only exist in the language to support legacy code that required it; they can be safely replaced in declarations with an "As" type clause that specifies the type explicitly, and they can be omitted in other identifier references.. /// - internal static string ObsoleteTypeHintInspection { + public static string ObsoleteTypeHintInspection { get { return ResourceManager.GetString("ObsoleteTypeHintInspection", resourceCulture); } @@ -531,7 +531,7 @@ internal static string ObsoleteTypeHintInspection { /// /// Looks up a localized string similar to On Local Error exists only for compatibility with previous versions of Visual Basic, and all Errors are treated as Local regardless of the Error statement. Use of this keyword inaccurately gives the impression that there is a distinction between types of error handling when there is not.. /// - internal static string OnLocalErrorInspection { + public static string OnLocalErrorInspection { get { return ResourceManager.GetString("OnLocalErrorInspection", resourceCulture); } @@ -540,7 +540,7 @@ internal static string OnLocalErrorInspection { /// /// Looks up a localized string similar to Arrays are typically zero-based. This option changes the default lower boundary for implicitly-sized arrays, which can introduce off-by-one errors if one isn't cautious.. /// - internal static string OptionBaseInspection { + public static string OptionBaseInspection { get { return ResourceManager.GetString("OptionBaseInspection", resourceCulture); } @@ -549,7 +549,7 @@ internal static string OptionBaseInspection { /// /// Looks up a localized string similar to This is the default setting, it does not need to be specified.. /// - internal static string OptionBaseZeroInspection { + public static string OptionBaseZeroInspection { get { return ResourceManager.GetString("OptionBaseZeroInspection", resourceCulture); } @@ -558,7 +558,7 @@ internal static string OptionBaseZeroInspection { /// /// Looks up a localized string similar to VBA will happily compile a typo: use 'Option Explicit' to prevent successfully compiling an erroneous program.. /// - internal static string OptionExplicitInspection { + public static string OptionExplicitInspection { get { return ResourceManager.GetString("OptionExplicitInspection", resourceCulture); } @@ -567,7 +567,7 @@ internal static string OptionExplicitInspection { /// /// Looks up a localized string similar to A parameter that is passed by reference and isn't assigned a new value/reference, could be passed by value instead.. /// - internal static string ParameterCanBeByValInspection { + public static string ParameterCanBeByValInspection { get { return ResourceManager.GetString("ParameterCanBeByValInspection", resourceCulture); } @@ -576,7 +576,7 @@ internal static string ParameterCanBeByValInspection { /// /// Looks up a localized string similar to A parameter is passed into a member that does not use it. Consider removing that parameter.. /// - internal static string ParameterNotUsedInspection { + public static string ParameterNotUsedInspection { get { return ResourceManager.GetString("ParameterNotUsedInspection", resourceCulture); } @@ -585,7 +585,7 @@ internal static string ParameterNotUsedInspection { /// /// Looks up a localized string similar to A procedure that only has one parameter passed by reference that is assigned a new value/reference before the procedure exits, is using a ByRef parameter as a return value: consider making it a function instead.. /// - internal static string ProcedureCanBeWrittenAsFunctionInspection { + public static string ProcedureCanBeWrittenAsFunctionInspection { get { return ResourceManager.GetString("ProcedureCanBeWrittenAsFunctionInspection", resourceCulture); } @@ -594,7 +594,7 @@ internal static string ProcedureCanBeWrittenAsFunctionInspection { /// /// Looks up a localized string similar to Rubberduck could not find any caller for a procedure. If the procedure is hooked to a macro-button, used as a user-defined function (UDF) or handles an application event that Rubberduck didn't know of you can safely ignore this inspection result; otherwise, consider removing it.. /// - internal static string ProcedureNotUsedInspection { + public static string ProcedureNotUsedInspection { get { return ResourceManager.GetString("ProcedureNotUsedInspection", resourceCulture); } @@ -603,7 +603,7 @@ internal static string ProcedureNotUsedInspection { /// /// Looks up a localized string similar to By default, all parameters are passed by reference, so it is not necessary to include the 'ByRef' modifier.. /// - internal static string RedundantByRefModifierInspection { + public static string RedundantByRefModifierInspection { get { return ResourceManager.GetString("RedundantByRefModifierInspection", resourceCulture); } @@ -612,7 +612,7 @@ internal static string RedundantByRefModifierInspection { /// /// Looks up a localized string similar to Being the default/implicit setting for this option, this instruction can be safely omitted.. /// - internal static string RedundantOptionInspection { + public static string RedundantOptionInspection { get { return ResourceManager.GetString("RedundantOptionInspection", resourceCulture); } @@ -621,7 +621,7 @@ internal static string RedundantOptionInspection { /// /// Looks up a localized string similar to An auto-instantiated object variable declaration at procedure scope changes how nulling the reference works, which can lead to unexpected behavior.. /// - internal static string SelfAssignedDeclarationInspection { + public static string SelfAssignedDeclarationInspection { get { return ResourceManager.GetString("SelfAssignedDeclarationInspection", resourceCulture); } @@ -630,7 +630,7 @@ internal static string SelfAssignedDeclarationInspection { /// /// Looks up a localized string similar to Two declarations are in scope and have the same identifier name. This means that only one of them will be available to use.. /// - internal static string ShadowedDeclarationInspection { + public static string ShadowedDeclarationInspection { get { return ResourceManager.GetString("ShadowedDeclarationInspection", resourceCulture); } @@ -639,7 +639,7 @@ internal static string ShadowedDeclarationInspection { /// /// Looks up a localized string similar to Excel already defines a globally scoped object variable with this reference. Consider using the sheet's 'CodeName' property.. /// - internal static string SheetAccessedUsingStringInspection { + public static string SheetAccessedUsingStringInspection { get { return ResourceManager.GetString("SheetAccessedUsingStringInspection", resourceCulture); } @@ -648,7 +648,7 @@ internal static string SheetAccessedUsingStringInspection { /// /// Looks up a localized string similar to Step of the for-next loop is not specified. This might be unintentional.. /// - internal static string StepIsNotSpecifiedInspection { + public static string StepIsNotSpecifiedInspection { get { return ResourceManager.GetString("StepIsNotSpecifiedInspection", resourceCulture); } @@ -657,7 +657,7 @@ internal static string StepIsNotSpecifiedInspection { /// /// Looks up a localized string similar to 1 is the default step in a for-next loop and therefore is redundant.. /// - internal static string StepOneIsRedundantInspection { + public static string StepOneIsRedundantInspection { get { return ResourceManager.GetString("StepOneIsRedundantInspection", resourceCulture); } @@ -666,7 +666,7 @@ internal static string StepOneIsRedundantInspection { /// /// Looks up a localized string similar to The 'Stop' keyword halts execution and brings up the debugger. Avoid its use in distributed code.. /// - internal static string StopKeywordInspection { + public static string StopKeywordInspection { get { return ResourceManager.GetString("StopKeywordInspection", resourceCulture); } @@ -675,7 +675,7 @@ internal static string StopKeywordInspection { /// /// Looks up a localized string similar to This is likely a bug. A variable is being referred to, but is never assigned.. /// - internal static string UnassignedVariableUsageInspection { + public static string UnassignedVariableUsageInspection { get { return ResourceManager.GetString("UnassignedVariableUsageInspection", resourceCulture); } @@ -684,7 +684,7 @@ internal static string UnassignedVariableUsageInspection { /// /// Looks up a localized string similar to Code that uses undeclared variables does not compile when Option Explicit is specified. Undeclared variables are always Variant, a data type that incurs unnecessary overhead and storage.. /// - internal static string UndeclaredVariableInspection { + public static string UndeclaredVariableInspection { get { return ResourceManager.GetString("UndeclaredVariableInspection", resourceCulture); } @@ -693,7 +693,7 @@ internal static string UndeclaredVariableInspection { /// /// Looks up a localized string similar to Error handling should be restored after using 'On Error Resume Next'.. /// - internal static string UnhandledOnErrorResumeNextInspection { + public static string UnhandledOnErrorResumeNextInspection { get { return ResourceManager.GetString("UnhandledOnErrorResumeNextInspection", resourceCulture); } @@ -702,7 +702,7 @@ internal static string UnhandledOnErrorResumeNextInspection { /// /// Looks up a localized string similar to Detects Case Clauses that will never execute. . /// - internal static string UnreachableCaseInspection { + public static string UnreachableCaseInspection { get { return ResourceManager.GetString("UnreachableCaseInspection", resourceCulture); } @@ -712,7 +712,7 @@ internal static string UnreachableCaseInspection { /// Looks up a localized string similar to A string-returning equivalent function exists and should preferably be used to avoid implicit type conversions. ///If the parameter can be null, ignore this inspection result; passing a null value to a function expecting a string would raise a type mismatch runtime error.. /// - internal static string UntypedFunctionUsageInspection { + public static string UntypedFunctionUsageInspection { get { return ResourceManager.GetString("UntypedFunctionUsageInspection", resourceCulture); } @@ -721,7 +721,7 @@ internal static string UntypedFunctionUsageInspection { /// /// Looks up a localized string similar to Identifier names should indicate what they're used for and should be readable; avoid disemvoweling, numeric suffixes, and 1-2 character names.. /// - internal static string UseMeaningfulNameInspection { + public static string UseMeaningfulNameInspection { get { return ResourceManager.GetString("UseMeaningfulNameInspection", resourceCulture); } @@ -730,7 +730,7 @@ internal static string UseMeaningfulNameInspection { /// /// Looks up a localized string similar to Variable is not assigned. If this isn't intended, there's probably a bug. Ignore this inspection result if the variable is assigned in another procedure via a ByRef parameter.. /// - internal static string VariableNotAssignedInspection { + public static string VariableNotAssignedInspection { get { return ResourceManager.GetString("VariableNotAssignedInspection", resourceCulture); } @@ -739,7 +739,7 @@ internal static string VariableNotAssignedInspection { /// /// Looks up a localized string similar to Variable is not referred to. /// - internal static string VariableNotUsedInspection { + public static string VariableNotUsedInspection { get { return ResourceManager.GetString("VariableNotUsedInspection", resourceCulture); } @@ -748,7 +748,7 @@ internal static string VariableNotUsedInspection { /// /// Looks up a localized string similar to A variable whose type isn't explicitly declared, is implicitly 'Variant'. Consider making it an explicit 'Variant' if that's intended, or declare a more specific type.. /// - internal static string VariableTypeNotDeclaredInspection { + public static string VariableTypeNotDeclaredInspection { get { return ResourceManager.GetString("VariableTypeNotDeclaredInspection", resourceCulture); } @@ -757,7 +757,7 @@ internal static string VariableTypeNotDeclaredInspection { /// /// Looks up a localized string similar to A property that exposes a mutator but no accessor is a design smell and makes a confusing API. Consider exposing a getter, or converting the mutator to a method.. /// - internal static string WriteOnlyPropertyInspection { + public static string WriteOnlyPropertyInspection { get { return ResourceManager.GetString("WriteOnlyPropertyInspection", resourceCulture); } diff --git a/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs b/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs index a0111fba23..474bacc8c6 100644 --- a/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionNames.Designer.cs @@ -22,7 +22,7 @@ namespace Rubberduck.Resources.Inspections { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class InspectionNames { + public class InspectionNames { private static global::System.Resources.ResourceManager resourceMan; @@ -36,7 +36,7 @@ internal InspectionNames() { /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Rubberduck.Resources.Inspections.InspectionNames", typeof(InspectionNames).Assembly); @@ -51,7 +51,7 @@ internal InspectionNames() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -63,7 +63,7 @@ internal InspectionNames() { /// /// Looks up a localized string similar to Late bound WorksheetFunction call.. /// - internal static string ApplicationWorksheetFunctionInspection { + public static string ApplicationWorksheetFunctionInspection { get { return ResourceManager.GetString("ApplicationWorksheetFunctionInspection", resourceCulture); } @@ -72,7 +72,7 @@ internal static string ApplicationWorksheetFunctionInspection { /// /// Looks up a localized string similar to ByVal parameter is assigned. /// - internal static string AssignedByValParameterInspection { + public static string AssignedByValParameterInspection { get { return ResourceManager.GetString("AssignedByValParameterInspection", resourceCulture); } @@ -81,7 +81,7 @@ internal static string AssignedByValParameterInspection { /// /// Looks up a localized string similar to Assignment is not used. /// - internal static string AssignmentNotUsedInspection { + public static string AssignmentNotUsedInspection { get { return ResourceManager.GetString("AssignmentNotUsedInspection", resourceCulture); } @@ -90,7 +90,7 @@ internal static string AssignmentNotUsedInspection { /// /// Looks up a localized string similar to Boolean literal assignment in conditional. /// - internal static string BooleanAssignedInIfElseInspection { + public static string BooleanAssignedInIfElseInspection { get { return ResourceManager.GetString("BooleanAssignedInIfElseInspection", resourceCulture); } @@ -99,7 +99,7 @@ internal static string BooleanAssignedInIfElseInspection { /// /// Looks up a localized string similar to Constant is not used. /// - internal static string ConstantNotUsedInspection { + public static string ConstantNotUsedInspection { get { return ResourceManager.GetString("ConstantNotUsedInspection", resourceCulture); } @@ -108,7 +108,7 @@ internal static string ConstantNotUsedInspection { /// /// Looks up a localized string similar to Project name is not specified. /// - internal static string DefaultProjectNameInspection { + public static string DefaultProjectNameInspection { get { return ResourceManager.GetString("DefaultProjectNameInspection", resourceCulture); } @@ -117,7 +117,7 @@ internal static string DefaultProjectNameInspection { /// /// Looks up a localized string similar to Usage of 'Def[Type]' statement. /// - internal static string DefTypeStatementInspection { + public static string DefTypeStatementInspection { get { return ResourceManager.GetString("DefTypeStatementInspection", resourceCulture); } @@ -126,7 +126,7 @@ internal static string DefTypeStatementInspection { /// /// Looks up a localized string similar to Annotation is duplicated. /// - internal static string DuplicatedAnnotationInspection { + public static string DuplicatedAnnotationInspection { get { return ResourceManager.GetString("DuplicatedAnnotationInspection", resourceCulture); } @@ -135,7 +135,7 @@ internal static string DuplicatedAnnotationInspection { /// /// Looks up a localized string similar to Empty 'Case' block. /// - internal static string EmptyCaseBlockInspection { + public static string EmptyCaseBlockInspection { get { return ResourceManager.GetString("EmptyCaseBlockInspection", resourceCulture); } @@ -144,7 +144,7 @@ internal static string EmptyCaseBlockInspection { /// /// Looks up a localized string similar to Empty 'Do...While' Loop. /// - internal static string EmptyDoWhileBlockInspection { + public static string EmptyDoWhileBlockInspection { get { return ResourceManager.GetString("EmptyDoWhileBlockInspection", resourceCulture); } @@ -153,7 +153,7 @@ internal static string EmptyDoWhileBlockInspection { /// /// Looks up a localized string similar to Empty 'Else' block. /// - internal static string EmptyElseBlockInspection { + public static string EmptyElseBlockInspection { get { return ResourceManager.GetString("EmptyElseBlockInspection", resourceCulture); } @@ -162,7 +162,7 @@ internal static string EmptyElseBlockInspection { /// /// Looks up a localized string similar to Empty 'For Each...Next' Loop. /// - internal static string EmptyForEachBlockInspection { + public static string EmptyForEachBlockInspection { get { return ResourceManager.GetString("EmptyForEachBlockInspection", resourceCulture); } @@ -171,7 +171,7 @@ internal static string EmptyForEachBlockInspection { /// /// Looks up a localized string similar to Empty 'For...Next' Loop. /// - internal static string EmptyForLoopBlockInspection { + public static string EmptyForLoopBlockInspection { get { return ResourceManager.GetString("EmptyForLoopBlockInspection", resourceCulture); } @@ -180,7 +180,7 @@ internal static string EmptyForLoopBlockInspection { /// /// Looks up a localized string similar to Empty conditional branch. /// - internal static string EmptyIfBlockInspection { + public static string EmptyIfBlockInspection { get { return ResourceManager.GetString("EmptyIfBlockInspection", resourceCulture); } @@ -189,7 +189,7 @@ internal static string EmptyIfBlockInspection { /// /// Looks up a localized string similar to Empty module. /// - internal static string EmptyModuleInspection { + public static string EmptyModuleInspection { get { return ResourceManager.GetString("EmptyModuleInspection", resourceCulture); } @@ -198,7 +198,7 @@ internal static string EmptyModuleInspection { /// /// Looks up a localized string similar to Empty string literal. /// - internal static string EmptyStringLiteralInspection { + public static string EmptyStringLiteralInspection { get { return ResourceManager.GetString("EmptyStringLiteralInspection", resourceCulture); } @@ -207,7 +207,7 @@ internal static string EmptyStringLiteralInspection { /// /// Looks up a localized string similar to Empty 'While...Wend' loop. /// - internal static string EmptyWhileWendBlockInspection { + public static string EmptyWhileWendBlockInspection { get { return ResourceManager.GetString("EmptyWhileWendBlockInspection", resourceCulture); } @@ -216,7 +216,7 @@ internal static string EmptyWhileWendBlockInspection { /// /// Looks up a localized string similar to Public field breaks encapsulation. /// - internal static string EncapsulatePublicFieldInspection { + public static string EncapsulatePublicFieldInspection { get { return ResourceManager.GetString("EncapsulatePublicFieldInspection", resourceCulture); } @@ -225,7 +225,7 @@ internal static string EncapsulatePublicFieldInspection { /// /// Looks up a localized string similar to Member access may return 'Nothing'. /// - internal static string ExcelMemberMayReturnNothingInspection { + public static string ExcelMemberMayReturnNothingInspection { get { return ResourceManager.GetString("ExcelMemberMayReturnNothingInspection", resourceCulture); } @@ -234,7 +234,7 @@ internal static string ExcelMemberMayReturnNothingInspection { /// /// Looks up a localized string similar to Function return value is never used. /// - internal static string FunctionReturnValueNotUsedInspection { + public static string FunctionReturnValueNotUsedInspection { get { return ResourceManager.GetString("FunctionReturnValueNotUsedInspection", resourceCulture); } @@ -243,7 +243,7 @@ internal static string FunctionReturnValueNotUsedInspection { /// /// Looks up a localized string similar to Host-specific bracketed expression is only evaluated at runtime. /// - internal static string HostSpecificExpressionInspection { + public static string HostSpecificExpressionInspection { get { return ResourceManager.GetString("HostSpecificExpressionInspection", resourceCulture); } @@ -252,7 +252,7 @@ internal static string HostSpecificExpressionInspection { /// /// Looks up a localized string similar to Variable uses Hungarian notation.. /// - internal static string HungarianNotationInspection { + public static string HungarianNotationInspection { get { return ResourceManager.GetString("HungarianNotationInspection", resourceCulture); } @@ -261,7 +261,7 @@ internal static string HungarianNotationInspection { /// /// Looks up a localized string similar to Illegal annotation. /// - internal static string IllegalAnnotationInspection { + public static string IllegalAnnotationInspection { get { return ResourceManager.GetString("IllegalAnnotationInspection", resourceCulture); } @@ -270,7 +270,7 @@ internal static string IllegalAnnotationInspection { /// /// Looks up a localized string similar to Implicit reference to ActiveSheet. /// - internal static string ImplicitActiveSheetReferenceInspection { + public static string ImplicitActiveSheetReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveSheetReferenceInspection", resourceCulture); } @@ -279,7 +279,7 @@ internal static string ImplicitActiveSheetReferenceInspection { /// /// Looks up a localized string similar to Implicit reference to ActiveWorkbook. /// - internal static string ImplicitActiveWorkbookReferenceInspection { + public static string ImplicitActiveWorkbookReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveWorkbookReferenceInspection", resourceCulture); } @@ -288,7 +288,7 @@ internal static string ImplicitActiveWorkbookReferenceInspection { /// /// Looks up a localized string similar to Implicit ByRef parameter. /// - internal static string ImplicitByRefModifierInspection { + public static string ImplicitByRefModifierInspection { get { return ResourceManager.GetString("ImplicitByRefModifierInspection", resourceCulture); } @@ -297,7 +297,7 @@ internal static string ImplicitByRefModifierInspection { /// /// Looks up a localized string similar to Implicit default member assignment. /// - internal static string ImplicitDefaultMemberAssignmentInspection { + public static string ImplicitDefaultMemberAssignmentInspection { get { return ResourceManager.GetString("ImplicitDefaultMemberAssignmentInspection", resourceCulture); } @@ -306,7 +306,7 @@ internal static string ImplicitDefaultMemberAssignmentInspection { /// /// Looks up a localized string similar to Implicitly public member. /// - internal static string ImplicitPublicMemberInspection { + public static string ImplicitPublicMemberInspection { get { return ResourceManager.GetString("ImplicitPublicMemberInspection", resourceCulture); } @@ -315,7 +315,7 @@ internal static string ImplicitPublicMemberInspection { /// /// Looks up a localized string similar to Member return type is implicitly 'Variant'. /// - internal static string ImplicitVariantReturnTypeInspection { + public static string ImplicitVariantReturnTypeInspection { get { return ResourceManager.GetString("ImplicitVariantReturnTypeInspection", resourceCulture); } @@ -324,7 +324,7 @@ internal static string ImplicitVariantReturnTypeInspection { /// /// Looks up a localized string similar to Use of 16-bit integer type. /// - internal static string IntegerDataTypeInspection { + public static string IntegerDataTypeInspection { get { return ResourceManager.GetString("IntegerDataTypeInspection", resourceCulture); } @@ -333,7 +333,7 @@ internal static string IntegerDataTypeInspection { /// /// Looks up a localized string similar to Inappropriate use of 'IsMissing' function. /// - internal static string IsMissingOnInappropriateArgumentInspection { + public static string IsMissingOnInappropriateArgumentInspection { get { return ResourceManager.GetString("IsMissingOnInappropriateArgumentInspection", resourceCulture); } @@ -342,7 +342,7 @@ internal static string IsMissingOnInappropriateArgumentInspection { /// /// Looks up a localized string similar to Inappropriate use of 'IsMissing' function. /// - internal static string IsMissingWithNonArgumentParameterInspection { + public static string IsMissingWithNonArgumentParameterInspection { get { return ResourceManager.GetString("IsMissingWithNonArgumentParameterInspection", resourceCulture); } @@ -351,7 +351,7 @@ internal static string IsMissingWithNonArgumentParameterInspection { /// /// Looks up a localized string similar to Line label is not used. /// - internal static string LineLabelNotUsedInspection { + public static string LineLabelNotUsedInspection { get { return ResourceManager.GetString("LineLabelNotUsedInspection", resourceCulture); } @@ -360,7 +360,7 @@ internal static string LineLabelNotUsedInspection { /// /// Looks up a localized string similar to Member not found. /// - internal static string MemberNotOnInterfaceInspection { + public static string MemberNotOnInterfaceInspection { get { return ResourceManager.GetString("MemberNotOnInterfaceInspection", resourceCulture); } @@ -369,7 +369,7 @@ internal static string MemberNotOnInterfaceInspection { /// /// Looks up a localized string similar to Missing annotation parameter. /// - internal static string MissingAnnotationArgumentInspection { + public static string MissingAnnotationArgumentInspection { get { return ResourceManager.GetString("MissingAnnotationArgumentInspection", resourceCulture); } @@ -378,7 +378,7 @@ internal static string MissingAnnotationArgumentInspection { /// /// Looks up a localized string similar to Missing annotation. /// - internal static string MissingAnnotationInspection { + public static string MissingAnnotationInspection { get { return ResourceManager.GetString("MissingAnnotationInspection", resourceCulture); } @@ -387,7 +387,7 @@ internal static string MissingAnnotationInspection { /// /// Looks up a localized string similar to Missing attribute. /// - internal static string MissingAttributeInspection { + public static string MissingAttributeInspection { get { return ResourceManager.GetString("MissingAttributeInspection", resourceCulture); } @@ -396,7 +396,7 @@ internal static string MissingAttributeInspection { /// /// Looks up a localized string similar to Use of 'Dim' keyword at module level. /// - internal static string ModuleScopeDimKeywordInspection { + public static string ModuleScopeDimKeywordInspection { get { return ResourceManager.GetString("ModuleScopeDimKeywordInspection", resourceCulture); } @@ -405,7 +405,7 @@ internal static string ModuleScopeDimKeywordInspection { /// /// Looks up a localized string similar to Module without '@Folder' annotation. /// - internal static string ModuleWithoutFolderInspection { + public static string ModuleWithoutFolderInspection { get { return ResourceManager.GetString("ModuleWithoutFolderInspection", resourceCulture); } @@ -414,7 +414,7 @@ internal static string ModuleWithoutFolderInspection { /// /// Looks up a localized string similar to Scope of variable is broader than it needs to be. /// - internal static string MoveFieldCloserToUsageInspection { + public static string MoveFieldCloserToUsageInspection { get { return ResourceManager.GetString("MoveFieldCloserToUsageInspection", resourceCulture); } @@ -423,7 +423,7 @@ internal static string MoveFieldCloserToUsageInspection { /// /// Looks up a localized string similar to Parameter declaration is split on multiple lines. /// - internal static string MultilineParameterInspection { + public static string MultilineParameterInspection { get { return ResourceManager.GetString("MultilineParameterInspection", resourceCulture); } @@ -432,7 +432,7 @@ internal static string MultilineParameterInspection { /// /// Looks up a localized string similar to Multiple declarations in single instruction. /// - internal static string MultipleDeclarationsInspection { + public static string MultipleDeclarationsInspection { get { return ResourceManager.GetString("MultipleDeclarationsInspection", resourceCulture); } @@ -441,7 +441,7 @@ internal static string MultipleDeclarationsInspection { /// /// Looks up a localized string similar to Non-returning function or property getter. /// - internal static string NonReturningFunctionInspection { + public static string NonReturningFunctionInspection { get { return ResourceManager.GetString("NonReturningFunctionInspection", resourceCulture); } @@ -450,7 +450,7 @@ internal static string NonReturningFunctionInspection { /// /// Looks up a localized string similar to Object variable assignment requires 'Set' keyword. /// - internal static string ObjectVariableNotSetInspection { + public static string ObjectVariableNotSetInspection { get { return ResourceManager.GetString("ObjectVariableNotSetInspection", resourceCulture); } @@ -459,7 +459,7 @@ internal static string ObjectVariableNotSetInspection { /// /// Looks up a localized string similar to Use of obsolete 'CDecl' calling convention. /// - internal static string ObsoleteCallingConventionInspection { + public static string ObsoleteCallingConventionInspection { get { return ResourceManager.GetString("ObsoleteCallingConventionInspection", resourceCulture); } @@ -468,7 +468,7 @@ internal static string ObsoleteCallingConventionInspection { /// /// Looks up a localized string similar to Use of obsolete 'Call' statement. /// - internal static string ObsoleteCallStatementInspection { + public static string ObsoleteCallStatementInspection { get { return ResourceManager.GetString("ObsoleteCallStatementInspection", resourceCulture); } @@ -477,7 +477,7 @@ internal static string ObsoleteCallStatementInspection { /// /// Looks up a localized string similar to Use of obsolete 'Rem' statement. /// - internal static string ObsoleteCommentSyntaxInspection { + public static string ObsoleteCommentSyntaxInspection { get { return ResourceManager.GetString("ObsoleteCommentSyntaxInspection", resourceCulture); } @@ -486,7 +486,7 @@ internal static string ObsoleteCommentSyntaxInspection { /// /// Looks up a localized string similar to Use of obsolete 'Error' statement. /// - internal static string ObsoleteErrorSyntaxInspection { + public static string ObsoleteErrorSyntaxInspection { get { return ResourceManager.GetString("ObsoleteErrorSyntaxInspection", resourceCulture); } @@ -495,7 +495,7 @@ internal static string ObsoleteErrorSyntaxInspection { /// /// Looks up a localized string similar to Use of obsolete 'Global' access modifier. /// - internal static string ObsoleteGlobalInspection { + public static string ObsoleteGlobalInspection { get { return ResourceManager.GetString("ObsoleteGlobalInspection", resourceCulture); } @@ -504,7 +504,7 @@ internal static string ObsoleteGlobalInspection { /// /// Looks up a localized string similar to Use of obsolete explicit 'Let' statement. /// - internal static string ObsoleteLetStatementInspection { + public static string ObsoleteLetStatementInspection { get { return ResourceManager.GetString("ObsoleteLetStatementInspection", resourceCulture); } @@ -513,7 +513,7 @@ internal static string ObsoleteLetStatementInspection { /// /// Looks up a localized string similar to Member marked as '@Obsolete' is used. /// - internal static string ObsoleteMemberUsageInspection { + public static string ObsoleteMemberUsageInspection { get { return ResourceManager.GetString("ObsoleteMemberUsageInspection", resourceCulture); } @@ -522,7 +522,7 @@ internal static string ObsoleteMemberUsageInspection { /// /// Looks up a localized string similar to Obsolete Type hint usage. /// - internal static string ObsoleteTypeHintInspection { + public static string ObsoleteTypeHintInspection { get { return ResourceManager.GetString("ObsoleteTypeHintInspection", resourceCulture); } @@ -531,7 +531,7 @@ internal static string ObsoleteTypeHintInspection { /// /// Looks up a localized string similar to On Local Error statement. /// - internal static string OnLocalErrorInspection { + public static string OnLocalErrorInspection { get { return ResourceManager.GetString("OnLocalErrorInspection", resourceCulture); } @@ -540,7 +540,7 @@ internal static string OnLocalErrorInspection { /// /// Looks up a localized string similar to 'Option Base 1' is specified. /// - internal static string OptionBaseInspection { + public static string OptionBaseInspection { get { return ResourceManager.GetString("OptionBaseInspection", resourceCulture); } @@ -549,7 +549,7 @@ internal static string OptionBaseInspection { /// /// Looks up a localized string similar to 'Option Base 0' is redundant. /// - internal static string OptionBaseZeroInspection { + public static string OptionBaseZeroInspection { get { return ResourceManager.GetString("OptionBaseZeroInspection", resourceCulture); } @@ -558,7 +558,7 @@ internal static string OptionBaseZeroInspection { /// /// Looks up a localized string similar to 'Option Explicit' is not specified. /// - internal static string OptionExplicitInspection { + public static string OptionExplicitInspection { get { return ResourceManager.GetString("OptionExplicitInspection", resourceCulture); } @@ -567,7 +567,7 @@ internal static string OptionExplicitInspection { /// /// Looks up a localized string similar to Parameter can be passed by value. /// - internal static string ParameterCanBeByValInspection { + public static string ParameterCanBeByValInspection { get { return ResourceManager.GetString("ParameterCanBeByValInspection", resourceCulture); } @@ -576,7 +576,7 @@ internal static string ParameterCanBeByValInspection { /// /// Looks up a localized string similar to Parameter is not referred to. /// - internal static string ParameterNotUsedInspection { + public static string ParameterNotUsedInspection { get { return ResourceManager.GetString("ParameterNotUsedInspection", resourceCulture); } @@ -585,7 +585,7 @@ internal static string ParameterNotUsedInspection { /// /// Looks up a localized string similar to Procedure can be written as a function. /// - internal static string ProcedureCanBeWrittenAsFunctionInspection { + public static string ProcedureCanBeWrittenAsFunctionInspection { get { return ResourceManager.GetString("ProcedureCanBeWrittenAsFunctionInspection", resourceCulture); } @@ -594,7 +594,7 @@ internal static string ProcedureCanBeWrittenAsFunctionInspection { /// /// Looks up a localized string similar to Procedure is not referred to. /// - internal static string ProcedureNotUsedInspection { + public static string ProcedureNotUsedInspection { get { return ResourceManager.GetString("ProcedureNotUsedInspection", resourceCulture); } @@ -603,7 +603,7 @@ internal static string ProcedureNotUsedInspection { /// /// Looks up a localized string similar to Redundant 'ByRef' modifier. /// - internal static string RedundantByRefModifierInspection { + public static string RedundantByRefModifierInspection { get { return ResourceManager.GetString("RedundantByRefModifierInspection", resourceCulture); } @@ -612,7 +612,7 @@ internal static string RedundantByRefModifierInspection { /// /// Looks up a localized string similar to Redundant module option. /// - internal static string RedundantOptionInspection { + public static string RedundantOptionInspection { get { return ResourceManager.GetString("RedundantOptionInspection", resourceCulture); } @@ -621,7 +621,7 @@ internal static string RedundantOptionInspection { /// /// Looks up a localized string similar to Object variable reference is auto-instantiated. /// - internal static string SelfAssignedDeclarationInspection { + public static string SelfAssignedDeclarationInspection { get { return ResourceManager.GetString("SelfAssignedDeclarationInspection", resourceCulture); } @@ -630,7 +630,7 @@ internal static string SelfAssignedDeclarationInspection { /// /// Looks up a localized string similar to Shadowed declaration. /// - internal static string ShadowedDeclarationInspection { + public static string ShadowedDeclarationInspection { get { return ResourceManager.GetString("ShadowedDeclarationInspection", resourceCulture); } @@ -639,7 +639,7 @@ internal static string ShadowedDeclarationInspection { /// /// Looks up a localized string similar to Statically accessible sheet accessed using string. /// - internal static string SheetAccessedUsingStringInspection { + public static string SheetAccessedUsingStringInspection { get { return ResourceManager.GetString("SheetAccessedUsingStringInspection", resourceCulture); } @@ -648,7 +648,7 @@ internal static string SheetAccessedUsingStringInspection { /// /// Looks up a localized string similar to 'For...Next' loop step is not specified. /// - internal static string StepIsNotSpecifiedInspection { + public static string StepIsNotSpecifiedInspection { get { return ResourceManager.GetString("StepIsNotSpecifiedInspection", resourceCulture); } @@ -657,7 +657,7 @@ internal static string StepIsNotSpecifiedInspection { /// /// Looks up a localized string similar to 'For...Next' loop step 1 is redundant. /// - internal static string StepOneIsRedundantInspection { + public static string StepOneIsRedundantInspection { get { return ResourceManager.GetString("StepOneIsRedundantInspection", resourceCulture); } @@ -666,7 +666,7 @@ internal static string StepOneIsRedundantInspection { /// /// Looks up a localized string similar to 'Stop' keyword. /// - internal static string StopKeywordInspection { + public static string StopKeywordInspection { get { return ResourceManager.GetString("StopKeywordInspection", resourceCulture); } @@ -675,7 +675,7 @@ internal static string StopKeywordInspection { /// /// Looks up a localized string similar to Variable is used but not assigned. /// - internal static string UnassignedVariableUsageInspection { + public static string UnassignedVariableUsageInspection { get { return ResourceManager.GetString("UnassignedVariableUsageInspection", resourceCulture); } @@ -684,7 +684,7 @@ internal static string UnassignedVariableUsageInspection { /// /// Looks up a localized string similar to Undeclared variable. /// - internal static string UndeclaredVariableInspection { + public static string UndeclaredVariableInspection { get { return ResourceManager.GetString("UndeclaredVariableInspection", resourceCulture); } @@ -693,7 +693,7 @@ internal static string UndeclaredVariableInspection { /// /// Looks up a localized string similar to Unhandled 'On Error Resume Next'. /// - internal static string UnhandledOnErrorResumeNextInspection { + public static string UnhandledOnErrorResumeNextInspection { get { return ResourceManager.GetString("UnhandledOnErrorResumeNextInspection", resourceCulture); } @@ -702,7 +702,7 @@ internal static string UnhandledOnErrorResumeNextInspection { /// /// Looks up a localized string similar to Case Clause(s) cannot be reached. /// - internal static string UnreachableCaseInspection { + public static string UnreachableCaseInspection { get { return ResourceManager.GetString("UnreachableCaseInspection", resourceCulture); } @@ -711,7 +711,7 @@ internal static string UnreachableCaseInspection { /// /// Looks up a localized string similar to Use of variant-returning string function. /// - internal static string UntypedFunctionUsageInspection { + public static string UntypedFunctionUsageInspection { get { return ResourceManager.GetString("UntypedFunctionUsageInspection", resourceCulture); } @@ -720,7 +720,7 @@ internal static string UntypedFunctionUsageInspection { /// /// Looks up a localized string similar to Use meaningful names. /// - internal static string UseMeaningfulNameInspection { + public static string UseMeaningfulNameInspection { get { return ResourceManager.GetString("UseMeaningfulNameInspection", resourceCulture); } @@ -729,7 +729,7 @@ internal static string UseMeaningfulNameInspection { /// /// Looks up a localized string similar to Variable is not assigned. /// - internal static string VariableNotAssignedInspection { + public static string VariableNotAssignedInspection { get { return ResourceManager.GetString("VariableNotAssignedInspection", resourceCulture); } @@ -738,7 +738,7 @@ internal static string VariableNotAssignedInspection { /// /// Looks up a localized string similar to Variable is not referred to. /// - internal static string VariableNotUsedInspection { + public static string VariableNotUsedInspection { get { return ResourceManager.GetString("VariableNotUsedInspection", resourceCulture); } @@ -747,7 +747,7 @@ internal static string VariableNotUsedInspection { /// /// Looks up a localized string similar to Implicitly 'Variant' variable. /// - internal static string VariableTypeNotDeclaredInspection { + public static string VariableTypeNotDeclaredInspection { get { return ResourceManager.GetString("VariableTypeNotDeclaredInspection", resourceCulture); } @@ -756,7 +756,7 @@ internal static string VariableTypeNotDeclaredInspection { /// /// Looks up a localized string similar to Write-only property. /// - internal static string WriteOnlyPropertyInspection { + public static string WriteOnlyPropertyInspection { get { return ResourceManager.GetString("WriteOnlyPropertyInspection", resourceCulture); } diff --git a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs index ec61bb7a7d..e128f4c4e1 100644 --- a/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionResults.Designer.cs @@ -22,7 +22,7 @@ namespace Rubberduck.Resources.Inspections { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class InspectionResults { + public class InspectionResults { private static global::System.Resources.ResourceManager resourceMan; @@ -36,7 +36,7 @@ internal InspectionResults() { /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Rubberduck.Resources.Inspections.InspectionResults", typeof(InspectionResults).Assembly); @@ -51,7 +51,7 @@ internal InspectionResults() { /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -63,7 +63,7 @@ internal InspectionResults() { /// /// Looks up a localized string similar to {0} ({1} results).. /// - internal static string AggregateInspection { + public static string AggregateInspection { get { return ResourceManager.GetString("AggregateInspection", resourceCulture); } @@ -72,7 +72,7 @@ internal static string AggregateInspection { /// /// Looks up a localized string similar to Use of late bound 'Application.{0}' member.. /// - internal static string ApplicationWorksheetFunctionInspection { + public static string ApplicationWorksheetFunctionInspection { get { return ResourceManager.GetString("ApplicationWorksheetFunctionInspection", resourceCulture); } @@ -81,7 +81,7 @@ internal static string ApplicationWorksheetFunctionInspection { /// /// Looks up a localized string similar to Parameter '{0}' is passed 'ByVal' and assigned a value.. /// - internal static string AssignedByValParameterInspection { + public static string AssignedByValParameterInspection { get { return ResourceManager.GetString("AssignedByValParameterInspection", resourceCulture); } @@ -90,7 +90,7 @@ internal static string AssignedByValParameterInspection { /// /// Looks up a localized string similar to An assignment is immediately overridden by another assignment or is never referenced.. /// - internal static string AssignmentNotUsedInspection { + public static string AssignmentNotUsedInspection { get { return ResourceManager.GetString("AssignmentNotUsedInspection", resourceCulture); } @@ -99,7 +99,7 @@ internal static string AssignmentNotUsedInspection { /// /// Looks up a localized string similar to Boolean literal '{0}' assigned in conditional.. /// - internal static string BooleanAssignedInIfElseInspection { + public static string BooleanAssignedInIfElseInspection { get { return ResourceManager.GetString("BooleanAssignedInIfElseInspection", resourceCulture); } @@ -108,7 +108,7 @@ internal static string BooleanAssignedInIfElseInspection { /// /// Looks up a localized string similar to Project '{0}' has default name.. /// - internal static string DefaultProjectNameInspection { + public static string DefaultProjectNameInspection { get { return ResourceManager.GetString("DefaultProjectNameInspection", resourceCulture); } @@ -117,7 +117,7 @@ internal static string DefaultProjectNameInspection { /// /// Looks up a localized string similar to Consider the explicit use of 'As {0}' instead of '{1}'.. /// - internal static string DefTypeStatementInspection { + public static string DefTypeStatementInspection { get { return ResourceManager.GetString("DefTypeStatementInspection", resourceCulture); } @@ -126,7 +126,7 @@ internal static string DefTypeStatementInspection { /// /// Looks up a localized string similar to Annotation '{0}' is duplicated.. /// - internal static string DuplicatedAnnotationInspection { + public static string DuplicatedAnnotationInspection { get { return ResourceManager.GetString("DuplicatedAnnotationInspection", resourceCulture); } @@ -135,7 +135,7 @@ internal static string DuplicatedAnnotationInspection { /// /// Looks up a localized string similar to 'Case' block contains no executable statements.. /// - internal static string EmptyCaseBlockInspection { + public static string EmptyCaseBlockInspection { get { return ResourceManager.GetString("EmptyCaseBlockInspection", resourceCulture); } @@ -144,7 +144,7 @@ internal static string EmptyCaseBlockInspection { /// /// Looks up a localized string similar to 'Do...While' loop contains no executable statements.. /// - internal static string EmptyDoWhileBlockInspection { + public static string EmptyDoWhileBlockInspection { get { return ResourceManager.GetString("EmptyDoWhileBlockInspection", resourceCulture); } @@ -153,7 +153,7 @@ internal static string EmptyDoWhileBlockInspection { /// /// Looks up a localized string similar to 'Else' block contains no executable statements.. /// - internal static string EmptyElseBlockInspection { + public static string EmptyElseBlockInspection { get { return ResourceManager.GetString("EmptyElseBlockInspection", resourceCulture); } @@ -162,7 +162,7 @@ internal static string EmptyElseBlockInspection { /// /// Looks up a localized string similar to 'For...Each' loop contains no executable statements.. /// - internal static string EmptyForEachBlockInspection { + public static string EmptyForEachBlockInspection { get { return ResourceManager.GetString("EmptyForEachBlockInspection", resourceCulture); } @@ -171,7 +171,7 @@ internal static string EmptyForEachBlockInspection { /// /// Looks up a localized string similar to 'For...Next' loop contains no executable statements.. /// - internal static string EmptyForLoopBlockInspection { + public static string EmptyForLoopBlockInspection { get { return ResourceManager.GetString("EmptyForLoopBlockInspection", resourceCulture); } @@ -180,7 +180,7 @@ internal static string EmptyForLoopBlockInspection { /// /// Looks up a localized string similar to 'If' block contains no executable statements.. /// - internal static string EmptyIfBlockInspection { + public static string EmptyIfBlockInspection { get { return ResourceManager.GetString("EmptyIfBlockInspection", resourceCulture); } @@ -189,7 +189,7 @@ internal static string EmptyIfBlockInspection { /// /// Looks up a localized string similar to Module/class '{0}' is empty.. /// - internal static string EmptyModuleInspection { + public static string EmptyModuleInspection { get { return ResourceManager.GetString("EmptyModuleInspection", resourceCulture); } @@ -198,7 +198,7 @@ internal static string EmptyModuleInspection { /// /// Looks up a localized string similar to 'vbNullString' preferred to empty string literals.. /// - internal static string EmptyStringLiteralInspection { + public static string EmptyStringLiteralInspection { get { return ResourceManager.GetString("EmptyStringLiteralInspection", resourceCulture); } @@ -207,7 +207,7 @@ internal static string EmptyStringLiteralInspection { /// /// Looks up a localized string similar to 'While...Wend' loop contains no executable statements.. /// - internal static string EmptyWhileWendBlockInspection { + public static string EmptyWhileWendBlockInspection { get { return ResourceManager.GetString("EmptyWhileWendBlockInspection", resourceCulture); } @@ -216,7 +216,7 @@ internal static string EmptyWhileWendBlockInspection { /// /// Looks up a localized string similar to Public field '{0}' breaks encapsulation.. /// - internal static string EncapsulatePublicFieldInspection { + public static string EncapsulatePublicFieldInspection { get { return ResourceManager.GetString("EncapsulatePublicFieldInspection", resourceCulture); } @@ -225,7 +225,7 @@ internal static string EncapsulatePublicFieldInspection { /// /// Looks up a localized string similar to Result of '{0}' call is not tested for 'Nothing'.. /// - internal static string ExcelMemberMayReturnNothingInspection { + public static string ExcelMemberMayReturnNothingInspection { get { return ResourceManager.GetString("ExcelMemberMayReturnNothingInspection", resourceCulture); } @@ -234,7 +234,7 @@ internal static string ExcelMemberMayReturnNothingInspection { /// /// Looks up a localized string similar to Return value of function '{0}' is never used.. /// - internal static string FunctionReturnValueNotUsedInspection { + public static string FunctionReturnValueNotUsedInspection { get { return ResourceManager.GetString("FunctionReturnValueNotUsedInspection", resourceCulture); } @@ -243,7 +243,7 @@ internal static string FunctionReturnValueNotUsedInspection { /// /// Looks up a localized string similar to Expression '{0}' cannot be validated at compile-time.. /// - internal static string HostSpecificExpressionInspection { + public static string HostSpecificExpressionInspection { get { return ResourceManager.GetString("HostSpecificExpressionInspection", resourceCulture); } @@ -252,7 +252,7 @@ internal static string HostSpecificExpressionInspection { /// /// Looks up a localized string similar to Consider renaming {0} '{1}'.. /// - internal static string IdentifierNameInspection { + public static string IdentifierNameInspection { get { return ResourceManager.GetString("IdentifierNameInspection", resourceCulture); } @@ -261,7 +261,7 @@ internal static string IdentifierNameInspection { /// /// Looks up a localized string similar to {0} '{1}' is not used.. /// - internal static string IdentifierNotUsedInspection { + public static string IdentifierNotUsedInspection { get { return ResourceManager.GetString("IdentifierNotUsedInspection", resourceCulture); } @@ -270,7 +270,7 @@ internal static string IdentifierNotUsedInspection { /// /// Looks up a localized string similar to Annotation '{0}' is illegal in this context.. /// - internal static string IllegalAnnotationInspection { + public static string IllegalAnnotationInspection { get { return ResourceManager.GetString("IllegalAnnotationInspection", resourceCulture); } @@ -279,7 +279,7 @@ internal static string IllegalAnnotationInspection { /// /// Looks up a localized string similar to Member '{0}' implicitly references 'ActiveSheet'.. /// - internal static string ImplicitActiveSheetReferenceInspection { + public static string ImplicitActiveSheetReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveSheetReferenceInspection", resourceCulture); } @@ -288,7 +288,7 @@ internal static string ImplicitActiveSheetReferenceInspection { /// /// Looks up a localized string similar to Member '{0}' implicitly references 'ActiveWorkbook'.. /// - internal static string ImplicitActiveWorkbookReferenceInspection { + public static string ImplicitActiveWorkbookReferenceInspection { get { return ResourceManager.GetString("ImplicitActiveWorkbookReferenceInspection", resourceCulture); } @@ -297,7 +297,7 @@ internal static string ImplicitActiveWorkbookReferenceInspection { /// /// Looks up a localized string similar to Parameter '{0}' is implicitly passed by reference.. /// - internal static string ImplicitByRefModifierInspection { + public static string ImplicitByRefModifierInspection { get { return ResourceManager.GetString("ImplicitByRefModifierInspection", resourceCulture); } @@ -306,7 +306,7 @@ internal static string ImplicitByRefModifierInspection { /// /// Looks up a localized string similar to Assignment to '{0}' implicitly assigns default member of class '{1}'.. /// - internal static string ImplicitDefaultMemberAssignmentInspection { + public static string ImplicitDefaultMemberAssignmentInspection { get { return ResourceManager.GetString("ImplicitDefaultMemberAssignmentInspection", resourceCulture); } @@ -315,7 +315,7 @@ internal static string ImplicitDefaultMemberAssignmentInspection { /// /// Looks up a localized string similar to Member '{0}' is implicitly public.. /// - internal static string ImplicitPublicMemberInspection { + public static string ImplicitPublicMemberInspection { get { return ResourceManager.GetString("ImplicitPublicMemberInspection", resourceCulture); } @@ -324,7 +324,7 @@ internal static string ImplicitPublicMemberInspection { /// /// Looks up a localized string similar to {0} '{1}' is implicitly 'Variant'.. /// - internal static string ImplicitVariantDeclarationInspection { + public static string ImplicitVariantDeclarationInspection { get { return ResourceManager.GetString("ImplicitVariantDeclarationInspection", resourceCulture); } @@ -333,7 +333,7 @@ internal static string ImplicitVariantDeclarationInspection { /// /// Looks up a localized string similar to Return type of member '{0}' is implicitly 'Variant'.. /// - internal static string ImplicitVariantReturnTypeInspection { + public static string ImplicitVariantReturnTypeInspection { get { return ResourceManager.GetString("ImplicitVariantReturnTypeInspection", resourceCulture); } @@ -342,7 +342,7 @@ internal static string ImplicitVariantReturnTypeInspection { /// /// Looks up a localized string similar to {0} '{1}' is declared as 'Integer'.. /// - internal static string IntegerDataTypeInspection { + public static string IntegerDataTypeInspection { get { return ResourceManager.GetString("IntegerDataTypeInspection", resourceCulture); } @@ -351,7 +351,7 @@ internal static string IntegerDataTypeInspection { /// /// Looks up a localized string similar to 'IsMissing' will always return false with the passed argument.. /// - internal static string IsMissingOnInappropriateArgumentInspection { + public static string IsMissingOnInappropriateArgumentInspection { get { return ResourceManager.GetString("IsMissingOnInappropriateArgumentInspection", resourceCulture); } @@ -360,7 +360,7 @@ internal static string IsMissingOnInappropriateArgumentInspection { /// /// Looks up a localized string similar to 'IsMissing' is passed an expresssion that is not an argument to the enclosing procedure.. /// - internal static string IsMissingWithNonArgumentParameterInspection { + public static string IsMissingWithNonArgumentParameterInspection { get { return ResourceManager.GetString("IsMissingWithNonArgumentParameterInspection", resourceCulture); } @@ -369,7 +369,7 @@ internal static string IsMissingWithNonArgumentParameterInspection { /// /// Looks up a localized string similar to Line label '{0}' is not used.. /// - internal static string LineLabelNotUsedInspection { + public static string LineLabelNotUsedInspection { get { return ResourceManager.GetString("LineLabelNotUsedInspection", resourceCulture); } @@ -378,7 +378,7 @@ internal static string LineLabelNotUsedInspection { /// /// Looks up a localized string similar to Member '{0}' was not found on the compile-time interface for type '{1}'.. /// - internal static string MemberNotOnInterfaceInspection { + public static string MemberNotOnInterfaceInspection { get { return ResourceManager.GetString("MemberNotOnInterfaceInspection", resourceCulture); } @@ -387,7 +387,7 @@ internal static string MemberNotOnInterfaceInspection { /// /// Looks up a localized string similar to Expression '{0}' was expected to contain a parameter, but none was specified.. /// - internal static string MissingAnnotationArgumentInspection { + public static string MissingAnnotationArgumentInspection { get { return ResourceManager.GetString("MissingAnnotationArgumentInspection", resourceCulture); } @@ -396,7 +396,7 @@ internal static string MissingAnnotationArgumentInspection { /// /// Looks up a localized string similar to Module or member '{0}' has a '{1}' attribute, but no corresponding annotation.. /// - internal static string MissingAnnotationInspection { + public static string MissingAnnotationInspection { get { return ResourceManager.GetString("MissingAnnotationInspection", resourceCulture); } @@ -405,7 +405,7 @@ internal static string MissingAnnotationInspection { /// /// Looks up a localized string similar to Module or member '{0}' has a '{1}' annotation, but no corresponding attribute.. /// - internal static string MissingAttributeInspection { + public static string MissingAttributeInspection { get { return ResourceManager.GetString("MissingAttributeInspection", resourceCulture); } @@ -414,7 +414,7 @@ internal static string MissingAttributeInspection { /// /// Looks up a localized string similar to Module-level variable '{0}' is declared with the 'Dim' keyword.. /// - internal static string ModuleScopeDimKeywordInspection { + public static string ModuleScopeDimKeywordInspection { get { return ResourceManager.GetString("ModuleScopeDimKeywordInspection", resourceCulture); } @@ -423,7 +423,7 @@ internal static string ModuleScopeDimKeywordInspection { /// /// Looks up a localized string similar to Module '{0}' has no '@Folder' annotation. /// - internal static string ModuleWithoutFolderInspection { + public static string ModuleWithoutFolderInspection { get { return ResourceManager.GetString("ModuleWithoutFolderInspection", resourceCulture); } @@ -432,7 +432,7 @@ internal static string ModuleWithoutFolderInspection { /// /// Looks up a localized string similar to Move module-level variable '{0}' to a smaller scope.. /// - internal static string MoveFieldCloserToUsageInspection { + public static string MoveFieldCloserToUsageInspection { get { return ResourceManager.GetString("MoveFieldCloserToUsageInspection", resourceCulture); } @@ -441,7 +441,7 @@ internal static string MoveFieldCloserToUsageInspection { /// /// Looks up a localized string similar to Parameter '{0}' is specified on multiple lines.. /// - internal static string MultilineParameterInspection { + public static string MultilineParameterInspection { get { return ResourceManager.GetString("MultilineParameterInspection", resourceCulture); } @@ -450,7 +450,7 @@ internal static string MultilineParameterInspection { /// /// Looks up a localized string similar to Instruction contains multiple declarations.. /// - internal static string MultipleDeclarationsInspection { + public static string MultipleDeclarationsInspection { get { return ResourceManager.GetString("MultipleDeclarationsInspection", resourceCulture); } @@ -459,7 +459,7 @@ internal static string MultipleDeclarationsInspection { /// /// Looks up a localized string similar to Return value for member '{0}' is never assigned.. /// - internal static string NonReturningFunctionInspection { + public static string NonReturningFunctionInspection { get { return ResourceManager.GetString("NonReturningFunctionInspection", resourceCulture); } @@ -468,7 +468,7 @@ internal static string NonReturningFunctionInspection { /// /// Looks up a localized string similar to Object variable '{0}' is assigned without the 'Set' keyword.. /// - internal static string ObjectVariableNotSetInspection { + public static string ObjectVariableNotSetInspection { get { return ResourceManager.GetString("ObjectVariableNotSetInspection", resourceCulture); } @@ -477,7 +477,7 @@ internal static string ObjectVariableNotSetInspection { /// /// Looks up a localized string similar to '{0}' is declared using the obsolete 'CDecl' calling convention.. /// - internal static string ObsoleteCallingConventionInspection { + public static string ObsoleteCallingConventionInspection { get { return ResourceManager.GetString("ObsoleteCallingConventionInspection", resourceCulture); } @@ -486,7 +486,7 @@ internal static string ObsoleteCallingConventionInspection { /// /// Looks up a localized string similar to Assignment uses obsolete 'Call' modifier.. /// - internal static string ObsoleteCallStatementInspection { + public static string ObsoleteCallStatementInspection { get { return ResourceManager.GetString("ObsoleteCallStatementInspection", resourceCulture); } @@ -495,7 +495,7 @@ internal static string ObsoleteCallStatementInspection { /// /// Looks up a localized string similar to Comment uses obsolete 'Rem' marker.. /// - internal static string ObsoleteCommentSyntaxInspection { + public static string ObsoleteCommentSyntaxInspection { get { return ResourceManager.GetString("ObsoleteCommentSyntaxInspection", resourceCulture); } @@ -504,7 +504,7 @@ internal static string ObsoleteCommentSyntaxInspection { /// /// Looks up a localized string similar to A run-time error is raised using the obsolete 'Error' statement.. /// - internal static string ObsoleteErrorSyntaxInspection { + public static string ObsoleteErrorSyntaxInspection { get { return ResourceManager.GetString("ObsoleteErrorSyntaxInspection", resourceCulture); } @@ -513,7 +513,7 @@ internal static string ObsoleteErrorSyntaxInspection { /// /// Looks up a localized string similar to {0} '{1}' uses obsolete 'Global' access modifier.. /// - internal static string ObsoleteGlobalInspection { + public static string ObsoleteGlobalInspection { get { return ResourceManager.GetString("ObsoleteGlobalInspection", resourceCulture); } @@ -522,7 +522,7 @@ internal static string ObsoleteGlobalInspection { /// /// Looks up a localized string similar to Assignment uses obsolete 'Let' modifier.. /// - internal static string ObsoleteLetStatementInspection { + public static string ObsoleteLetStatementInspection { get { return ResourceManager.GetString("ObsoleteLetStatementInspection", resourceCulture); } @@ -531,7 +531,7 @@ internal static string ObsoleteLetStatementInspection { /// /// Looks up a localized string similar to Consider replacing the call to '{0}'. {1}. /// - internal static string ObsoleteMemberUsageInspection { + public static string ObsoleteMemberUsageInspection { get { return ResourceManager.GetString("ObsoleteMemberUsageInspection", resourceCulture); } @@ -540,7 +540,7 @@ internal static string ObsoleteMemberUsageInspection { /// /// Looks up a localized string similar to {0} of {1} '{2}' uses an obsolete type hint.. /// - internal static string ObsoleteTypeHintInspection { + public static string ObsoleteTypeHintInspection { get { return ResourceManager.GetString("ObsoleteTypeHintInspection", resourceCulture); } @@ -549,7 +549,7 @@ internal static string ObsoleteTypeHintInspection { /// /// Looks up a localized string similar to 'On Local Error' statement detected.. /// - internal static string OnLocalErrorInspection { + public static string OnLocalErrorInspection { get { return ResourceManager.GetString("OnLocalErrorInspection", resourceCulture); } @@ -558,7 +558,7 @@ internal static string OnLocalErrorInspection { /// /// Looks up a localized string similar to Component '{0}' uses 'Option Base 1'.. /// - internal static string OptionBaseInspection { + public static string OptionBaseInspection { get { return ResourceManager.GetString("OptionBaseInspection", resourceCulture); } @@ -567,7 +567,7 @@ internal static string OptionBaseInspection { /// /// Looks up a localized string similar to Component '{0}' uses 'Option Base 0'.. /// - internal static string OptionBaseZeroInspection { + public static string OptionBaseZeroInspection { get { return ResourceManager.GetString("OptionBaseZeroInspection", resourceCulture); } @@ -576,7 +576,7 @@ internal static string OptionBaseZeroInspection { /// /// Looks up a localized string similar to 'Option Explicit' is not specified in '{0}'.. /// - internal static string OptionExplicitInspection { + public static string OptionExplicitInspection { get { return ResourceManager.GetString("OptionExplicitInspection", resourceCulture); } @@ -585,7 +585,7 @@ internal static string OptionExplicitInspection { /// /// Looks up a localized string similar to Parameter '{0}' can be passed by value.. /// - internal static string ParameterCanBeByValInspection { + public static string ParameterCanBeByValInspection { get { return ResourceManager.GetString("ParameterCanBeByValInspection", resourceCulture); } @@ -594,7 +594,7 @@ internal static string ParameterCanBeByValInspection { /// /// Looks up a localized string similar to Parameter '{0}' is never used.. /// - internal static string ParameterNotUsedInspection { + public static string ParameterNotUsedInspection { get { return ResourceManager.GetString("ParameterNotUsedInspection", resourceCulture); } @@ -603,7 +603,7 @@ internal static string ParameterNotUsedInspection { /// /// Looks up a localized string similar to Procedure '{0}' can be written as a function.. /// - internal static string ProcedureCanBeWrittenAsFunctionInspection { + public static string ProcedureCanBeWrittenAsFunctionInspection { get { return ResourceManager.GetString("ProcedureCanBeWrittenAsFunctionInspection", resourceCulture); } @@ -612,7 +612,7 @@ internal static string ProcedureCanBeWrittenAsFunctionInspection { /// /// Looks up a localized string similar to Procedure '{0}' can be written as a function.. /// - internal static string ProcedureShouldBeFunctionInspection { + public static string ProcedureShouldBeFunctionInspection { get { return ResourceManager.GetString("ProcedureShouldBeFunctionInspection", resourceCulture); } @@ -621,7 +621,7 @@ internal static string ProcedureShouldBeFunctionInspection { /// /// Looks up a localized string similar to Parameter '{0}' has a redundant 'ByRef' modifier.. /// - internal static string RedundantByRefModifierInspection { + public static string RedundantByRefModifierInspection { get { return ResourceManager.GetString("RedundantByRefModifierInspection", resourceCulture); } @@ -630,7 +630,7 @@ internal static string RedundantByRefModifierInspection { /// /// Looks up a localized string similar to '{0}' has no effect.. /// - internal static string RedundantOptionInspection { + public static string RedundantOptionInspection { get { return ResourceManager.GetString("RedundantOptionInspection", resourceCulture); } @@ -639,7 +639,7 @@ internal static string RedundantOptionInspection { /// /// Looks up a localized string similar to Object reference '{0}' is auto-instantiated.. /// - internal static string SelfAssignedDeclarationInspection { + public static string SelfAssignedDeclarationInspection { get { return ResourceManager.GetString("SelfAssignedDeclarationInspection", resourceCulture); } @@ -648,7 +648,7 @@ internal static string SelfAssignedDeclarationInspection { /// /// Looks up a localized string similar to {0} '{1}' hides {2} '{3}'.. /// - internal static string ShadowedDeclarationInspection { + public static string ShadowedDeclarationInspection { get { return ResourceManager.GetString("ShadowedDeclarationInspection", resourceCulture); } @@ -657,7 +657,7 @@ internal static string ShadowedDeclarationInspection { /// /// Looks up a localized string similar to Statically accessible sheet can be referred to by its code name.. /// - internal static string SheetAccessedUsingStringInspection { + public static string SheetAccessedUsingStringInspection { get { return ResourceManager.GetString("SheetAccessedUsingStringInspection", resourceCulture); } @@ -666,7 +666,7 @@ internal static string SheetAccessedUsingStringInspection { /// /// Looks up a localized string similar to 'Step' not specified.. /// - internal static string StepIsNotSpecifiedInspection { + public static string StepIsNotSpecifiedInspection { get { return ResourceManager.GetString("StepIsNotSpecifiedInspection", resourceCulture); } @@ -675,7 +675,7 @@ internal static string StepIsNotSpecifiedInspection { /// /// Looks up a localized string similar to 1 is the default step in a 'For...Next' loop and therefore is redundant.. /// - internal static string StepOneIsRedundantInspection { + public static string StepOneIsRedundantInspection { get { return ResourceManager.GetString("StepOneIsRedundantInspection", resourceCulture); } @@ -684,7 +684,7 @@ internal static string StepOneIsRedundantInspection { /// /// Looks up a localized string similar to 'Stop' keyword halts execution.. /// - internal static string StopKeywordInspection { + public static string StopKeywordInspection { get { return ResourceManager.GetString("StopKeywordInspection", resourceCulture); } @@ -693,7 +693,7 @@ internal static string StopKeywordInspection { /// /// Looks up a localized string similar to Variable '{0}' is used but not assigned.. /// - internal static string UnassignedVariableUsageInspection { + public static string UnassignedVariableUsageInspection { get { return ResourceManager.GetString("UnassignedVariableUsageInspection", resourceCulture); } @@ -702,7 +702,7 @@ internal static string UnassignedVariableUsageInspection { /// /// Looks up a localized string similar to Local variable '{0}' is not declared.. /// - internal static string UndeclaredVariableInspection { + public static string UndeclaredVariableInspection { get { return ResourceManager.GetString("UndeclaredVariableInspection", resourceCulture); } @@ -711,7 +711,7 @@ internal static string UndeclaredVariableInspection { /// /// Looks up a localized string similar to Errors are ignored but never handled again.. /// - internal static string UnhandledOnErrorResumeNextInspection { + public static string UnhandledOnErrorResumeNextInspection { get { return ResourceManager.GetString("UnhandledOnErrorResumeNextInspection", resourceCulture); } @@ -720,7 +720,7 @@ internal static string UnhandledOnErrorResumeNextInspection { /// /// Looks up a localized string similar to Case clause '{0}' cannot be reached.. /// - internal static string UnreachableCaseInspection { + public static string UnreachableCaseInspection { get { return ResourceManager.GetString("UnreachableCaseInspection", resourceCulture); } @@ -729,7 +729,7 @@ internal static string UnreachableCaseInspection { /// /// Looks up a localized string similar to Unreachable Case Else: all matches exist within prior Case statement(s).. /// - internal static string UnreachableCaseInspection_CaseElse { + public static string UnreachableCaseInspection_CaseElse { get { return ResourceManager.GetString("UnreachableCaseInspection_CaseElse", resourceCulture); } @@ -738,7 +738,7 @@ internal static string UnreachableCaseInspection_CaseElse { /// /// Looks up a localized string similar to Unreachable: Case Statement contains invalid range clause(s).. /// - internal static string UnreachableCaseInspection_InherentlyUnreachable { + public static string UnreachableCaseInspection_InherentlyUnreachable { get { return ResourceManager.GetString("UnreachableCaseInspection_InherentlyUnreachable", resourceCulture); } @@ -747,7 +747,7 @@ internal static string UnreachableCaseInspection_InherentlyUnreachable { /// /// Looks up a localized string similar to Unreachable: Case Statement will cause a Run-time error 6 (Overflow).. /// - internal static string UnreachableCaseInspection_Overflow { + public static string UnreachableCaseInspection_Overflow { get { return ResourceManager.GetString("UnreachableCaseInspection_Overflow", resourceCulture); } @@ -756,7 +756,7 @@ internal static string UnreachableCaseInspection_Overflow { /// /// Looks up a localized string similar to Unreachable: Case Statement will cause a Run-time error 13 (Mismatch).. /// - internal static string UnreachableCaseInspection_TypeMismatch { + public static string UnreachableCaseInspection_TypeMismatch { get { return ResourceManager.GetString("UnreachableCaseInspection_TypeMismatch", resourceCulture); } @@ -765,7 +765,7 @@ internal static string UnreachableCaseInspection_TypeMismatch { /// /// Looks up a localized string similar to Unreachable: Never matches or is equivalent to a prior Case statement.. /// - internal static string UnreachableCaseInspection_Unreachable { + public static string UnreachableCaseInspection_Unreachable { get { return ResourceManager.GetString("UnreachableCaseInspection_Unreachable", resourceCulture); } @@ -774,7 +774,7 @@ internal static string UnreachableCaseInspection_Unreachable { /// /// Looks up a localized string similar to Replace function '{0}' with existing typed function.. /// - internal static string UntypedFunctionUsageInspection { + public static string UntypedFunctionUsageInspection { get { return ResourceManager.GetString("UntypedFunctionUsageInspection", resourceCulture); } @@ -783,7 +783,7 @@ internal static string UntypedFunctionUsageInspection { /// /// Looks up a localized string similar to Variable '{0}' is not assigned.. /// - internal static string VariableNotAssignedInspection { + public static string VariableNotAssignedInspection { get { return ResourceManager.GetString("VariableNotAssignedInspection", resourceCulture); } @@ -792,7 +792,7 @@ internal static string VariableNotAssignedInspection { /// /// Looks up a localized string similar to {0} '{1}' is implicitly 'Variant'.. /// - internal static string VariableTypeNotDeclaredInspection { + public static string VariableTypeNotDeclaredInspection { get { return ResourceManager.GetString("VariableTypeNotDeclaredInspection", resourceCulture); } @@ -801,7 +801,7 @@ internal static string VariableTypeNotDeclaredInspection { /// /// Looks up a localized string similar to Property '{0}' has no getter.. /// - internal static string WriteOnlyPropertyInspection { + public static string WriteOnlyPropertyInspection { get { return ResourceManager.GetString("WriteOnlyPropertyInspection", resourceCulture); } diff --git a/Rubberduck.Resources/Rubberduck.Resources.csproj b/Rubberduck.Resources/Rubberduck.Resources.csproj index 5e05ae3570..7205ec5764 100644 --- a/Rubberduck.Resources/Rubberduck.Resources.csproj +++ b/Rubberduck.Resources/Rubberduck.Resources.csproj @@ -24,7 +24,7 @@ - ResXFileCodeGenerator + PublicResXFileCodeGenerator $([System.String]::Copy('%(FileName)')).Designer.cs diff --git a/Rubberduck.Resources/Settings/AutoCompletesPage.Designer.cs b/Rubberduck.Resources/Settings/AutoCompletesPage.Designer.cs index e71b292377..18a7c254a2 100644 --- a/Rubberduck.Resources/Settings/AutoCompletesPage.Designer.cs +++ b/Rubberduck.Resources/Settings/AutoCompletesPage.Designer.cs @@ -61,160 +61,70 @@ internal AutoCompletesPage() { } /// - /// Looks up a localized string similar to Close curly braces '{'. + /// Looks up a localized string similar to Block Completion. /// - public static string AutoCompleteClosingBraceDescription { + public static string BlockCompletion { get { - return ResourceManager.GetString("AutoCompleteClosingBraceDescription", resourceCulture); + return ResourceManager.GetString("BlockCompletion", resourceCulture); } } /// - /// Looks up a localized string similar to Close square brackets '['. - /// - public static string AutoCompleteClosingBracketDescription { - get { - return ResourceManager.GetString("AutoCompleteClosingBracketDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close parentheses '('. - /// - public static string AutoCompleteClosingParentheseDescription { - get { - return ResourceManager.GetString("AutoCompleteClosingParentheseDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close string literals '"'. - /// - public static string AutoCompleteClosingStringDescription { - get { - return ResourceManager.GetString("AutoCompleteClosingStringDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close 'Do [Until|While]...Loop' loop blocks. - /// - public static string AutoCompleteDoBlockDescription { - get { - return ResourceManager.GetString("AutoCompleteDoBlockDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close 'Enum' blocks. - /// - public static string AutoCompleteEnumBlockDescription { - get { - return ResourceManager.GetString("AutoCompleteEnumBlockDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close 'For [Each]...Next' loop blocks. - /// - public static string AutoCompleteForBlockDescription { - get { - return ResourceManager.GetString("AutoCompleteForBlockDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Override 'Function' member block completion. - /// - public static string AutoCompleteFunctionBlockDescription { - get { - return ResourceManager.GetString("AutoCompleteFunctionBlockDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close 'If' blocks. - /// - public static string AutoCompleteIfBlockDescription { - get { - return ResourceManager.GetString("AutoCompleteIfBlockDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Treat 'On Error Resume Next...GoTo 0' as a block. - /// - public static string AutoCompleteOnErrorResumeNextBlockDescription { - get { - return ResourceManager.GetString("AutoCompleteOnErrorResumeNextBlockDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close precompiler '#If' blocks. - /// - public static string AutoCompletePrecompilerIfBlockDescription { - get { - return ResourceManager.GetString("AutoCompletePrecompilerIfBlockDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Override 'Property' member block completion. + /// Looks up a localized string similar to Autocomplete blocks on ENTER. /// - public static string AutoCompletePropertyBlockDescription { + public static string CompleteBlockOnEnter { get { - return ResourceManager.GetString("AutoCompletePropertyBlockDescription", resourceCulture); + return ResourceManager.GetString("CompleteBlockOnEnter", resourceCulture); } } /// - /// Looks up a localized string similar to Close 'Select' blocks. + /// Looks up a localized string similar to Autocomplete blocks on TAB. /// - public static string AutoCompleteSelectBlockDescription { + public static string CompleteBlockOnTab { get { - return ResourceManager.GetString("AutoCompleteSelectBlockDescription", resourceCulture); + return ResourceManager.GetString("CompleteBlockOnTab", resourceCulture); } } /// - /// Looks up a localized string similar to Override 'Sub' member block completion. + /// Looks up a localized string similar to Concatenate 'vbNewLine' on Ctrl+Enter. /// - public static string AutoCompleteSubBlockDescription { + public static string ConcatVbNewLine { get { - return ResourceManager.GetString("AutoCompleteSubBlockDescription", resourceCulture); + return ResourceManager.GetString("ConcatVbNewLine", resourceCulture); } } /// - /// Looks up a localized string similar to Close 'Type' blocks. + /// Looks up a localized string similar to Enable autocompletion features. /// - public static string AutoCompleteTypeBlockDescription { + public static string EnableAutocompleteLabel { get { - return ResourceManager.GetString("AutoCompleteTypeBlockDescription", resourceCulture); + return ResourceManager.GetString("EnableAutocompleteLabel", resourceCulture); } } /// - /// Looks up a localized string similar to Close 'While...Wend' loop blocks. + /// Looks up a localized string similar to Enable block completion. /// - public static string AutoCompleteWhileBlockDescription { + public static string EnableBlockCompletion { get { - return ResourceManager.GetString("AutoCompleteWhileBlockDescription", resourceCulture); + return ResourceManager.GetString("EnableBlockCompletion", resourceCulture); } } /// - /// Looks up a localized string similar to Close 'With' blocks. + /// Looks up a localized string similar to Enable self-closing pairs. /// - public static string AutoCompleteWithBlockDescription { + public static string EnableSelfClosingPairs { get { - return ResourceManager.GetString("AutoCompleteWithBlockDescription", resourceCulture); + return ResourceManager.GetString("EnableSelfClosingPairs", resourceCulture); } } /// - /// Looks up a localized string similar to Enable smart concatenation. + /// Looks up a localized string similar to Enable smart-concatenation. /// public static string EnableSmartConcat { get { @@ -223,38 +133,38 @@ public static string EnableSmartConcat { } /// - /// Looks up a localized string similar to Autocomplete blocks on ENTER. + /// Looks up a localized string similar to Autocompletion Settings. /// - public static string HandleEnterKey { + public static string PageHeader { get { - return ResourceManager.GetString("HandleEnterKey", resourceCulture); + return ResourceManager.GetString("PageHeader", resourceCulture); } } /// - /// Looks up a localized string similar to Autocomplete blocks on TAB. + /// Looks up a localized string similar to Configure which Rubberduck autocompletions are enabled.. /// - public static string HandleTabKey { + public static string PageInstructions { get { - return ResourceManager.GetString("HandleTabKey", resourceCulture); + return ResourceManager.GetString("PageInstructions", resourceCulture); } } /// - /// Looks up a localized string similar to Autocompletion Settings. + /// Looks up a localized string similar to Self-Closing Pairs. /// - public static string PageHeader { + public static string SelfClosingPairs { get { - return ResourceManager.GetString("PageHeader", resourceCulture); + return ResourceManager.GetString("SelfClosingPairs", resourceCulture); } } /// - /// Looks up a localized string similar to Configure which Rubberduck autocompletions are enabled.. + /// Looks up a localized string similar to Smart-Concatenation. /// - public static string PageInstructions { + public static string SmartConcat { get { - return ResourceManager.GetString("PageInstructions", resourceCulture); + return ResourceManager.GetString("SmartConcat", resourceCulture); } } } diff --git a/Rubberduck.Resources/Settings/SettingsUI.Designer.cs b/Rubberduck.Resources/Settings/SettingsUI.Designer.cs index e37a412e19..cb5cd64526 100644 --- a/Rubberduck.Resources/Settings/SettingsUI.Designer.cs +++ b/Rubberduck.Resources/Settings/SettingsUI.Designer.cs @@ -69,15 +69,6 @@ public static string ConfirmResetSettings { } } - /// - /// Looks up a localized string similar to Enable autocompletion. Feature isn't fully completed and may behave in unintended ways.. - /// - public static string EnableAutocompleteLabel { - get { - return ResourceManager.GetString("EnableAutocompleteLabel", resourceCulture); - } - } - /// /// Looks up a localized string similar to Export. /// From 8094b70355dedcbcefae905323a87a2df33d4094 Mon Sep 17 00:00:00 2001 From: comintern Date: Thu, 1 Nov 2018 22:58:29 -0500 Subject: [PATCH 038/107] Update inspection result test now that the resource file is fixed. --- .../ExcelMemberMayReturnNothingInspection.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs b/Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs index 965d30837c..7d422f5abc 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Concrete/MemberAccessMayReturnNothingInspection/ExcelMemberMayReturnNothingInspection.cs @@ -25,6 +25,6 @@ public ExcelMemberMayReturnNothingInspection(RubberduckParserState state) : base .Where(decl => decl.ProjectName.Equals("Excel") && ExcelMembers.Any(member => decl.QualifiedName.ToString().EndsWith(member))) .ToList(); - public override string ResultTemplate => Description; //InspectionResults.ExcelMemberMayReturnNothingInspection; + public override string ResultTemplate => InspectionResults.ExcelMemberMayReturnNothingInspection; } } From e28d67c0510ba5f4d1ac0e14e6b7c2f2aeeac0de Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Fri, 2 Nov 2018 12:12:48 +0100 Subject: [PATCH 039/107] Rewire and streamline the ModuleRewriter tests With the new rewriting setup the source of IModuleRewriters changed. --- .../PostProcessing/ModuleRewriterTests.cs | 519 +++--------------- 1 file changed, 76 insertions(+), 443 deletions(-) diff --git a/RubberduckTests/PostProcessing/ModuleRewriterTests.cs b/RubberduckTests/PostProcessing/ModuleRewriterTests.cs index 3c43934c79..f5bfb3b672 100644 --- a/RubberduckTests/PostProcessing/ModuleRewriterTests.cs +++ b/RubberduckTests/PostProcessing/ModuleRewriterTests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using Antlr4.Runtime; using NUnit.Framework; using Moq; @@ -68,18 +67,18 @@ public void RewriteDoesNotRewriteIfNotDirty() public void RewriterInsertsRewriterOutputAtLine1() { const string content = @"Option Explicit"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out component).Object; - - using (var state = MockParser.CreateAndParse(vbe)) + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out var component).Object; + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe); + using (state) { if (state.Status != ParserState.Ready) { Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); } - var rewriter = state.GetRewriter(component); - rewriter.Rewrite(); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); + var rewriter = rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName); + rewriteSession.Rewrite(); Assert.AreEqual(content, rewriter.GetText()); } @@ -94,26 +93,9 @@ public void RemovesModuleVariableDeclarationStatement() const string content = @" Private foo As String "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("No variable was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -125,26 +107,9 @@ public void RemovesModuleConstantDeclarationStatement() const string content = @" Private Const foo As String = ""Something"" "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("No constant was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -160,26 +125,9 @@ Sub DoSomething() Dim foo As String End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("No variable was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -195,27 +143,9 @@ Sub DoSomething() Const foo As String = ""Something"" End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("No constant was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - var rewrittenCode = rewriter.GetText(); - Assert.AreEqual(expected, rewrittenCode); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -230,26 +160,9 @@ End Sub Sub DoSomething(ByVal foo As Long) End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Parameter); - if (target == null) - { - Assert.Inconclusive("No parameter was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Parameter, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -262,26 +175,9 @@ Public Event SomeEvent() const string content = @" Public Event SomeEvent(ByVal foo As Long) "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Parameter); - if (target == null) - { - Assert.Inconclusive("No parameter was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Parameter, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -294,26 +190,9 @@ public void RemovesDeclareFunctionParameterDeclaration() const string content = @" Declare PtrSafe Function Foo Lib ""Z"" Alias ""Y"" (ByVal bar As Long) As Long "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Parameter); - if (target == null) - { - Assert.Inconclusive("No parameter was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Parameter, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -330,26 +209,9 @@ Sub DoSomething() Dim foo As String, bar As Integer End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "foo" && d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("No 'foo' variable was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => target.IdentifierName == "foo"); + Assert.AreEqual(expected, actual); } [Test] @@ -366,26 +228,9 @@ Sub DoSomething() Const foo As String = ""Something"", bar As Integer = 42 End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "foo" && d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("No 'foo' constant was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => target.IdentifierName == "foo"); + Assert.AreEqual(expected, actual); } [Test] @@ -400,26 +245,9 @@ End Sub Sub DoSomething(ByVal foo As Long, ByVal bar As Long) End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "foo" && d.DeclarationType == DeclarationType.Parameter); - if (target == null) - { - Assert.Inconclusive("No 'foo' parameter was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Parameter, target => target.IdentifierName == "foo"); + Assert.AreEqual(expected, actual); } [Test] @@ -436,26 +264,9 @@ Sub DoSomething() Dim foo As String, bar As Integer End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("No variable was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -470,26 +281,9 @@ End Sub Sub DoSomething(ByVal foo As Long, ByVal bar As Long) End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Parameter); - if (target == null) - { - Assert.Inconclusive("No parameter was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Parameter, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -506,26 +300,9 @@ Sub DoSomething() Const foo As String = ""Something"", bar As Integer = 42 End Sub "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("No 'bar' constant was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -539,26 +316,9 @@ Private foo _ As _ String "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("No variable was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -572,26 +332,9 @@ Private Const foo _ As String = _ ""Something"" "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("No constant was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => true); + Assert.AreEqual(expected, actual); } [Test] @@ -604,26 +347,9 @@ public void RemovesFirstVariableInDeclarationList() const string expected = @" Private bar As Long "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "foo" && d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("Target variable was not found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => target.IdentifierName == "foo"); + Assert.AreEqual(expected, actual); } [Test] @@ -636,26 +362,9 @@ public void RemovesFirstConstantInDeclarationList() const string expected = @" Private Const bar As Long = 42 "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "foo" && d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("Target constant was not found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => target.IdentifierName == "foo"); + Assert.AreEqual(expected, actual); } [Test] @@ -668,26 +377,9 @@ public void RemovesLastVariableInDeclarationList() const string expected = @" Private foo As String "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("Target variable was not found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -700,26 +392,9 @@ public void RemovesLastConstantInDeclarationList() const string expected = @" Private Const foo As String = ""Something"" "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("Target constant was not found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -732,26 +407,9 @@ public void RemovesMiddleVariableInDeclarationList() const string expected = @" Private foo As String, buzz As Integer "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("Target variable was not found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -764,26 +422,9 @@ public void RemovesMiddleConstantInDeclarationList() const string expected = @" Private Const foo As String = ""Something"", buzz As Integer = 12 "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Constant); - if (target == null) - { - Assert.Inconclusive("Target constant was not found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -799,26 +440,9 @@ buzz As Integer Private foo As String, _ buzz As Integer "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) - { - if (state.Status != ParserState.Ready) - { - Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); - } - - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Variable); - if (target == null) - { - Assert.Inconclusive("Target variable was found in test code."); - } - - var rewriter = state.GetRewriter(target); - rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); - } + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Variable, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); } [Test] @@ -837,36 +461,45 @@ Private Const foo _ As String = ""Something"", _ buzz As Integer = 12 "; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(content, out _).Object; - using (var state = MockParser.CreateAndParse(vbe)) + + var actual = RewrittenForTargetRemovalCode(content, DeclarationType.Constant, target => target.IdentifierName == "bar"); + Assert.AreEqual(expected, actual); + } + + private static IProjectsProvider TestProvider(QualifiedModuleName module, ICodeModule testModule) + { + var component = new Mock(); + component.Setup(c => c.CodeModule).Returns(testModule); + var provider = new Mock(); + provider.Setup(p => p.Component(It.IsAny())) + .Returns(qmn => qmn.Equals(module) ? component.Object : null); + return provider.Object; + } + + private string RewrittenForTargetRemovalCode(string inputCode, DeclarationType targetType, Func targetCondition) + { + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out _).Object; + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe); + using (state) { if (state.Status != ParserState.Ready) { Assert.Inconclusive("Parser isn't ready. Test cannot proceed."); } - var declarations = state.AllUserDeclarations; - var target = declarations.SingleOrDefault(d => d.IdentifierName == "bar" && d.DeclarationType == DeclarationType.Constant); + var target = state.DeclarationFinder.UserDeclarations(targetType).SingleOrDefault(targetCondition); if (target == null) { - Assert.Inconclusive("Target constant was found in test code."); + Assert.Inconclusive("No target was found in test code."); } - var rewriter = state.GetRewriter(target); + var rewriteSession = rewritingManager.CheckOutCodePaneSession(); + var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName); + rewriter.Remove(target); - Assert.AreEqual(expected, rewriter.GetText()); + return rewriter.GetText(); } } - - private IProjectsProvider TestProvider(QualifiedModuleName module, ICodeModule testModule) - { - var component = new Mock(); - component.Setup(c => c.CodeModule).Returns(testModule); - var provider = new Mock(); - provider.Setup(p => p.Component(It.IsAny())) - .Returns(qmn => qmn.Equals(module) ? component.Object : null); - return provider.Object; - } } } From a297eabfa64f2e6468e20238440b97f32eec407b Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Fri, 2 Nov 2018 12:26:00 +0100 Subject: [PATCH 040/107] Remove _projectsProvider from ReorderParameter refactoring It was only ever needed because of a superfluous part of the execution. --- .../RefactorReorderParametersCommand.cs | 2 +- .../ReorderParametersRefactoring.cs | 19 ++--- .../Refactoring/ReorderParametersTests.cs | 69 +++++++++---------- 3 files changed, 41 insertions(+), 49 deletions(-) diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs index 7d2c39cd63..0cec0484e8 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs @@ -75,7 +75,7 @@ protected override void OnExecute(object parameter) using (var view = new ReorderParametersDialog(new ReorderParametersViewModel(_state))) { var factory = new ReorderParametersPresenterFactory(Vbe, view, _state, _msgbox); - var refactoring = new ReorderParametersRefactoring(Vbe, factory, _msgbox, _state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(Vbe, factory, _msgbox); refactoring.Refactor(selection.Value); } } diff --git a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs index 54cfd1b896..a0ed7f03f7 100644 --- a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs +++ b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs @@ -3,10 +3,9 @@ using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Symbols; - using Rubberduck.Resources; +using Rubberduck.Resources; using Rubberduck.VBEditor; using Rubberduck.Parsing.Rewriter; -using Rubberduck.VBEditor.ComManagement; using Rubberduck.VBEditor.SafeComWrappers.Abstract; using System; using System.Collections.Generic; @@ -21,14 +20,13 @@ public class ReorderParametersRefactoring : IRefactoring private ReorderParametersModel _model; private readonly IMessageBox _messageBox; private readonly HashSet _rewriters = new HashSet(); - private readonly IProjectsProvider _projectsProvider; - public ReorderParametersRefactoring(IVBE vbe, IRefactoringPresenterFactory factory, IMessageBox messageBox, IProjectsProvider projectsProvider) + public ReorderParametersRefactoring(IVBE vbe, IRefactoringPresenterFactory factory, + IMessageBox messageBox) { _vbe = vbe; _factory = factory; _messageBox = messageBox; - _projectsProvider = projectsProvider; } public void Refactor() @@ -153,17 +151,14 @@ private void AdjustReferences(IEnumerable references) continue; } - var component = _projectsProvider.Component(reference.QualifiedModuleName); - using (var module = component.CodeModule) - { - RewriteCall(argumentList, module); - } + var module = reference.QualifiedModuleName; + RewriteCall(argumentList, module); } } - private void RewriteCall(VBAParser.ArgumentListContext argList, ICodeModule module) + private void RewriteCall(VBAParser.ArgumentListContext argList, QualifiedModuleName module) { - var rewriter = _model.State.GetRewriter(module.Parent); + var rewriter = _model.State.GetRewriter(module); var args = argList.argument().Select((s, i) => new { Index = i, Text = s.GetText() }).ToList(); for (var i = 0; i < _model.Parameters.Count; i++) diff --git a/RubberduckTests/Refactoring/ReorderParametersTests.cs b/RubberduckTests/Refactoring/ReorderParametersTests.cs index 9ccf0b4939..0d0014a79d 100644 --- a/RubberduckTests/Refactoring/ReorderParametersTests.cs +++ b/RubberduckTests/Refactoring/ReorderParametersTests.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Windows.Forms; using NUnit.Framework; using Moq; using Rubberduck.Refactorings; using Rubberduck.Refactorings.ReorderParameters; -using Rubberduck.UI; using Rubberduck.VBEditor; using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.VBEditor.SafeComWrappers.Abstract; @@ -35,8 +33,7 @@ public void ReorderParams_SwapPositions() @"Private Sub Foo(ByVal arg2 As String, ByVal arg1 As Integer) End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); using (var state = MockParser.CreateAndParse(vbe.Object)) { @@ -48,7 +45,7 @@ public void ReorderParams_SwapPositions() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -84,7 +81,7 @@ public void ReorderParams_SwapPositions_SignatureContainsParamName() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -128,7 +125,7 @@ Sub Goo() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -164,7 +161,7 @@ public void ReorderParams_RefactorDeclaration() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(model.TargetDeclaration); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -195,7 +192,7 @@ public void ReorderParams_RefactorDeclaration_FailsInvalidTarget() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); try { @@ -249,7 +246,7 @@ public void ReorderParams_WithOptionalParam() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -295,7 +292,7 @@ End Sub var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -349,7 +346,7 @@ Private Function foo(ByVal b As Integer, ByRef a As Integer) As Integer var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -403,7 +400,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -442,7 +439,7 @@ public void ReorderParametersRefactoring_ReorderNamedParams_Function() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -496,7 +493,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -540,7 +537,7 @@ public void ReorderParametersRefactoring_ReorderGetter() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -577,7 +574,7 @@ public void ReorderParametersRefactoring_ReorderLetter() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -614,7 +611,7 @@ public void ReorderParametersRefactoring_ReorderSetter() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -703,7 +700,7 @@ public void ReorderParametersRefactoring_SignatureOnMultipleLines() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -758,7 +755,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -803,7 +800,7 @@ End Sub var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -873,7 +870,7 @@ End Sub var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -957,7 +954,7 @@ End Sub var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -997,7 +994,7 @@ public void ReorderParams_MoveOptionalParamBeforeNonOptionalParamFails() var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -1050,7 +1047,7 @@ End Sub var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -1093,7 +1090,7 @@ Private Property Set Foo(ByVal arg2 As String, ByVal arg1 As Integer, ByVal arg3 //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -1136,7 +1133,7 @@ Private Property Let Foo(ByVal arg2 As String, ByVal arg1 As Integer, ByVal arg3 //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -1160,7 +1157,7 @@ public void ReorderParams_PresenterIsNull() var factory = new ReorderParametersPresenterFactory(vbe.Object, null, state, null); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory, null); refactoring.Refactor(); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -1215,7 +1212,7 @@ Private Sub IClass1_DoSomething(ByVal b As String, ByVal a As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1271,7 +1268,7 @@ Private Sub IClass1_DoSomething(ByVal v2 As String, ByVal v1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1339,7 +1336,7 @@ Private Sub IClass1_DoSomething(ByVal s As String, ByVal i As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1400,7 +1397,7 @@ Private Sub IClass1_DoSomething(ByVal b As String, ByVal a As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1494,7 +1491,7 @@ Private Sub abc_Foo(ByVal arg2 As String, ByVal arg1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1550,7 +1547,7 @@ Private Sub abc_Foo(ByVal arg2 As String, ByVal arg1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1606,7 +1603,7 @@ Private Sub abc_Foo(ByVal s As String, ByVal i As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1675,7 +1672,7 @@ Private Sub abc_Foo(ByVal v2 As String, ByVal v1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, state.ProjectsProvider); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); From fa74ea361ebc4ffd32181f555d4d819b29ef4ade Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Fri, 2 Nov 2018 12:47:37 +0100 Subject: [PATCH 041/107] Add some comment to quickfixes not using the IRewriteSession handed to them The quickfixes using a refactoring currently cannot pass on the IRewriteSession to the refactoring, which handles its own rewriting separately. Moreover, the AddIdentifierToWhitelistQuickfix does not need it because it is not changing code. --- .../QuickFixes/AddIdentifierToWhiteListQuickFix.cs | 1 + Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs | 3 ++- .../QuickFixes/MoveFieldCloserToUsageQuickFix.cs | 3 ++- .../QuickFixes/RemoveUnusedParameterQuickFix.cs | 3 ++- .../QuickFixes/RenameDeclarationQuickFix.cs | 3 ++- 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs index a175c4c54d..83ed7f9c43 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/AddIdentifierToWhiteListQuickFix.cs @@ -18,6 +18,7 @@ public AddIdentifierToWhiteListQuickFix(IPersistanceService Date: Fri, 2 Nov 2018 13:40:12 +0100 Subject: [PATCH 042/107] Make the RenameRefactoring use a QualifiedSelection? to store the initial selection Previously, it used a tuple of ICodeModule and Selection, which was leaking SCWs. --- .../Rename/RenameRefactoring.cs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Rubberduck.Refactorings/Rename/RenameRefactoring.cs b/Rubberduck.Refactorings/Rename/RenameRefactoring.cs index a902caa18f..84b07f3dad 100644 --- a/Rubberduck.Refactorings/Rename/RenameRefactoring.cs +++ b/Rubberduck.Refactorings/Rename/RenameRefactoring.cs @@ -26,7 +26,7 @@ public class RenameRefactoring : IRefactoring private readonly IMessageBox _messageBox; private readonly RubberduckParserState _state; private RenameModel _model; - private Tuple _initialSelection; + private QualifiedSelection? _initialSelection; private readonly List _modulesToRewrite; private readonly Dictionary _renameActions; private readonly List _neverRenameIdentifiers; @@ -43,8 +43,10 @@ public RenameRefactoring(IVBE vbe, IRefactoringPresenterFactory(activeCodePane, activeCodePane.IsWrappingNullReference ? Selection.Empty : activeCodePane.Selection); + using (var activeCodePane = _vbe.ActiveCodePane) + { + _initialSelection = activeCodePane.GetQualifiedSelection(); + } _modulesToRewrite = new List(); _renameActions = new Dictionary { @@ -597,7 +599,7 @@ private void CacheInitialSelection(QualifiedSelection qSelection) { if (!codePane.IsWrappingNullReference) { - _initialSelection = new Tuple(codePane, codePane.Selection); + _initialSelection = codePane.GetQualifiedSelection(); } } } @@ -605,9 +607,22 @@ private void CacheInitialSelection(QualifiedSelection qSelection) private void RestoreInitialSelection() { - if (!_initialSelection.Item1.IsWrappingNullReference) + if (!_initialSelection.HasValue) + { + return; + } + + var qualifiedSelection = _initialSelection.Value; + var component = _state.ProjectsProvider.Component(qualifiedSelection.QualifiedName); + using (var codeModule = component.CodeModule) { - _initialSelection.Item1.Selection = _initialSelection.Item2; + using (var codePane = codeModule.CodePane) + { + if (!codePane.IsWrappingNullReference) + { + codePane.Selection = qualifiedSelection.Selection; + } + } } } From fa2dd3b1f882e154cfd76a20636ab18ff0d356a5 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Fri, 2 Nov 2018 14:54:44 +0100 Subject: [PATCH 043/107] Rewire the RenameRefactoring and its tests This includes a bug fix to the RewritingManager. --- .../QuickFixes/RenameDeclarationQuickFix.cs | 6 +- .../UI/CodeExplorer/Commands/RenameCommand.cs | 7 +- .../CodePaneRefactorRenameCommand.cs | 7 +- .../FormDesignerRefactorRenameCommand.cs | 7 +- .../ProjectExplorerRefactorRenameCommand.cs | 7 +- .../Rewriter/RewritingManager.cs | 4 +- .../Rename/RenameRefactoring.cs | 150 ++++++++---------- RubberduckTests/Refactoring/RenameTests.cs | 30 ++-- 8 files changed, 110 insertions(+), 108 deletions(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs index 0028c14c8d..d6a898d95c 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RenameDeclarationQuickFix.cs @@ -16,13 +16,15 @@ public sealed class RenameDeclarationQuickFix : QuickFixBase { private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public RenameDeclarationQuickFix(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public RenameDeclarationQuickFix(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) : base(typeof(HungarianNotationInspection), typeof(UseMeaningfulNameInspection), typeof(DefaultProjectNameInspection)) { _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -32,7 +34,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio using (var view = new RenameDialog(new RenameViewModel(_state))) { var factory = new RenamePresenterFactory(_vbe, view, _state); - var refactoring = new RenameRefactoring(_vbe, factory, _messageBox, _state); + var refactoring = new RenameRefactoring(_vbe, factory, _messageBox, _state, _state.ProjectsProvider, _rewritingManager); refactoring.Refactor(result.Target); } } diff --git a/Rubberduck.Core/UI/CodeExplorer/Commands/RenameCommand.cs b/Rubberduck.Core/UI/CodeExplorer/Commands/RenameCommand.cs index 84c194b603..fdde7a567d 100644 --- a/Rubberduck.Core/UI/CodeExplorer/Commands/RenameCommand.cs +++ b/Rubberduck.Core/UI/CodeExplorer/Commands/RenameCommand.cs @@ -2,6 +2,7 @@ using NLog; using Rubberduck.Interaction; using Rubberduck.Navigation.CodeExplorer; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.Rename; using Rubberduck.UI.Command; @@ -15,13 +16,15 @@ public class RenameCommand : CommandBase, IDisposable { private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IRefactoringDialog _view; private readonly IMessageBox _msgBox; - public RenameCommand(IVBE vbe, IRefactoringDialog view, RubberduckParserState state, IMessageBox msgBox) : base(LogManager.GetCurrentClassLogger()) + public RenameCommand(IVBE vbe, IRefactoringDialog view, RubberduckParserState state, IMessageBox msgBox, IRewritingManager rewritingManager) : base(LogManager.GetCurrentClassLogger()) { _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _view = view; _msgBox = msgBox; } @@ -34,7 +37,7 @@ protected override bool EvaluateCanExecute(object parameter) protected override void OnExecute(object parameter) { var factory = new RenamePresenterFactory(_vbe, _view, _state); - var refactoring = new RenameRefactoring(_vbe, factory, _msgBox, _state); + var refactoring = new RenameRefactoring(_vbe, factory, _msgBox, _state, _state.ProjectsProvider, _rewritingManager); refactoring.Refactor(((ICodeExplorerDeclarationViewModel)parameter).Declaration); } diff --git a/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs index be5492999e..a2ee18bafa 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/CodePaneRefactorRenameCommand.cs @@ -1,5 +1,6 @@ using System.Runtime.InteropServices; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.Rename; @@ -12,12 +13,14 @@ namespace Rubberduck.UI.Command.Refactorings public class CodePaneRefactorRenameCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public CodePaneRefactorRenameCommand(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public CodePaneRefactorRenameCommand(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) : base (vbe) { _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -68,7 +71,7 @@ protected override void OnExecute(object parameter) using (var view = new RenameDialog(new RenameViewModel(_state))) { var factory = new RenamePresenterFactory(Vbe, view, _state); - var refactoring = new RenameRefactoring(Vbe, factory, _messageBox, _state); + var refactoring = new RenameRefactoring(Vbe, factory, _messageBox, _state, _state.ProjectsProvider, _rewritingManager); refactoring.Refactor(target); } diff --git a/Rubberduck.Core/UI/Command/Refactorings/FormDesignerRefactorRenameCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/FormDesignerRefactorRenameCommand.cs index 7c874ec5aa..dc3cb89f52 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/FormDesignerRefactorRenameCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/FormDesignerRefactorRenameCommand.cs @@ -1,6 +1,7 @@ using System.Linq; using System.Runtime.InteropServices; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.Rename; @@ -14,12 +15,14 @@ namespace Rubberduck.UI.Command.Refactorings public class FormDesignerRefactorRenameCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public FormDesignerRefactorRenameCommand(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public FormDesignerRefactorRenameCommand(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) : base (vbe) { _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -34,7 +37,7 @@ protected override void OnExecute(object parameter) using (var view = new RenameDialog(new RenameViewModel(_state))) { var factory = new RenamePresenterFactory(Vbe, view, _state); - var refactoring = new RenameRefactoring(Vbe, factory, _messageBox, _state); + var refactoring = new RenameRefactoring(Vbe, factory, _messageBox, _state, _state.ProjectsProvider, _rewritingManager); var target = GetTarget(); diff --git a/Rubberduck.Core/UI/Command/Refactorings/ProjectExplorerRefactorRenameCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/ProjectExplorerRefactorRenameCommand.cs index a752a38052..a9e183a414 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/ProjectExplorerRefactorRenameCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/ProjectExplorerRefactorRenameCommand.cs @@ -1,6 +1,7 @@ using System.Linq; using System.Runtime.InteropServices; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.Rename; @@ -13,12 +14,14 @@ namespace Rubberduck.UI.Command.Refactorings public class ProjectExplorerRefactorRenameCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _msgBox; - public ProjectExplorerRefactorRenameCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgBox) + public ProjectExplorerRefactorRenameCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgBox, IRewritingManager rewritingManager) : base (vbe) { _state = state; + _rewritingManager = rewritingManager; _msgBox = msgBox; } @@ -32,7 +35,7 @@ protected override void OnExecute(object parameter) using (var view = new RenameDialog(new RenameViewModel(_state))) { var factory = new RenamePresenterFactory(Vbe, view, _state); - var refactoring = new RenameRefactoring(Vbe, factory, _msgBox, _state); + var refactoring = new RenameRefactoring(Vbe, factory, _msgBox, _state, _state.ProjectsProvider, _rewritingManager); var target = GetTarget(); diff --git a/Rubberduck.Parsing/Rewriter/RewritingManager.cs b/Rubberduck.Parsing/Rewriter/RewritingManager.cs index d8c9e155dd..02b9a353e5 100644 --- a/Rubberduck.Parsing/Rewriter/RewritingManager.cs +++ b/Rubberduck.Parsing/Rewriter/RewritingManager.cs @@ -58,10 +58,10 @@ private bool IsCurrentlyActive(IRewriteSession rewriteSession) { switch (rewriteSession) { + case CodePaneRewriteSession codePaneSession: + return _activeCodePaneSessions.Contains(codePaneSession); case AttributesRewriteSession attributeSession: return _activeAttributesSessions.Contains(attributeSession); - case CodePaneRewriteSession codePaneSession: - return _activeAttributesSessions.Contains(codePaneSession); default: throw new NotSupportedException(nameof(rewriteSession)); } diff --git a/Rubberduck.Refactorings/Rename/RenameRefactoring.cs b/Rubberduck.Refactorings/Rename/RenameRefactoring.cs index 84b07f3dad..241d556dd5 100644 --- a/Rubberduck.Refactorings/Rename/RenameRefactoring.cs +++ b/Rubberduck.Refactorings/Rename/RenameRefactoring.cs @@ -12,6 +12,8 @@ using System.Runtime.InteropServices; using System.Collections.Generic; using Rubberduck.Parsing.Grammar; +using Rubberduck.Parsing.Rewriter; +using Rubberduck.VBEditor.ComManagement; using Rubberduck.VBEditor.SafeComWrappers; namespace Rubberduck.Refactorings.Rename @@ -24,31 +26,32 @@ public class RenameRefactoring : IRefactoring private readonly IVBE _vbe; private readonly IRefactoringPresenterFactory _factory; private readonly IMessageBox _messageBox; - private readonly RubberduckParserState _state; + private readonly IDeclarationFinderProvider _declarationFinderProvider; + private readonly IProjectsProvider _projectsProvider; + private readonly IRewritingManager _rewritingManager; private RenameModel _model; private QualifiedSelection? _initialSelection; - private readonly List _modulesToRewrite; - private readonly Dictionary _renameActions; + private readonly IDictionary> _renameActions; private readonly List _neverRenameIdentifiers; private bool IsInterfaceMemberRename { set; get; } private bool IsControlEventHandlerRename { set; get; } private bool IsUserEventHandlerRename { set; get; } - private bool RequestParseAfterRename { set; get; } - public RenameRefactoring(IVBE vbe, IRefactoringPresenterFactory factory, IMessageBox messageBox, RubberduckParserState state) + public RenameRefactoring(IVBE vbe, IRefactoringPresenterFactory factory, IMessageBox messageBox, IDeclarationFinderProvider declarationFinderProvider, IProjectsProvider projectsProvider, IRewritingManager rewritingManager) { _vbe = vbe; _factory = factory; _messageBox = messageBox; - _state = state; + _declarationFinderProvider = declarationFinderProvider; + _projectsProvider = projectsProvider; + _rewritingManager = rewritingManager; _model = null; using (var activeCodePane = _vbe.ActiveCodePane) { _initialSelection = activeCodePane.GetQualifiedSelection(); } - _modulesToRewrite = new List(); - _renameActions = new Dictionary + _renameActions = new Dictionary> { {DeclarationType.Member, RenameMember}, {DeclarationType.Parameter, RenameParameter}, @@ -58,7 +61,6 @@ public RenameRefactoring(IVBE vbe, IRefactoringPresenterFactory item.Name == target.IdentifierName)) @@ -229,7 +231,7 @@ private bool IsValidTarget(Declaration target) } else if (target.DeclarationType.HasFlag(DeclarationType.Module)) { - var component = _state.ProjectsProvider.Component(target.QualifiedName.QualifiedModuleName); + var component = _projectsProvider.Component(target.QualifiedName.QualifiedModuleName); using (var module = component.CodeModule) { if (module.IsWrappingNullReference) @@ -247,7 +249,7 @@ private bool TrySetNewName(IRenamePresenter presenter) var result = presenter.Show(_model.Target); if (result == null) { return false; } - var conflicts = _state.DeclarationFinder.FindNewDeclarationNameConflicts(_model.NewName, _model.Target); + var conflicts = _declarationFinderProvider.DeclarationFinder.FindNewDeclarationNameConflicts(_model.NewName, _model.Target); if (conflicts.Any()) { @@ -261,7 +263,7 @@ private bool TrySetNewName(IRenamePresenter presenter) private Declaration ResolveEventHandlerToControl(Declaration userTarget) { - var control = _state.DeclarationFinder.UserDeclarations(DeclarationType.Control) + var control = _declarationFinderProvider.DeclarationFinder.UserDeclarations(DeclarationType.Control) .FirstOrDefault(ctrl => userTarget.Scope.StartsWith($"{ctrl.ParentScope}.{ctrl.IdentifierName}_")); IsControlEventHandlerRename = control != null; @@ -271,7 +273,7 @@ private Declaration ResolveEventHandlerToControl(Declaration userTarget) private Declaration ResolveEventHandlerToUserEvent(Declaration userTarget) { - var withEventsDeclarations = _state.DeclarationFinder.UserDeclarations(DeclarationType.Variable) + var withEventsDeclarations = _declarationFinderProvider.DeclarationFinder.UserDeclarations(DeclarationType.Variable) .Where(varDec => varDec.IsWithEvents).ToList(); if (!withEventsDeclarations.Any()) { return null; } @@ -280,11 +282,11 @@ private Declaration ResolveEventHandlerToUserEvent(Declaration userTarget) { if (userTarget.IdentifierName.StartsWith($"{withEvent.IdentifierName}_")) { - if (_state.DeclarationFinder.FindHandlersForWithEventsField(withEvent).Contains(userTarget)) + if (_declarationFinderProvider.DeclarationFinder.FindHandlersForWithEventsField(withEvent).Contains(userTarget)) { var eventName = userTarget.IdentifierName.Remove(0, $"{withEvent.IdentifierName}_".Length); - var eventDeclaration = _state.DeclarationFinder.UserDeclarations(DeclarationType.Event).FirstOrDefault(ev => ev.IdentifierName.Equals(eventName) + var eventDeclaration = _declarationFinderProvider.DeclarationFinder.UserDeclarations(DeclarationType.Event).FirstOrDefault(ev => ev.IdentifierName.Equals(eventName) && withEvent.AsTypeName.Equals(ev.ParentDeclaration.IdentifierName)); IsUserEventHandlerRename = eventDeclaration != null; @@ -306,7 +308,7 @@ private Declaration ResolveRenameTargetIfInterfaceImplementationSelected(Declara return interfaceMember; } - private void Rename() + private void Rename(IRewriteSession rewriteSession) { Debug.Assert(!_model.NewName.Equals(_model.Target.IdentifierName, StringComparison.InvariantCultureIgnoreCase), $"input validation fail: New Name equals Original Name ({_model.Target.IdentifierName})"); @@ -315,31 +317,31 @@ private void Rename() if (actionKeys.Any()) { Debug.Assert(actionKeys.Count == 1, $"{actionKeys.Count} Rename Actions have flag '{_model.Target.DeclarationType.ToString()}'"); - _renameActions[actionKeys.FirstOrDefault()](); + _renameActions[actionKeys.FirstOrDefault()](rewriteSession); } else { - RenameStandardElements(_model.Target, _model.NewName); + RenameStandardElements(_model.Target, _model.NewName, rewriteSession); } } - private void RenameMember() + private void RenameMember(IRewriteSession rewriteSession) { if (_model.Target.DeclarationType.HasFlag(DeclarationType.Property)) { - var members = _state.DeclarationFinder.MatchName(_model.Target.IdentifierName) + var members = _declarationFinderProvider.DeclarationFinder.MatchName(_model.Target.IdentifierName) .Where(item => item.ProjectId == _model.Target.ProjectId && item.ComponentName == _model.Target.ComponentName && item.DeclarationType.HasFlag(DeclarationType.Property)); foreach (var member in members) { - RenameStandardElements(member, _model.NewName); + RenameStandardElements(member, _model.NewName, rewriteSession); } } else { - RenameStandardElements(_model.Target, _model.NewName); + RenameStandardElements(_model.Target, _model.NewName, rewriteSession); } if (!IsInterfaceMemberRename) @@ -347,18 +349,18 @@ private void RenameMember() return; } - var implementations = _state.DeclarationFinder.FindAllInterfaceImplementingMembers() + var implementations = _declarationFinderProvider.DeclarationFinder.FindAllInterfaceImplementingMembers() .Where(impl => ReferenceEquals(_model.Target.ParentDeclaration, impl.InterfaceImplemented) && impl.InterfaceMemberImplemented.IdentifierName.Equals(_model.Target.IdentifierName)); - RenameDefinedFormatMembers(implementations.ToList(), PrependUnderscoreFormat); + RenameDefinedFormatMembers(implementations.ToList(), PrependUnderscoreFormat, rewriteSession); } - private void RenameParameter() + private void RenameParameter(IRewriteSession rewriteSession) { if (_model.Target.ParentDeclaration.DeclarationType.HasFlag(DeclarationType.Property)) { - var parameters = _state.DeclarationFinder.MatchName(_model.Target.IdentifierName).Where(param => + var parameters = _declarationFinderProvider.DeclarationFinder.MatchName(_model.Target.IdentifierName).Where(param => param.ParentDeclaration.DeclarationType.HasFlag(DeclarationType.Property) && param.DeclarationType == DeclarationType.Parameter && param.ParentDeclaration.IdentifierName.Equals(_model.Target.ParentDeclaration.IdentifierName) @@ -366,38 +368,38 @@ private void RenameParameter() foreach (var param in parameters) { - RenameStandardElements(param, _model.NewName); + RenameStandardElements(param, _model.NewName, rewriteSession); } } else { - RenameStandardElements(_model.Target, _model.NewName); + RenameStandardElements(_model.Target, _model.NewName, rewriteSession); } } - private void RenameEvent() + private void RenameEvent(IRewriteSession rewriteSession) { - RenameStandardElements(_model.Target, _model.NewName); + RenameStandardElements(_model.Target, _model.NewName, rewriteSession); - var withEventsDeclarations = _state.DeclarationFinder.UserDeclarations(DeclarationType.Variable) + var withEventsDeclarations = _declarationFinderProvider.DeclarationFinder.UserDeclarations(DeclarationType.Variable) .Where(varDec => varDec.IsWithEvents && varDec.AsTypeName.Equals(_model.Target.ParentDeclaration.IdentifierName)); - var eventHandlers = withEventsDeclarations.SelectMany(we => _state.DeclarationFinder.FindHandlersForWithEventsField(we)); - RenameDefinedFormatMembers(eventHandlers.ToList(), PrependUnderscoreFormat); + var eventHandlers = withEventsDeclarations.SelectMany(we => _declarationFinderProvider.DeclarationFinder.FindHandlersForWithEventsField(we)); + RenameDefinedFormatMembers(eventHandlers.ToList(), PrependUnderscoreFormat, rewriteSession); } - private void RenameVariable() + private void RenameVariable(IRewriteSession rewriteSession) { if ((_model.Target.Accessibility == Accessibility.Public || _model.Target.Accessibility == Accessibility.Implicit) && _model.Target.ParentDeclaration is ClassModuleDeclaration classDeclaration && classDeclaration.Subtypes.Any()) { - RenameMember(); + RenameMember(rewriteSession); } else if (_model.Target.DeclarationType.HasFlag(DeclarationType.Control)) { - var component = _state.ProjectsProvider.Component(_model.Target.QualifiedName.QualifiedModuleName); + var component = _projectsProvider.Component(_model.Target.QualifiedName.QualifiedModuleName); using (var controls = component.Controls) { using (var control = controls.SingleOrDefault(item => item.Name == _model.Target.IdentifierName)) @@ -408,26 +410,24 @@ private void RenameVariable() control.Name = _model.NewName; } } - RenameReferences(_model.Target, _model.NewName); + RenameReferences(_model.Target, _model.NewName, rewriteSession); var controlEventHandlers = FindEventHandlersForControl(_model.Target); - RenameDefinedFormatMembers(controlEventHandlers.ToList(), AppendUnderscoreFormat); + RenameDefinedFormatMembers(controlEventHandlers.ToList(), AppendUnderscoreFormat, rewriteSession); } else { - RenameStandardElements(_model.Target, _model.NewName); + RenameStandardElements(_model.Target, _model.NewName, rewriteSession); if (_model.Target.IsWithEvents) { - var eventHandlers = _state.DeclarationFinder.FindHandlersForWithEventsField(_model.Target); - RenameDefinedFormatMembers(eventHandlers.ToList(), AppendUnderscoreFormat); + var eventHandlers = _declarationFinderProvider.DeclarationFinder.FindHandlersForWithEventsField(_model.Target); + RenameDefinedFormatMembers(eventHandlers.ToList(), AppendUnderscoreFormat, rewriteSession); } } } - private void RenameModule() + private void RenameModule(IRewriteSession rewriteSession) { - RequestParseAfterRename = false; - - RenameReferences(_model.Target, _model.NewName); + RenameReferences(_model.Target, _model.NewName, rewriteSession); if (_model.Target.DeclarationType.HasFlag(DeclarationType.ClassModule)) { @@ -436,12 +436,12 @@ private void RenameModule() var ctxt = reference.Context.GetAncestor(); if (ctxt != null) { - RenameDefinedFormatMembers(_state.DeclarationFinder.FindInterfaceMembersForImplementsContext(ctxt).ToList(), AppendUnderscoreFormat); + RenameDefinedFormatMembers(_declarationFinderProvider.DeclarationFinder.FindInterfaceMembersForImplementsContext(ctxt).ToList(), AppendUnderscoreFormat, rewriteSession); } } } - var component = _state.ProjectsProvider.Component(_model.Target.QualifiedName.QualifiedModuleName); + var component = _projectsProvider.Component(_model.Target.QualifiedName.QualifiedModuleName); switch (component.Type) { case ComponentType.Document: @@ -489,9 +489,9 @@ private void RenameModule() } } - private void RenameProject() + //The parameter is not used, but it is required for the _renameActions dictionary. + private void RenameProject(IRewriteSession rewriteSession) { - RequestParseAfterRename = false; var project = ProjectById(_vbe, _model.Target.ProjectId); if (project != null) @@ -517,7 +517,7 @@ private IVBProject ProjectById(IVBE vbe, string projectId) return null; } - private void RenameDefinedFormatMembers(IReadOnlyCollection members, string underscoreFormat) + private void RenameDefinedFormatMembers(IReadOnlyCollection members, string underscoreFormat, IRewriteSession rewriteSession) { if (!members.Any()) { return; } @@ -526,17 +526,17 @@ private void RenameDefinedFormatMembers(IReadOnlyCollection members foreach (var member in members) { var newMemberName = member.IdentifierName.Replace(targetFragment, replacementFragment); - RenameStandardElements(member, newMemberName); + RenameStandardElements(member, newMemberName, rewriteSession); } } - private void RenameStandardElements(Declaration target, string newName) + private void RenameStandardElements(Declaration target, string newName, IRewriteSession rewriteSession) { - RenameReferences(target, newName); - RenameDeclaration(target, newName); + RenameReferences(target, newName, rewriteSession); + RenameDeclaration(target, newName, rewriteSession); } - private void RenameReferences(Declaration target, string newName) + private void RenameReferences(Declaration target, string newName, IRewriteSession rewriteSession) { var modules = target.References .Where(reference => @@ -544,8 +544,7 @@ private void RenameReferences(Declaration target, string newName) foreach (var grouping in modules) { - _modulesToRewrite.Add(grouping.Key); - var rewriter = _state.GetRewriter(grouping.Key); + var rewriter = rewriteSession.CheckOutModuleRewriter(grouping.Key); foreach (var reference in grouping) { rewriter.Replace(reference.Context, newName); @@ -553,10 +552,9 @@ private void RenameReferences(Declaration target, string newName) } } - private void RenameDeclaration(Declaration target, string newName) + private void RenameDeclaration(Declaration target, string newName, IRewriteSession rewriteSession) { - _modulesToRewrite.Add(target.QualifiedName.QualifiedModuleName); - var rewriter = _state.GetRewriter(target.QualifiedName.QualifiedModuleName); + var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedName.QualifiedModuleName); if (target.Context is IIdentifierContext context) { @@ -564,27 +562,11 @@ private void RenameDeclaration(Declaration target, string newName) } } - private void Rewrite() - { - foreach (var module in _modulesToRewrite.Distinct()) - { - _state.GetRewriter(module).Rewrite(); - } - } - - private void Reparse() - { - if (RequestParseAfterRename) - { - _state.OnParseRequested(this); - } - } - private IEnumerable FindEventHandlersForControl(Declaration control) { if (control != null && control.DeclarationType.HasFlag(DeclarationType.Control)) { - return _state.DeclarationFinder.FindEventHandlers() + return _declarationFinderProvider.DeclarationFinder.FindEventHandlers() .Where(ev => ev.Scope.StartsWith($"{control.ParentScope}.{control.IdentifierName}_")); } return Enumerable.Empty(); @@ -592,7 +574,7 @@ private IEnumerable FindEventHandlersForControl(Declaration control private void CacheInitialSelection(QualifiedSelection qSelection) { - var component = _state.ProjectsProvider.Component(qSelection.QualifiedName); + var component = _projectsProvider.Component(qSelection.QualifiedName); using (var codeModule = component.CodeModule) { using (var codePane = codeModule.CodePane) @@ -613,7 +595,7 @@ private void RestoreInitialSelection() } var qualifiedSelection = _initialSelection.Value; - var component = _state.ProjectsProvider.Component(qualifiedSelection.QualifiedName); + var component = _projectsProvider.Component(qualifiedSelection.QualifiedName); using (var codeModule = component.CodeModule) { using (var codePane = codeModule.CodePane) @@ -639,7 +621,7 @@ private string BuildDefaultErrorMessage(Declaration target) private List NeverRenameList() { - return _state.DeclarationFinder.FindEventHandlers() + return _declarationFinderProvider.DeclarationFinder.FindEventHandlers() .Where(ev => ev.IdentifierName.StartsWith("Class_") || ev.IdentifierName.StartsWith("UserForm_") || ev.IdentifierName.StartsWith("auto_")) diff --git a/RubberduckTests/Refactoring/RenameTests.cs b/RubberduckTests/Refactoring/RenameTests.cs index ff2f4d283f..33fcb38858 100644 --- a/RubberduckTests/Refactoring/RenameTests.cs +++ b/RubberduckTests/Refactoring/RenameTests.cs @@ -14,6 +14,7 @@ using Rubberduck.UI.Refactorings.Rename; using Rubberduck.Interaction; using Rubberduck.Common; +using Rubberduck.Parsing.Rewriter; namespace RubberduckTests.Refactoring { @@ -1857,7 +1858,8 @@ public void RenameRefactoring_RenameCodeModule() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, "Class1", ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -1871,7 +1873,7 @@ public void RenameRefactoring_RenameCodeModule() var factory = SetupFactory(model); - var refactoring = new RenameRefactoring(vbeWrapper, factory.Object, msgbox.Object, state); + var refactoring = new RenameRefactoring(vbeWrapper, factory.Object, msgbox.Object, state, state.ProjectsProvider, rewritingManager); refactoring.Refactor(model.Target); Assert.AreSame(newName, component.CodeModule.Name); @@ -1895,7 +1897,8 @@ public void RenameRefactoring_RenameProject() .AddProjectToVbeBuilder() .Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var msgbox = new Mock(); @@ -1907,7 +1910,7 @@ public void RenameRefactoring_RenameProject() var factory = SetupFactory(model); - var refactoring = new RenameRefactoring(vbeWrapper, factory.Object, msgbox.Object, state); + var refactoring = new RenameRefactoring(vbeWrapper, factory.Object, msgbox.Object, state, state.ProjectsProvider, rewritingManager); refactoring.Refactor(model.Target); Assert.AreEqual(newName, vbe.Object.VBProjects[0].Name); @@ -2494,7 +2497,8 @@ public void Rename_PresenterIsNull() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var codePaneMock = new Mock(); @@ -2505,7 +2509,7 @@ public void Rename_PresenterIsNull() var vbeWrapper = vbe.Object; var factory = new RenamePresenterFactory(vbeWrapper, null, state); - var refactoring = new RenameRefactoring(vbeWrapper, factory, null, state); + var refactoring = new RenameRefactoring(vbeWrapper, factory, null, state, state.ProjectsProvider, rewritingManager); refactoring.Refactor(); var rewriter = state.GetRewriter(component); @@ -2641,7 +2645,8 @@ public void RenameRefactoring_RenameClassModule_DoesNotChangeMeReferences() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, "ClassModule1", ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -2655,7 +2660,7 @@ public void RenameRefactoring_RenameClassModule_DoesNotChangeMeReferences() var factory = SetupFactory(model); - var refactoring = new RenameRefactoring(vbeWrapper, factory.Object, msgbox.Object, state); + var refactoring = new RenameRefactoring(vbeWrapper, factory.Object, msgbox.Object, state, state.ProjectsProvider, rewritingManager); refactoring.Refactor(model.Target); Assert.AreSame(newName, component.CodeModule.Name); @@ -2727,7 +2732,7 @@ private static void InitializeTestDataObject(RenameTestsDataObject tdo tdo.MsgBox.Setup(m => m.ConfirmYesNo(It.IsAny(), It.IsAny(), It.IsAny())).Returns(tdo.MsgBoxReturn == ConfirmationOutcome.Yes); tdo.VBE = tdo.VBE ?? BuildProject(tdo.ProjectName, tdo.ModuleTestSetupDefs); - tdo.ParserState = MockParser.CreateAndParse(tdo.VBE); + (tdo.ParserState, tdo.RewritingManager) = MockParser.CreateAndParseWithRewritingManager(tdo.VBE); CreateQualifiedSelectionForTestCase(tdo); tdo.RenameModel = new RenameModel(tdo.VBE, tdo.ParserState, tdo.QualifiedSelection) { NewName = tdo.NewName }; @@ -2736,7 +2741,7 @@ private static void InitializeTestDataObject(RenameTestsDataObject tdo var factory = SetupFactory(tdo.RenameModel); - tdo.RenameRefactoringUnderTest = new RenameRefactoring(tdo.VBE, factory.Object, tdo.MsgBox.Object, tdo.ParserState); + tdo.RenameRefactoringUnderTest = new RenameRefactoring(tdo.VBE, factory.Object, tdo.MsgBox.Object, tdo.ParserState, tdo.ParserState.ProjectsProvider, tdo.RewritingManager); } private static void AddTestModuleDefinition(RenameTestsDataObject tdo, RenameTestModuleDefinition inputOutput) @@ -2783,9 +2788,9 @@ private static void CheckRenameRefactorTestResults(RenameTestsDataObject tdo) { if (inputOutput.CheckExpectedEqualsActual) { - var rewriter = tdo.ParserState.GetRewriter(RetrieveComponent(tdo, inputOutput.ModuleName).CodeModule.Parent); + var codeModule = RetrieveComponent(tdo, inputOutput.ModuleName).CodeModule; var expected = inputOutput.Expected; - var actual = rewriter.GetText(); + var actual = codeModule.Content(); Assert.AreEqual(expected, actual); } } @@ -2925,6 +2930,7 @@ public RenameTestsDataObject(string selection, string newName) public IVBE VBE { get; set; } public RubberduckParserState ParserState { get; set; } + public IRewritingManager RewritingManager { get; set; } public string ProjectName { get; set; } public string NewName { get; set; } public string SelectionModuleName { get; set; } From 3d55d22b6590200ff3e4d8fd38674cb2b7aac77f Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Fri, 2 Nov 2018 22:27:41 +0100 Subject: [PATCH 044/107] Rewire the ReorderParametersRefactoring and its tests The ReorderParametersCommand and its tests had to change, too. --- .../RefactorReorderParametersCommand.cs | 7 +- .../ReorderParametersRefactoring.cs | 58 ++--- .../Commands/RefactorCommandTests.cs | 224 +++++++++++------- .../Refactoring/ReorderParametersTests.cs | 181 ++++++++------ 4 files changed, 284 insertions(+), 186 deletions(-) diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs index 0cec0484e8..d78f996956 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorReorderParametersCommand.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using Rubberduck.Common; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.ReorderParameters; @@ -14,12 +15,14 @@ namespace Rubberduck.UI.Command.Refactorings public class RefactorReorderParametersCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _msgbox; - public RefactorReorderParametersCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgbox) + public RefactorReorderParametersCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgbox, IRewritingManager rewritingManager) : base (vbe) { _state = state; + _rewritingManager = rewritingManager; _msgbox = msgbox; } @@ -75,7 +78,7 @@ protected override void OnExecute(object parameter) using (var view = new ReorderParametersDialog(new ReorderParametersViewModel(_state))) { var factory = new ReorderParametersPresenterFactory(Vbe, view, _state, _msgbox); - var refactoring = new ReorderParametersRefactoring(Vbe, factory, _msgbox); + var refactoring = new ReorderParametersRefactoring(Vbe, factory, _msgbox, _rewritingManager); refactoring.Refactor(selection.Value); } } diff --git a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs index a0ed7f03f7..d97435338d 100644 --- a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs +++ b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs @@ -19,14 +19,15 @@ public class ReorderParametersRefactoring : IRefactoring private readonly IRefactoringPresenterFactory _factory; private ReorderParametersModel _model; private readonly IMessageBox _messageBox; - private readonly HashSet _rewriters = new HashSet(); + private readonly IRewritingManager _rewritingManager; public ReorderParametersRefactoring(IVBE vbe, IRefactoringPresenterFactory factory, - IMessageBox messageBox) + IMessageBox messageBox, IRewritingManager rewritingManager) { _vbe = vbe; _factory = factory; _messageBox = messageBox; + _rewritingManager = rewritingManager; } public void Refactor() @@ -52,21 +53,16 @@ public void Refactor() var oldSelection = pane.GetQualifiedSelection(); - AdjustReferences(_model.TargetDeclaration.References); - AdjustSignatures(); + var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); + AdjustReferences(_model.TargetDeclaration.References, rewriteSession); + AdjustSignatures(rewriteSession); + rewriteSession.Rewrite(); if (oldSelection.HasValue && !pane.IsWrappingNullReference) { pane.Selection = oldSelection.Value.Selection; } } - - foreach (var rewriter in _rewriters) - { - rewriter.Rewrite(); - } - - _model.State.OnParseRequested(this); } public void Refactor(QualifiedSelection target) @@ -126,7 +122,7 @@ private bool IsValidParamOrder() return false; } - private void AdjustReferences(IEnumerable references) + private void AdjustReferences(IEnumerable references, IRewriteSession rewriteSession) { foreach (var reference in references.Where(item => item.Context != _model.TargetDeclaration.Context)) { @@ -152,13 +148,13 @@ private void AdjustReferences(IEnumerable references) } var module = reference.QualifiedModuleName; - RewriteCall(argumentList, module); + RewriteCall(argumentList, module, rewriteSession); } } - private void RewriteCall(VBAParser.ArgumentListContext argList, QualifiedModuleName module) + private void RewriteCall(VBAParser.ArgumentListContext argList, QualifiedModuleName module, IRewriteSession rewriteSession) { - var rewriter = _model.State.GetRewriter(module); + var rewriter = rewriteSession.CheckOutModuleRewriter(module); var args = argList.argument().Select((s, i) => new { Index = i, Text = s.GetText() }).ToList(); for (var i = 0; i < _model.Parameters.Count; i++) @@ -171,11 +167,9 @@ private void RewriteCall(VBAParser.ArgumentListContext argList, QualifiedModuleN var arg = argList.argument()[i]; rewriter.Replace(arg, args.Single(s => s.Index == _model.Parameters[i].Index).Text); } - - _rewriters.Add(rewriter); } - private void AdjustSignatures() + private void AdjustSignatures(IRewriteSession rewriteSession) { var proc = (dynamic)_model.TargetDeclaration.Context; var paramList = (VBAParser.ArgListContext)proc.argList(); @@ -189,8 +183,8 @@ private void AdjustSignatures() if (setter != null) { - AdjustSignatures(setter); - AdjustReferences(setter.References); + AdjustSignatures(setter, rewriteSession); + AdjustReferences(setter.References, rewriteSession); } var letter = _model.Declarations.FirstOrDefault(item => item.ParentScope == _model.TargetDeclaration.ParentScope && @@ -199,19 +193,19 @@ private void AdjustSignatures() if (letter != null) { - AdjustSignatures(letter); - AdjustReferences(letter.References); + AdjustSignatures(letter, rewriteSession); + AdjustReferences(letter.References, rewriteSession); } } - RewriteSignature(_model.TargetDeclaration, paramList); + RewriteSignature(_model.TargetDeclaration, paramList, rewriteSession); foreach (var withEvents in _model.Declarations.Where(item => item.IsWithEvents && item.AsTypeName == _model.TargetDeclaration.ComponentName)) { foreach (var reference in _model.Declarations.FindEventProcedures(withEvents)) { - AdjustReferences(reference.References); - AdjustSignatures(reference); + AdjustReferences(reference.References, rewriteSession); + AdjustSignatures(reference, rewriteSession); } } @@ -228,12 +222,12 @@ private void AdjustSignatures() foreach (var interfaceImplentation in implementations) { - AdjustReferences(interfaceImplentation.References); - AdjustSignatures(interfaceImplentation); + AdjustReferences(interfaceImplentation.References, rewriteSession); + AdjustSignatures(interfaceImplentation, rewriteSession); } } - private void AdjustSignatures(Declaration declaration) + private void AdjustSignatures(Declaration declaration, IRewriteSession rewriteSession) { var proc = (dynamic) declaration.Context.Parent; VBAParser.ArgListContext paramList; @@ -248,12 +242,12 @@ private void AdjustSignatures(Declaration declaration) paramList = (VBAParser.ArgListContext) proc.subStmt().argList(); } - RewriteSignature(declaration, paramList); + RewriteSignature(declaration, paramList, rewriteSession); } - private void RewriteSignature(Declaration target, VBAParser.ArgListContext paramList) + private void RewriteSignature(Declaration target, VBAParser.ArgListContext paramList, IRewriteSession rewriteSession) { - var rewriter = _model.State.GetRewriter(target); + var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName); var parameters = paramList.arg().Select((s, i) => new { Index = i, Text = s.GetText() }).ToList(); for (var i = 0; i < _model.Parameters.Count; i++) @@ -261,8 +255,6 @@ private void RewriteSignature(Declaration target, VBAParser.ArgListContext param var param = paramList.arg()[i]; rewriter.Replace(param, parameters.SingleOrDefault(s => s.Index == _model.Parameters[i].Index)?.Text); } - - _rewriters.Add(rewriter); } } } diff --git a/RubberduckTests/Commands/RefactorCommandTests.cs b/RubberduckTests/Commands/RefactorCommandTests.cs index 81f77f5321..23471bbbe3 100644 --- a/RubberduckTests/Commands/RefactorCommandTests.cs +++ b/RubberduckTests/Commands/RefactorCommandTests.cs @@ -2,7 +2,6 @@ using NUnit.Framework; using Moq; using Rubberduck.Parsing.VBA; -using Rubberduck.UI; using Rubberduck.UI.Command.Refactorings; using Rubberduck.VBEditor; using Rubberduck.VBEditor.SafeComWrappers; @@ -23,7 +22,8 @@ public void EncapsulateField_CanExecute_NullActiveCodePane() var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); @@ -37,7 +37,8 @@ public void EncapsulateField_CanExecute_NonReadyState() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); @@ -57,7 +58,8 @@ Dim d As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 9, 2, 9)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); @@ -76,7 +78,8 @@ Sub Foo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 7, 2, 7)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); @@ -95,7 +98,8 @@ Sub Foo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 5, 1, 5)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); @@ -111,7 +115,8 @@ public void ExtractInterface_CanExecute_NullActiveCodePane() var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -126,7 +131,8 @@ public void ExtractInterface_CanExecute_NonReadyState() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(string.Empty, ComponentType.ClassModule, out component, new Selection()); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); @@ -141,7 +147,8 @@ public void ExtractInterface_CanExecute_NoMembers() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule("Option Explicit", ComponentType.ClassModule, out component, new Selection()); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); Assert.IsFalse(extractInterfaceCommand.CanExecute(null)); @@ -158,7 +165,8 @@ public void ExtractInterface_CanExecute_Proc_StdModule() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -172,7 +180,8 @@ public void ExtractInterface_CanExecute_Field() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule("Dim d As Boolean", ComponentType.ClassModule, out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -207,7 +216,8 @@ End Sub Assert.Inconclusive("The active code pane should be the one with the method stub."); } - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); Assert.IsTrue(extractInterfaceCommand.CanExecute(null)); @@ -233,7 +243,8 @@ public void ExtractInterface_CanExecute_ClassWithMembers_SameNameAsClassWithMemb vbe.Setup(s => s.ActiveCodePane).Returns(proj1.Object.VBComponents[0].CodeModule.CodePane); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -251,7 +262,8 @@ public void ExtractInterface_CanExecute_Proc() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -270,7 +282,8 @@ public void ExtractInterface_CanExecute_Function() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -288,7 +301,8 @@ public void ExtractInterface_CanExecute_PropertyGet() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -306,7 +320,8 @@ public void ExtractInterface_CanExecute_PropertyLet() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -324,7 +339,8 @@ public void ExtractInterface_CanExecute_PropertySet() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); @@ -340,7 +356,8 @@ public void ImplementInterface_CanExecute_NullActiveCodePane() var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null); @@ -355,7 +372,8 @@ public void ImplementInterface_CanExecute_NonReadyState() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); @@ -370,7 +388,8 @@ public void ImplementInterface_CanExecute_ImplementsInterfaceNotSelected() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(string.Empty, ComponentType.ClassModule, out component, new Selection()); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null); @@ -389,7 +408,8 @@ public void ImplementInterface_CanExecute_ImplementsInterfaceSelected() .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null); @@ -404,7 +424,8 @@ public void IntroduceField_CanExecute_NullActiveCodePane() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var msgbox = new Mock(); @@ -420,7 +441,8 @@ public void IntroduceField_CanExecute_NonReadyState() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); @@ -436,7 +458,8 @@ public void IntroduceField_CanExecute_Field() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var msgbox = new Mock(); @@ -456,7 +479,8 @@ Dim d As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var msgbox = new Mock(); @@ -472,7 +496,8 @@ public void IntroduceParameter_CanExecute_NullActiveCodePane() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var msgbox = new Mock(); @@ -488,7 +513,8 @@ public void IntroduceParameter_CanExecute_NonReadyState() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); @@ -504,7 +530,8 @@ public void IntroduceParameter_CanExecute_Field() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var msgbox = new Mock(); @@ -524,7 +551,8 @@ Dim d As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var msgbox = new Mock(); @@ -540,7 +568,8 @@ public void MoveCloserToUsage_CanExecute_NullActiveCodePane() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); @@ -555,7 +584,8 @@ public void MoveCloserToUsage_CanExecute_NonReadyState() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); @@ -570,7 +600,8 @@ public void MoveCloserToUsage_CanExecute_Field_NoReferences() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); @@ -589,7 +620,8 @@ Dim d As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); @@ -603,7 +635,8 @@ public void MoveCloserToUsage_CanExecute_Const_NoReferences() { IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Private Const const_abc = 0", out component, Selection.Home); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); @@ -623,7 +656,8 @@ Sub Foo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 5, 1, 5)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); @@ -643,7 +677,8 @@ Dim d As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); @@ -664,7 +699,8 @@ Dim d As Integer IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 17, 1, 17)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); @@ -679,7 +715,8 @@ public void RemoveParameters_CanExecute_NullActiveCodePane() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -694,7 +731,8 @@ public void RemoveParameters_CanExecute_NonReadyState() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); @@ -712,7 +750,8 @@ public void RemoveParameters_CanExecute_Event_NoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -730,7 +769,8 @@ public void RemoveParameters_CanExecute_Proc_NoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -748,7 +788,8 @@ public void RemoveParameters_CanExecute_Function_NoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -766,7 +807,8 @@ public void RemoveParameters_CanExecute_PropertyGet_NoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -784,7 +826,8 @@ public void RemoveParameters_CanExecute_PropertyLet_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -802,7 +845,8 @@ public void RemoveParameters_CanExecute_PropertySet_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -819,7 +863,8 @@ public void RemoveParameters_CanExecute_Event_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -837,7 +882,8 @@ public void RemoveParameters_CanExecute_Proc_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -855,7 +901,8 @@ public void RemoveParameters_CanExecute_Function_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -873,7 +920,8 @@ public void RemoveParameters_CanExecute_PropertyGet_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -891,7 +939,8 @@ public void RemoveParameters_CanExecute_PropertyLet_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -909,7 +958,8 @@ public void RemoveParameters_CanExecute_PropertySet_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); @@ -924,10 +974,11 @@ public void ReorderParameters_CanExecute_NullActiveCodePane() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -939,11 +990,12 @@ public void ReorderParameters_CanExecute_NonReadyState() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -957,10 +1009,11 @@ public void ReorderParameters_CanExecute_Event_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -975,10 +1028,11 @@ public void ReorderParameters_CanExecute_Proc_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -993,10 +1047,11 @@ public void ReorderParameters_CanExecute_Function_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -1011,10 +1066,11 @@ public void ReorderParameters_CanExecute_PropertyGet_OneParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -1029,10 +1085,11 @@ public void ReorderParameters_CanExecute_PropertyLet_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -1047,10 +1104,11 @@ public void ReorderParameters_CanExecute_PropertySet_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(reorderParametersCommand.CanExecute(null)); } } @@ -1064,10 +1122,11 @@ public void ReorderParameters_CanExecute_Event_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(reorderParametersCommand.CanExecute(null)); } } @@ -1082,10 +1141,11 @@ public void ReorderParameters_CanExecute_Proc_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(reorderParametersCommand.CanExecute(null)); } } @@ -1100,10 +1160,11 @@ public void ReorderParameters_CanExecute_Function_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(reorderParametersCommand.CanExecute(null)); } } @@ -1118,10 +1179,11 @@ public void ReorderParameters_CanExecute_PropertyGet_TwoParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(reorderParametersCommand.CanExecute(null)); } } @@ -1136,10 +1198,11 @@ public void ReorderParameters_CanExecute_PropertyLet_ThreeParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(reorderParametersCommand.CanExecute(null)); } } @@ -1154,10 +1217,11 @@ public void ReorderParameters_CanExecute_PropertySet_ThreeParams() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { - var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null); + var reorderParametersCommand = new RefactorReorderParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(reorderParametersCommand.CanExecute(null)); } } diff --git a/RubberduckTests/Refactoring/ReorderParametersTests.cs b/RubberduckTests/Refactoring/ReorderParametersTests.cs index 0d0014a79d..6dad0fe4eb 100644 --- a/RubberduckTests/Refactoring/ReorderParametersTests.cs +++ b/RubberduckTests/Refactoring/ReorderParametersTests.cs @@ -34,7 +34,8 @@ public void ReorderParams_SwapPositions() End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -45,7 +46,7 @@ public void ReorderParams_SwapPositions() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -70,7 +71,8 @@ public void ReorderParams_SwapPositions_SignatureContainsParamName() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -81,7 +83,7 @@ public void ReorderParams_SwapPositions_SignatureContainsParamName() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -114,7 +116,8 @@ Sub Goo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -125,7 +128,7 @@ Sub Goo() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -150,7 +153,8 @@ public void ReorderParams_RefactorDeclaration() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -161,7 +165,7 @@ public void ReorderParams_RefactorDeclaration() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(model.TargetDeclaration); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -181,7 +185,8 @@ public void ReorderParams_RefactorDeclaration_FailsInvalidTarget() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -192,7 +197,7 @@ public void ReorderParams_RefactorDeclaration_FailsInvalidTarget() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); try { @@ -228,7 +233,8 @@ public void ReorderParams_WithOptionalParam() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -246,7 +252,7 @@ public void ReorderParams_WithOptionalParam() var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -281,7 +287,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -292,7 +299,7 @@ End Sub var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -335,7 +342,8 @@ Private Function foo(ByVal b As Integer, ByRef a As Integer) As Integer IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -346,7 +354,7 @@ Private Function foo(ByVal b As Integer, ByRef a As Integer) As Integer var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -381,7 +389,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -400,7 +409,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -427,7 +436,8 @@ public void ReorderParametersRefactoring_ReorderNamedParams_Function() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -439,7 +449,7 @@ public void ReorderParametersRefactoring_ReorderNamedParams_Function() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -474,7 +484,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -493,7 +504,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -518,7 +529,8 @@ public void ReorderParametersRefactoring_ReorderGetter() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -537,7 +549,7 @@ public void ReorderParametersRefactoring_ReorderGetter() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -562,7 +574,8 @@ public void ReorderParametersRefactoring_ReorderLetter() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -574,7 +587,7 @@ public void ReorderParametersRefactoring_ReorderLetter() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -599,7 +612,8 @@ public void ReorderParametersRefactoring_ReorderSetter() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -611,7 +625,7 @@ public void ReorderParametersRefactoring_ReorderSetter() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -631,7 +645,8 @@ public void ReorderParametersRefactoring_ReorderLastParamFromSetter_NotAllowed() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -655,7 +670,8 @@ public void ReorderParametersRefactoring_ReorderLastParamFromLetter_NotAllowed() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -688,7 +704,8 @@ public void ReorderParametersRefactoring_SignatureOnMultipleLines() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -700,7 +717,7 @@ public void ReorderParametersRefactoring_SignatureOnMultipleLines() //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -743,7 +760,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -755,7 +773,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -786,7 +804,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -800,7 +819,7 @@ End Sub var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -849,7 +868,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -870,7 +890,7 @@ End Sub var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -933,7 +953,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -954,7 +975,7 @@ End Sub var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -974,7 +995,8 @@ public void ReorderParams_MoveOptionalParamBeforeNonOptionalParamFails() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -994,7 +1016,7 @@ public void ReorderParams_MoveOptionalParamBeforeNonOptionalParamFails() var messageBox = new Mock(); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -1029,7 +1051,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -1047,7 +1070,7 @@ End Sub var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -1078,7 +1101,8 @@ Private Property Set Foo(ByVal arg2 As String, ByVal arg1 As Integer, ByVal arg3 IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -1090,7 +1114,7 @@ Private Property Set Foo(ByVal arg2 As String, ByVal arg1 As Integer, ByVal arg3 //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -1121,7 +1145,8 @@ Private Property Let Foo(ByVal arg2 As String, ByVal arg1 As Integer, ByVal arg3 IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -1133,7 +1158,7 @@ Private Property Let Foo(ByVal arg2 As String, ByVal arg1 As Integer, ByVal arg3 //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -1152,12 +1177,13 @@ public void ReorderParams_PresenterIsNull() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var factory = new ReorderParametersPresenterFactory(vbe.Object, null, state, null); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory, null, rewritingManager); refactoring.Refactor(); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -1198,7 +1224,8 @@ Private Sub IClass1_DoSomething(ByVal b As String, ByVal a As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1212,7 +1239,7 @@ Private Sub IClass1_DoSomething(ByVal b As String, ByVal a As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1254,7 +1281,8 @@ Private Sub IClass1_DoSomething(ByVal v2 As String, ByVal v1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1268,7 +1296,7 @@ Private Sub IClass1_DoSomething(ByVal v2 As String, ByVal v1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1321,7 +1349,8 @@ Private Sub IClass1_DoSomething(ByVal s As String, ByVal i As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1336,7 +1365,7 @@ Private Sub IClass1_DoSomething(ByVal s As String, ByVal i As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1380,7 +1409,8 @@ Private Sub IClass1_DoSomething(ByVal b As String, ByVal a As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1397,7 +1427,7 @@ Private Sub IClass1_DoSomething(ByVal b As String, ByVal a As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1429,7 +1459,8 @@ Private Sub IClass1_DoSomething(ByVal a As Integer, ByVal b As String) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1477,7 +1508,8 @@ Private Sub abc_Foo(ByVal arg2 As String, ByVal arg1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1491,7 +1523,7 @@ Private Sub abc_Foo(ByVal arg2 As String, ByVal arg1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1533,7 +1565,8 @@ Private Sub abc_Foo(ByVal arg2 As String, ByVal arg1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1547,7 +1580,7 @@ Private Sub abc_Foo(ByVal arg2 As String, ByVal arg1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1589,7 +1622,8 @@ Private Sub abc_Foo(ByVal s As String, ByVal i As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1603,7 +1637,7 @@ Private Sub abc_Foo(ByVal s As String, ByVal i As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1657,7 +1691,8 @@ Private Sub abc_Foo(ByVal v2 As String, ByVal v1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1672,7 +1707,7 @@ Private Sub abc_Foo(ByVal v2 As String, ByVal v1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null); + var refactoring = new ReorderParametersRefactoring(vbe.Object, factory.Object, null, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1694,7 +1729,8 @@ public void Presenter_ParameterlessMemberCreatesNullModel() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var messageBox = new Mock(); @@ -1721,7 +1757,8 @@ public void Presenter_SingleParameterMemberCreatesNullModel() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var messageBox = new Mock(); @@ -1749,7 +1786,8 @@ Private Sub Foo(ByVal arg1 As Integer, ByVal arg2 As String) IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var factory = new ReorderParametersPresenterFactory(vbe.Object, null, state, null); @@ -1774,7 +1812,8 @@ public void Factory_NullSelectionCreatesNullPresenter() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); From df916120ebe3080d3716d1dc7974d33ac9294262 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Fri, 2 Nov 2018 22:47:49 +0100 Subject: [PATCH 045/107] Rewire the MoveCloserToUsageRefactoring --- .../MoveFieldCloserToUsageQuickFix.cs | 12 +- .../RefactorMoveCloserToUsageCommand.cs | 7 +- .../MoveCloserToUsageRefactoring.cs | 47 ++-- .../Commands/RefactorCommandTests.cs | 16 +- .../MoveFieldCloserToUsageQuickFixTests.cs | 2 +- .../Refactoring/MoveCloserToUsageTests.cs | 249 ++++++++++-------- 6 files changed, 173 insertions(+), 160 deletions(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs index 773bf9ab6c..696287fea3 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/MoveFieldCloserToUsageQuickFix.cs @@ -14,20 +14,22 @@ public sealed class MoveFieldCloserToUsageQuickFix : QuickFixBase { private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public MoveFieldCloserToUsageQuickFix(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public MoveFieldCloserToUsageQuickFix(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) : base(typeof(MoveFieldCloserToUsageInspection)) { _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } //The rewriteSession is optional since it is not used in this particular quickfix because it is a refactoring quickfix. public override void Fix(IInspectionResult result, IRewriteSession rewriteSession = null) { - var refactoring = new MoveCloserToUsageRefactoring(_vbe, _state, _messageBox); + var refactoring = new MoveCloserToUsageRefactoring(_vbe, _state, _messageBox, _rewritingManager); refactoring.Refactor(result.Target); } @@ -36,8 +38,8 @@ public override string Description(IInspectionResult result) return string.Format(InspectionResults.MoveFieldCloserToUsageInspection, result.Target.IdentifierName); } - public override bool CanFixInProcedure => true; - public override bool CanFixInModule => true; - public override bool CanFixInProject => true; + public override bool CanFixInProcedure => false; + public override bool CanFixInModule => false; + public override bool CanFixInProject => false; } } \ No newline at end of file diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorMoveCloserToUsageCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorMoveCloserToUsageCommand.cs index 335d2be99a..05bf350ce7 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorMoveCloserToUsageCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorMoveCloserToUsageCommand.cs @@ -1,5 +1,6 @@ using System.Linq; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.MoveCloserToUsage; @@ -10,12 +11,14 @@ namespace Rubberduck.UI.Command.Refactorings public class RefactorMoveCloserToUsageCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _msgbox; - public RefactorMoveCloserToUsageCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgbox) + public RefactorMoveCloserToUsageCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgbox, IRewritingManager rewritingManager) :base(vbe) { _state = state; + _rewritingManager = rewritingManager; _msgbox = msgbox; } @@ -43,7 +46,7 @@ protected override void OnExecute(object parameter) if (selection.HasValue) { - var refactoring = new MoveCloserToUsageRefactoring(Vbe, _state, _msgbox); + var refactoring = new MoveCloserToUsageRefactoring(Vbe, _state, _msgbox, _rewritingManager); refactoring.Refactor(selection.Value); } } diff --git a/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs b/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs index dd5ae4f942..8d5c5e878d 100644 --- a/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs +++ b/Rubberduck.Refactorings/MoveCloserToUsage/MoveCloserToUsageRefactoring.cs @@ -21,16 +21,17 @@ public class MoveCloserToUsageRefactoring : IRefactoring private readonly List _declarations; private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; private Declaration _target; - - private readonly HashSet _rewriters = new HashSet(); - public MoveCloserToUsageRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public MoveCloserToUsageRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) { + //TODO: Use the DeclarationFinder instead and inject an IDeclarationFinderProvider instead of the RubberduckParserState. (Callers are not affected.) _declarations = state.AllUserDeclarations.ToList(); _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -106,23 +107,20 @@ private void MoveCloserToUsage() oldSelection = pane.GetQualifiedSelection(); } - InsertNewDeclaration(); - RemoveOldDeclaration(); - UpdateOtherModules(); + var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); + InsertNewDeclaration(rewriteSession); + RemoveOldDeclaration(rewriteSession); + UpdateOtherModules(rewriteSession); + rewriteSession.Rewrite(); if (oldSelection.HasValue && !pane.IsWrappingNullReference) { pane.Selection = oldSelection.Value.Selection; } } - foreach (var rewriter in _rewriters) - { - rewriter.Rewrite(); - } - Reparse(); } - private void UpdateOtherModules() + private void UpdateOtherModules(IRewriteSession rewriteSession) { QualifiedSelection? oldSelection = null; using (var pane = _vbe.ActiveCodePane) @@ -140,7 +138,7 @@ private void UpdateOtherModules() if (newTarget != null) { - UpdateCallsToOtherModule(newTarget.References.ToList()); + UpdateCallsToOtherModule(newTarget.References.ToList(), rewriteSession); } if (oldSelection.HasValue) @@ -150,7 +148,7 @@ private void UpdateOtherModules() } } - private void InsertNewDeclaration() + private void InsertNewDeclaration(IRewriteSession rewriteSession) { var newVariable = $"Dim {_target.IdentifierName} As {_target.AsTypeName}{Environment.NewLine}"; @@ -174,21 +172,17 @@ private void InsertNewDeclaration() } var padding = new string(' ', indentLength); - var rewriter = _state.GetRewriter(firstReference.QualifiedModuleName); + var rewriter = rewriteSession.CheckOutModuleRewriter(firstReference.QualifiedModuleName); rewriter.InsertBefore(insertionIndex, newVariable + padding); - - _rewriters.Add(rewriter); } - private void RemoveOldDeclaration() + private void RemoveOldDeclaration(IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(_target); + var rewriter = rewriteSession.CheckOutModuleRewriter(_target.QualifiedModuleName); rewriter.Remove(_target); - - _rewriters.Add(rewriter); } - private void UpdateCallsToOtherModule(IEnumerable references) + private void UpdateCallsToOtherModule(IEnumerable references, IRewriteSession rewriteSession) { foreach (var reference in references.OrderByDescending(o => o.Selection.StartLine).ThenByDescending(t => t.Selection.StartColumn)) { @@ -212,17 +206,10 @@ private void UpdateCallsToOtherModule(IEnumerable reference continue; } - var rewriter = _state.GetRewriter(reference.QualifiedModuleName); + var rewriter = rewriteSession.CheckOutModuleRewriter(reference.QualifiedModuleName); var tokenInterval = Interval.Of(parent.SourceInterval.a, reference.Context.SourceInterval.b); rewriter.Replace(tokenInterval, reference.IdentifierName); - - _rewriters.Add(rewriter); } } - - private void Reparse() - { - _state.OnParseRequested(this); - } } } diff --git a/RubberduckTests/Commands/RefactorCommandTests.cs b/RubberduckTests/Commands/RefactorCommandTests.cs index 23471bbbe3..07a385145e 100644 --- a/RubberduckTests/Commands/RefactorCommandTests.cs +++ b/RubberduckTests/Commands/RefactorCommandTests.cs @@ -572,7 +572,7 @@ public void MoveCloserToUsage_CanExecute_NullActiveCodePane() using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -589,7 +589,7 @@ public void MoveCloserToUsage_CanExecute_NonReadyState() { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -604,7 +604,7 @@ public void MoveCloserToUsage_CanExecute_Field_NoReferences() using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -624,7 +624,7 @@ Dim d As Boolean using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -639,7 +639,7 @@ public void MoveCloserToUsage_CanExecute_Const_NoReferences() using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -660,7 +660,7 @@ Sub Foo() using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(moveCloserToUsageCommand.CanExecute(null)); } } @@ -681,7 +681,7 @@ Dim d As Boolean using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(moveCloserToUsageCommand.CanExecute(null)); } } @@ -703,7 +703,7 @@ Dim d As Integer using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(moveCloserToUsageCommand.CanExecute(null)); } } diff --git a/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs b/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs index 21dfce0cdb..0e8ded62e8 100644 --- a/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/MoveFieldCloserToUsageQuickFixTests.cs @@ -122,7 +122,7 @@ private string ApplyQuickFixToFirstInspectionResult(string inputCode) var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); var resultToFix = inspectionResults.First(); var rewriteSession = rewritingManager.CheckOutCodePaneSession(); - var quickFix = new MoveFieldCloserToUsageQuickFix(vbe.Object, state, new Mock().Object); + var quickFix = new MoveFieldCloserToUsageQuickFix(vbe.Object, state, new Mock().Object, rewritingManager); quickFix.Fix(resultToFix, rewriteSession); diff --git a/RubberduckTests/Refactoring/MoveCloserToUsageTests.cs b/RubberduckTests/Refactoring/MoveCloserToUsageTests.cs index d44bae5550..be766dffcc 100644 --- a/RubberduckTests/Refactoring/MoveCloserToUsageTests.cs +++ b/RubberduckTests/Refactoring/MoveCloserToUsageTests.cs @@ -1,13 +1,10 @@ using System.Linq; -using System.Windows.Forms; using NUnit.Framework; using Moq; using Rubberduck.Parsing.Symbols; using Rubberduck.Refactorings.MoveCloserToUsage; -using Rubberduck.UI; using Rubberduck.VBEditor; using Rubberduck.VBEditor.SafeComWrappers; -using Rubberduck.VBEditor.SafeComWrappers.Abstract; using RubberduckTests.Mocks; using Rubberduck.Interaction; @@ -37,16 +34,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -71,16 +69,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -108,16 +107,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -153,21 +153,22 @@ Dim bar As Boolean .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); var module1 = project.Object.VBComponents[0]; var module2 = project.Object.VBComponents[1]; - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter1 = state.GetRewriter(module1); - Assert.AreEqual(expectedCode1, rewriter1.GetText()); + var actualCode1 = module1.CodeModule.Content(); + Assert.AreEqual(expectedCode1, actualCode1); - var rewriter2 = state.GetRewriter(module2); - Assert.AreEqual(expectedCode2, rewriter2.GetText()); + var actualCode2 = module2.CodeModule.Content(); + Assert.AreEqual(expectedCode2, actualCode2); } } @@ -194,16 +195,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -231,16 +233,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -270,16 +273,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -310,16 +314,17 @@ Dim bat As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -350,16 +355,17 @@ Dim bar As Integer End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using (state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -390,16 +396,17 @@ Dim bat As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -430,16 +437,17 @@ Dim bay As Date End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -472,16 +480,17 @@ Dim bar As Integer End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -514,16 +523,17 @@ Dim bat As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -556,16 +566,17 @@ Dim bay As Date End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -582,20 +593,21 @@ Private Sub Foo() var selection = new Selection(1, 1); var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); var messageBox = new Mock(); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once()); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(inputCode, actualCode); } } @@ -616,19 +628,20 @@ Private Sub Bar() var selection = new Selection(1, 1); var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); var messageBox = new Mock(); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once()); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(inputCode, actualCode); } } @@ -652,16 +665,17 @@ Dim bar As Boolean var selection = new Selection(1, 1); var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -689,16 +703,17 @@ Sub Baz(ByVal bat As Boolean) var selection = new Selection(1, 1); var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -730,16 +745,17 @@ Sub Baz(ByVal bat As Boolean, ByVal bas As Boolean, ByVal bac As Boolean) var selection = new Selection(1, 1); var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -763,16 +779,17 @@ Private Sub Foo(): Baz True, True, bar: End Sub Private Sub Baz(ByVal bat As Boolean, ByVal bas As Boolean, ByVal bac As Boolean): End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -808,16 +825,17 @@ Debug.Print someParam End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -847,16 +865,17 @@ Debug.Print someParam End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -873,15 +892,16 @@ Private Sub Foo() End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(state.AllUserDeclarations.First(d => d.DeclarationType != DeclarationType.Variable)); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(inputCode, actualCode); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); } @@ -901,20 +921,21 @@ Private Sub Foo() var selection = new Selection(2, 15); var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(inputCode, actualCode); } } @@ -954,19 +975,19 @@ End With End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = state.DeclarationFinder .UserDeclarations(DeclarationType.Variable) .Where(d => d.IdentifierName == "count") .Single().QualifiedSelection; - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.NotNull(rewriter); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -1013,7 +1034,7 @@ Public Sub Test() var selection = new Selection(1, 1); - const string expected = @" + const string expectedCode = @" Public Sub Test() Debug.Print ""Some statements between"" @@ -1031,17 +1052,17 @@ Dim foo As Class1 builder = builder.AddProject(project.Build()); var vbe = builder.Build(); - var testComponent = project.MockComponents.Find(mc => mc.Object.Name.Equals("Module1")); - var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(testComponent.Object), selection); + var component = project.MockComponents.Find(mc => mc.Object.Name.Equals("Module1")).Object; + var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); - var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new MoveCloserToUsageRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(testComponent.Object); - var actual = rewriter.GetText(); - Assert.AreEqual(expected, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } } From 245e0fc81e92d52f51d8b7e4d8e10506cedd184d Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Fri, 2 Nov 2018 23:58:49 +0100 Subject: [PATCH 046/107] Rewire the EncapsulateFieldRefactoring Also contains one correction to a test for the RenameRefactoring --- .../QuickFixes/EncapsulateFieldQuickFix.cs | 6 +- .../RefactorEncapsulateFieldCommand.cs | 7 +- .../EncapsulateFieldRefactoring.cs | 40 ++--- .../Commands/RefactorCommandTests.cs | 10 +- .../Refactoring/EncapsulateFieldTests.cs | 162 ++++++++++-------- RubberduckTests/Refactoring/RenameTests.cs | 4 +- 6 files changed, 128 insertions(+), 101 deletions(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs index 4162521d5a..dcbe44b31a 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/EncapsulateFieldQuickFix.cs @@ -14,13 +14,15 @@ public sealed class EncapsulateFieldQuickFix : QuickFixBase { private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IIndenter _indenter; - public EncapsulateFieldQuickFix(IVBE vbe, RubberduckParserState state, IIndenter indenter) + public EncapsulateFieldQuickFix(IVBE vbe, RubberduckParserState state, IIndenter indenter, IRewritingManager rewritingManager) : base(typeof(EncapsulatePublicFieldInspection)) { _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _indenter = indenter; } @@ -30,7 +32,7 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio using (var view = new EncapsulateFieldDialog(new EncapsulateFieldViewModel(_state, _indenter))) { var factory = new EncapsulateFieldPresenterFactory(_vbe, _state, view); - var refactoring = new EncapsulateFieldRefactoring(_vbe, _indenter, factory); + var refactoring = new EncapsulateFieldRefactoring(_vbe, _indenter, factory, _rewritingManager); refactoring.Refactor(result.Target); } } diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorEncapsulateFieldCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorEncapsulateFieldCommand.cs index 84c90016d5..a5bda2f06a 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorEncapsulateFieldCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorEncapsulateFieldCommand.cs @@ -1,4 +1,5 @@ using System.Runtime.InteropServices; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.EncapsulateField; @@ -12,12 +13,14 @@ namespace Rubberduck.UI.Command.Refactorings public class RefactorEncapsulateFieldCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly Indenter _indenter; - public RefactorEncapsulateFieldCommand(IVBE vbe, RubberduckParserState state, Indenter indenter) + public RefactorEncapsulateFieldCommand(IVBE vbe, RubberduckParserState state, Indenter indenter, IRewritingManager rewritingManager) : base(vbe) { _state = state; + _rewritingManager = rewritingManager; _indenter = indenter; } @@ -52,7 +55,7 @@ protected override void OnExecute(object parameter) using (var view = new EncapsulateFieldDialog(new EncapsulateFieldViewModel(_state, _indenter))) { var factory = new EncapsulateFieldPresenterFactory(Vbe, _state, view); - var refactoring = new EncapsulateFieldRefactoring(Vbe, _indenter, factory); + var refactoring = new EncapsulateFieldRefactoring(Vbe, _indenter, factory, _rewritingManager); refactoring.Refactor(); } } diff --git a/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs b/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs index 49798c650d..c34e6fd775 100644 --- a/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs +++ b/Rubberduck.Refactorings/EncapsulateField/EncapsulateFieldRefactoring.cs @@ -13,35 +13,35 @@ public class EncapsulateFieldRefactoring : IRefactoring { private readonly IVBE _vbe; private readonly IIndenter _indenter; + private readonly IRewritingManager _rewritingManager; private readonly IRefactoringPresenterFactory _factory; private EncapsulateFieldModel _model; - private readonly HashSet _referenceRewriters = new HashSet(); - - public EncapsulateFieldRefactoring(IVBE vbe, IIndenter indenter, IRefactoringPresenterFactory factory) + public EncapsulateFieldRefactoring(IVBE vbe, IIndenter indenter, IRefactoringPresenterFactory factory, IRewritingManager rewritingManager) { _vbe = vbe; _indenter = indenter; _factory = factory; + _rewritingManager = rewritingManager; } public void Refactor() { var presenter = _factory.Create(); - if (presenter == null) { return; } + if (presenter == null) + { + return; + } _model = presenter.Show(); - if (_model == null) { return; } - - var target = _model.TargetDeclaration; - var rewriter = _model.State.GetRewriter(target); - AddProperty(rewriter); - - rewriter.Rewrite(); - foreach (var referenceRewriter in _referenceRewriters) + if (_model == null) { - referenceRewriter.Rewrite(); + return; } + + var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); + AddProperty(rewriteSession); + rewriteSession.Rewrite(); } public void Refactor(QualifiedSelection target) @@ -71,9 +71,11 @@ public void Refactor(Declaration target) Refactor(); } - private void AddProperty(IExecutableModuleRewriter rewriter) + private void AddProperty(IRewriteSession rewriteSession) { - UpdateReferences(); + var rewriter = rewriteSession.CheckOutModuleRewriter(_model.TargetDeclaration.QualifiedModuleName); + + UpdateReferences(rewriteSession); SetFieldToPrivate(rewriter); var members = _model.State.DeclarationFinder @@ -109,18 +111,16 @@ private void AddProperty(IExecutableModuleRewriter rewriter) } } - private void UpdateReferences() + private void UpdateReferences(IRewriteSession rewriteSession) { foreach (var reference in _model.TargetDeclaration.References) { - var rewriter = _model.State.GetRewriter(reference.QualifiedModuleName); + var rewriter = rewriteSession.CheckOutModuleRewriter(reference.QualifiedModuleName); rewriter.Replace(reference.Context, _model.PropertyName); - - _referenceRewriters.Add(rewriter); } } - private void SetFieldToPrivate(IExecutableModuleRewriter rewriter) + private void SetFieldToPrivate(IModuleRewriter rewriter) { if (_model.TargetDeclaration.Accessibility != Accessibility.Private) { diff --git a/RubberduckTests/Commands/RefactorCommandTests.cs b/RubberduckTests/Commands/RefactorCommandTests.cs index 07a385145e..4d3e6d7223 100644 --- a/RubberduckTests/Commands/RefactorCommandTests.cs +++ b/RubberduckTests/Commands/RefactorCommandTests.cs @@ -26,7 +26,7 @@ public void EncapsulateField_CanExecute_NullActiveCodePane() using (state) { - var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); + var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(encapsulateFieldCommand.CanExecute(null)); } } @@ -42,7 +42,7 @@ public void EncapsulateField_CanExecute_NonReadyState() { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); - var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); + var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(encapsulateFieldCommand.CanExecute(null)); } } @@ -62,7 +62,7 @@ Dim d As Boolean using (state) { - var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); + var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(encapsulateFieldCommand.CanExecute(null)); } } @@ -82,7 +82,7 @@ Sub Foo() using (state) { - var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); + var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(encapsulateFieldCommand.CanExecute(null)); } } @@ -102,7 +102,7 @@ Sub Foo() using (state) { - var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null); + var encapsulateFieldCommand = new RefactorEncapsulateFieldCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(encapsulateFieldCommand.CanExecute(null)); } } diff --git a/RubberduckTests/Refactoring/EncapsulateFieldTests.cs b/RubberduckTests/Refactoring/EncapsulateFieldTests.cs index 780ca0d686..112034ecfa 100644 --- a/RubberduckTests/Refactoring/EncapsulateFieldTests.cs +++ b/RubberduckTests/Refactoring/EncapsulateFieldTests.cs @@ -43,7 +43,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -60,11 +61,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -96,7 +98,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -113,11 +116,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -146,7 +150,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -163,11 +168,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -192,7 +198,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -209,11 +216,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -256,7 +264,8 @@ Function Bar() As Integer IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -273,11 +282,12 @@ Function Bar() As Integer //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -326,7 +336,8 @@ Property Set Foo(ByVal vall As Variant) IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -343,11 +354,12 @@ Property Set Foo(ByVal vall As Variant) //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -378,7 +390,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -395,11 +408,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -440,7 +454,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -457,11 +472,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -494,7 +510,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -511,11 +528,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -548,7 +566,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -565,11 +584,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -598,7 +618,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -615,11 +636,12 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -664,7 +686,8 @@ Sub Bar(ByVal name As Integer) IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -681,11 +704,12 @@ Sub Bar(ByVal name As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(model.TargetDeclaration); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var targetComponent = state.ProjectsProvider.Component(model.TargetDeclaration.QualifiedModuleName); + var actualCode = targetComponent.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -749,7 +773,8 @@ Sub Bar(ByVal v As Integer) var component = project.Object.VBComponents[0]; vbe.Setup(v => v.ActiveCodePane).Returns(component.CodeModule.CodePane); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -768,7 +793,7 @@ Sub Bar(ByVal v As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); var actualCode1 = module1.Content(); @@ -776,12 +801,6 @@ Sub Bar(ByVal v As Integer) Assert.AreEqual(expectedCode1, actualCode1); Assert.AreEqual(expectedCode2, actualCode2); - - var rewriter1 = state.GetRewriter(module1.Parent); - Assert.AreEqual(expectedCode1, rewriter1.GetText()); - - var rewriter2 = state.GetRewriter(module2.Parent); - Assert.AreEqual(expectedCode2, rewriter2.GetText()); } } @@ -810,7 +829,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -827,11 +847,11 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(state.AllUserDeclarations.FindVariable(qualifiedSelection)); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -846,17 +866,18 @@ public void EncapsulateField_PresenterIsNull() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var vbeWrapper = vbe.Object; var factory = new EncapsulateFieldPresenterFactory(vbeWrapper, state, null); - var refactoring = new EncapsulateFieldRefactoring(vbeWrapper, CreateIndenter(vbe.Object), factory); + var refactoring = new EncapsulateFieldRefactoring(vbeWrapper, CreateIndenter(vbe.Object), factory, rewritingManager); refactoring.Refactor(); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(inputCode, actualCode); } } @@ -872,7 +893,8 @@ public void EncapsulateField_ModelIsNull() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -880,11 +902,11 @@ public void EncapsulateField_ModelIsNull() //SetupFactory var factory = SetupFactory(null); - var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object); + var refactoring = new EncapsulateFieldRefactoring(vbe.Object, CreateIndenter(vbe.Object), factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(inputCode, actualCode); } } @@ -899,7 +921,7 @@ public void GivenNullActiveCodePane_FactoryReturnsNullPresenter() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + using(var state = MockParser.CreateAndParse(vbe.Object)) { vbe.Object.ActiveCodePane = null; @@ -1015,7 +1037,7 @@ public void Presenter_Reject_ReturnsNull() } } - //TODO: The tests below are commented out pending some sort of refactoring that enables them + //TODO: The tests below are ignored pending some sort of refactoring that enables them //to actually *test* something. Currently, all of the behavior the tests are looking for is //being mocked. // SEE: https://github.com/rubberduck-vba/Rubberduck/issues/3072 diff --git a/RubberduckTests/Refactoring/RenameTests.cs b/RubberduckTests/Refactoring/RenameTests.cs index 33fcb38858..1984f2d327 100644 --- a/RubberduckTests/Refactoring/RenameTests.cs +++ b/RubberduckTests/Refactoring/RenameTests.cs @@ -2512,8 +2512,8 @@ public void Rename_PresenterIsNull() var refactoring = new RenameRefactoring(vbeWrapper, factory, null, state, state.ProjectsProvider, rewritingManager); refactoring.Refactor(); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(inputCode, actualCode); } } From ce18bea47aca8dd38c1e97c125904261ef37d0c6 Mon Sep 17 00:00:00 2001 From: comintern Date: Fri, 2 Nov 2018 19:47:21 -0500 Subject: [PATCH 047/107] Update inspection info. --- Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs | 2 +- Rubberduck.Resources/Inspections/InspectionInfo.resx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs index 16e73ced43..3b152e5c14 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs +++ b/Rubberduck.Resources/Inspections/InspectionInfo.Designer.cs @@ -223,7 +223,7 @@ public static string EncapsulatePublicFieldInspection { } /// - /// Looks up a localized string similar to A Function or Property returning a reference type that can be 'Nothing' should not have the return value used with a test for 'Is Nothing'. If the member does not return a valid object, attempting to use the return value will result in a run-time error 91 - "Object variable or With block variable not set".. + /// Looks up a localized string similar to A procedure that returns an object may return 'Nothing'. That will cause a runtime error 91 - "Object variable or With block variable not set" on subsequent member access. Perform an 'Is Nothing' check after the 'Set' assignment to guard against runtime errors.. /// public static string ExcelMemberMayReturnNothingInspection { get { diff --git a/Rubberduck.Resources/Inspections/InspectionInfo.resx b/Rubberduck.Resources/Inspections/InspectionInfo.resx index 3958388d8a..667f35d337 100644 --- a/Rubberduck.Resources/Inspections/InspectionInfo.resx +++ b/Rubberduck.Resources/Inspections/InspectionInfo.resx @@ -350,6 +350,6 @@ If the parameter can be null, ignore this inspection result; passing a null valu An assignment is immediately overridden by another assignment or is never referenced. - A Function or Property returning a reference type that can be 'Nothing' should not have the return value used with a test for 'Is Nothing'. If the member does not return a valid object, attempting to use the return value will result in a run-time error 91 - "Object variable or With block variable not set". + A procedure that returns an object may return 'Nothing'. That will cause a runtime error 91 - "Object variable or With block variable not set" on subsequent member access. Perform an 'Is Nothing' check after the 'Set' assignment to guard against runtime errors. \ No newline at end of file From d17817036830652858e75750d3694279be205842 Mon Sep 17 00:00:00 2001 From: comintern Date: Fri, 2 Nov 2018 19:47:54 -0500 Subject: [PATCH 048/107] Added forgotten check for ignore annotation. --- ...berAccessMayReturnNothingInspectionBase.cs | 2 +- ...elMemberMayReturnNothingInspectionTests.cs | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs b/Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs index 1754f33449..b78e9cf604 100644 --- a/Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs +++ b/Rubberduck.CodeAnalysis/Inspections/Abstract/MemberAccessMayReturnNothingInspectionBase.cs @@ -28,7 +28,7 @@ protected override IEnumerable DoGetInspectionResults() } var output = new List(); - foreach (var reference in interesting) + foreach (var reference in interesting.Where(use => !IsIgnoringInspectionResultFor(use, AnnotationName))) { var access = reference.Context.GetAncestor(); var usageContext = access.Parent is VBAParser.IndexExprContext diff --git a/RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs b/RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs index f797dc1610..6a8a8e7ee1 100644 --- a/RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs +++ b/RubberduckTests/Inspections/ExcelMemberMayReturnNothingInspectionTests.cs @@ -33,6 +33,29 @@ End Sub } } + [Test] + [Category("Inspections")] + public void ExcelMemberMayReturnNothing_Ignored_DoesNotReturnResult() + { + const string inputCode = + @"Sub UnderTest() + Dim ws As Worksheet + Set ws = Sheet1 + '@Ignore ExcelMemberMayReturnNothing + foo = ws.UsedRange.Find(""foo"").Row +End Sub +"; + + using (var state = ArrangeParserAndParse(inputCode)) + { + + var inspection = new ExcelMemberMayReturnNothingInspection(state); + var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); + + Assert.IsFalse(inspectionResults.Any()); + } + } + [Test] [Category("Inspections")] public void ExcelMemberMayReturnNothing_ReturnsNoResult_ResultIsNothingInAssignment() From 15a95306824dc10d149cc6f6619272f1bd706935 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 3 Nov 2018 12:24:39 +0100 Subject: [PATCH 049/107] Rewire the IntroduceParameterRefactoring --- .../RefactorIntroduceParameterCommand.cs | 7 +- .../IntroduceParameterRefactoring.cs | 45 ++-- .../Commands/RefactorCommandTests.cs | 8 +- .../Refactoring/IntroduceParameterTests.cs | 193 ++++++++++-------- 4 files changed, 137 insertions(+), 116 deletions(-) diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceParameterCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceParameterCommand.cs index 941caa49b3..c7a334a0a3 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceParameterCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceParameterCommand.cs @@ -1,5 +1,6 @@ using Rubberduck.Common; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.IntroduceParameter; @@ -10,12 +11,14 @@ namespace Rubberduck.UI.Command.Refactorings public class RefactorIntroduceParameterCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public RefactorIntroduceParameterCommand (IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public RefactorIntroduceParameterCommand (IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) :base(vbe) { _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -49,7 +52,7 @@ protected override void OnExecute(object parameter) return; } - var refactoring = new IntroduceParameterRefactoring(Vbe, _state, _messageBox); + var refactoring = new IntroduceParameterRefactoring(Vbe, _state, _messageBox, _rewritingManager); refactoring.Refactor(selection.Value); } } diff --git a/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs b/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs index 85e43dbe5e..56cbfd67c8 100644 --- a/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs +++ b/Rubberduck.Refactorings/IntroduceParameter/IntroduceParameterRefactoring.cs @@ -16,11 +16,10 @@ public class IntroduceParameterRefactoring : IRefactoring { private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IList _declarations; private readonly IMessageBox _messageBox; - private readonly HashSet _rewriters = new HashSet(); - private static readonly DeclarationType[] ValidDeclarationTypes = { DeclarationType.Function, @@ -30,10 +29,12 @@ public class IntroduceParameterRefactoring : IRefactoring DeclarationType.PropertySet }; - public IntroduceParameterRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public IntroduceParameterRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) { _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; + //TODO: Make this use the DeclarationFinder and inject an IDeclarationFinderProvider instead of the RubberduckParserState. (Does not affect the callers.) _declarations = state.AllDeclarations.ToList(); _messageBox = messageBox; } @@ -89,9 +90,6 @@ private void PromoteVariable(Declaration target) return; } - var rewriter = _state.GetRewriter(target); - _rewriters.Add(rewriter); - using (var pane = _vbe.ActiveCodePane) { QualifiedSelection? oldSelection = null; @@ -100,19 +98,19 @@ private void PromoteVariable(Declaration target) oldSelection = pane.GetQualifiedSelection(); } - UpdateSignature(target); + var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); + + var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName); + UpdateSignature(target, rewriteSession); rewriter.Remove(target); + rewriteSession.Rewrite(); + if (oldSelection.HasValue && !pane.IsWrappingNullReference) { pane.Selection = oldSelection.Value.Selection; } } - - foreach (var tokenRewriter in _rewriters) - { - tokenRewriter.Rewrite(); - } } private bool PromptIfMethodImplementsInterface(Declaration targetVariable) @@ -138,7 +136,7 @@ private bool PromptIfMethodImplementsInterface(Declaration targetVariable) return _messageBox.Question(message, RubberduckUI.IntroduceParameter_Caption); } - private void UpdateSignature(Declaration targetVariable) + private void UpdateSignature(Declaration targetVariable, IRewriteSession rewriteSession) { var functionDeclaration = (ModuleBodyElementDeclaration)_declarations.FindTarget(targetVariable.QualifiedSelection, ValidDeclarationTypes); @@ -147,11 +145,11 @@ private void UpdateSignature(Declaration targetVariable) if (functionDeclaration.DeclarationType.HasFlag(DeclarationType.Property)) { - UpdateProperties(functionDeclaration, targetVariable); + UpdateProperties(functionDeclaration, targetVariable, rewriteSession); } else { - AddParameter(functionDeclaration, targetVariable, paramList); + AddParameter(functionDeclaration, targetVariable, paramList, rewriteSession); } var interfaceImplementation = functionDeclaration.InterfaceMemberImplemented; @@ -161,28 +159,27 @@ private void UpdateSignature(Declaration targetVariable) return; } - UpdateSignature(interfaceImplementation, targetVariable); + UpdateSignature(interfaceImplementation, targetVariable, rewriteSession); var interfaceImplementations = _state.DeclarationFinder.FindInterfaceImplementationMembers(functionDeclaration.InterfaceMemberImplemented) .Where(member => !ReferenceEquals(member, functionDeclaration)); foreach (var implementation in interfaceImplementations) { - UpdateSignature(implementation, targetVariable); + UpdateSignature(implementation, targetVariable, rewriteSession); } } - private void UpdateSignature(Declaration targetMethod, Declaration targetVariable) + private void UpdateSignature(Declaration targetMethod, Declaration targetVariable, IRewriteSession rewriteSession) { var proc = (dynamic) targetMethod.Context; var paramList = (VBAParser.ArgListContext) proc.argList(); - AddParameter(targetMethod, targetVariable, paramList); + AddParameter(targetMethod, targetVariable, paramList, rewriteSession); } - private void AddParameter(Declaration targetMethod, Declaration targetVariable, VBAParser.ArgListContext paramList) + private void AddParameter(Declaration targetMethod, Declaration targetVariable, VBAParser.ArgListContext paramList, IRewriteSession rewriteSession) { - var rewriter = _state.GetRewriter(targetMethod); - _rewriters.Add(rewriter); + var rewriter = rewriteSession.CheckOutModuleRewriter(targetMethod.QualifiedModuleName); var argList = paramList.arg(); var newParameter = $"{Tokens.ByVal} {targetVariable.IdentifierName} {Tokens.As} {targetVariable.AsTypeName}"; @@ -203,7 +200,7 @@ private void AddParameter(Declaration targetMethod, Declaration targetVariable, } } - private void UpdateProperties(Declaration knownProperty, Declaration targetVariable) + private void UpdateProperties(Declaration knownProperty, Declaration targetVariable, IRewriteSession rewriteSession) { var propertyGet = _declarations.FirstOrDefault(d => d.DeclarationType == DeclarationType.PropertyGet && @@ -241,7 +238,7 @@ private void UpdateProperties(Declaration knownProperty, Declaration targetVaria properties.OrderByDescending(o => o.Selection.StartLine) .ThenByDescending(t => t.Selection.StartColumn)) { - UpdateSignature(property, targetVariable); + UpdateSignature(property, targetVariable, rewriteSession); } } } diff --git a/RubberduckTests/Commands/RefactorCommandTests.cs b/RubberduckTests/Commands/RefactorCommandTests.cs index 4d3e6d7223..5bd17cc313 100644 --- a/RubberduckTests/Commands/RefactorCommandTests.cs +++ b/RubberduckTests/Commands/RefactorCommandTests.cs @@ -501,7 +501,7 @@ public void IntroduceParameter_CanExecute_NullActiveCodePane() { var msgbox = new Mock(); - var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object); + var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsFalse(introduceParameterCommand.CanExecute(null)); } } @@ -519,7 +519,7 @@ public void IntroduceParameter_CanExecute_NonReadyState() state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); var msgbox = new Mock(); - var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object); + var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsFalse(introduceParameterCommand.CanExecute(null)); } } @@ -535,7 +535,7 @@ public void IntroduceParameter_CanExecute_Field() { var msgbox = new Mock(); - var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object); + var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsFalse(introduceParameterCommand.CanExecute(null)); } } @@ -556,7 +556,7 @@ Dim d As Boolean { var msgbox = new Mock(); - var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object); + var introduceParameterCommand = new RefactorIntroduceParameterCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsTrue(introduceParameterCommand.CanExecute(null)); } } diff --git a/RubberduckTests/Refactoring/IntroduceParameterTests.cs b/RubberduckTests/Refactoring/IntroduceParameterTests.cs index defb837696..f32e6d4700 100644 --- a/RubberduckTests/Refactoring/IntroduceParameterTests.cs +++ b/RubberduckTests/Refactoring/IntroduceParameterTests.cs @@ -1,10 +1,8 @@ using System.Linq; -using System.Windows.Forms; using NUnit.Framework; using Moq; using Rubberduck.Parsing.Symbols; using Rubberduck.Refactorings.IntroduceParameter; -using Rubberduck.UI; using Rubberduck.VBEditor; using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.VBEditor.SafeComWrappers.Abstract; @@ -34,16 +32,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -67,16 +66,17 @@ Dim bar As Boolean End Function"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -98,16 +98,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -132,16 +133,17 @@ As _ End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -165,16 +167,17 @@ Dim bar As Boolean End Sub"; // note: the VBE removes extra spaces var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -202,16 +205,17 @@ bap As Integer End Sub"; // note: the VBE removes extra spaces var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -238,16 +242,17 @@ bap As Integer End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bat"); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, new Mock().Object); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, new Mock().Object, rewritingManager); refactoring.Refactor(target); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -273,16 +278,17 @@ bat As Date End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bap"); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(target); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -306,16 +312,17 @@ public void IntroduceParameterRefactoring_MultipleVariablesInStatement_OnOneLine End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bar"); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(target); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -332,19 +339,22 @@ Private Sub Foo() End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "fizz"); refactoring.Refactor(target); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + + const string expectedCode = inputCode; + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -361,19 +371,22 @@ Private Sub Foo() End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "fizz"); refactoring.Refactor(target); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + + const string expectedCode = inputCode; + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -402,16 +415,16 @@ Property Let Foo(ByVal fizz As Boolean, ByVal bar As Integer, ByVal buzz As Bool End Property"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bar"); refactoring.Refactor(target); - var rewriter = state.GetRewriter(component); - var actualCode = rewriter.GetText(); + var actualCode = component.CodeModule.Content(); Assert.AreEqual(expectedCode, actualCode); } } @@ -441,16 +454,17 @@ Property Set Foo(ByVal fizz As Boolean, ByVal bar As Integer, ByVal buzz As Vari End Property"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bar"); refactoring.Refactor(target); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -487,28 +501,27 @@ Sub IClass1_fizz(ByVal boo As Boolean, ByVal fizz As Date) .AddComponent("Class1", ComponentType.ClassModule, inputCode2) .Build(); var vbe = builder.AddProject(project).Build(); - var component0 = project.Object.VBComponents[0]; - var component1 = project.Object.VBComponents[1]; + var component1 = project.Object.VBComponents[0]; + var component2 = project.Object.VBComponents[1]; vbe.Setup(v => v.ActiveCodePane).Returns(component1.CodeModule.CodePane); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); messageBox.Setup(m => m.Question(It.IsAny(), It.IsAny())).Returns(true); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "fizz" && e.DeclarationType == DeclarationType.Variable); refactoring.Refactor(target); - var rewriter1 = state.GetRewriter(component0); - var actual1 = rewriter1.GetText(); - Assert.AreEqual(expectedCode1, actual1); + var actualCode1 = component1.CodeModule.Content(); + Assert.AreEqual(expectedCode1, actualCode1); - var rewriter2 = state.GetRewriter(component1); - var actual2 = rewriter2.GetText(); - Assert.AreEqual(expectedCode2, actual2); + var actualCode2 = component2.CodeModule.Content(); + Assert.AreEqual(expectedCode2, actualCode2); messageBox.Verify(m => m.Question(It.IsAny(), It.IsAny()), Times.Once()); } @@ -566,25 +579,27 @@ Sub IClass1_fizz(ByVal boo As Boolean, ByVal fizz As Date) var component3 = project.Object.VBComponents[2]; vbe.Setup(v => v.ActiveCodePane).Returns(component2.CodeModule.CodePane); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); messageBox.Setup(m => m.Question(It.IsAny(), It.IsAny())).Returns(true); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "fizz" && e.DeclarationType == DeclarationType.Variable); refactoring.Refactor(target); - var rewriter1 = state.GetRewriter(component1); - Assert.AreEqual(expectedCode1, rewriter1.GetText()); + var actualCode1 = component1.CodeModule.Content(); + Assert.AreEqual(expectedCode1, actualCode1); + + var actualCode2 = component2.CodeModule.Content(); + Assert.AreEqual(expectedCode2, actualCode2); - var rewriter2 = state.GetRewriter(component2); - Assert.AreEqual(expectedCode2, rewriter2.GetText()); + var actualCode3 = component3.CodeModule.Content(); + Assert.AreEqual(expectedCode3, actualCode3); - var rewriter3 = state.GetRewriter(component3); - Assert.AreEqual(expectedCode3, rewriter3.GetText()); messageBox.Verify(m => m.Question(It.IsAny(), It.IsAny()), Times.Once()); } } @@ -616,22 +631,25 @@ Dim fizz As Date var component2 = project.Object.VBComponents[1]; vbe.Setup(v => v.ActiveCodePane).Returns(component2.CodeModule.CodePane); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); messageBox.Setup(m => m.ConfirmYesNo(It.IsAny(), It.IsAny(), It.IsAny())).Returns(false); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "fizz" && e.DeclarationType == DeclarationType.Variable); refactoring.Refactor(target); - var rewriter1 = state.GetRewriter(component1); - Assert.AreEqual(inputCode1, rewriter1.GetText()); + const string expectedCode1 = inputCode1; + var actualCode1 = component1.CodeModule.Content(); + Assert.AreEqual(expectedCode1, actualCode1); - var rewriter2 = state.GetRewriter(component2); - Assert.AreEqual(inputCode2, rewriter2.GetText()); + const string expectedCode2 = inputCode2; + var actualCode2 = component2.CodeModule.Content(); + Assert.AreEqual(expectedCode2, actualCode2); } } @@ -652,16 +670,17 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, null, rewritingManager); var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bar" && e.DeclarationType == DeclarationType.Variable); refactoring.Refactor(target); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -677,18 +696,20 @@ Dim bar As Boolean End Sub"; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); - var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceParameterRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(state.AllUserDeclarations.First(d => d.DeclarationType != DeclarationType.Variable)); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(inputCode, rewriter.GetText()); + const string expectedCode = inputCode; + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } } From 2ad16f68d605f6755ca40ae5eebac9c4743a0478 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 3 Nov 2018 12:41:12 +0100 Subject: [PATCH 050/107] Rewire the IntroduceFieldRefactoring --- .../RefactorIntroduceFieldCommand.cs | 7 +- .../IntroduceFieldRefactoring.cs | 22 ++-- .../Commands/RefactorCommandTests.cs | 8 +- .../Refactoring/IntroduceFieldTests.cs | 119 ++++++++++-------- 4 files changed, 88 insertions(+), 68 deletions(-) diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceFieldCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceFieldCommand.cs index 939ed3e429..a5dc9eacc0 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceFieldCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorIntroduceFieldCommand.cs @@ -1,5 +1,6 @@ using Rubberduck.Common; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.IntroduceField; @@ -10,12 +11,14 @@ namespace Rubberduck.UI.Command.Refactorings public class RefactorIntroduceFieldCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public RefactorIntroduceFieldCommand (IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public RefactorIntroduceFieldCommand (IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) :base(vbe) { _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -49,7 +52,7 @@ protected override void OnExecute(object parameter) return; } - var refactoring = new IntroduceFieldRefactoring(Vbe, _state, _messageBox); + var refactoring = new IntroduceFieldRefactoring(Vbe, _state, _messageBox, _rewritingManager); refactoring.Refactor(selection.Value); } } diff --git a/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs b/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs index 80a5040ae8..f768fc32f7 100644 --- a/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs +++ b/Rubberduck.Refactorings/IntroduceField/IntroduceFieldRefactoring.cs @@ -7,7 +7,6 @@ using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; -using Rubberduck.UI; using Rubberduck.Resources; using Rubberduck.VBEditor; using Rubberduck.VBEditor.SafeComWrappers.Abstract; @@ -19,9 +18,10 @@ public class IntroduceFieldRefactoring : IRefactoring private readonly IList _declarations; private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public IntroduceFieldRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public IntroduceFieldRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) { _declarations = state.AllUserDeclarations .Where(i => i.DeclarationType == DeclarationType.Variable) @@ -29,6 +29,7 @@ public IntroduceFieldRefactoring(IVBE vbe, RubberduckParserState state, IMessage _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -55,8 +56,7 @@ public void Refactor(QualifiedSelection selection) return; } - var rewriter = _state.GetRewriter(target); - PromoteVariable(rewriter, target); + PromoteVariable(target); } public void Refactor(Declaration target) @@ -67,11 +67,10 @@ public void Refactor(Declaration target) throw new ArgumentException(@"Invalid declaration type", nameof(target)); } - var rewriter = _state.GetRewriter(target); - PromoteVariable(rewriter, target); + PromoteVariable(target); } - private void PromoteVariable(IExecutableModuleRewriter rewriter, Declaration target) + private void PromoteVariable(Declaration target) { if (new[] { DeclarationType.ClassModule, DeclarationType.ProceduralModule }.Contains(target.ParentDeclaration.DeclarationType)) { @@ -81,9 +80,14 @@ private void PromoteVariable(IExecutableModuleRewriter rewriter, Declaration tar var oldSelection = _vbe.GetActiveSelection(); + var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); + var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName); + rewriter.Remove(target); AddField(rewriter, target); + rewriteSession.Rewrite(); + if (oldSelection.HasValue) { var component = _state.ProjectsProvider.Component(oldSelection.Value.QualifiedName); @@ -95,11 +99,9 @@ private void PromoteVariable(IExecutableModuleRewriter rewriter, Declaration tar } } } - - rewriter.Rewrite(); } - private void AddField(IExecutableModuleRewriter rewriter, Declaration target) + private void AddField(IModuleRewriter rewriter, Declaration target) { var content = $"{Tokens.Private} {target.IdentifierName} {Tokens.As} {target.AsTypeName}\r\n"; var members = _state.DeclarationFinder.Members(target.QualifiedName.QualifiedModuleName) diff --git a/RubberduckTests/Commands/RefactorCommandTests.cs b/RubberduckTests/Commands/RefactorCommandTests.cs index 5bd17cc313..2607a6e5ac 100644 --- a/RubberduckTests/Commands/RefactorCommandTests.cs +++ b/RubberduckTests/Commands/RefactorCommandTests.cs @@ -429,7 +429,7 @@ public void IntroduceField_CanExecute_NullActiveCodePane() { var msgbox = new Mock(); - var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object); + var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsFalse(introduceFieldCommand.CanExecute(null)); } } @@ -447,7 +447,7 @@ public void IntroduceField_CanExecute_NonReadyState() state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); var msgbox = new Mock(); - var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object); + var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsFalse(introduceFieldCommand.CanExecute(null)); } } @@ -463,7 +463,7 @@ public void IntroduceField_CanExecute_Field() { var msgbox = new Mock(); - var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object); + var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsFalse(introduceFieldCommand.CanExecute(null)); } } @@ -484,7 +484,7 @@ Dim d As Boolean { var msgbox = new Mock(); - var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object); + var introduceFieldCommand = new RefactorIntroduceFieldCommand(vbe.Object, state, msgbox.Object, rewritingManager); Assert.IsTrue(introduceFieldCommand.CanExecute(null)); } } diff --git a/RubberduckTests/Refactoring/IntroduceFieldTests.cs b/RubberduckTests/Refactoring/IntroduceFieldTests.cs index b4e8125408..985f9f1eb6 100644 --- a/RubberduckTests/Refactoring/IntroduceFieldTests.cs +++ b/RubberduckTests/Refactoring/IntroduceFieldTests.cs @@ -1,12 +1,10 @@ using System; using System.Linq; -using System.Windows.Forms; using NUnit.Framework; using Moq; using Rubberduck.Common; using Rubberduck.Parsing.Symbols; using Rubberduck.Refactorings.IntroduceField; -using Rubberduck.UI; using Rubberduck.VBEditor; using Rubberduck.VBEditor.SafeComWrappers.Abstract; using RubberduckTests.Mocks; @@ -37,16 +35,17 @@ Private Sub Foo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -72,16 +71,17 @@ Private Function Foo() As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -107,16 +107,17 @@ Private Sub Foo(ByVal buz As Integer) IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -145,16 +146,17 @@ Private Sub Foo(ByVal buz As Integer) IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -184,16 +186,17 @@ Private Sub Foo(ByVal buz As Integer, _ IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -223,16 +226,17 @@ bap As Integer IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -260,16 +264,17 @@ bap As Integer IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var target = state.AllUserDeclarations.SingleOrDefault(e => e.IdentifierName == "bat"); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, new Mock().Object); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, new Mock().Object, rewritingManager); refactoring.Refactor(target); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -299,16 +304,17 @@ bat As Date IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -335,16 +341,17 @@ Private Sub Foo(ByVal buz As Integer, _ IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -363,18 +370,22 @@ Private Sub Foo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); var messageBox = new Mock(); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); - Assert.AreEqual(inputCode, component.CodeModule.Content()); + + const string expectedCode = inputCode; + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -393,20 +404,22 @@ Private Sub Foo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); var messageBox = new Mock(); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(inputCode, actual); + const string expectedCode = inputCode; + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -430,16 +443,17 @@ Private Sub Foo() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); - var refactoring = new IntroduceFieldRefactoring((vbe.Object), state, null); + var refactoring = new IntroduceFieldRefactoring((vbe.Object), state, null, rewritingManager); refactoring.Refactor(state.AllUserDeclarations.FindVariable(qualifiedSelection)); - var actual = state.GetRewriter(component).GetText(); - Assert.AreEqual(expectedCode, actual); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -456,12 +470,13 @@ Dim bar As Boolean IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var messageBox = new Mock(); - var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object); + var refactoring = new IntroduceFieldRefactoring(vbe.Object, state, messageBox.Object, rewritingManager); try { @@ -472,7 +487,7 @@ Dim bar As Boolean messageBox.Verify(m => m.NotifyWarn(It.IsAny(), It.IsAny()), Times.Once); Assert.AreEqual("target", e.ParamName); - var actual = state.GetRewriter(component).GetText(); + var actual = component.CodeModule.Content(); Assert.AreEqual(inputCode, actual); return; } From d3267cec06de46c5fc4ee4a5cf2f99c51bd5dc77 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 3 Nov 2018 13:40:00 +0100 Subject: [PATCH 051/107] Rewire the ImplementInterface- and ExtractInterfaceRefactoring --- .../RefactorExtractInterfaceCommand.cs | 7 +- .../RefactorImplementInterfaceCommand.cs | 7 +- .../ExtractInterfaceRefactoring.cs | 39 +++- .../ImplementInterfaceRefactoring.cs | 17 +- .../Commands/RefactorCommandTests.cs | 32 +-- .../Refactoring/ExtractInterfaceTests.cs | 35 ++-- .../Refactoring/ImplementInterfaceTests.cs | 182 ++++++++++-------- 7 files changed, 191 insertions(+), 128 deletions(-) diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorExtractInterfaceCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorExtractInterfaceCommand.cs index 7412073304..0ff6b12a9c 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorExtractInterfaceCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorExtractInterfaceCommand.cs @@ -5,6 +5,7 @@ using Rubberduck.Interaction; using Rubberduck.Parsing; using Rubberduck.Parsing.Grammar; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.ExtractInterface; @@ -18,12 +19,14 @@ namespace Rubberduck.UI.Command.Refactorings public class RefactorExtractInterfaceCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public RefactorExtractInterfaceCommand(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public RefactorExtractInterfaceCommand(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) :base(vbe) { _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -85,7 +88,7 @@ protected override void OnExecute(object parameter) using (var view = new ExtractInterfaceDialog(new ExtractInterfaceViewModel())) { var factory = new ExtractInterfacePresenterFactory(Vbe, _state, view); - var refactoring = new ExtractInterfaceRefactoring(Vbe, _messageBox, factory); + var refactoring = new ExtractInterfaceRefactoring(Vbe, _messageBox, factory, _rewritingManager); refactoring.Refactor(); } } diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorImplementInterfaceCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorImplementInterfaceCommand.cs index 3f62d4dbdb..7afa78e1bb 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorImplementInterfaceCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorImplementInterfaceCommand.cs @@ -1,6 +1,7 @@ using System.Linq; using System.Runtime.InteropServices; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.ImplementInterface; @@ -12,12 +13,14 @@ namespace Rubberduck.UI.Command.Refactorings public class RefactorImplementInterfaceCommand : RefactorCommandBase { private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _msgBox; - public RefactorImplementInterfaceCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgBox) + public RefactorImplementInterfaceCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgBox, IRewritingManager rewritingManager) : base(vbe) { _state = state; + _rewritingManager = rewritingManager; _msgBox = msgBox; } @@ -51,7 +54,7 @@ protected override void OnExecute(object parameter) return; } } - var refactoring = new ImplementInterfaceRefactoring(Vbe, _state, _msgBox); + var refactoring = new ImplementInterfaceRefactoring(Vbe, _state, _msgBox, _rewritingManager); refactoring.Refactor(); } } diff --git a/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs b/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs index 69997a2486..282d32e4d0 100644 --- a/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs +++ b/Rubberduck.Refactorings/ExtractInterface/ExtractInterfaceRefactoring.cs @@ -1,9 +1,12 @@ using System; +using System.Collections.Generic; using System.Linq; +using NLog; using Rubberduck.Interaction; using Rubberduck.Parsing.Grammar; using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; +using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.ImplementInterface; using Rubberduck.VBEditor; using Rubberduck.VBEditor.SafeComWrappers; @@ -15,12 +18,16 @@ public class ExtractInterfaceRefactoring : IRefactoring { private readonly IVBE _vbe; private readonly IMessageBox _messageBox; + private readonly IRewritingManager _rewritingManager; private readonly IRefactoringPresenterFactory _factory; private ExtractInterfaceModel _model; - public ExtractInterfaceRefactoring(IVBE vbe, IMessageBox messageBox, IRefactoringPresenterFactory factory) + private readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + public ExtractInterfaceRefactoring(IVBE vbe, IMessageBox messageBox, IRefactoringPresenterFactory factory, IRewritingManager rewritingManager) { _vbe = vbe; + _rewritingManager = rewritingManager; _messageBox = messageBox; _factory = factory; } @@ -86,6 +93,16 @@ public void Refactor(Declaration target) } private void AddInterface() + { + //We need to suspend here since addin the interface and rewriting will both trigger a reparse. + var suspendResult = _model.State.OnSuspendParser(this, new[] {ParserState.Ready}, AddInterfaceInternal); + if (suspendResult != SuspensionResult.Completed) + { + _logger.Warn("Extract interface failed."); + } + } + + private void AddInterfaceInternal() { var targetProject = _model.TargetDeclaration.Project; if (targetProject == null) @@ -93,7 +110,10 @@ private void AddInterface() return; //The target project is not available. } - var rewriter = _model.State.GetRewriter(_model.TargetDeclaration); + AddInterfaceClass(_model.TargetDeclaration, _model.InterfaceName, GetInterfaceModuleBody()); + + var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); + var rewriter = rewriteSession.CheckOutModuleRewriter(_model.TargetDeclaration.QualifiedModuleName); var firstNonFieldMember = _model.State.DeclarationFinder.Members(_model.TargetDeclaration) .OrderBy(o => o.Selection) @@ -102,28 +122,35 @@ private void AddInterface() AddInterfaceMembersToClass(rewriter); + //We have to reparse here already, because + rewriteSession.Rewrite(); + } + + private void AddInterfaceClass(Declaration implementingClass, string interfaceName, string interfaceBody) + { + var targetProject = implementingClass.Project; using (var components = targetProject.VBComponents) { using (var interfaceComponent = components.Add(ComponentType.ClassModule)) { using (var interfaceModule = interfaceComponent.CodeModule) { - interfaceComponent.Name = _model.InterfaceName; + interfaceComponent.Name = interfaceName; var optionPresent = interfaceModule.CountOfLines > 1; if (!optionPresent) { interfaceModule.InsertLines(1, $"{Tokens.Option} {Tokens.Explicit}{Environment.NewLine}"); } - interfaceModule.InsertLines(3, GetInterfaceModuleBody()); + interfaceModule.InsertLines(3, interfaceBody); } } } } - private void AddInterfaceMembersToClass(IExecutableModuleRewriter rewriter) + private void AddInterfaceMembersToClass(IModuleRewriter rewriter) { - var implementInterfaceRefactoring = new ImplementInterfaceRefactoring(_vbe, _model.State, _messageBox); + var implementInterfaceRefactoring = new ImplementInterfaceRefactoring(_vbe, _model.State, _messageBox, _rewritingManager); implementInterfaceRefactoring.Refactor(_model.Members.Select(m => m.Member).ToList(), rewriter, _model.InterfaceName); } diff --git a/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs b/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs index f78f800f8c..46a78d6eed 100644 --- a/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs +++ b/Rubberduck.Refactorings/ImplementInterface/ImplementInterfaceRefactoring.cs @@ -16,6 +16,7 @@ public class ImplementInterfaceRefactoring : IRefactoring { private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; private readonly List _declarations; @@ -24,10 +25,11 @@ public class ImplementInterfaceRefactoring : IRefactoring private const string MemberBody = " Err.Raise 5 'TODO implement interface member"; - public ImplementInterfaceRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public ImplementInterfaceRefactoring(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) { _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _declarations = state.AllUserDeclarations.ToList(); _messageBox = messageBox; } @@ -77,7 +79,10 @@ public void Refactor(QualifiedSelection selection) var oldSelection = _vbe.GetActiveSelection(); - ImplementMissingMembers(_state.GetRewriter(_targetClass)); + var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); + var rewriter = rewriteSession.CheckOutModuleRewriter(_targetClass.QualifiedModuleName); + ImplementMissingMembers(rewriter); + rewriteSession.Rewrite(); if (oldSelection.HasValue) { @@ -99,12 +104,12 @@ public void Refactor(Declaration target) throw new NotSupportedException(); } - internal void Refactor(List members, IExecutableModuleRewriter rewriter, string interfaceName) + internal void Refactor(List members, IModuleRewriter rewriter, string interfaceName) { AddItems(members, rewriter, interfaceName); } - private void ImplementMissingMembers(IExecutableModuleRewriter rewriter) + private void ImplementMissingMembers(IModuleRewriter rewriter) { var implemented = _targetClass.Members .Where(decl => decl is ModuleBodyElementDeclaration member && ReferenceEquals(member.InterfaceImplemented, _targetInterface)) @@ -119,14 +124,12 @@ private void ImplementMissingMembers(IExecutableModuleRewriter rewriter) AddItems(nonImplementedMembers, rewriter, _targetInterface.IdentifierName); } - private void AddItems(IEnumerable missingMembers, IExecutableModuleRewriter rewriter, string interfaceName) + private void AddItems(IEnumerable missingMembers, IModuleRewriter rewriter, string interfaceName) { var missingMembersText = missingMembers.Aggregate(string.Empty, (current, member) => current + Environment.NewLine + GetInterfaceMember(member, interfaceName)); rewriter.InsertAfter(rewriter.TokenStream.Size, Environment.NewLine + missingMembersText); - - rewriter.Rewrite(); } private string GetInterfaceMember(Declaration member, string interfaceName) diff --git a/RubberduckTests/Commands/RefactorCommandTests.cs b/RubberduckTests/Commands/RefactorCommandTests.cs index 2607a6e5ac..25484a9c1c 100644 --- a/RubberduckTests/Commands/RefactorCommandTests.cs +++ b/RubberduckTests/Commands/RefactorCommandTests.cs @@ -119,7 +119,7 @@ public void ExtractInterface_CanExecute_NullActiveCodePane() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(extractInterfaceCommand.CanExecute(null)); } } @@ -136,7 +136,7 @@ public void ExtractInterface_CanExecute_NonReadyState() { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(extractInterfaceCommand.CanExecute(null)); } } @@ -150,7 +150,7 @@ public void ExtractInterface_CanExecute_NoMembers() var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(extractInterfaceCommand.CanExecute(null)); } } @@ -169,7 +169,7 @@ public void ExtractInterface_CanExecute_Proc_StdModule() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(extractInterfaceCommand.CanExecute(null)); } } @@ -184,7 +184,7 @@ public void ExtractInterface_CanExecute_Field() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(extractInterfaceCommand.CanExecute(null)); } } @@ -219,7 +219,7 @@ End Sub var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(extractInterfaceCommand.CanExecute(null)); } } @@ -247,7 +247,7 @@ public void ExtractInterface_CanExecute_ClassWithMembers_SameNameAsClassWithMemb using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(extractInterfaceCommand.CanExecute(null)); } } @@ -266,7 +266,7 @@ public void ExtractInterface_CanExecute_Proc() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); var canExecute = extractInterfaceCommand.CanExecute(null); Assert.IsTrue(canExecute); } @@ -286,7 +286,7 @@ public void ExtractInterface_CanExecute_Function() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(extractInterfaceCommand.CanExecute(null)); } } @@ -305,7 +305,7 @@ public void ExtractInterface_CanExecute_PropertyGet() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(extractInterfaceCommand.CanExecute(null)); } } @@ -324,7 +324,7 @@ public void ExtractInterface_CanExecute_PropertyLet() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(extractInterfaceCommand.CanExecute(null)); } } @@ -343,7 +343,7 @@ public void ExtractInterface_CanExecute_PropertySet() using (state) { - var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null); + var extractInterfaceCommand = new RefactorExtractInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(extractInterfaceCommand.CanExecute(null)); } } @@ -360,7 +360,7 @@ public void ImplementInterface_CanExecute_NullActiveCodePane() using (state) { - var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null); + var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(implementInterfaceCommand.CanExecute(null)); } } @@ -377,7 +377,7 @@ public void ImplementInterface_CanExecute_NonReadyState() { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); - var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null); + var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(implementInterfaceCommand.CanExecute(null)); } } @@ -392,7 +392,7 @@ public void ImplementInterface_CanExecute_ImplementsInterfaceNotSelected() using (state) { - var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null); + var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(implementInterfaceCommand.CanExecute(null)); } } @@ -412,7 +412,7 @@ public void ImplementInterface_CanExecute_ImplementsInterfaceSelected() using (state) { - var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null); + var implementInterfaceCommand = new RefactorImplementInterfaceCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(implementInterfaceCommand.CanExecute(null)); } } diff --git a/RubberduckTests/Refactoring/ExtractInterfaceTests.cs b/RubberduckTests/Refactoring/ExtractInterfaceTests.cs index d2dda92cf7..fb66b5b9b9 100644 --- a/RubberduckTests/Refactoring/ExtractInterfaceTests.cs +++ b/RubberduckTests/Refactoring/ExtractInterfaceTests.cs @@ -50,7 +50,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -61,7 +62,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object); + var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); var actualCode = component.CodeModule.Content(); @@ -156,7 +157,8 @@ End Property IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -167,7 +169,7 @@ End Property //SetupFactory var factory = SetupFactory(model); - var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object); + var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedInterfaceCode, component.Collection[1].CodeModule.Content()); @@ -240,7 +242,8 @@ End Function IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -252,7 +255,7 @@ End Function //SetupFactory var factory = SetupFactory(model); - var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object); + var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedInterfaceCode, component.Collection[1].CodeModule.Content()); @@ -273,7 +276,8 @@ public void ExtractInterfaceRefactoring_IgnoresField() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -297,7 +301,8 @@ public void ExtractInterfaceRefactoring_NullPresenter_NoChanges() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -309,7 +314,7 @@ public void ExtractInterfaceRefactoring_NullPresenter_NoChanges() var factory = SetupFactory(model); factory.Setup(f => f.Create()).Returns(value: null); - var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object); + var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object, rewritingManager); refactoring.Refactor(); Assert.AreEqual(1, vbe.Object.ActiveVBProject.VBComponents.Count()); @@ -330,7 +335,8 @@ public void ExtractInterfaceRefactoring_NullModel_NoChanges() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -345,7 +351,7 @@ public void ExtractInterfaceRefactoring_NullModel_NoChanges() var factory = SetupFactory(model); factory.Setup(f => f.Create()).Returns(presenter.Object); - var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object); + var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object, rewritingManager); refactoring.Refactor(); Assert.AreEqual(1, vbe.Object.ActiveVBProject.VBComponents.Count()); @@ -386,7 +392,8 @@ End Sub IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -398,7 +405,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object); + var refactoring = new ExtractInterfaceRefactoring(vbe.Object, null, factory.Object, rewritingManager); refactoring.Refactor(state.AllUserDeclarations.Single(s => s.DeclarationType == DeclarationType.ClassModule)); Assert.AreEqual(expectedInterfaceCode, component.Collection[1].CodeModule.Content()); @@ -501,7 +508,7 @@ public void Factory_NullSelectionNullReturnsNullPresenter() IVBComponent component; var vbe = MockVbeBuilder.BuildFromSingleModule(inputCode, ComponentType.ClassModule, out component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + using(var state = MockParser.CreateAndParse(vbe.Object)) { vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); diff --git a/RubberduckTests/Refactoring/ImplementInterfaceTests.cs b/RubberduckTests/Refactoring/ImplementInterfaceTests.cs index f86525042a..e20ba70e4f 100644 --- a/RubberduckTests/Refactoring/ImplementInterfaceTests.cs +++ b/RubberduckTests/Refactoring/ImplementInterfaceTests.cs @@ -39,16 +39,17 @@ End Sub var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -88,16 +89,17 @@ End Sub var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -151,16 +153,16 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - var actualCode = rewriter.GetText(); + var actualCode = component.CodeModule.Content(); Assert.AreEqual(expectedCode, actualCode); } } @@ -195,16 +197,17 @@ End Sub var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -238,16 +241,17 @@ End Function var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -281,16 +285,17 @@ End Function var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -324,16 +329,17 @@ End Function var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -367,16 +373,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -410,16 +417,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -453,16 +461,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -496,16 +505,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -539,16 +549,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -582,16 +593,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -625,16 +637,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -689,16 +702,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -760,16 +774,17 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -800,16 +815,17 @@ End Sub var project = vbe.Object.VBProjects[0]; var component = project.VBComponents["Sheet1"]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -840,16 +856,17 @@ End Sub var project = vbe.Object.VBProjects[0]; var component = project.VBComponents["Form1"]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var rewriter = state.GetRewriter(component); - Assert.AreEqual(expectedCode, rewriter.GetText()); + var actualCode = component.CodeModule.Content(); + Assert.AreEqual(expectedCode, actualCode); } } @@ -884,15 +901,16 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actualCode = state.GetRewriter(component).GetText(); + var actualCode = component.CodeModule.Content(); Assert.AreEqual(expectedCode, actualCode); } } @@ -928,15 +946,16 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actualCode = state.GetRewriter(component).GetText(); + var actualCode = component.CodeModule.Content(); Assert.AreEqual(expectedCode, actualCode); } } @@ -978,15 +997,16 @@ End Property var vbe = builder.AddProject(project).Build(); var component = project.Object.VBComponents[1]; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), Selection.Home); - var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null); + var refactoring = new ImplementInterfaceRefactoring(vbe.Object, state, null, rewritingManager); refactoring.Refactor(qualifiedSelection); - var actualCode = state.GetRewriter(component).GetText(); + var actualCode = component.CodeModule.Content(); Assert.AreEqual(expectedCode, actualCode); } } From 5f5ffe725cbfa7762c9d4788de742fa17c4cf9e1 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 3 Nov 2018 14:35:32 +0100 Subject: [PATCH 052/107] Rewire the RemoveParameterRefactoring --- .../RemoveUnusedParameterQuickFix.cs | 16 +- .../RefactorRemoveParametersCommand.cs | 7 +- .../RemoveParametersRefactoring.cs | 56 ++--- .../Commands/RefactorCommandTests.cs | 228 +++++++----------- .../RemoveUnusedParameterQuickFixTests.cs | 4 +- .../Refactoring/RemoveParametersTests.cs | 166 +++++++------ 6 files changed, 213 insertions(+), 264 deletions(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs index b56fe993fa..aa02c472ad 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/RemoveUnusedParameterQuickFix.cs @@ -14,13 +14,15 @@ public sealed class RemoveUnusedParameterQuickFix : QuickFixBase { private readonly IVBE _vbe; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; private readonly IMessageBox _messageBox; - public RemoveUnusedParameterQuickFix(IVBE vbe, RubberduckParserState state, IMessageBox messageBox) + public RemoveUnusedParameterQuickFix(IVBE vbe, RubberduckParserState state, IMessageBox messageBox, IRewritingManager rewritingManager) : base(typeof(ParameterNotUsedInspection)) { _vbe = vbe; _state = state; + _rewritingManager = rewritingManager; _messageBox = messageBox; } @@ -29,8 +31,10 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio { using (var dialog = new RemoveParametersDialog(new RemoveParametersViewModel(_state))) { - var refactoring = new RemoveParametersRefactoring(_vbe, - new RemoveParametersPresenterFactory(_vbe, dialog, _state, _messageBox)); + var refactoring = new RemoveParametersRefactoring( + _vbe, + new RemoveParametersPresenterFactory(_vbe, dialog, _state, _messageBox), + _rewritingManager); refactoring.QuickFix(_state, result.QualifiedSelection); } @@ -38,8 +42,8 @@ public override void Fix(IInspectionResult result, IRewriteSession rewriteSessio public override string Description(IInspectionResult result) => Resources.Inspections.QuickFixes.RemoveUnusedParameterQuickFix; - public override bool CanFixInProcedure => true; - public override bool CanFixInModule => true; - public override bool CanFixInProject => true; + public override bool CanFixInProcedure => false; + public override bool CanFixInModule => false; + public override bool CanFixInProject => false; } } \ No newline at end of file diff --git a/Rubberduck.Core/UI/Command/Refactorings/RefactorRemoveParametersCommand.cs b/Rubberduck.Core/UI/Command/Refactorings/RefactorRemoveParametersCommand.cs index 5fc79a8236..20322bdeac 100644 --- a/Rubberduck.Core/UI/Command/Refactorings/RefactorRemoveParametersCommand.cs +++ b/Rubberduck.Core/UI/Command/Refactorings/RefactorRemoveParametersCommand.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using Rubberduck.Common; using Rubberduck.Interaction; +using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA; using Rubberduck.Refactorings.RemoveParameters; @@ -16,12 +17,14 @@ public class RefactorRemoveParametersCommand : RefactorCommandBase { private readonly IMessageBox _msgbox; private readonly RubberduckParserState _state; + private readonly IRewritingManager _rewritingManager; - public RefactorRemoveParametersCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgbox) + public RefactorRemoveParametersCommand(IVBE vbe, RubberduckParserState state, IMessageBox msgbox, IRewritingManager rewritingManager) : base (vbe) { _msgbox = msgbox; _state = state; + _rewritingManager = rewritingManager; } private static readonly DeclarationType[] ValidDeclarationTypes = @@ -75,7 +78,7 @@ protected override void OnExecute(object parameter) using (var view = new RemoveParametersDialog(new RemoveParametersViewModel(_state))) { var factory = new RemoveParametersPresenterFactory(Vbe, view, _state, _msgbox); - var refactoring = new RemoveParametersRefactoring(Vbe, factory); + var refactoring = new RemoveParametersRefactoring(Vbe, factory, _rewritingManager); refactoring.Refactor(selection.Value); } } diff --git a/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs b/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs index 0246b69023..72918de6c2 100644 --- a/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs +++ b/Rubberduck.Refactorings/RemoveParameters/RemoveParametersRefactoring.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using Antlr4.Runtime; -using Antlr4.Runtime.Tree; using Rubberduck.Common; using Rubberduck.Interaction; using Rubberduck.Parsing; @@ -20,12 +18,13 @@ public class RemoveParametersRefactoring : IRefactoring { private readonly IVBE _vbe; private readonly IRefactoringPresenterFactory _factory; + private readonly IRewritingManager _rewritingManager; private RemoveParametersModel _model; - private readonly HashSet _rewriters = new HashSet(); - public RemoveParametersRefactoring(IVBE vbe, IRefactoringPresenterFactory factory) + public RemoveParametersRefactoring(IVBE vbe, IRefactoringPresenterFactory factory, IRewritingManager rewritingManager) { _vbe = vbe; + _rewritingManager = rewritingManager; _factory = factory; } @@ -54,8 +53,6 @@ public void Refactor() pane.Selection = oldSelection.Value.Selection; } } - - _model.State.OnParseRequested(this); } public void Refactor(QualifiedSelection target) @@ -113,16 +110,15 @@ private void RemoveParameters() throw new NullReferenceException("Parameter is null"); } - AdjustReferences(_model.TargetDeclaration.References, _model.TargetDeclaration); - AdjustSignatures(); + var rewritingSession = _rewritingManager.CheckOutCodePaneSession(); - foreach (var rewriter in _rewriters) - { - rewriter.Rewrite(); - } + AdjustReferences(_model.TargetDeclaration.References, _model.TargetDeclaration, rewritingSession); + AdjustSignatures(rewritingSession); + + rewritingSession.Rewrite(); } - private void AdjustReferences(IEnumerable references, Declaration method) + private void AdjustReferences(IEnumerable references, Declaration method, IRewriteSession rewriteSession) { foreach (var reference in references.Where(item => item.Context != method.Context)) { @@ -158,14 +154,13 @@ private void AdjustReferences(IEnumerable references, Decla continue; } - RemoveCallArguments(argumentList, reference.QualifiedModuleName); + RemoveCallArguments(argumentList, reference.QualifiedModuleName, rewriteSession); } } - private void RemoveCallArguments(VBAParser.ArgumentListContext argList, QualifiedModuleName module) + private void RemoveCallArguments(VBAParser.ArgumentListContext argList, QualifiedModuleName module, IRewriteSession rewriteSession) { - var rewriter = _model.State.GetRewriter(module); - _rewriters.Add(rewriter); + var rewriter = rewriteSession.CheckOutModuleRewriter(module); var usesNamedArguments = false; var args = argList.children.OfType().ToList(); @@ -211,7 +206,7 @@ private void RemoveCallArguments(VBAParser.ArgumentListContext argList, Qualifie RemoveTrailingComma(rewriter, argList, usesNamedArguments); } - private void AdjustSignatures() + private void AdjustSignatures(IRewriteSession rewriteSession) { // if we are adjusting a property getter, check if we need to adjust the letter/setter too if (_model.TargetDeclaration.DeclarationType == DeclarationType.PropertyGet) @@ -219,19 +214,19 @@ private void AdjustSignatures() var setter = GetLetterOrSetter(_model.TargetDeclaration, DeclarationType.PropertySet); if (setter != null) { - RemoveSignatureParameters(setter); - AdjustReferences(setter.References, setter); + RemoveSignatureParameters(setter, rewriteSession); + AdjustReferences(setter.References, setter, rewriteSession); } var letter = GetLetterOrSetter(_model.TargetDeclaration, DeclarationType.PropertyLet); if (letter != null) { - RemoveSignatureParameters(letter); - AdjustReferences(letter.References, letter); + RemoveSignatureParameters(letter, rewriteSession); + AdjustReferences(letter.References, letter, rewriteSession); } } - RemoveSignatureParameters(_model.TargetDeclaration); + RemoveSignatureParameters(_model.TargetDeclaration, rewriteSession); var eventImplementations = _model.Declarations .Where(item => item.IsWithEvents && item.AsTypeName == _model.TargetDeclaration.ComponentName) @@ -239,8 +234,8 @@ private void AdjustSignatures() foreach (var eventImplementation in eventImplementations) { - AdjustReferences(eventImplementation.References, eventImplementation); - RemoveSignatureParameters(eventImplementation); + AdjustReferences(eventImplementation.References, eventImplementation, rewriteSession); + RemoveSignatureParameters(eventImplementation, rewriteSession); } var interfaceImplementations = _model.State.DeclarationFinder.FindAllInterfaceImplementingMembers().Where(item => @@ -250,8 +245,8 @@ private void AdjustSignatures() foreach (var interfaceImplentation in interfaceImplementations) { - AdjustReferences(interfaceImplentation.References, interfaceImplentation); - RemoveSignatureParameters(interfaceImplentation); + AdjustReferences(interfaceImplentation.References, interfaceImplentation, rewriteSession); + RemoveSignatureParameters(interfaceImplentation, rewriteSession); } } @@ -262,9 +257,9 @@ private Declaration GetLetterOrSetter(Declaration declaration, DeclarationType d && item.DeclarationType == declarationType); } - private void RemoveSignatureParameters(Declaration target) + private void RemoveSignatureParameters(Declaration target, IRewriteSession rewriteSession) { - var rewriter = _model.State.GetRewriter(target); + var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName); var parameters = ((IParameterizedDeclaration)target).Parameters.OrderBy(o => o.Selection).ToList(); @@ -274,13 +269,12 @@ private void RemoveSignatureParameters(Declaration target) } RemoveTrailingComma(rewriter); - _rewriters.Add(rewriter); } //Issue 4319. If there are 3 or more arguments and the user elects to remove 2 or more of //the last arguments, then we need to specifically remove the trailing comma from //the last 'kept' argument. - private void RemoveTrailingComma(IExecutableModuleRewriter rewriter, VBAParser.ArgumentListContext argList = null, bool usesNamedParams = false) + private void RemoveTrailingComma(IModuleRewriter rewriter, VBAParser.ArgumentListContext argList = null, bool usesNamedParams = false) { var commaLocator = RetrieveTrailingCommaInfo(_model.RemoveParameters, _model.Parameters); if (!commaLocator.RequiresTrailingCommaRemoval) diff --git a/RubberduckTests/Commands/RefactorCommandTests.cs b/RubberduckTests/Commands/RefactorCommandTests.cs index 25484a9c1c..1586c4b72d 100644 --- a/RubberduckTests/Commands/RefactorCommandTests.cs +++ b/RubberduckTests/Commands/RefactorCommandTests.cs @@ -18,8 +18,7 @@ public class RefactorCommandTests [Test] public void EncapsulateField_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); @@ -35,8 +34,7 @@ public void EncapsulateField_CanExecute_NullActiveCodePane() [Test] public void EncapsulateField_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -56,8 +54,7 @@ public void EncapsulateField_CanExecute_LocalVariable() Dim d As Boolean End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 9, 2, 9)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(2, 9, 2, 9)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -76,8 +73,7 @@ public void EncapsulateField_CanExecute_Proc() Sub Foo() End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 7, 2, 7)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(2, 7, 2, 7)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -96,8 +92,7 @@ public void EncapsulateField_CanExecute_Field() Sub Foo() End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 5, 1, 5)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 5, 1, 5)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -111,8 +106,7 @@ Sub Foo() [Test] public void ExtractInterface_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); @@ -128,8 +122,7 @@ public void ExtractInterface_CanExecute_NullActiveCodePane() [Test] public void ExtractInterface_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule(string.Empty, ComponentType.ClassModule, out component, new Selection()); + var vbe = MockVbeBuilder.BuildFromSingleModule(string.Empty, ComponentType.ClassModule, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -145,8 +138,7 @@ public void ExtractInterface_CanExecute_NonReadyState() [Test] public void ExtractInterface_CanExecute_NoMembers() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule("Option Explicit", ComponentType.ClassModule, out component, new Selection()); + var vbe = MockVbeBuilder.BuildFromSingleModule("Option Explicit", ComponentType.ClassModule, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -163,8 +155,7 @@ public void ExtractInterface_CanExecute_Proc_StdModule() @"Sub foo() End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -178,8 +169,7 @@ public void ExtractInterface_CanExecute_Proc_StdModule() [Test] public void ExtractInterface_CanExecute_Field() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule("Dim d As Boolean", ComponentType.ClassModule, out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleModule("Dim d As Boolean", ComponentType.ClassModule, out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -260,8 +250,7 @@ public void ExtractInterface_CanExecute_Proc() @"Sub foo() End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -280,8 +269,7 @@ public void ExtractInterface_CanExecute_Function() @"Function foo() As Integer End Function"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -299,8 +287,7 @@ public void ExtractInterface_CanExecute_PropertyGet() @"Property Get foo() As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -318,8 +305,7 @@ public void ExtractInterface_CanExecute_PropertyLet() @"Property Let foo(value) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -337,8 +323,7 @@ public void ExtractInterface_CanExecute_PropertySet() @"Property Set foo(value) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleModule(input, ComponentType.ClassModule, out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -352,8 +337,7 @@ public void ExtractInterface_CanExecute_PropertySet() [Test] public void ImplementInterface_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); @@ -369,8 +353,7 @@ public void ImplementInterface_CanExecute_NullActiveCodePane() [Test] public void ImplementInterface_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -386,8 +369,7 @@ public void ImplementInterface_CanExecute_NonReadyState() [Test] public void ImplementInterface_CanExecute_ImplementsInterfaceNotSelected() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleModule(string.Empty, ComponentType.ClassModule, out component, new Selection()); + var vbe = MockVbeBuilder.BuildFromSingleModule(string.Empty, ComponentType.ClassModule, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -421,8 +403,7 @@ public void ImplementInterface_CanExecute_ImplementsInterfaceSelected() [Test] public void IntroduceField_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -438,8 +419,7 @@ public void IntroduceField_CanExecute_NullActiveCodePane() [Test] public void IntroduceField_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -456,8 +436,7 @@ public void IntroduceField_CanExecute_NonReadyState() [Test] public void IntroduceField_CanExecute_Field() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -477,8 +456,7 @@ public void IntroduceField_CanExecute_LocalVariable() Dim d As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(2, 10, 2, 10)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -493,8 +471,7 @@ Dim d As Boolean [Test] public void IntroduceParameter_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -510,8 +487,7 @@ public void IntroduceParameter_CanExecute_NullActiveCodePane() [Test] public void IntroduceParameter_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -528,8 +504,7 @@ public void IntroduceParameter_CanExecute_NonReadyState() [Test] public void IntroduceParameter_CanExecute_Field() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -549,8 +524,7 @@ public void IntroduceParameter_CanExecute_LocalVariable() Dim d As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(2, 10, 2, 10)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -565,14 +539,13 @@ Dim d As Boolean [Test] public void MoveCloserToUsage_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -581,8 +554,7 @@ public void MoveCloserToUsage_CanExecute_NullActiveCodePane() [Test] public void MoveCloserToUsage_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -598,13 +570,12 @@ public void MoveCloserToUsage_CanExecute_NonReadyState() [Test] public void MoveCloserToUsage_CanExecute_Field_NoReferences() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Dim d As Boolean", out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -618,13 +589,12 @@ public void MoveCloserToUsage_CanExecute_LocalVariable_NoReferences() Dim d As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(2, 10, 2, 10)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -633,13 +603,12 @@ Dim d As Boolean [Test] public void MoveCloserToUsage_CanExecute_Const_NoReferences() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Private Const const_abc = 0", out component, Selection.Home); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule("Private Const const_abc = 0", out _, Selection.Home); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(moveCloserToUsageCommand.CanExecute(null)); } } @@ -654,13 +623,12 @@ Sub Foo() d = True End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 5, 1, 5)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 5, 1, 5)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(moveCloserToUsageCommand.CanExecute(null)); } } @@ -675,13 +643,12 @@ Dim d As Boolean d = True End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(2, 10, 2, 10)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(2, 10, 2, 10)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(moveCloserToUsageCommand.CanExecute(null)); } } @@ -697,13 +664,12 @@ Dim d As Integer d = const_abc End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 17, 1, 17)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 17, 1, 17)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); + var moveCloserToUsageCommand = new RefactorMoveCloserToUsageCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(moveCloserToUsageCommand.CanExecute(null)); } } @@ -712,14 +678,13 @@ Dim d As Integer [Test] public void RemoveParameters_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -728,15 +693,14 @@ public void RemoveParameters_CanExecute_NullActiveCodePane() [Test] public void RemoveParameters_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { state.SetStatusAndFireStateChanged(this, ParserState.ResolvedDeclarations, CancellationToken.None); - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -748,13 +712,12 @@ public void RemoveParameters_CanExecute_Event_NoParams() const string input = @"Public Event Foo()"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -767,13 +730,12 @@ public void RemoveParameters_CanExecute_Proc_NoParams() @"Sub foo() End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 6, 1, 6)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -786,13 +748,12 @@ public void RemoveParameters_CanExecute_Function_NoParams() @"Function foo() As Integer End Function"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 11, 1, 11)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -805,13 +766,12 @@ public void RemoveParameters_CanExecute_PropertyGet_NoParams() @"Property Get foo() As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -824,13 +784,12 @@ public void RemoveParameters_CanExecute_PropertyLet_OneParam() @"Property Let foo(value) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -843,13 +802,12 @@ public void RemoveParameters_CanExecute_PropertySet_OneParam() @"Property Set foo(value) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsFalse(removeParametersCommand.CanExecute(null)); } } @@ -861,13 +819,12 @@ public void RemoveParameters_CanExecute_Event_OneParam() const string input = @"Public Event Foo(value)"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(removeParametersCommand.CanExecute(null)); } } @@ -880,13 +837,12 @@ public void RemoveParameters_CanExecute_Proc_OneParam() @"Sub foo(value) End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 6, 1, 6)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(removeParametersCommand.CanExecute(null)); } } @@ -899,13 +855,12 @@ public void RemoveParameters_CanExecute_Function_OneParam() @"Function foo(value) As Integer End Function"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 11, 1, 11)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(removeParametersCommand.CanExecute(null)); } } @@ -918,13 +873,12 @@ public void RemoveParameters_CanExecute_PropertyGet_OneParam() @"Property Get foo(value) As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(removeParametersCommand.CanExecute(null)); } } @@ -937,13 +891,12 @@ public void RemoveParameters_CanExecute_PropertyLet_TwoParams() @"Property Let foo(value1, value2) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(removeParametersCommand.CanExecute(null)); } } @@ -956,13 +909,12 @@ public void RemoveParameters_CanExecute_PropertySet_TwoParams() @"Property Set foo(value1, value2) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { - var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null); + var removeParametersCommand = new RefactorRemoveParametersCommand(vbe.Object, state, null, rewritingManager); Assert.IsTrue(removeParametersCommand.CanExecute(null)); } } @@ -971,8 +923,7 @@ public void RemoveParameters_CanExecute_PropertySet_TwoParams() [Test] public void ReorderParameters_CanExecute_NullActiveCodePane() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); vbe.Setup(v => v.ActiveCodePane).Returns((ICodePane)null); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -987,8 +938,7 @@ public void ReorderParameters_CanExecute_NullActiveCodePane() [Test] public void ReorderParameters_CanExecute_NonReadyState() { - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(string.Empty, out _); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) @@ -1007,8 +957,7 @@ public void ReorderParameters_CanExecute_Event_OneParam() const string input = @"Public Event Foo(value)"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1026,8 +975,7 @@ public void ReorderParameters_CanExecute_Proc_OneParam() @"Sub foo(value) End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 6, 1, 6)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1045,8 +993,7 @@ public void ReorderParameters_CanExecute_Function_OneParam() @"Function foo(value) As Integer End Function"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 11, 1, 11)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1064,8 +1011,7 @@ public void ReorderParameters_CanExecute_PropertyGet_OneParam() @"Property Get foo(value) As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1083,8 +1029,7 @@ public void ReorderParameters_CanExecute_PropertyLet_TwoParams() @"Property Let foo(value1, value2) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1102,8 +1047,7 @@ public void ReorderParameters_CanExecute_PropertySet_TwoParams() @"Property Set foo(value1, value2) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1120,8 +1064,7 @@ public void ReorderParameters_CanExecute_Event_TwoParams() const string input = @"Public Event Foo(value1, value2)"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1139,8 +1082,7 @@ public void ReorderParameters_CanExecute_Proc_TwoParams() @"Sub foo(value1, value2) End Sub"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 6, 1, 6)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 6, 1, 6)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1158,8 +1100,7 @@ public void ReorderParameters_CanExecute_Function_TwoParams() @"Function foo(value1, value2) As Integer End Function"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 11, 1, 11)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 11, 1, 11)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1177,8 +1118,7 @@ public void ReorderParameters_CanExecute_PropertyGet_TwoParams() @"Property Get foo(value1, value2) As Boolean End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1196,8 +1136,7 @@ public void ReorderParameters_CanExecute_PropertyLet_ThreeParams() @"Property Let foo(value1, value2, value3) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { @@ -1215,8 +1154,7 @@ public void ReorderParameters_CanExecute_PropertySet_ThreeParams() @"Property Set foo(value1, value2, value3) End Property"; - IVBComponent component; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out component, new Selection(1, 16, 1, 16)); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(input, out _, new Selection(1, 16, 1, 16)); var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); using (state) { diff --git a/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs b/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs index 3440580bbd..d2d618d14d 100644 --- a/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs +++ b/RubberduckTests/QuickFixes/RemoveUnusedParameterQuickFixTests.cs @@ -34,8 +34,8 @@ Private Sub Foo() var inspectionResults = inspection.GetInspectionResults(CancellationToken.None); var rewriteSession = rewritingManager.CheckOutCodePaneSession(); - new RemoveUnusedParameterQuickFix(vbe.Object, state, new Mock().Object).Fix( - inspectionResults.First(), rewriteSession); + new RemoveUnusedParameterQuickFix(vbe.Object, state, new Mock().Object, rewritingManager) + .Fix(inspectionResults.First(), rewriteSession); Assert.AreEqual(expectedCode, component.CodeModule.Content()); } diff --git a/RubberduckTests/Refactoring/RemoveParametersTests.cs b/RubberduckTests/Refactoring/RemoveParametersTests.cs index 3c7780195b..4536d7b923 100644 --- a/RubberduckTests/Refactoring/RemoveParametersTests.cs +++ b/RubberduckTests/Refactoring/RemoveParametersTests.cs @@ -75,11 +75,11 @@ public void RemoveParametersRefactoring_SignatureParamRemoval(int numParams, str expect = expect.Equals(preamble) ? expect : expect.Remove(expect.Length - 2); expect = expect + ")"; - string inputCode = + var inputCode = $@"{input} End Sub"; - string expectedCode = + var expectedCode = $@"{expect} End Sub"; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); @@ -100,8 +100,8 @@ public void RemoveParametersRefactoring_SignatureParamRemoval(int numParams, str [Category("Remove Parameters")] public void RemoveParametersRefactoring_SignatureAndReferenceParamRemoval(int numParams, string paramsToRemove) { - var preamble = "Private Sub Foo("; - var refPreamble = "Foo "; + const string preamble = "Private Sub Foo("; + const string refPreamble = "Foo "; var input = preamble; var refInput = refPreamble; for (var argNum = 1; argNum <= numParams; argNum++) @@ -135,7 +135,7 @@ public void RemoveParametersRefactoring_SignatureAndReferenceParamRemoval(int nu expect = expect + ")"; refExpect = refExpect.Equals(refPreamble) ? refExpect : refExpect.Remove(refExpect.Length - 1); - string inputCode = + var inputCode = $@"{input} End Sub @@ -147,7 +147,7 @@ Private Sub AnotherBar() {refInput} End Sub"; - string expectedCode = + var expectedCode = $@"{expect} End Sub @@ -184,7 +184,7 @@ Public Sub Goo() End Sub "; - var userParamRemovalChoices = new int[] { 1, 2, 3 }; + var userParamRemovalChoices = new[] { 1, 2, 3 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -212,7 +212,7 @@ Public Sub Goo() End Sub "; - var userParamRemovalChoices = new int[] { 1, 2 }; + var userParamRemovalChoices = new[] { 1, 2 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -240,7 +240,7 @@ Public Sub Goo() End Sub "; - var userParamRemovalChoices = new int[] { 2 }; + var userParamRemovalChoices = new[] { 2 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -267,7 +267,7 @@ Sub goo() foo asd, sdf End Sub"; - var userParamRemovalChoices = new int[] { 2 }; + var userParamRemovalChoices = new[] { 2 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -286,7 +286,7 @@ public void RemoveParametersRefactoring_RemoveLastFromFunction() @"Private Function Foo(ByVal arg1 As Integer) As Boolean End Function"; - var userParamRemovalChoices = new int[] { 1 }; + var userParamRemovalChoices = new[] { 1 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -315,7 +315,7 @@ public void RemoveParametersRefactoring_RemoveAllFromFunction() [Category("Remove Parameters")] public void RemoveParametersRefactoring_RemoveAllFromFunction_UpdateCallReferences(string input, string expected) { - string inputCode = + var inputCode = $@"Private Function Foo(ByVal ar|g1 As Integer, ByVal arg2 As String) As Boolean End Function @@ -325,7 +325,7 @@ Dim test As Boolean End Sub "; - string expectedCode = + var expectedCode = $@"Private Function Foo() As Boolean End Function @@ -362,7 +362,7 @@ Foo arg1 End Sub "; - var userParamRemovalChoices = new int[] { 1,2 }; + var userParamRemovalChoices = new[] { 1,2 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -389,7 +389,7 @@ Private Sub goo() foo 1, 2, 5, 7 End Sub"; - var userParamRemovalChoices = new int[] {2,3,5}; + var userParamRemovalChoices = new[] {2,3,5}; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -433,7 +433,7 @@ Private Property Get Foo(ByVal arg1 As Integer, arg2 As Integer, arg3 As Integer Private Property Get Foo(ByVal arg1 As Integer, arg3 As Integer) As Integer End Property"; - var userParamRemovalChoices = new int[] { 1 }; + var userParamRemovalChoices = new[] { 1 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -452,8 +452,9 @@ Private Property Set Foo(ByVal arg1 As Integer, ByVal arg2 As String) Private Property Set Foo(ByVal arg2 As String) End Property"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var parameter = state.AllUserDeclarations.SingleOrDefault(p => @@ -468,7 +469,7 @@ Private Property Set Foo(ByVal arg2 As String) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.QuickFix(state, qualifiedSelection); Assert.AreEqual(expectedCode, component.CodeModule.Content()); @@ -488,7 +489,7 @@ public void RemoveParametersRefactoring_RemoveFirstParamFromSetter() @"Private Property Set Foo(ByVal arg2 As String) End Property"; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -517,7 +518,7 @@ Private Sub Bar() End Sub "; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -550,7 +551,7 @@ Dim x As Variant End Sub "; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -586,7 +587,7 @@ Private Function foo(ByVal b As Integer) As Integer foo = a + b End Function"; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -615,7 +616,7 @@ Foo 10 End Sub "; - var userParamRemovalChoices = new int[] { 1 }; + var userParamRemovalChoices = new[] { 1 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -654,7 +655,8 @@ End Sub var declaringComponent = projectBuilder.MockComponents[0].Object; var callingComponent = projectBuilder.MockComponents[1].Object; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(declaringComponent), selection); @@ -666,7 +668,7 @@ End Sub //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); var resultCallingCode = callingComponent.CodeModule.Content(); @@ -709,7 +711,7 @@ Public Sub Goo(ByVal arg1 As Integer, _ End Sub "; - var userParamRemovalChoices = new int[] { 1 }; + var userParamRemovalChoices = new[] { 1 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -750,7 +752,7 @@ Public Sub Goo(ByVal arg1 As Integer, _ End Sub "; - var userParamRemovalChoices = new int[] { 1,2 }; + var userParamRemovalChoices = new[] { 1,2 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -767,7 +769,7 @@ public void RemoveParametersRefactoring_RemoveLastParamFromSetter_NotAllowed() End Property"; var selection = new Selection(1, 23, 1, 27); - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); using (var state = MockParser.CreateAndParse(vbe.Object)) { @@ -790,7 +792,7 @@ public void RemoveParametersRefactoring_RemoveLastParamFromLetter_NotAllowed() End Property"; var selection = new Selection(1, 23, 1, 27); - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); using (var state = MockParser.CreateAndParse(vbe.Object)) { @@ -821,7 +823,7 @@ End Property Private Property Set Foo(ByVal arg2 As String) End Property"; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -846,7 +848,7 @@ End Property Private Property Let Foo(ByVal arg2 As String) End Property"; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -873,7 +875,7 @@ Private Sub Goo(ByVal arg1 As Integer) Foo End Sub"; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -902,7 +904,7 @@ Foo arg1 Foo 1 End Sub"; - var userParamRemovalChoices = new int[] { 1 }; + var userParamRemovalChoices = new[] { 1 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -933,7 +935,7 @@ Private Sub Goo(ByVal arg1 As Integer) Foo ""test"" End Sub"; - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -972,7 +974,7 @@ Foo 1 Foo ,3 End Sub"; - var userParamRemovalChoices = new int[] { 1 }; + var userParamRemovalChoices = new[] { 1 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -994,7 +996,7 @@ public void RemoveParametersRefactoring_SignatureOnMultipleLines() ByVal arg3 As Date) End Sub"; // note: VBE removes excess spaces - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -1016,7 +1018,7 @@ public void RemoveParametersRefactoring_SignatureOnMultipleLines_RemoveSecond() ByVal arg3 As Date) End Sub"; // note: VBE removes excess spaces - var userParamRemovalChoices = new int[] { 1 }; + var userParamRemovalChoices = new[] { 1 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -1039,7 +1041,7 @@ public void RemoveParametersRefactoring_SignatureOnMultipleLines_RemoveLast() ByVal arg2 As String) End Sub"; // note: VBE removes excess spaces - var userParamRemovalChoices = new int[] { 2 }; + var userParamRemovalChoices = new[] { 2 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -1061,7 +1063,7 @@ public void RemoveParametersRefactoring_PassTargetIn() ByVal arg3 As Date) End Sub"; // note: VBE removes excess spaces - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -1097,7 +1099,7 @@ Private Sub Goo(ByVal arg1 as Integer, ByVal arg2 As String, ByVal arg3 As Date) End Sub "; // note: IDE removes excess spaces - var userParamRemovalChoices = new int[] { 0 }; + var userParamRemovalChoices = new[] { 0 }; var actual = RemoveParams(inputCode, paramIndices: userParamRemovalChoices); Assert.AreEqual(expectedCode, actual); @@ -1137,7 +1139,8 @@ Private Sub IClass1_DoSomething(ByVal a As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1151,7 +1154,7 @@ Private Sub IClass1_DoSomething(ByVal a As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1193,7 +1196,8 @@ Private Sub IClass1_DoSomething(ByVal v1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1207,7 +1211,7 @@ Private Sub IClass1_DoSomething(ByVal v1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1260,7 +1264,8 @@ Private Sub IClass1_DoSomething(ByVal i As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1275,7 +1280,7 @@ Private Sub IClass1_DoSomething(ByVal i As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1318,7 +1323,8 @@ Private Sub abc_Foo(ByVal arg1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1332,7 +1338,7 @@ Private Sub abc_Foo(ByVal arg1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1374,7 +1380,8 @@ Private Sub abc_Foo(ByVal arg1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1388,7 +1395,7 @@ Private Sub abc_Foo(ByVal arg1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1430,7 +1437,8 @@ Private Sub abc_Foo(ByVal i As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1444,7 +1452,7 @@ Private Sub abc_Foo(ByVal i As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1497,7 +1505,8 @@ Private Sub abc_Foo(ByVal v1 As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1512,7 +1521,7 @@ Private Sub abc_Foo(ByVal v1 As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1556,7 +1565,8 @@ Private Sub IClass1_DoSomething(ByVal a As Integer) .Build(); var vbe = builder.AddProject(project).Build(); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(project.Object.VBComponents[0]), selection); @@ -1573,7 +1583,7 @@ Private Sub IClass1_DoSomething(ByVal a As Integer) //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(expectedCode1, module1.Content()); @@ -1629,9 +1639,10 @@ public void RemoveParams_RefactorDeclaration_FailsInvalidTarget() End Sub"; var selection = new Selection(1, 23, 1, 27); - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -1640,7 +1651,7 @@ public void RemoveParams_RefactorDeclaration_FailsInvalidTarget() var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); try { @@ -1668,13 +1679,14 @@ public void RemoveParams_PresenterIsNull() @"Private Sub Foo() End Sub"; - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var factory = new RemoveParametersPresenterFactory(vbe.Object, null, state, null); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory, rewritingManager); refactoring.Refactor(); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -1692,9 +1704,10 @@ public void RemoveParams_ModelIsNull() End Sub"; var selection = new Selection(1, 23, 1, 27); - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -1704,7 +1717,7 @@ public void RemoveParams_ModelIsNull() //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); refactoring.Refactor(qualifiedSelection); Assert.AreEqual(inputCode, component.CodeModule.Content()); @@ -1722,9 +1735,9 @@ public void Presenter_Accept_AutoMarksSingleParamAsRemoved() End Sub"; var selection = new Selection(1, 15, 1, 15); - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out IVBComponent component, selection); + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component, selection); - using (var state = MockParser.CreateAndParse(vbe.Object)) + using(var state = MockParser.CreateAndParse(vbe.Object)) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection); @@ -1793,23 +1806,20 @@ public void Factory_NullSelectionNullReturnsNullPresenter() } } - private string RemoveParams(string inputCode, bool passInTarget = false, Selection? selection = null, IEnumerable paramIndices = null) + private static string RemoveParams(string inputCode, bool passInTarget = false, Selection? selection = null, IEnumerable paramIndices = null) { var codeString = inputCode.ToCodeString(); if (!selection.HasValue) { - Selection? derivedSelect = codeString.CaretPosition.ToOneBased(); + var derivedSelect = codeString.CaretPosition.ToOneBased(); - if (!derivedSelect.HasValue) - { - Assert.Fail($"Unable to derive user selection for test"); - } selection = derivedSelect; } - var vbe = MockVbeBuilder.BuildFromSingleStandardModule(codeString.Code, out IVBComponent component, selection.Value); - var result = string.Empty; - using (var state = MockParser.CreateAndParse(vbe.Object)) + var vbe = MockVbeBuilder.BuildFromSingleStandardModule(codeString.Code, out var component, selection.Value); + string result; + var (state, rewritingManager) = MockParser.CreateAndParseWithRewritingManager(vbe.Object); + using(state) { var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection.Value); @@ -1832,7 +1842,7 @@ private string RemoveParams(string inputCode, bool passInTarget = false, Selecti //SetupFactory var factory = SetupFactory(model); - var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object); + var refactoring = new RemoveParametersRefactoring(vbe.Object, factory.Object, rewritingManager); if (passInTarget) { refactoring.Refactor(model.TargetDeclaration); From f22b5cc25790e910e296cde98c72bc0fded8d27a Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 3 Nov 2018 14:58:43 +0100 Subject: [PATCH 053/107] Remove the rewriters from the ModuleStates and RubberduckParserState All interaction with rewriters is to go through an IRewriteSession in the future, which is acquired from an IRewritingManager. --- Rubberduck.API/VBA/Parser.cs | 15 ++------ Rubberduck.Parsing/VBA/ModuleState.cs | 15 -------- .../VBA/RubberduckParserState.cs | 37 +------------------ .../CodeExplorer/CodeExplorerTests.cs | 10 +---- RubberduckTests/Mocks/MockParser.cs | 12 +----- .../ArgumentRewriterInfoFinderTests.cs | 32 +++++++++------- .../ConstantRewriterInfoFinderTests.cs | 16 ++++---- .../ParameterRewriterInfoFinderTests.cs | 16 ++++---- .../VariableRewriterInfoFinderTests.cs | 16 ++++---- 9 files changed, 54 insertions(+), 115 deletions(-) diff --git a/Rubberduck.API/VBA/Parser.cs b/Rubberduck.API/VBA/Parser.cs index 9c6f52ec1e..7b24f41100 100644 --- a/Rubberduck.API/VBA/Parser.cs +++ b/Rubberduck.API/VBA/Parser.cs @@ -94,17 +94,8 @@ internal Parser(object vbe) : this() _vbeEvents = VBEEvents.Initialize(_vbe); var declarationFinderFactory = new ConcurrentlyConstructedDeclarationFinderFactory(); var projectRepository = new ProjectsRepository(_vbe); - - var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); - var sourceFileHandler = _vbe.TempSourceFileHandler; - var attributesSourceCodeHandler = new SourceFileHandlerSourceCodeHandlerAdapter(sourceFileHandler, projectRepository); - var moduleRewriterFactory = new ModuleRewriterFactory( - codePaneSourceCodeHandler, - attributesSourceCodeHandler); - - _state = new RubberduckParserState(_vbe, projectRepository, declarationFinderFactory, _vbeEvents, moduleRewriterFactory); + _state = new RubberduckParserState(_vbe, projectRepository, declarationFinderFactory, _vbeEvents); _state.StateChanged += _state_StateChanged; - var vbeVersion = double.Parse(_vbe.Version, CultureInfo.InvariantCulture); var predefinedCompilationConstants = new VBAPredefinedCompilationConstants(vbeVersion); var typeLibProvider = new TypeLibWrapperProvider(projectRepository); @@ -136,7 +127,9 @@ internal Parser(object vbe) : this() //new RubberduckApiDeclarations(_state) } ); - + var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); + var sourceFileHandler = _vbe.TempSourceFileHandler; + var attributesSourceCodeHandler = new SourceFileHandlerSourceCodeHandlerAdapter(sourceFileHandler, projectRepository); var moduleParser = new ModuleParser( codePaneSourceCodeHandler, attributesSourceCodeHandler, diff --git a/Rubberduck.Parsing/VBA/ModuleState.cs b/Rubberduck.Parsing/VBA/ModuleState.cs index 3762f665bf..27eedbcfe1 100644 --- a/Rubberduck.Parsing/VBA/ModuleState.cs +++ b/Rubberduck.Parsing/VBA/ModuleState.cs @@ -4,7 +4,6 @@ using Antlr4.Runtime; using Antlr4.Runtime.Tree; using Rubberduck.Parsing.Annotations; -using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.Symbols; using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.Parsing.VBA.Parsing.ParsingExceptions; @@ -17,8 +16,6 @@ public class ModuleState public ConcurrentDictionary UnresolvedMemberDeclarations { get; private set; } public ITokenStream CodePaneTokenStream { get; private set; } public ITokenStream AttributesTokenStream { get; private set; } - public IExecutableModuleRewriter CodePaneRewriter { get; private set; } - public IExecutableModuleRewriter AttributesRewriter { get; private set; } public IParseTree ParseTree { get; private set; } public IParseTree AttributesPassParseTree { get; private set; } public ParserState State { get; private set; } @@ -86,12 +83,6 @@ public ModuleState SetCodePaneTokenStream(ITokenStream codePaneTokenStream) return this; } - public ModuleState SetCodePaneRewriter(IExecutableModuleRewriter codePaneRewriter) - { - CodePaneRewriter = codePaneRewriter; - return this; - } - public ModuleState SetParseTree(IParseTree parseTree, CodeKind codeKind) { switch (codeKind) @@ -157,12 +148,6 @@ public ModuleState SetAttributesTokenStream(ITokenStream attributesTokenStream) return this; } - public ModuleState SetAttributesRewriter(IExecutableModuleRewriter attributesRewriter) - { - AttributesRewriter = attributesRewriter; - return this; - } - private bool _isDisposed; public void Dispose() diff --git a/Rubberduck.Parsing/VBA/RubberduckParserState.cs b/Rubberduck.Parsing/VBA/RubberduckParserState.cs index 7457b85d12..3426bb5ad4 100644 --- a/Rubberduck.Parsing/VBA/RubberduckParserState.cs +++ b/Rubberduck.Parsing/VBA/RubberduckParserState.cs @@ -144,12 +144,10 @@ public sealed class RubberduckParserState : IDisposable, IDeclarationFinderProvi private readonly IVBEEvents _vbeEvents; private readonly IHostApplication _hostApp; private readonly IDeclarationFinderFactory _declarationFinderFactory; - //TODO: Remove this again in a later PR when all rewriters get acquired via IRewriteSessions. - private readonly IModuleRewriterFactory _moduleRewriterFactory; /// Provides event handling from the VBE. Static method must be already called prior to constructing the method. [SuppressMessage("ReSharper", "JoinNullCheckWithUsage")] - public RubberduckParserState(IVBE vbe, IProjectsRepository projectRepository, IDeclarationFinderFactory declarationFinderFactory, IVBEEvents vbeEvents, IModuleRewriterFactory moduleRewriterFactory) + public RubberduckParserState(IVBE vbe, IProjectsRepository projectRepository, IDeclarationFinderFactory declarationFinderFactory, IVBEEvents vbeEvents) { if (vbe == null) { @@ -171,15 +169,9 @@ public RubberduckParserState(IVBE vbe, IProjectsRepository projectRepository, ID throw new ArgumentNullException(nameof(vbeEvents)); } - if (moduleRewriterFactory == null) - { - throw new ArgumentNullException(nameof(moduleRewriterFactory)); - } - _vbe = vbe; _projectRepository = projectRepository; _declarationFinderFactory = declarationFinderFactory; - _moduleRewriterFactory = moduleRewriterFactory; _vbeEvents = vbeEvents; var values = Enum.GetValues(typeof(ParserState)); @@ -854,9 +846,6 @@ private bool RemoveKeysFromCollections(IEnumerable keys) public void SetCodePaneTokenStream(QualifiedModuleName module, ITokenStream codePaneTokenStream) { _moduleStates[module].SetCodePaneTokenStream(codePaneTokenStream); - - var rewriter = _moduleRewriterFactory.CodePaneRewriter(module, codePaneTokenStream); - _moduleStates[module].SetCodePaneRewriter(rewriter); } public void SaveContentHash(QualifiedModuleName module) @@ -939,27 +928,6 @@ public bool IsDirty() return false; } - public IExecutableModuleRewriter GetRewriter(IVBComponent component) - { - return GetRewriter(component.QualifiedModuleName); - } - - public IExecutableModuleRewriter GetRewriter(QualifiedModuleName qualifiedModuleName) - { - return _moduleStates[qualifiedModuleName].CodePaneRewriter; - } - - public IExecutableModuleRewriter GetRewriter(Declaration declaration) - { - var qualifiedModuleName = declaration.QualifiedSelection.QualifiedName; - return GetRewriter(qualifiedModuleName); - } - - public IExecutableModuleRewriter GetAttributeRewriter(QualifiedModuleName qualifiedModuleName) - { - return _moduleStates[qualifiedModuleName].AttributesRewriter; - } - public ITokenStream GetCodePaneTokenStream(QualifiedModuleName qualifiedModuleName) { return _moduleStates[qualifiedModuleName].CodePaneTokenStream; @@ -1080,9 +1048,6 @@ private void ClearAsTypeDeclarationPointingToReference(QualifiedModuleName refer public void SetAttributesTokenStream(QualifiedModuleName module, ITokenStream attributesTokenStream) { _moduleStates[module].SetAttributesTokenStream(attributesTokenStream); - - var rewriter = _moduleRewriterFactory.AttributesRewriter(module, attributesTokenStream); - _moduleStates[module].SetAttributesRewriter(rewriter); } //todo: Remove this again in favor of injection of the IRewritingManager into the callers. diff --git a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs index 16b82c6378..b26917025b 100644 --- a/RubberduckTests/CodeExplorer/CodeExplorerTests.cs +++ b/RubberduckTests/CodeExplorer/CodeExplorerTests.cs @@ -2877,15 +2877,7 @@ public void CompareByNodeType_FoldersAreSortedByName() private RubberduckParserState TestParserState(Mock vbe, IProjectsRepository projectsRepository) { var vbeEvents = MockVbeEvents.CreateMockVbeEvents(vbe); - - var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectsRepository); - //We use the same handler because to achieve consistency between the return values. - var attributesSourceCodeHandler = codePaneSourceCodeHandler; - var moduleRewriterFactory = new ModuleRewriterFactory( - codePaneSourceCodeHandler, - attributesSourceCodeHandler); - - return new RubberduckParserState(vbe.Object, projectsRepository, new DeclarationFinderFactory(), vbeEvents.Object, moduleRewriterFactory); + return new RubberduckParserState(vbe.Object, projectsRepository, new DeclarationFinderFactory(), vbeEvents.Object); } private Configuration GetDefaultUnitTestConfig() diff --git a/RubberduckTests/Mocks/MockParser.cs b/RubberduckTests/Mocks/MockParser.cs index 5080ca337d..cd9c494867 100644 --- a/RubberduckTests/Mocks/MockParser.cs +++ b/RubberduckTests/Mocks/MockParser.cs @@ -45,18 +45,10 @@ public static RubberduckParserState ParseString(string inputCode, out QualifiedM public static (SynchronousParseCoordinator parser, IRewritingManager rewritingManager) CreateWithRewriteManager(IVBE vbe, string serializedComProjectsPath = null) { - var vbeEvents = MockVbeEvents.CreateMockVbeEvents(new Moq.Mock()); + var vbeEvents = MockVbeEvents.CreateMockVbeEvents(new Mock()); var declarationFinderFactory = new DeclarationFinderFactory(); var projectRepository = new ProjectsRepository(vbe); - - var codePaneSourceCodeHandler = new CodePaneSourceCodeHandler(projectRepository); - //We use the same handler because to achieve consistency between the return values. - var attributesSourceCodeHandler = codePaneSourceCodeHandler; - var moduleRewriterFactory = new ModuleRewriterFactory( - codePaneSourceCodeHandler, - attributesSourceCodeHandler); - - var state = new RubberduckParserState(vbe, projectRepository, declarationFinderFactory, vbeEvents.Object, moduleRewriterFactory); + var state = new RubberduckParserState(vbe, projectRepository, declarationFinderFactory, vbeEvents.Object); return CreateWithRewriteManager(vbe, state, projectRepository, serializedComProjectsPath); } diff --git a/RubberduckTests/Rewriter/ArgumentRewriterInfoFinderTests.cs b/RubberduckTests/Rewriter/ArgumentRewriterInfoFinderTests.cs index 26931df3ae..627685d8c3 100644 --- a/RubberduckTests/Rewriter/ArgumentRewriterInfoFinderTests.cs +++ b/RubberduckTests/Rewriter/ArgumentRewriterInfoFinderTests.cs @@ -108,19 +108,25 @@ Public Sub Baz() private void TestEnclosedCode(string inputCode, string enclosingModuleBodyElementName, int argumentPosition, string expectedEnclosedCode) { var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - var state = MockParser.CreateAndParse(vbe.Object); - - var enclosingModuleBodyElementDeclarationContext = state.DeclarationFinder.MatchName(enclosingModuleBodyElementName).First().Context; - var enclosingModuleBodyElementContext = enclosingModuleBodyElementDeclarationContext.GetAncestor(); - var enclosingModuleBodyElementBodyContext = enclosingModuleBodyElementContext.GetDescendent(); - var argumentListContext = enclosingModuleBodyElementBodyContext.GetDescendent(); - var argumentContext = argumentListContext.argument(argumentPosition-1); - - var infoFinder = new ArgumentRewriterInfoFinder(); - var info = infoFinder.GetRewriterInfo(argumentContext); - - var actualEnclosedCode = state.GetRewriter(component).TokenStream.GetText(info.StartTokenIndex, info.StopTokenIndex); - Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var enclosingModuleBodyElementDeclarationContext = state.DeclarationFinder + .MatchName(enclosingModuleBodyElementName).First().Context; + var enclosingModuleBodyElementContext = enclosingModuleBodyElementDeclarationContext + .GetAncestor(); + var enclosingModuleBodyElementBodyContext = + enclosingModuleBodyElementContext.GetDescendent(); + var argumentListContext = + enclosingModuleBodyElementBodyContext.GetDescendent(); + var argumentContext = argumentListContext.argument(argumentPosition - 1); + + var infoFinder = new ArgumentRewriterInfoFinder(); + var info = infoFinder.GetRewriterInfo(argumentContext); + + var actualEnclosedCode = state.GetCodePaneTokenStream(component.QualifiedModuleName) + .GetText(info.StartTokenIndex, info.StopTokenIndex); + Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + } } } } \ No newline at end of file diff --git a/RubberduckTests/Rewriter/ConstantRewriterInfoFinderTests.cs b/RubberduckTests/Rewriter/ConstantRewriterInfoFinderTests.cs index 0ce7e6e095..b2a7dcd4da 100644 --- a/RubberduckTests/Rewriter/ConstantRewriterInfoFinderTests.cs +++ b/RubberduckTests/Rewriter/ConstantRewriterInfoFinderTests.cs @@ -409,15 +409,17 @@ Private Sub Whatever(brr As Integer) private void TestEnclosedCode(string inputCode, string constantName, string expectedEnclosedCode) { var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - var state = MockParser.CreateAndParse(vbe.Object); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var constantSubStmtContext = state.DeclarationFinder.MatchName(constantName).First().Context; - var constantSubStmtContext = state.DeclarationFinder.MatchName(constantName).First().Context; + var infoFinder = new ConstantRewriterInfoFinder(); + var info = infoFinder.GetRewriterInfo(constantSubStmtContext); - var infoFinder = new ConstantRewriterInfoFinder(); - var info = infoFinder.GetRewriterInfo(constantSubStmtContext); - - var actualEnclosedCode = state.GetRewriter(component).TokenStream.GetText(info.StartTokenIndex, info.StopTokenIndex); - Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + var actualEnclosedCode = state.GetCodePaneTokenStream(component.QualifiedModuleName) + .GetText(info.StartTokenIndex, info.StopTokenIndex); + Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + } } } } diff --git a/RubberduckTests/Rewriter/ParameterRewriterInfoFinderTests.cs b/RubberduckTests/Rewriter/ParameterRewriterInfoFinderTests.cs index acb6ca3a12..7f1e2339cc 100644 --- a/RubberduckTests/Rewriter/ParameterRewriterInfoFinderTests.cs +++ b/RubberduckTests/Rewriter/ParameterRewriterInfoFinderTests.cs @@ -82,15 +82,17 @@ public void TestParameterRewriterInfoFinder_Last() private void TestEnclosedCode(string inputCode, string parameterName, string expectedEnclosedCode) { var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - var state = MockParser.CreateAndParse(vbe.Object); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var argContext = state.DeclarationFinder.MatchName(parameterName).First().Context; - var argContext = state.DeclarationFinder.MatchName(parameterName).First().Context; + var infoFinder = new ParameterRewriterInfoFinder(); + var info = infoFinder.GetRewriterInfo(argContext); - var infoFinder = new ParameterRewriterInfoFinder(); - var info = infoFinder.GetRewriterInfo(argContext); - - var actualEnclosedCode = state.GetRewriter(component).TokenStream.GetText(info.StartTokenIndex, info.StopTokenIndex); - Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + var actualEnclosedCode = state.GetCodePaneTokenStream(component.QualifiedModuleName) + .GetText(info.StartTokenIndex, info.StopTokenIndex); + Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + } } } } diff --git a/RubberduckTests/Rewriter/VariableRewriterInfoFinderTests.cs b/RubberduckTests/Rewriter/VariableRewriterInfoFinderTests.cs index 5cc12196b0..e88b797a07 100644 --- a/RubberduckTests/Rewriter/VariableRewriterInfoFinderTests.cs +++ b/RubberduckTests/Rewriter/VariableRewriterInfoFinderTests.cs @@ -409,15 +409,17 @@ Private Sub Whatever(brr As Integer) private void TestEnclosedCode(string inputCode, string variableName, string expectedEnclosedCode) { var vbe = MockVbeBuilder.BuildFromSingleStandardModule(inputCode, out var component); - var state = MockParser.CreateAndParse(vbe.Object); + using (var state = MockParser.CreateAndParse(vbe.Object)) + { + var variableSubStmtContext = state.DeclarationFinder.MatchName(variableName).First().Context; - var variableSubStmtContext = state.DeclarationFinder.MatchName(variableName).First().Context; + var infoFinder = new VariableRewriterInfoFinder(); + var info = infoFinder.GetRewriterInfo(variableSubStmtContext); - var infoFinder = new VariableRewriterInfoFinder(); - var info = infoFinder.GetRewriterInfo(variableSubStmtContext); - - var actualEnclosedCode = state.GetRewriter(component).TokenStream.GetText(info.StartTokenIndex, info.StopTokenIndex); - Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + var actualEnclosedCode = state.GetCodePaneTokenStream(component.QualifiedModuleName) + .GetText(info.StartTokenIndex, info.StopTokenIndex); + Assert.AreEqual(expectedEnclosedCode, actualEnclosedCode); + } } } } From 7a81d8fea236083d98378821d30da1953cc5ab47 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Sat, 3 Nov 2018 15:03:21 +0100 Subject: [PATCH 054/107] Remove the RewriteManager from the RubberDuckParserState All users have been rewired. So, it does not have to be property injected anymore. --- Rubberduck.Parsing/VBA/ParseCoordinator.cs | 4 ---- Rubberduck.Parsing/VBA/RubberduckParserState.cs | 4 ---- 2 files changed, 8 deletions(-) diff --git a/Rubberduck.Parsing/VBA/ParseCoordinator.cs b/Rubberduck.Parsing/VBA/ParseCoordinator.cs index a8a1490cf1..eec03d5602 100644 --- a/Rubberduck.Parsing/VBA/ParseCoordinator.cs +++ b/Rubberduck.Parsing/VBA/ParseCoordinator.cs @@ -72,10 +72,6 @@ public ParseCoordinator( state.SuspendRequest += SuspendRequested; _requestorStack = new ConcurrentStack(); - - //todo: Remove this again in favor of injection of the IRewritingManager into the callers RubberduckParserState.RewritingManager. - //This gets property injected here because the construction of the rewritingManager ultimately depend on the RubberduckParserState. - state.RewritingManager = rewritingManager; } // In production, the cancellation token should be accessed inside the CancellationSyncObject diff --git a/Rubberduck.Parsing/VBA/RubberduckParserState.cs b/Rubberduck.Parsing/VBA/RubberduckParserState.cs index 3426bb5ad4..5287882971 100644 --- a/Rubberduck.Parsing/VBA/RubberduckParserState.cs +++ b/Rubberduck.Parsing/VBA/RubberduckParserState.cs @@ -1050,10 +1050,6 @@ public void SetAttributesTokenStream(QualifiedModuleName module, ITokenStream at _moduleStates[module].SetAttributesTokenStream(attributesTokenStream); } - //todo: Remove this again in favor of injection of the IRewritingManager into the callers. - public IRewritingManager RewritingManager { get; internal set; } - - private bool _isDisposed; public void Dispose() { From b7ce4c9f9dc662bfe89739d205b6e0a290fcc1da Mon Sep 17 00:00:00 2001 From: comintern Date: Sun, 4 Nov 2018 09:58:53 -0600 Subject: [PATCH 055/107] Address potential race condition and potentially un-disposed objects on TryAdd failure. --- .../WindowsApi/SubclassManager.cs | 79 +++++++++++++------ 1 file changed, 54 insertions(+), 25 deletions(-) diff --git a/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs b/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs index cd69f4ef7e..f0d6ce7bdc 100644 --- a/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs +++ b/Rubberduck.VBEEditor/WindowsApi/SubclassManager.cs @@ -37,36 +37,65 @@ public SubclassingWindow Subclass(IntPtr hwnd) return null; } - if (_subclasses.TryGetValue(hwnd, out var existing)) + lock (ThreadLock) + { + if (_subclasses.TryGetValue(hwnd, out var existing)) + { + return existing; + } + + // Any additional cases also need to be added to IsSubclassable above. + switch (windowType) + { + case WindowType.CodePane: + return TrackNewCodePane(hwnd); + case WindowType.DesignerWindow: + return TrackNewDesigner(hwnd); + default: + return null; + } + } + } + + private CodePaneSubclass TrackNewCodePane(IntPtr hwnd) + { + var codePane = new CodePaneSubclass(hwnd, null); + try { - return existing; + if (_subclasses.TryAdd(hwnd, codePane)) + { + codePane.ReleasingHandle += SubclassRemoved; + codePane.CaptionChanged += AssociateCodePane; + SubclassLogger.Trace($"Subclassed hWnd 0x{hwnd.ToInt64():X8} as CodePane."); + return codePane; + } } + catch (Exception ex) + { + SubclassLogger.Error(ex); + } + codePane.Dispose(); + return null; + } - // Any additional cases also need to be added to IsSubclassable above. - switch (windowType) + private DesignerWindowSubclass TrackNewDesigner(IntPtr hwnd) + { + var designer = new DesignerWindowSubclass(hwnd); + try + { + if (_subclasses.TryAdd(hwnd, designer)) + { + designer.ReleasingHandle += SubclassRemoved; + SubclassLogger.Trace($"Subclassed hWnd 0x{hwnd.ToInt64():X8} as DesignerWindow."); + return designer; + } + } + catch (Exception ex) { - case WindowType.CodePane: - lock (ThreadLock) - { - var codePane = new CodePaneSubclass(hwnd, null); - _subclasses.TryAdd(hwnd, codePane); - codePane.ReleasingHandle += SubclassRemoved; - codePane.CaptionChanged += AssociateCodePane; - SubclassLogger.Trace($"Subclassed hWnd 0x{hwnd.ToInt64():X8} as CodePane."); - return codePane; - } - case WindowType.DesignerWindow: - lock (ThreadLock) - { - var designer = new DesignerWindowSubclass(hwnd); - _subclasses.TryAdd(hwnd, designer); - designer.ReleasingHandle += SubclassRemoved; - SubclassLogger.Trace($"Subclassed hWnd 0x{hwnd.ToInt64():X8} as DesignerWindow."); - return designer; - } - default: - return null; + SubclassLogger.Error(ex); } + designer.Dispose(); + return null; } private void SubclassRemoved(object sender, EventArgs eventArgs) From e575520724bd88a8cef652e2ede6ceaa5f28d6f8 Mon Sep 17 00:00:00 2001 From: Joe Iaquinto <41589436+JosephIaquinto@users.noreply.github.com> Date: Mon, 5 Nov 2018 10:19:22 -0500 Subject: [PATCH 056/107] Fix typo in About.md probject --> project --- docs/About.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/About.md b/docs/About.md index 2d378b13f0..6e81f9e782 100644 --- a/docs/About.md +++ b/docs/About.md @@ -6,7 +6,7 @@ It's an add-in for the VBA IDE, the glorious *Visual Basic Editor* (VBE) - which Rubberduck wants to help its users write better, cleaner, maintainable code. The many **code inspections** and **refactoring tools** help harmlessly making changes to the code, and **unit testing** helps writing a *safety net* that makes it easy to know exactly what broke when you made that *small little harmless modification*. -Rubberduck wants to bring VBA into the 21st century, and wants to see more open-source VBA repositories on [GitHub](https://github.com/) - VBA code and **source control** don't traditionally exactly work hand in hand; unless you've automated it, exporting each module one by one to your local repository, fetching the remote changes, re-importing every module one by one back into the project, ...is *a little bit* tedious. Rubberduck reduces this tedium by allowing you to export all modules from your probject to wherever you have your source control set up. +Rubberduck wants to bring VBA into the 21st century, and wants to see more open-source VBA repositories on [GitHub](https://github.com/) - VBA code and **source control** don't traditionally exactly work hand in hand; unless you've automated it, exporting each module one by one to your local repository, fetching the remote changes, re-importing every module one by one back into the project, ...is *a little bit* tedious. Rubberduck reduces this tedium by allowing you to export all modules from your project to wherever you have your source control set up. --- From 0ded26bd5ba153a84d6cba515803881d33ae3e44 Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Tue, 6 Nov 2018 00:46:11 +0100 Subject: [PATCH 057/107] Add tests for IRewriteSession implementations Contains extraction of a partial interface from the RubberduckParserState (IParseManager) in order to allow mocking the corresponding functionality. --- Rubberduck.Core/UI/Command/ReparseCommand.cs | 2 - .../Root/RubberduckIoCInstaller.cs | 2 +- .../Rewriter/AttributesRewriteSession.cs | 10 +- .../Rewriter/CodePaneRewriteSession.cs | 8 +- Rubberduck.Parsing/VBA/IParseManager.cs | 14 ++ .../VBA/RubberduckParserState.cs | 3 +- .../Rewriter/AttributesRewriteSessionTests.cs | 71 ++++++ .../Rewriter/CodePaneRewriteSessionTests.cs | 102 +++++++++ .../Rewriter/RewriteSessionTestBase.cs | 216 ++++++++++++++++++ 9 files changed, 414 insertions(+), 14 deletions(-) create mode 100644 Rubberduck.Parsing/VBA/IParseManager.cs create mode 100644 RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs create mode 100644 RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs create mode 100644 RubberduckTests/Rewriter/RewriteSessionTestBase.cs diff --git a/Rubberduck.Core/UI/Command/ReparseCommand.cs b/Rubberduck.Core/UI/Command/ReparseCommand.cs index dc1244ecfe..fee6998e88 100644 --- a/Rubberduck.Core/UI/Command/ReparseCommand.cs +++ b/Rubberduck.Core/UI/Command/ReparseCommand.cs @@ -2,14 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; -using System.Windows.Forms; using NLog; using Rubberduck.Interaction; using Rubberduck.Parsing.VBA; using Rubberduck.Settings; using Rubberduck.SettingsProvider; using Rubberduck.Resources; -using Rubberduck.UI.CodeExplorer.Commands; using Rubberduck.VBEditor.ComManagement.TypeLibsAPI; using Rubberduck.VBEditor.SafeComWrappers; using Rubberduck.VBEditor.SafeComWrappers.Abstract; diff --git a/Rubberduck.Main/Root/RubberduckIoCInstaller.cs b/Rubberduck.Main/Root/RubberduckIoCInstaller.cs index b11031b66a..cf2b0905fa 100644 --- a/Rubberduck.Main/Root/RubberduckIoCInstaller.cs +++ b/Rubberduck.Main/Root/RubberduckIoCInstaller.cs @@ -93,7 +93,7 @@ public void Install(IWindsorContainer container, IConfigurationStore store) container.Register(Component.For() .ImplementedBy() .LifestyleSingleton()); - container.Register(Component.For() + container.Register(Component.For() .ImplementedBy() .LifestyleSingleton()); container.Register(Component.For() diff --git a/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs index de94ed5b72..8d84bfe427 100644 --- a/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs +++ b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs @@ -6,24 +6,24 @@ namespace Rubberduck.Parsing.Rewriter { public class AttributesRewriteSession : RewriteSessionBase { - private readonly RubberduckParserState _state; + private readonly IParseManager _parseManager; - public AttributesRewriteSession(RubberduckParserState state, IRewriterProvider rewriterProvider, + public AttributesRewriteSession(IParseManager parseManager, IRewriterProvider rewriterProvider, Func rewritingAllowed) : base(rewriterProvider, rewritingAllowed) { - _state = state; + _parseManager = parseManager; } protected override IExecutableModuleRewriter ModuleRewriter(QualifiedModuleName module) { - return RewriterProvider.CodePaneModuleRewriter(module); + return RewriterProvider.AttributesModuleRewriter(module); } protected override void RewriteInternal() { //The suspension ensures that only one parse gets executed instead of two for each rewritten module. - var result = _state.OnSuspendParser(this, new[] {ParserState.Ready}, ExecuteAllRewriters); + var result = _parseManager.OnSuspendParser(this, new[] {ParserState.Ready}, ExecuteAllRewriters); if(result != SuspensionResult.Completed) { Logger.Warn($"Rewriting attribute modules did not succeed. suspension result = {result}"); diff --git a/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs b/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs index 4b731d7bc7..a76d6b91f9 100644 --- a/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs +++ b/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs @@ -6,13 +6,13 @@ namespace Rubberduck.Parsing.Rewriter { public class CodePaneRewriteSession : RewriteSessionBase { - private readonly RubberduckParserState _state; + private readonly IParseManager _parseManager; - public CodePaneRewriteSession(RubberduckParserState state, IRewriterProvider rewriterProvider, + public CodePaneRewriteSession(IParseManager parseManager, IRewriterProvider rewriterProvider, Func rewritingAllowed) : base(rewriterProvider, rewritingAllowed) { - _state = state; + _parseManager = parseManager; } @@ -27,7 +27,7 @@ protected override void RewriteInternal() { rewriter.Rewrite(); } - _state.OnParseRequested(this); + _parseManager.OnParseRequested(this); } } } \ No newline at end of file diff --git a/Rubberduck.Parsing/VBA/IParseManager.cs b/Rubberduck.Parsing/VBA/IParseManager.cs new file mode 100644 index 0000000000..fc9bda0947 --- /dev/null +++ b/Rubberduck.Parsing/VBA/IParseManager.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; + +namespace Rubberduck.Parsing.VBA +{ + public interface IParseManager + { + event EventHandler StateChanged; + event EventHandler ModuleStateChanged; + + void OnParseRequested(object requestor); + SuspensionResult OnSuspendParser(object requestor, IEnumerable allowedRunStates, Action busyAction, int millisecondsTimeout = -1); + } +} \ No newline at end of file diff --git a/Rubberduck.Parsing/VBA/RubberduckParserState.cs b/Rubberduck.Parsing/VBA/RubberduckParserState.cs index e4e6ad6c76..a72c870928 100644 --- a/Rubberduck.Parsing/VBA/RubberduckParserState.cs +++ b/Rubberduck.Parsing/VBA/RubberduckParserState.cs @@ -12,7 +12,6 @@ using Rubberduck.VBEditor; using Rubberduck.Parsing.Annotations; using NLog; -using Rubberduck.Parsing.Rewriter; using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.VBEditor.ComManagement; using Rubberduck.VBEditor.Events; @@ -120,7 +119,7 @@ public RubberduckStatusMessageEventArgs(string message) public string Message { get; } } - public sealed class RubberduckParserState : IDisposable, IDeclarationFinderProvider, IParseTreeProvider + public sealed class RubberduckParserState : IDisposable, IDeclarationFinderProvider, IParseTreeProvider, IParseManager { public const int NoTimeout = -1; diff --git a/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs b/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs new file mode 100644 index 0000000000..21ca2513f2 --- /dev/null +++ b/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Moq; +using NUnit.Framework; +using Rubberduck.Parsing.Rewriter; +using Rubberduck.Parsing.VBA; +using Rubberduck.Parsing.VBA.Parsing; +using Rubberduck.VBEditor; + +namespace RubberduckTests.Rewriter +{ + [TestFixture] + public class AttributesRewriteSessionTests : RewriteSessionTestBase + { + [Test] + [Category("Rewriter")] + public void UsesASuspendActionToRewrite() + { + var mockParseManager = new Mock(); + mockParseManager.Setup(m => m.OnSuspendParser(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) + .Callback((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => suspendAction()) + .Returns((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => SuspensionResult.Completed); + + var rewriteSession = RewriteSession(mockParseManager.Object, session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + + rewriteSession.Rewrite(); + + mockParseManager.Verify(m => m.OnSuspendParser(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Once); + } + + [Test] + [Category("Rewriter")] + public void DoesNotCallRewriteOutsideTheSuspendAction() + { + var mockParseManager = new Mock(); + mockParseManager.Setup(m => m.OnSuspendParser(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) + .Returns((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => SuspensionResult.Completed); + + var rewriteSession = RewriteSession(mockParseManager.Object, session => true, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); + + rewriteSession.Rewrite(); + + mockRewriter.Verify(m => m.Rewrite(), Times.Never); + } + + [Test] + [Category("Rewriter")] + public void ChecksOutAttributesRewriters() + { + var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + + rewriteSession.CheckOutModuleRewriter(module); + + var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); + Assert.AreEqual(CodeKind.AttributesCode, codeKind); + } + + protected override IRewriteSession RewriteSession(IParseManager parseManager, Func rewritingAllowed, out MockRewriterProvider mockProvider) + { + mockProvider = new MockRewriterProvider(); + return new AttributesRewriteSession(parseManager, mockProvider, rewritingAllowed); + } + } +} \ No newline at end of file diff --git a/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs b/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs new file mode 100644 index 0000000000..efeb565a10 --- /dev/null +++ b/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs @@ -0,0 +1,102 @@ +using System; +using System.Linq; +using Moq; +using NUnit.Framework; +using Rubberduck.Parsing.Rewriter; +using Rubberduck.Parsing.VBA; +using Rubberduck.Parsing.VBA.Parsing; +using Rubberduck.VBEditor; + +namespace RubberduckTests.Rewriter +{ + [TestFixture] + public class CodePaneRewriteSessionTests : RewriteSessionTestBase + { + [Test] + [Category("Rewriter")] + public void RequestsParseAfterRewriteIfNotInvalidatedAndParsingAllowed() + { + var mockParseManager = new Mock(); + mockParseManager.Setup(m => m.OnParseRequested(It.IsAny())); + + var rewriteSession = RewriteSession(mockParseManager.Object, session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + var otherModule = new QualifiedModuleName("TestProject", string.Empty, "OtherTestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.CheckOutModuleRewriter(otherModule); + + rewriteSession.Rewrite(); + + mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Once); + } + + [Test] + [Category("Rewriter")] + public void DoesNotCallRequestsParseAfterRewriteIfInvalidated() + { + var mockParseManager = new Mock(); + mockParseManager.Setup(m => m.OnParseRequested(It.IsAny())); + + var rewriteSession = RewriteSession(mockParseManager.Object, session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + var otherModule = new QualifiedModuleName("TestProject", string.Empty, "OtherTestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.Invalidate(); + rewriteSession.CheckOutModuleRewriter(otherModule); + + rewriteSession.Rewrite(); + + mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Never); + } + + [Test] + [Category("Rewriter")] + public void DoesNotRequestsParseAfterRewriteIfNotParsingAllowed() + { + var mockParseManager = new Mock(); + mockParseManager.Setup(m => m.OnParseRequested(It.IsAny())); + + var rewriteSession = RewriteSession(mockParseManager.Object, session => false, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + var otherModule = new QualifiedModuleName("TestProject", string.Empty, "OtherTestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.CheckOutModuleRewriter(otherModule); + + rewriteSession.Rewrite(); + + mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Never); + } + + [Test] + [Category("Rewriter")] + public void DoesNotRequestParseIfNoRewritersAreCheckedOut() + { + var mockParseManager = new Mock(); + mockParseManager.Setup(m => m.OnParseRequested(It.IsAny())); + var rewriteSession = RewriteSession(mockParseManager.Object, session => true, out _); + + rewriteSession.Rewrite(); + + mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Never); + } + + [Test] + [Category("Rewriter")] + public void ChecksOutCodePaneRewriters() + { + var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + + rewriteSession.CheckOutModuleRewriter(module); + + var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); + Assert.AreEqual(CodeKind.CodePaneCode, codeKind); + } + + protected override IRewriteSession RewriteSession(IParseManager parseManager, Func rewritingAllowed, out MockRewriterProvider mockProvider) + { + mockProvider = new MockRewriterProvider(); + return new CodePaneRewriteSession(parseManager, mockProvider, rewritingAllowed); + } + } +} \ No newline at end of file diff --git a/RubberduckTests/Rewriter/RewriteSessionTestBase.cs b/RubberduckTests/Rewriter/RewriteSessionTestBase.cs new file mode 100644 index 0000000000..727814dc2d --- /dev/null +++ b/RubberduckTests/Rewriter/RewriteSessionTestBase.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Moq; +using NUnit.Framework; +using Rubberduck.Parsing.Rewriter; +using Rubberduck.Parsing.VBA; +using Rubberduck.Parsing.VBA.Parsing; +using Rubberduck.VBEditor; + +namespace RubberduckTests.Rewriter +{ + [TestFixture] + public abstract class RewriteSessionTestBase + { + [Test] + [Category("Rewriter")] + public void IsNotInvalidatedAtStart() + { + var rewriteSession = RewriteSession(session => true, out _); + Assert.IsFalse(rewriteSession.IsInvalidated); + } + + [Test] + [Category("Rewriter")] + public void IsInvalidatedAfterCallingInvalidate() + { + var rewriteSession = RewriteSession(session => true, out _); + rewriteSession.Invalidate(); + Assert.IsTrue(rewriteSession.IsInvalidated); + } + + [Test] + [Category("Rewriter")] + public void CallsRewritingAllowedOnRewriteIfNotInvalidatedAndRewritersHaveBeenCheckedOut() + { + var isCalled = false; + var rewriteSession = RewriteSession(session => + { + isCalled = true; + return true; + }, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.Rewrite(); + Assert.IsTrue(isCalled); + } + + [Test] + [Category("Rewriter")] + public void DoesNotCallRewritingAllowedOnRewriteIfNoRewritersHaveBeenCheckedOut() + { + var isCalled = false; + var rewriteSession = RewriteSession(session => + { + isCalled = true; + return true; + }, out _); + rewriteSession.Rewrite(); + Assert.IsFalse(isCalled); + } + + [Test] + [Category("Rewriter")] + public void DoesNotCallRewritingAllowedOnRewriteIfInvalidated() + { + var isCalled = false; + var rewriteSession = RewriteSession(session => + { + isCalled = true; + return true; + }, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + var otherModule = new QualifiedModuleName("TestProject", string.Empty, "OtherTestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.Invalidate(); + rewriteSession.CheckOutModuleRewriter(otherModule); + + rewriteSession.Rewrite(); + Assert.IsFalse(isCalled); + } + + [Test] + [Category("Rewriter")] + public void CallsRewriteOnAllCheckedOutRewritersIfNotInvalidatedAndParsingAllowed() + { + var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty,"TestModule"); + var otherModule = new QualifiedModuleName("TestProject", string.Empty, "OtherTestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.CheckOutModuleRewriter(otherModule); + + var requestedRewriters = mockRewriterProvider.RequestedRewriters(); + + rewriteSession.Rewrite(); + + foreach (var (qmn, codeKind, mockRewriter) in requestedRewriters) + { + mockRewriter.Verify(m => m.Rewrite(), Times.Once); + } + } + + [Test] + [Category("Rewriter")] + public void DoesNotCallRewriteOnAnyCheckedOutRewriterIfInvalidated() + { + var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + var otherModule = new QualifiedModuleName("TestProject", string.Empty, "OtherTestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.Invalidate(); + rewriteSession.CheckOutModuleRewriter(otherModule); + + var requestedRewriters = mockRewriterProvider.RequestedRewriters(); + + rewriteSession.Rewrite(); + + foreach (var (qmn, codeKind, mockRewriter) in requestedRewriters) + { + mockRewriter.Verify(m => m.Rewrite(), Times.Never); + } + } + + [Test] + [Category("Rewriter")] + public void DoesNotCallRewriteOnAnCheckedOutRewriterIfNotParsingAllowed() + { + var rewriteSession = RewriteSession(session => false, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + var otherModule = new QualifiedModuleName("TestProject", string.Empty, "OtherTestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.CheckOutModuleRewriter(otherModule); + + var requestedRewriters = mockRewriterProvider.RequestedRewriters(); + + rewriteSession.Rewrite(); + + foreach (var (qmn, codeKind, mockRewriter) in requestedRewriters) + { + mockRewriter.Verify(m => m.Rewrite(), Times.Never); + } + } + + [Test] + [Category("Rewriter")] + public void ReturnsTheSameRewriterOnMultipleCheckoutsForTheSameModule() + { + var rewriteSession = RewriteSession(session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + var initialRewriter = rewriteSession.CheckOutModuleRewriter(module); + var nextRewriter = rewriteSession.CheckOutModuleRewriter(module); + + Assert.AreEqual(initialRewriter, nextRewriter); + } + + [Test] + [Category("Rewriter")] + public void CallsRewriteOnlyOnceForRewritersCheckedOutMultipleTimes() + { + var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.CheckOutModuleRewriter(module); + var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); + + rewriteSession.Rewrite(); + + mockRewriter.Verify(m => m.Rewrite(), Times.Once); + } + + protected IRewriteSession RewriteSession(Func rewritingAllowed, + out MockRewriterProvider mockProvider) + { + var parseManager = new Mock(); + parseManager.Setup(m => m.OnSuspendParser(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) + .Callback((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => suspendAction()) + .Returns((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => SuspensionResult.Completed); + return RewriteSession(parseManager.Object, rewritingAllowed, out mockProvider); + } + + protected abstract IRewriteSession RewriteSession(IParseManager parseManager, Func rewritingAllowed, out MockRewriterProvider mockProvider); + } + + + public class MockRewriterProvider: IRewriterProvider + { + private readonly List<(QualifiedModuleName module, CodeKind codeKind, Mock moduleRewriter)> _requestedRewriters = new List<(QualifiedModuleName module, CodeKind codeKind, Mock moduleRewriter)>(); + + public IExecutableModuleRewriter CodePaneModuleRewriter(QualifiedModuleName module) + { + var rewriter = CreateMockModuleRewriter(); + _requestedRewriters.Add((module, CodeKind.CodePaneCode, rewriter)); + return rewriter.Object; + } + + private static Mock CreateMockModuleRewriter() + { + var mock = new Mock(); + mock.Setup(m => m.Rewrite()); + + return mock; + } + + public IExecutableModuleRewriter AttributesModuleRewriter(QualifiedModuleName module) + { + var rewriter = CreateMockModuleRewriter(); + _requestedRewriters.Add((module, CodeKind.AttributesCode, rewriter)); + return rewriter.Object; + } + + public IEnumerable<(QualifiedModuleName module, CodeKind codeKind, Mock moduleRewriter)> RequestedRewriters() + { + return _requestedRewriters; + } + } +} \ No newline at end of file From d6de269f1d67426545ad4dffcb45c00d8369b2c6 Mon Sep 17 00:00:00 2001 From: Mathieu Guindon Date: Mon, 5 Nov 2018 20:57:09 -0500 Subject: [PATCH 058/107] refactored for testability of SCP handler --- .../AutoComplete/Service/SelfClosingPair.cs | 25 ++- .../SelfClosingPairCompletionService.cs | 57 ++++--- .../Service/SelfClosingPairHandler.cs | 125 ++++++++------- .../Service/ShowIntelliSenseCommand.cs | 3 + .../Settings/AutoCompleteSettings.cs | 12 ++ .../SelfClosingPairCompletionTests.cs | 149 ++++++++++++------ 6 files changed, 240 insertions(+), 131 deletions(-) diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPair.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPair.cs index e2157d98f3..e6540da023 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPair.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPair.cs @@ -1,7 +1,18 @@ -namespace Rubberduck.AutoComplete.Service +using Rubberduck.VBEditor; +using System; + +namespace Rubberduck.AutoComplete.Service { - public class SelfClosingPair + public class SelfClosingPair : IEquatable { + [Flags] + public enum MatchType + { + NoMatch = 0, + OpeningCharacterMatch = 1, + ClosingCharacterMatch = 2, + } + public SelfClosingPair(char opening, char closing) { OpeningChar = opening; @@ -15,5 +26,15 @@ public SelfClosingPair(char opening, char closing) /// True if is the same as . /// public bool IsSymetric => OpeningChar == ClosingChar; + + public bool Equals(SelfClosingPair other) => other?.OpeningChar == OpeningChar && + other.ClosingChar == ClosingChar; + + public override bool Equals(object obj) + { + return obj is SelfClosingPair scp && Equals(scp); + } + + public override int GetHashCode() => HashCode.Compute(OpeningChar, ClosingChar); } } \ No newline at end of file diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs index 24b0fff2ee..524820318f 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs @@ -12,18 +12,25 @@ namespace Rubberduck.AutoComplete.Service { public class SelfClosingPairCompletionService { + /* + // note: this works... but the VBE makes an annoying DING! when the command isn't available. + // todo: implement our own intellisense, then uncomment this code. private readonly IShowIntelliSenseCommand _showIntelliSense; public SelfClosingPairCompletionService(IShowIntelliSenseCommand showIntelliSense) { _showIntelliSense = showIntelliSense; } + */ - public CodeString Execute(SelfClosingPair pair, CodeString original, char input) + public bool Execute(SelfClosingPair pair, CodeString original, char input, out CodeString result) { + result = null; + var previousCharIsClosingChar = original.CaretPosition.StartColumn > 0 && original.CaretLine[original.CaretPosition.StartColumn - 1] == pair.ClosingChar; + var nextCharIsClosingChar = original.CaretPosition.StartColumn < original.CaretLine.Length && original.CaretLine[original.CaretPosition.StartColumn] == pair.ClosingChar; @@ -33,49 +40,51 @@ public CodeString Execute(SelfClosingPair pair, CodeString original, char input) previousCharIsClosingChar && !nextCharIsClosingChar || original.IsComment || (original.IsInsideStringLiteral && !nextCharIsClosingChar)) { - return null; + return false; } if (input == pair.OpeningChar) { - var result = HandleOpeningChar(pair, original); - return result; + return HandleOpeningChar(pair, original, out result); } - + if (input == pair.ClosingChar) { - return HandleClosingChar(pair, original); + return HandleClosingChar(pair, original, out result); } if (input == '\b') { - return Execute(pair, original, Keys.Back); + return Execute(pair, original, Keys.Back, out result); } - return null; + return false; } - public CodeString Execute(SelfClosingPair pair, CodeString original, Keys input) + public bool Execute(SelfClosingPair pair, CodeString original, Keys input, out CodeString result) { + result = null; if (original.IsComment) { - return null; + // not handling backspace in comments + return false; } if (input == Keys.Back) { - return HandleBackspace(pair, original); + result = HandleBackspace(pair, original); + return true; } - return null; + return false; } - private CodeString HandleOpeningChar(SelfClosingPair pair, CodeString original) + private bool HandleOpeningChar(SelfClosingPair pair, CodeString original, out CodeString result) { var nextPosition = original.CaretPosition.ShiftRight(); var autoCode = new string(new[] { pair.OpeningChar, pair.ClosingChar }); var lines = original.Lines; - var line = lines[original.CaretPosition.StartLine]; + var line = original.CaretLine; string newCode; if (string.IsNullOrEmpty(line)) @@ -94,14 +103,17 @@ private CodeString HandleOpeningChar(SelfClosingPair pair, CodeString original) } lines[original.CaretPosition.StartLine] = newCode; - return new CodeString(string.Join("\r\n", lines), nextPosition, new Selection(original.SnippetPosition.StartLine, 1, original.SnippetPosition.EndLine, 1)); + result = new CodeString(string.Join("\r\n", lines), nextPosition, new Selection(original.SnippetPosition.StartLine, 1, original.SnippetPosition.EndLine, 1)); + return true; } - private CodeString HandleClosingChar(SelfClosingPair pair, CodeString original) + private bool HandleClosingChar(SelfClosingPair pair, CodeString original, out CodeString result) { + result = null; if (pair.IsSymetric) { - return null; + // a symetric pair would have already been handled with the opening character. + return false; } var nextIsClosingChar = original.CaretLine.Length > original.CaretCharIndex && @@ -111,17 +123,14 @@ private CodeString HandleClosingChar(SelfClosingPair pair, CodeString original) var nextPosition = original.CaretPosition.ShiftRight(); var newCode = original.Code; - return new CodeString(newCode, nextPosition, new Selection(original.SnippetPosition.StartLine, 1, original.SnippetPosition.EndLine, 1)); + result = new CodeString(newCode, nextPosition, new Selection(original.SnippetPosition.StartLine, 1, original.SnippetPosition.EndLine, 1)); + return true; } - return null; - } - private CodeString HandleBackspace(SelfClosingPair pair, CodeString original) - { - return DeleteMatchingTokens(pair, original); + return false; } - private CodeString DeleteMatchingTokens(SelfClosingPair pair, CodeString original) + private CodeString HandleBackspace(SelfClosingPair pair, CodeString original) { var position = original.CaretPosition; var lines = original.Lines; diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs index f50212287f..a195bc033f 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; -using System.Diagnostics; -using System.Windows.Forms; +using System.Linq; using Rubberduck.Settings; using Rubberduck.VBEditor; using Rubberduck.VBEditor.Events; @@ -10,86 +9,92 @@ namespace Rubberduck.AutoComplete.Service { public class SelfClosingPairHandler : AutoCompleteHandlerBase { - private static readonly IEnumerable SelfClosingPairs = new List - { - new SelfClosingPair('(', ')'), - new SelfClosingPair('"', '"'), - new SelfClosingPair('[', ']'), - new SelfClosingPair('{', '}'), - }; - + private readonly IDictionary _selfClosingPairs; private readonly SelfClosingPairCompletionService _scpService; public SelfClosingPairHandler(ICodePaneHandler pane, SelfClosingPairCompletionService scpService) : base(pane) { + var pairs = new[] + { + new SelfClosingPair('(', ')'), + new SelfClosingPair('"', '"'), + new SelfClosingPair('[', ']'), + new SelfClosingPair('{', '}'), + }; + _selfClosingPairs = pairs + .Select(p => new {Key = p.OpeningChar, Pair = p}) + .Union(pairs.Where(p => !p.IsSymetric).Select(p => new {Key = p.ClosingChar, Pair = p})) + .ToDictionary(p => p.Key, p => p.Pair); + _scpService = scpService; } public override CodeString Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings) { + if (!_selfClosingPairs.TryGetValue(e.Character, out var pair) && e.Character != '\b') + { + return null; + } + var original = CodePaneHandler.GetCurrentLogicalLine(e.Module); - foreach (var pair in SelfClosingPairs) + if (!HandleInternal(e, original, pair, out var result)) { - var isPresent = original.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}"); - - var result = ExecuteSelfClosingPair(e, original, pair); - if (result == null) - { - continue; - } - - var prettified = CodePaneHandler.Prettify(e.Module, original); - if (!isPresent && original.CaretLine.Length + 2 == prettified.CaretLine.Length && - prettified.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}")) - { - // prettifier just added the pair for us; likely a Sub or Function statement. - prettified = original; // pretend this didn't happen. note: probably breaks if original has extra whitespace. - } - - result = ExecuteSelfClosingPair(e, prettified, pair); - if (result == null) - { - continue; - } - - result = CodePaneHandler.Prettify(e.Module, result); - - var currentLine = result.Lines[result.CaretPosition.StartLine]; - if (!string.IsNullOrWhiteSpace(currentLine) && - currentLine.EndsWith(" ") && - result.CaretPosition.StartColumn == currentLine.Length) - { - result = result.ReplaceLine(result.CaretPosition.StartLine, currentLine.TrimEnd()); - } - - if (pair.OpeningChar == '(' && e.Character != '\b' && !result.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}")) - { - // VBE eats it. just bail out. - return null; - } - - e.Handled = true; - result = new CodeString(result.Code, result.CaretPosition, new Selection(result.SnippetPosition.StartLine, 1, result.SnippetPosition.EndLine, 1)); - return result; + return null; } - return null; + var snippetPosition = new Selection(result.SnippetPosition.StartLine, 1, result.SnippetPosition.EndLine, 1); + result = new CodeString(result.Code, result.CaretPosition, snippetPosition); + + e.Handled = true; + return result; } - private CodeString ExecuteSelfClosingPair(AutoCompleteEventArgs e, CodeString original, SelfClosingPair pair) + private bool HandleInternal(AutoCompleteEventArgs e, CodeString original, SelfClosingPair pair, out CodeString result) { - CodeString result; - if (e.Character == '\b' && original.CaretPosition.StartColumn > 1) + var isPresent = original.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}"); + + if (!ExecuteSelfClosingPair(e, original, pair, out result)) { - result = _scpService.Execute(pair, original, Keys.Back); + return false; } - else + + var prettified = CodePaneHandler.Prettify(e.Module, original); + if (!isPresent && original.CaretLine.Length + 2 == prettified.CaretLine.Length && + prettified.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}")) { - result = _scpService.Execute(pair, original, e.Character); + // prettifier just added the pair for us; likely a Sub or Function statement. + prettified = original; // pretend this didn't happen. note: probably breaks if original has extra whitespace. } - return result; + if (!ExecuteSelfClosingPair(e, prettified, pair, out result)) + { + return false; + } + + result = CodePaneHandler.Prettify(e.Module, result); + + var currentLine = result.Lines[result.CaretPosition.StartLine]; + if (!string.IsNullOrWhiteSpace(currentLine) && + currentLine.EndsWith(" ") && + result.CaretPosition.StartColumn == currentLine.Length) + { + result = result.ReplaceLine(result.CaretPosition.StartLine, currentLine.TrimEnd()); + } + + if (pair.OpeningChar == '(' && e.Character != '\b' && + !result.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}")) + { + // VBE eats it. just bail out. + return true; + } + + return true; + } + + private bool ExecuteSelfClosingPair(AutoCompleteEventArgs e, CodeString original, SelfClosingPair pair, out CodeString result) + { + return _scpService.Execute(pair, original, e.Character, out result); } } } \ No newline at end of file diff --git a/Rubberduck.Core/AutoComplete/Service/ShowIntelliSenseCommand.cs b/Rubberduck.Core/AutoComplete/Service/ShowIntelliSenseCommand.cs index 4663c29b39..63b7d057ad 100644 --- a/Rubberduck.Core/AutoComplete/Service/ShowIntelliSenseCommand.cs +++ b/Rubberduck.Core/AutoComplete/Service/ShowIntelliSenseCommand.cs @@ -7,6 +7,9 @@ namespace Rubberduck.AutoComplete.Service { public interface IShowIntelliSenseCommand { + /// + /// WARNING! Makes an utterly annoying DING! in the VBE if the "QuickInfo" command is unavailable. + /// void Execute(); } diff --git a/Rubberduck.Core/Settings/AutoCompleteSettings.cs b/Rubberduck.Core/Settings/AutoCompleteSettings.cs index a8fc519e70..eb00841bc0 100644 --- a/Rubberduck.Core/Settings/AutoCompleteSettings.cs +++ b/Rubberduck.Core/Settings/AutoCompleteSettings.cs @@ -27,6 +27,18 @@ public interface IAutoCompleteSettings [XmlType(AnonymousType = true)] public class AutoCompleteSettings : IAutoCompleteSettings, IEquatable { + public static AutoCompleteSettings AllEnabled => + new AutoCompleteSettings + { + IsEnabled = true, + BlockCompletion = + new BlockCompletionSettings {IsEnabled = true, CompleteOnEnter = true, CompleteOnTab = true}, + SmartConcat = + new SmartConcatSettings {IsEnabled = true, ConcatVbNewLineModifier = ModifierKeySetting.CtrlKey}, + SelfClosingPairs = + new SelfClosingPairSettings {IsEnabled = true} + }; + public AutoCompleteSettings() { SmartConcat = new SmartConcatSettings(); diff --git a/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs b/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs index 8840aa7a78..9aaee667f9 100644 --- a/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs +++ b/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs @@ -1,25 +1,72 @@ using NUnit.Framework; using System.Windows.Forms; +using Moq; using Rubberduck.AutoComplete.Service; +using Rubberduck.Settings; using Rubberduck.VBEditor; +using Rubberduck.VBEditor.SourceCodeHandling; +using Rubberduck.VBEditor.Events; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; namespace RubberduckTests.AutoComplete { + [TestFixture] + public class SelfClosingPairHandlerTests + { + private bool Run(CodeString original, CodeString prettified, CodeString rePrettified, out CodeString testResult, char input, bool isControlKeyDown = false, bool isDeleteKey = false) + { + var module = new Mock(); + var handler = new Mock(); + handler.Setup(e => e.GetCurrentLogicalLine(module.Object)).Returns(original); + handler.SetupSequence(e => e.Prettify(module.Object, original)) + .Returns(prettified) + .Returns(rePrettified); + + var service = new Mock(new Mock().Object); + var settings = AutoCompleteSettings.AllEnabled; + + var args = new AutoCompleteEventArgs(module.Object, input, isControlKeyDown, isDeleteKey); + var sut = new SelfClosingPairHandler(handler.Object, service.Object); + + var result = sut.Handle(args, settings); + if (result != null) + { + testResult = new TestCodeString(result); + return true; + } + + testResult = null; + return false; + } + } + [TestFixture] public class SelfClosingPairCompletionTests { - private TestCodeString Run(SelfClosingPair pair, CodeString original, char input) + private bool Run(SelfClosingPair pair, CodeString original, char input, out TestCodeString testResult) { - var sut = new SelfClosingPairCompletionService(null); - var result = sut.Execute(pair, original, input); - return result != null ? new TestCodeString(result) : null; + var sut = new SelfClosingPairCompletionService(); + if (sut.Execute(pair, original, input, out var result)) + { + testResult = new TestCodeString(result); + return true; + } + + testResult = null; + return false; } - private TestCodeString Run(SelfClosingPair pair, CodeString original, Keys input) + private bool Run(SelfClosingPair pair, CodeString original, Keys input, out TestCodeString testResult) { - var sut = new SelfClosingPairCompletionService(null); - var result = sut.Execute(pair, original, input); - return result != null ? new TestCodeString(result) : null; + var sut = new SelfClosingPairCompletionService(); + if (sut.Execute(pair, original, input, out var result)) + { + testResult = new TestCodeString(result); + return true; + } + + testResult = null; + return false; } [Test] @@ -30,7 +77,7 @@ public void PlacesCaretBetweenOpeningAndClosingChars() var original = "foo = MsgBox |".ToCodeString(); var expected = "foo = MsgBox \"|\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -42,7 +89,7 @@ public void PlacesCaretBetweenOpeningAndClosingChars_NestedPair() var original = "MsgBox (|)".ToCodeString(); var expected = "MsgBox (\"|\")".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -54,7 +101,7 @@ public void PlacesCaretBetweenOpeningAndClosingChars_PreservesPosition() var original = "foo = |".ToCodeString(); var expected = "foo = (|)".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -66,7 +113,7 @@ public void WhenNextPositionIsClosingChar_ClosingCharMovesSelection() var original = @"foo = MsgBox(|)".ToCodeString(); var expected = @"foo = MsgBox()|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -78,7 +125,7 @@ public void WhenNextPositionIsClosingChar_Nested_ClosingCharMovesSelection() var original = @"foo = MsgBox(""""|)".ToCodeString(); var expected = @"foo = MsgBox("""")|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -90,7 +137,7 @@ public void DeletingOpeningCharRemovesPairedClosingChar_Parens() var original = @"foo = (|2 + 2)".ToCodeString(); var expected = @"foo = |2 + 2".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -102,7 +149,7 @@ public void DeletingOpeningCharRemovesPairedClosingChar_StringDelimiter() var original = @"foo = ""|2 + 2""".ToCodeString(); var expected = @"foo = |2 + 2".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -114,8 +161,8 @@ public void DeletingOpeningCharRemovesPairedClosingChar_GivenOnlyThatOnTheLine() var original = $"{pair.OpeningChar}|{pair.ClosingChar}".ToCodeString(); var expected = string.Empty; - var result = Run(pair, original, input); - Assert.AreEqual(expected, result?.Code); + Assert.IsTrue(Run(pair, original, input, out var result)); + Assert.AreEqual(expected, result.Code); } [Test] @@ -125,7 +172,7 @@ public void BackspacingInsideComment_BailsOut() var input = Keys.Back; var original = "' _\r\n (|)".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -136,7 +183,7 @@ public void CanTypeClosingChar() var input = pair.ClosingChar; var original = "foo = |".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -148,7 +195,7 @@ public void DeletingOpeningCharRemovesPairedClosingChar_NestedParens() var original = @"foo = ((|2 + 2) + 42)".ToCodeString(); var expected = @"foo = (|2 + 2 + 42)".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -160,7 +207,7 @@ public void DeletingOpeningChar_CallStmtArgList() var original = "Call xy(|z)".ToCodeString(); var expected = "Call xy|z".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -172,7 +219,7 @@ public void DeletingOpeningChar_IndexExpr() var original = "foo = CInt(|z)".ToCodeString(); var expected = "foo = CInt|z".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -187,7 +234,7 @@ public void DeletingOpeningCharRemovesPairedClosingChar_NestedParensMultiline() var expected = @"foo = | _ (2 + 2) + 42".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -201,7 +248,7 @@ public void DeletingPairInLogicalLine_SelectionRemainsOnThatLineIfNonEmpty() var expected = @"foo = ""abc"" & _ | & ""a""".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -217,7 +264,7 @@ public void DeletingMatchingPair_RemovesTrailingEmptyContinuatedLine() var expected = @"foo = | _ (2 + 2) + 42".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -229,7 +276,7 @@ public void WhenNextPositionIsClosingChar_OpeningCharInsertsNewPair() var original = @"foo = MsgBox(|)".ToCodeString(); var expected = @"foo = MsgBox((|))".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -241,7 +288,7 @@ public void WhenCaretBetweenOpeningAndClosingChars_BackspaceRemovesBoth() var original = @"foo = MsgBox(|)".ToCodeString(); var expected = @"foo = MsgBox|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -253,7 +300,7 @@ public void BackspacingWorksWhenCaretIsNotOnLastNonEmptyLine_ConcatOnSameLine() var original = "foo = \"\" & _\r\n \"\" & _\r\n \"|\" & _\r\n \"\"".ToCodeString(); var expected = "foo = \"\" & _\r\n \"|\" & _\r\n \"\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -266,7 +313,7 @@ public void BackspacingWorksWhenCaretIsNotOnLastNonEmptyLine_ConcatOnNextLine() var original = "foo = \"\" _\r\n & \"\" _\r\n & \"|\" _\r\n & \"\"".ToCodeString(); var expected = "foo = \"\" _\r\n & \"|\" _\r\n & \"\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -278,7 +325,7 @@ public void WhenBackspacingClearsLineContinuatedCaretLine_PlacesCaretInsideStrin var original = "foo = \"test\" & _\r\n \"|\"".ToCodeString(); var expected = "foo = \"test|\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -290,7 +337,7 @@ public void WhenBackspacingClearsLineContinuatedCaretLine_WithConcatenatedVbNewL var original = "foo = \"test\" & vbNewLine & _\r\n \"|\"".ToCodeString(); var expected = "foo = \"test|\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -302,7 +349,7 @@ public void WhenBackspacingClearsLineContinuatedCaretLine_WithConcatenatedVbCrLf var original = "foo = \"test\" & vbCrLf & _\r\n \"|\"".ToCodeString(); var expected = "foo = \"test|\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -314,7 +361,7 @@ public void WhenBackspacingClearsLineContinuatedCaretLine_WithConcatenatedVbCr_P var original = "foo = \"test\" & vbCr & _\r\n \"|\"".ToCodeString(); var expected = "foo = \"test|\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -326,7 +373,7 @@ public void WhenBackspacingClearsLineContinuatedCaretLine_WithConcatenatedVbLf_P var original = "foo = \"test\" & vbLf & _\r\n \"|\"".ToCodeString(); var expected = "foo = \"test|\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -338,7 +385,7 @@ public void WhenCaretBetweenOpeningAndClosingChars_BackspaceRemovesBoth_Indented var original = @" foo = ""|""".ToCodeString(); var expected = @" foo = |".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -350,7 +397,7 @@ public void GivenEmptyIndentedLine_OpeningCharIsInsertedAtCaretPosition() var original = @" |".ToCodeString(); var expected = @" ""|""".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsTrue(Run(pair, original, input, out var result)); Assert.AreEqual(expected, result); } @@ -361,7 +408,7 @@ public void DeleteKey_ReturnsNull() var input = Keys.A; var original = @"MsgBox (|)".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -372,8 +419,8 @@ public void UnhandledKey_ReturnsDefault() var input = Keys.A; var original = @"MsgBox |".ToCodeString(); - var result = Run(pair, original, input); - Assert.AreEqual(result, default); + Assert.IsFalse(Run(pair, original, input, out var result)); + Assert.IsNull(result); } [Test] @@ -388,7 +435,7 @@ public void GivenClosingCharForUnmatchedOpeningChar_AsymetricPairBailsOut() var input = pair.ClosingChar; var original = "MsgBox (|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -404,7 +451,7 @@ public void GivenClosingCharForUnmatchedOpeningChar_SymetricPairBailsOut() var input = pair.ClosingChar; var original = "MsgBox \"|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -420,7 +467,7 @@ public void GivenClosingCharForUnmatchedOpeningCharNonConsecutive_SymetricPairBa var input = pair.ClosingChar; var original = "MsgBox \"foo|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -436,7 +483,7 @@ public void GivenOpeningCharInsideTerminatedStringLiteral_BailsOut() var input = pair.OpeningChar; var original = "MsgBox \"foo|\"".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -452,7 +499,7 @@ public void GivenOpeningCharInsideNonTerminatedStringLiteral_BailsOut() var input = pair.OpeningChar; var original = "MsgBox \"foo|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } @@ -468,8 +515,20 @@ public void GivenClosingCharForUnmatchedOpeningChar_SingleChar_SymetricPairBails var input = pair.ClosingChar; var original = "\"|".ToCodeString(); - var result = Run(pair, original, input); + Assert.IsFalse(Run(pair, original, input, out var result)); Assert.IsNull(result); } + + [Test] + public void GivenOpeningCharInsidePair_ReturnsNestedPair() + { + var pair = new SelfClosingPair('(',')'); + var input = pair.OpeningChar; + var original = "(|)".ToCodeString(); + var expected = "((|))".ToCodeString(); + + Assert.IsTrue(Run(pair, original, input, out var result)); + Assert.AreEqual(expected, result); + } } } From b8c14a951343c00959da84f612811ee2448810fe Mon Sep 17 00:00:00 2001 From: Mathieu Guindon Date: Mon, 5 Nov 2018 21:45:15 -0500 Subject: [PATCH 059/107] added tests --- .../AutoComplete/AutoCompleteHandlerBase.cs | 7 +- .../Service/AutoCompleteService.cs | 8 ++- .../Service/SelfClosingPairHandler.cs | 20 +++--- .../Service/SmartConcatenationHandler.cs | 13 ++-- .../SelfClosingPairCompletionTests.cs | 34 ---------- .../SelfClosingPairHandlerTests.cs | 66 +++++++++++++++++++ .../SmartConcatCompletionTests.cs | 8 ++- 7 files changed, 94 insertions(+), 62 deletions(-) create mode 100644 RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs diff --git a/Rubberduck.Core/AutoComplete/AutoCompleteHandlerBase.cs b/Rubberduck.Core/AutoComplete/AutoCompleteHandlerBase.cs index 7dd5eabfcb..2eb2da1fec 100644 --- a/Rubberduck.Core/AutoComplete/AutoCompleteHandlerBase.cs +++ b/Rubberduck.Core/AutoComplete/AutoCompleteHandlerBase.cs @@ -1,7 +1,4 @@ -using System; -using System.Linq; -using Rubberduck.Parsing.VBA.Extensions; -using Rubberduck.Settings; +using Rubberduck.Settings; using Rubberduck.VBEditor; using Rubberduck.VBEditor.Events; using Rubberduck.VBEditor.SourceCodeHandling; @@ -17,6 +14,6 @@ protected AutoCompleteHandlerBase(ICodePaneHandler pane) protected ICodePaneHandler CodePaneHandler { get; } - public abstract CodeString Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings); + public abstract bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings, out CodeString result); } } \ No newline at end of file diff --git a/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs b/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs index a45c93944c..6619ec046a 100644 --- a/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs +++ b/Rubberduck.Core/AutoComplete/Service/AutoCompleteService.cs @@ -135,11 +135,13 @@ private void HandleKeyDown(object sender, AutoCompleteEventArgs e) foreach (var handler in _handlers) { - var result = handler.Handle(e, _settings); - if (result != null && e.Handled) + if (!handler.Handle(e, _settings, out _)) { - return; + continue; } + + e.Handled = true; + return; } } diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs index a195bc033f..ed615e0df6 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs @@ -30,31 +30,32 @@ public SelfClosingPairHandler(ICodePaneHandler pane, SelfClosingPairCompletionSe _scpService = scpService; } - public override CodeString Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings) + public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings, out CodeString result) { + result = null; if (!_selfClosingPairs.TryGetValue(e.Character, out var pair) && e.Character != '\b') { - return null; + return false; } var original = CodePaneHandler.GetCurrentLogicalLine(e.Module); - if (!HandleInternal(e, original, pair, out var result)) + if (!HandleInternal(e, original, pair, out result)) { - return null; + return false; } var snippetPosition = new Selection(result.SnippetPosition.StartLine, 1, result.SnippetPosition.EndLine, 1); result = new CodeString(result.Code, result.CaretPosition, snippetPosition); e.Handled = true; - return result; + return true; } private bool HandleInternal(AutoCompleteEventArgs e, CodeString original, SelfClosingPair pair, out CodeString result) { var isPresent = original.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}"); - if (!ExecuteSelfClosingPair(e, original, pair, out result)) + if (!_scpService.Execute(pair, original, e.Character, out result)) { return false; } @@ -67,7 +68,7 @@ private bool HandleInternal(AutoCompleteEventArgs e, CodeString original, SelfCl prettified = original; // pretend this didn't happen. note: probably breaks if original has extra whitespace. } - if (!ExecuteSelfClosingPair(e, prettified, pair, out result)) + if (!_scpService.Execute(pair, prettified, e.Character, out result)) { return false; } @@ -91,10 +92,5 @@ private bool HandleInternal(AutoCompleteEventArgs e, CodeString original, SelfCl return true; } - - private bool ExecuteSelfClosingPair(AutoCompleteEventArgs e, CodeString original, SelfClosingPair pair, out CodeString result) - { - return _scpService.Execute(pair, original, e.Character, out result); - } } } \ No newline at end of file diff --git a/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs b/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs index b52ddb4d13..7c120886c8 100644 --- a/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs @@ -16,17 +16,18 @@ public SmartConcatenationHandler(ICodePaneHandler pane) { } - public override CodeString Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings) + public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings, out CodeString result) { + result = null; if (e.Character != '\r' || (!settings?.SmartConcat.IsEnabled ?? true)) { - return null; + return false; } var currentContent = CodePaneHandler.GetCurrentLogicalLine(e.Module); if (!currentContent.IsInsideStringLiteral) { - return null; + return false; } var lastIndexLeftOfCaret = currentContent.CaretLine.Length > 2 ? currentContent.CaretLine.Substring(0, currentContent.CaretPosition.StartColumn).LastIndexOf('"') : 0; @@ -51,16 +52,16 @@ public override CodeString Handle(AutoCompleteEventArgs e, AutoCompleteSettings var newPosition = new Selection(newContent.CaretPosition.StartLine + 1, indent + 1); e.Handled = true; - var result = new CodeString(newContent.Code, newPosition, + result = new CodeString(newContent.Code, newPosition, new Selection(newContent.SnippetPosition.StartLine, 1, newContent.SnippetPosition.EndLine, 1)); CodePaneHandler.SubstituteCode(e.Module, result); var finalSelection = new Selection(result.SnippetPosition.StartLine, 1).Offset(result.CaretPosition); CodePaneHandler.SetSelection(e.Module, finalSelection); - return result; + return true; } - return null; + return false; } } } \ No newline at end of file diff --git a/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs b/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs index 9aaee667f9..ecd27ae3a3 100644 --- a/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs +++ b/RubberduckTests/AutoComplete/SelfClosingPairCompletionTests.cs @@ -1,44 +1,10 @@ using NUnit.Framework; using System.Windows.Forms; -using Moq; using Rubberduck.AutoComplete.Service; -using Rubberduck.Settings; using Rubberduck.VBEditor; -using Rubberduck.VBEditor.SourceCodeHandling; -using Rubberduck.VBEditor.Events; -using Rubberduck.VBEditor.SafeComWrappers.Abstract; namespace RubberduckTests.AutoComplete { - [TestFixture] - public class SelfClosingPairHandlerTests - { - private bool Run(CodeString original, CodeString prettified, CodeString rePrettified, out CodeString testResult, char input, bool isControlKeyDown = false, bool isDeleteKey = false) - { - var module = new Mock(); - var handler = new Mock(); - handler.Setup(e => e.GetCurrentLogicalLine(module.Object)).Returns(original); - handler.SetupSequence(e => e.Prettify(module.Object, original)) - .Returns(prettified) - .Returns(rePrettified); - - var service = new Mock(new Mock().Object); - var settings = AutoCompleteSettings.AllEnabled; - - var args = new AutoCompleteEventArgs(module.Object, input, isControlKeyDown, isDeleteKey); - var sut = new SelfClosingPairHandler(handler.Object, service.Object); - - var result = sut.Handle(args, settings); - if (result != null) - { - testResult = new TestCodeString(result); - return true; - } - - testResult = null; - return false; - } - } [TestFixture] public class SelfClosingPairCompletionTests diff --git a/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs new file mode 100644 index 0000000000..7b3f5a0633 --- /dev/null +++ b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs @@ -0,0 +1,66 @@ +using NUnit.Framework; +using Moq; +using Rubberduck.AutoComplete.Service; +using Rubberduck.Settings; +using Rubberduck.VBEditor; +using Rubberduck.VBEditor.SourceCodeHandling; +using Rubberduck.VBEditor.Events; +using Rubberduck.VBEditor.SafeComWrappers.Abstract; + +namespace RubberduckTests.AutoComplete +{ + [TestFixture] + public class SelfClosingPairHandlerTests + { + private bool Run(CodeString original, CodeString prettified, char input, CodeString rePrettified, out TestCodeString testResult, bool isControlKeyDown = false, bool isDeleteKey = false) + { + var service = new Mock(); + return Run(service, original, prettified, input, rePrettified, out testResult, isControlKeyDown, isDeleteKey); + } + + private bool Run(Mock service, CodeString original, CodeString prettified, char input, CodeString rePrettified, out TestCodeString testResult, bool isControlKeyDown = false, bool isDeleteKey = false) + { + var module = new Mock(); + var handler = new Mock(); + handler.Setup(e => e.GetCurrentLogicalLine(module.Object)).Returns(original); + handler.SetupSequence(e => e.Prettify(module.Object, It.IsAny())) + .Returns(prettified) + .Returns(rePrettified); + + var settings = AutoCompleteSettings.AllEnabled; + + var args = new AutoCompleteEventArgs(module.Object, input, isControlKeyDown, isDeleteKey); + var sut = new SelfClosingPairHandler(handler.Object, service.Object); + + if (sut.Handle(args, settings, out var result)) + { + testResult = new TestCodeString(result); + return true; + } + + testResult = null; + return false; + } + + [Test] + public void GivenInvalidInput_ResultIsNull() + { + var input = 'A'; // note: not a self-closing pair opening or closing character, not a handled key (e.g. '\b'). + var original = "DoSomething |".ToCodeString(); + + Assert.IsFalse(Run(original, original, input, original, out var result)); + Assert.IsNull(result); + } + + [Test] + public void GivenValidInput_InvokesSCP() + { + var input = '"'; // note: not a self-closing pair opening or closing character, not a handled key (e.g. '\b'). + var original = "DoSomething |".ToCodeString(); + var rePrettified = @"DoSomething ""|""".ToCodeString(); + + Assert.IsTrue(Run(original, original, input, rePrettified, out var result)); + Assert.IsNotNull(result); + } + } +} diff --git a/RubberduckTests/AutoComplete/SmartConcatCompletionTests.cs b/RubberduckTests/AutoComplete/SmartConcatCompletionTests.cs index 823bbade48..31d516880e 100644 --- a/RubberduckTests/AutoComplete/SmartConcatCompletionTests.cs +++ b/RubberduckTests/AutoComplete/SmartConcatCompletionTests.cs @@ -79,8 +79,12 @@ private static TestCodeString Run(TestCodeString original, char input, bool isCt var sut = InitializeSut(original, out var module, out var settings); var args = new AutoCompleteEventArgs(module.Object, input, isCtrlDown, isDeleteKey); - var result = sut.Handle(args, settings); - return result == null ? null : new TestCodeString(result); + if (sut.Handle(args, settings, out var result)) + { + return new TestCodeString(result); + } + + return null; } private static SmartConcatenationHandler InitializeSut(TestCodeString code, out Mock module, out AutoCompleteSettings settings) From 8c69af0c3980e4a83cac3f1c28f7df64264c8c5d Mon Sep 17 00:00:00 2001 From: Mathieu Guindon Date: Mon, 5 Nov 2018 22:02:04 -0500 Subject: [PATCH 060/107] fixes #4468 --- .../AutoComplete/Service/SelfClosingPairHandler.cs | 6 ++++-- .../AutoComplete/SelfClosingPairHandlerTests.cs | 11 +++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs index ed615e0df6..5d5042f5d6 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs @@ -83,11 +83,13 @@ private bool HandleInternal(AutoCompleteEventArgs e, CodeString original, SelfCl result = result.ReplaceLine(result.CaretPosition.StartLine, currentLine.TrimEnd()); } - if (pair.OpeningChar == '(' && e.Character != '\b' && + if (pair.OpeningChar == '(' && + e.Character == pair.OpeningChar && !result.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}")) { // VBE eats it. just bail out. - return true; + result = null; + return false; } return true; diff --git a/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs index 7b3f5a0633..d71eb64040 100644 --- a/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs +++ b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs @@ -62,5 +62,16 @@ public void GivenValidInput_InvokesSCP() Assert.IsTrue(Run(original, original, input, rePrettified, out var result)); Assert.IsNotNull(result); } + + [Test] + public void GivenOpeningParenthesisOnOtherwiseNonEmptyLine_ReturnsFalse() + { + var input = '('; + var original = "foo = DateSerial(Year|)".ToCodeString(); + var rePrettified = "foo = DateSerial(Year(|))".ToCodeString(); + + Assert.IsFalse(Run(original, original, input, rePrettified, out var result)); + Assert.IsNull(result); + } } } From 35f188fa1b6b86e974659747fe3f37cf5652890b Mon Sep 17 00:00:00 2001 From: Mathieu Guindon Date: Mon, 5 Nov 2018 22:55:14 -0500 Subject: [PATCH 061/107] *actually* fixes #4468 --- .../SelfClosingPairCompletionService.cs | 29 +++---- .../Service/SelfClosingPairHandler.cs | 38 +++++++-- .../SelfClosingPairHandlerTests.cs | 80 +++++++++++++------ 3 files changed, 98 insertions(+), 49 deletions(-) diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs index 524820318f..fbe81b7f65 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairCompletionService.cs @@ -70,13 +70,7 @@ public bool Execute(SelfClosingPair pair, CodeString original, Keys input, out C return false; } - if (input == Keys.Back) - { - result = HandleBackspace(pair, original); - return true; - } - - return false; + return input == Keys.Back && HandleBackspace(pair, original, out result); } private bool HandleOpeningChar(SelfClosingPair pair, CodeString original, out CodeString result) @@ -130,8 +124,9 @@ private bool HandleClosingChar(SelfClosingPair pair, CodeString original, out Co return false; } - private CodeString HandleBackspace(SelfClosingPair pair, CodeString original) + private bool HandleBackspace(SelfClosingPair pair, CodeString original, out CodeString result) { + result = null; var position = original.CaretPosition; var lines = original.Lines; @@ -139,7 +134,7 @@ private CodeString HandleBackspace(SelfClosingPair pair, CodeString original) if (line.Length == 0) { // nothing to delete at caret position... bail out. - return null; + return false; } var previous = Math.Max(0, position.StartColumn - 1); @@ -155,24 +150,25 @@ private CodeString HandleBackspace(SelfClosingPair pair, CodeString original) if (line.Length == 2) { // entire line consists in the self-closing pair itself. - return new CodeString(string.Empty, default, Selection.Empty.ShiftRight()); + result = new CodeString(string.Empty, default, Selection.Empty.ShiftRight()); } // simple case; caret is between the opening and closing chars - remove both. lines[original.CaretPosition.StartLine] = line.Remove(previous, 2); - return new CodeString(string.Join("\r\n", lines), original.CaretPosition.ShiftLeft(), original.SnippetPosition); + result = new CodeString(string.Join("\r\n", lines), original.CaretPosition.ShiftLeft(), original.SnippetPosition); } if (previous < line.Length - 1 && previousChar == pair.OpeningChar) { - return DeleteMatchingTokensMultiline(pair, original); + return DeleteMatchingTokensMultiline(pair, original, out result); } - return null; + return result != null; } - private CodeString DeleteMatchingTokensMultiline(SelfClosingPair pair, CodeString original) + private bool DeleteMatchingTokensMultiline(SelfClosingPair pair, CodeString original, out CodeString result) { + result = null; var position = original.CaretPosition; var lines = original.Lines; var line = lines[original.CaretPosition.StartLine]; @@ -186,7 +182,7 @@ private CodeString DeleteMatchingTokensMultiline(SelfClosingPair pair, CodeStrin if (closingTokenPosition == default) { // could not locate the closing token... bail out. - return null; + return false; } var closingLine = lines[closingTokenPosition.EndLine].Remove(closingTokenPosition.StartColumn, 1); @@ -252,8 +248,9 @@ private CodeString DeleteMatchingTokensMultiline(SelfClosingPair pair, CodeStrin // remove any dangling empty lines... lines = lines.Where((x, i) => i <= position.StartLine || !string.IsNullOrWhiteSpace(x)).ToArray(); - return new CodeString(string.Join("\r\n", lines), finalCaretPosition, + result = new CodeString(string.Join("\r\n", lines), finalCaretPosition, new Selection(original.SnippetPosition.StartLine, 1, original.SnippetPosition.EndLine, 1)); + return true; } private static Selection HandleBackspaceContinuations(string[] nonEmptyLines, Selection finalCaretPosition) diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs index 5d5042f5d6..501f1922ef 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using Rubberduck.Settings; using Rubberduck.VBEditor; @@ -9,22 +10,23 @@ namespace Rubberduck.AutoComplete.Service { public class SelfClosingPairHandler : AutoCompleteHandlerBase { - private readonly IDictionary _selfClosingPairs; + private readonly IReadOnlyList _selfClosingPairs; + private readonly IDictionary _scpInputLookup; private readonly SelfClosingPairCompletionService _scpService; public SelfClosingPairHandler(ICodePaneHandler pane, SelfClosingPairCompletionService scpService) : base(pane) { - var pairs = new[] + _selfClosingPairs = new[] { new SelfClosingPair('(', ')'), new SelfClosingPair('"', '"'), new SelfClosingPair('[', ']'), new SelfClosingPair('{', '}'), }; - _selfClosingPairs = pairs + _scpInputLookup = _selfClosingPairs .Select(p => new {Key = p.OpeningChar, Pair = p}) - .Union(pairs.Where(p => !p.IsSymetric).Select(p => new {Key = p.ClosingChar, Pair = p})) + .Union(_selfClosingPairs.Where(p => !p.IsSymetric).Select(p => new {Key = p.ClosingChar, Pair = p})) .ToDictionary(p => p.Key, p => p.Pair); _scpService = scpService; @@ -33,15 +35,34 @@ public SelfClosingPairHandler(ICodePaneHandler pane, SelfClosingPairCompletionSe public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settings, out CodeString result) { result = null; - if (!_selfClosingPairs.TryGetValue(e.Character, out var pair) && e.Character != '\b') + if (!_scpInputLookup.TryGetValue(e.Character, out var pair) && e.Character != '\b') { return false; } var original = CodePaneHandler.GetCurrentLogicalLine(e.Module); - if (!HandleInternal(e, original, pair, out result)) + + if (pair != null) { - return false; + if (!HandleInternal(e, original, pair, out result)) + { + return false; + } + } + else if (e.Character == '\b') + { + foreach (var scp in _selfClosingPairs) + { + if (HandleInternal(e, original, scp, out result)) + { + break; + } + } + + if (result == null) + { + return false; + } } var snippetPosition = new Selection(result.SnippetPosition.StartLine, 1, result.SnippetPosition.EndLine, 1); @@ -87,7 +108,8 @@ private bool HandleInternal(AutoCompleteEventArgs e, CodeString original, SelfCl e.Character == pair.OpeningChar && !result.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}")) { - // VBE eats it. just bail out. + // VBE eats it. bail out but still swallow the keypress, since we've already re-prettified. + e.Handled = true; result = null; return false; } diff --git a/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs index d71eb64040..12401a27a8 100644 --- a/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs +++ b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs @@ -9,36 +9,62 @@ namespace RubberduckTests.AutoComplete { - [TestFixture] - public class SelfClosingPairHandlerTests + public class SelfClosingPairTestInfo { - private bool Run(CodeString original, CodeString prettified, char input, CodeString rePrettified, out TestCodeString testResult, bool isControlKeyDown = false, bool isDeleteKey = false) - { - var service = new Mock(); - return Run(service, original, prettified, input, rePrettified, out testResult, isControlKeyDown, isDeleteKey); - } + public SelfClosingPairTestInfo(CodeString original, char input, CodeString rePrettified) + : this(new Mock(), original, original, input, rePrettified) { } - private bool Run(Mock service, CodeString original, CodeString prettified, char input, CodeString rePrettified, out TestCodeString testResult, bool isControlKeyDown = false, bool isDeleteKey = false) + public SelfClosingPairTestInfo(CodeString original, char input) + : this(new Mock(), original, original, input, original) { } + + public SelfClosingPairTestInfo(CodeString original, CodeString prettified, char input) + : this(new Mock(), original, prettified, input, prettified) { } + + public SelfClosingPairTestInfo(Mock service, CodeString original, CodeString prettified, char input, CodeString rePrettified, bool isControlKeyDown = false, bool isDeleteKey = false) { - var module = new Mock(); - var handler = new Mock(); - handler.Setup(e => e.GetCurrentLogicalLine(module.Object)).Returns(original); - handler.SetupSequence(e => e.Prettify(module.Object, It.IsAny())) + Original = original; + Prettified = prettified; + Input = input; + RePrettified = rePrettified; + Settings = AutoCompleteSettings.AllEnabled; + + Service = service; + Module = new Mock(); + Handler = new Mock(); + Handler.Setup(e => e.GetCurrentLogicalLine(Module.Object)).Returns(original); + Handler.SetupSequence(e => e.Prettify(Module.Object, It.IsAny())) .Returns(prettified) .Returns(rePrettified); - var settings = AutoCompleteSettings.AllEnabled; + Args = new AutoCompleteEventArgs(Module.Object, input, isControlKeyDown, isDeleteKey); + } + + public Mock Module { get; set; } + public Mock Service { get; set; } + public Mock Handler { get; set; } + public CodeString Original { get; set; } + public CodeString Prettified { get; set; } + public char Input { get; set; } + public CodeString RePrettified { get; set; } + public AutoCompleteEventArgs Args { get; set; } + public AutoCompleteSettings Settings { get; set; } - var args = new AutoCompleteEventArgs(module.Object, input, isControlKeyDown, isDeleteKey); - var sut = new SelfClosingPairHandler(handler.Object, service.Object); + public TestCodeString Result { get; set; } + } - if (sut.Handle(args, settings, out var result)) + [TestFixture] + public class SelfClosingPairHandlerTests + { + private bool Run(SelfClosingPairTestInfo info) + { + var sut = new SelfClosingPairHandler(info.Handler.Object, info.Service.Object); + if (sut.Handle(info.Args, info.Settings, out var result)) { - testResult = new TestCodeString(result); + info.Result = new TestCodeString(result); return true; } - testResult = null; + info.Result = null; return false; } @@ -47,9 +73,10 @@ public void GivenInvalidInput_ResultIsNull() { var input = 'A'; // note: not a self-closing pair opening or closing character, not a handled key (e.g. '\b'). var original = "DoSomething |".ToCodeString(); + var info = new SelfClosingPairTestInfo(original, input); - Assert.IsFalse(Run(original, original, input, original, out var result)); - Assert.IsNull(result); + Assert.IsFalse(Run(info)); + Assert.IsNull(info.Result); } [Test] @@ -58,20 +85,23 @@ public void GivenValidInput_InvokesSCP() var input = '"'; // note: not a self-closing pair opening or closing character, not a handled key (e.g. '\b'). var original = "DoSomething |".ToCodeString(); var rePrettified = @"DoSomething ""|""".ToCodeString(); + var info = new SelfClosingPairTestInfo(original, input, rePrettified); - Assert.IsTrue(Run(original, original, input, rePrettified, out var result)); - Assert.IsNotNull(result); + Assert.IsTrue(Run(info)); + Assert.IsNotNull(info.Result); } [Test] - public void GivenOpeningParenthesisOnOtherwiseNonEmptyLine_ReturnsFalse() + public void GivenOpeningParenthesisOnOtherwiseNonEmptyLine_ReturnsFalseAndSwallowsKeypress() { var input = '('; var original = "foo = DateSerial(Year|)".ToCodeString(); var rePrettified = "foo = DateSerial(Year(|))".ToCodeString(); + var info = new SelfClosingPairTestInfo(original, input, rePrettified); - Assert.IsFalse(Run(original, original, input, rePrettified, out var result)); - Assert.IsNull(result); + Assert.IsFalse(Run(info)); + Assert.IsNull(info.Result); + Assert.IsTrue(info.Args.Handled); } } } From af5c7536dd7ced726433cded0d4190e768df264b Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Tue, 6 Nov 2018 16:44:00 +0100 Subject: [PATCH 062/107] Set AV cloning to shallow, be explicit in what kind of scripts we run --- appveyor.yml | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 499c53cb38..f6652b8e6f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -7,21 +7,18 @@ hosts: # enforce crlf fixing init: git config --global core.autocrlf true -# restrict how much history we try to grab -clone_depth: 3 +# we don't need history +shallow_clone: true # ignore a certain subset of files when evaluating build-changes skip_commits: files: - docs/* - '**/*.md' - # intermediately enable yml changes to trigger builds, because codecov changes only changes the codecov yml ... -# - '**/*.yml' - license - License.rtf branches: only: - master - - staging - next skip_tags: true @@ -44,6 +41,7 @@ dotnet_csproj: file: 'RubberduckBaseProject.csproj' # ;*\Rubberduck.Core.csproj' version: '{version}' assembly_version: '{version}' + # patching fails if we try to patch properties we didn't define #file_version: '{version}' #informational_version: '{version}' @@ -61,10 +59,10 @@ build: # Otherwise we might run tests against artifacts that do not exist test_script: # we use -returntargetcode to fail the build if tests fail - - OpenCover.Console.exe -register:user -returntargetcode -target:"nunit3-console.exe" -targetargs:".\RubberduckTests\bin\RubberduckTests.dll" -output:".\Rubberduck_Coverage.xml" - - OpenCover.Console.exe -register:user -returntargetcode -target:"nunit3-console.exe" -targetargs:".\RubberduckTestsCodeAnalysis\bin\RubberduckTestsCodeAnalysis.dll" -output:".\RubberduckCodeAnalysis_Coverage.xml" + - cmd: OpenCover.Console.exe -register:user -returntargetcode -target:"nunit3-console.exe" -targetargs:".\RubberduckTests\bin\RubberduckTests.dll" -output:".\Rubberduck_Coverage.xml" + - cmd: OpenCover.Console.exe -register:user -returntargetcode -target:"nunit3-console.exe" -targetargs:".\RubberduckTestsCodeAnalysis\bin\RubberduckTestsCodeAnalysis.dll" -output:".\RubberduckCodeAnalysis_Coverage.xml" # when using test_script, after_test seems to not be executed - - codecov -f "Rubberduck_Coverage.xml RubberduckCodeAnalysis_Coverage.xml" + - cmd: codecov -f "Rubberduck_Coverage.xml RubberduckCodeAnalysis_Coverage.xml" for: - branches: From 16a560769b71c981709c49fe9a5629ed35058cdd Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Tue, 6 Nov 2018 22:11:08 +0100 Subject: [PATCH 063/107] Add tests for the RewritingManager Also makes the IRewriteSession expose the target code kind in order to make the RewritingManager testable. --- .../Rewriter/AttributesRewriteSession.cs | 3 + .../Rewriter/CodePaneRewriteSession.cs | 2 + .../Rewriter/IRewriteSession.cs | 4 +- .../Rewriter/RewriteSessionBase.cs | 2 + .../Rewriter/RewritingManager.cs | 11 +- .../Rewriter/AttributesRewriteSessionTests.cs | 11 +- .../Rewriter/CodePaneRewriteSessionTests.cs | 11 +- .../Rewriter/RewriteManagerTests.cs | 228 ++++++++++++++++++ .../Rewriter/RewriteSessionTestBase.cs | 14 ++ 9 files changed, 264 insertions(+), 22 deletions(-) create mode 100644 RubberduckTests/Rewriter/RewriteManagerTests.cs diff --git a/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs index 8d84bfe427..fb8000c4c8 100644 --- a/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs +++ b/Rubberduck.Parsing/Rewriter/AttributesRewriteSession.cs @@ -1,5 +1,6 @@ using System; using Rubberduck.Parsing.VBA; +using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.VBEditor; namespace Rubberduck.Parsing.Rewriter @@ -15,6 +16,8 @@ public AttributesRewriteSession(IParseManager parseManager, IRewriterProvider re _parseManager = parseManager; } + public override CodeKind TargetCodeKind => CodeKind.AttributesCode; + protected override IExecutableModuleRewriter ModuleRewriter(QualifiedModuleName module) { return RewriterProvider.AttributesModuleRewriter(module); diff --git a/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs b/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs index a76d6b91f9..78c3204297 100644 --- a/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs +++ b/Rubberduck.Parsing/Rewriter/CodePaneRewriteSession.cs @@ -1,5 +1,6 @@ using System; using Rubberduck.Parsing.VBA; +using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.VBEditor; namespace Rubberduck.Parsing.Rewriter @@ -15,6 +16,7 @@ public CodePaneRewriteSession(IParseManager parseManager, IRewriterProvider rewr _parseManager = parseManager; } + public override CodeKind TargetCodeKind => CodeKind.CodePaneCode; protected override IExecutableModuleRewriter ModuleRewriter(QualifiedModuleName module) { diff --git a/Rubberduck.Parsing/Rewriter/IRewriteSession.cs b/Rubberduck.Parsing/Rewriter/IRewriteSession.cs index b4488592a4..6d20e3e366 100644 --- a/Rubberduck.Parsing/Rewriter/IRewriteSession.cs +++ b/Rubberduck.Parsing/Rewriter/IRewriteSession.cs @@ -1,4 +1,5 @@ -using Rubberduck.VBEditor; +using Rubberduck.Parsing.VBA.Parsing; +using Rubberduck.VBEditor; namespace Rubberduck.Parsing.Rewriter { @@ -8,5 +9,6 @@ public interface IRewriteSession void Rewrite(); bool IsInvalidated { get; } void Invalidate(); + CodeKind TargetCodeKind { get; } } } \ No newline at end of file diff --git a/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs b/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs index 9256d35c22..da2040c49f 100644 --- a/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs +++ b/Rubberduck.Parsing/Rewriter/RewriteSessionBase.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using NLog; +using Rubberduck.Parsing.VBA.Parsing; using Rubberduck.VBEditor; namespace Rubberduck.Parsing.Rewriter @@ -16,6 +17,7 @@ public abstract class RewriteSessionBase : IRewriteSession protected readonly Logger Logger = LogManager.GetCurrentClassLogger(); private readonly object _invalidationLockObject = new object(); + public abstract CodeKind TargetCodeKind { get; } protected RewriteSessionBase(IRewriterProvider rewriterProvider, Func rewritingAllowed) { diff --git a/Rubberduck.Parsing/Rewriter/RewritingManager.cs b/Rubberduck.Parsing/Rewriter/RewritingManager.cs index 02b9a353e5..60af3da64e 100644 --- a/Rubberduck.Parsing/Rewriter/RewritingManager.cs +++ b/Rubberduck.Parsing/Rewriter/RewritingManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Rubberduck.Parsing.VBA.Parsing; namespace Rubberduck.Parsing.Rewriter { @@ -56,12 +57,12 @@ private bool TryAllowExclusiveRewrite(IRewriteSession rewriteSession) private bool IsCurrentlyActive(IRewriteSession rewriteSession) { - switch (rewriteSession) + switch (rewriteSession.TargetCodeKind) { - case CodePaneRewriteSession codePaneSession: - return _activeCodePaneSessions.Contains(codePaneSession); - case AttributesRewriteSession attributeSession: - return _activeAttributesSessions.Contains(attributeSession); + case CodeKind.CodePaneCode: + return _activeCodePaneSessions.Contains(rewriteSession); + case CodeKind.AttributesCode: + return _activeAttributesSessions.Contains(rewriteSession); default: throw new NotSupportedException(nameof(rewriteSession)); } diff --git a/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs b/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs index 21ca2513f2..94e0c78cbe 100644 --- a/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs +++ b/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs @@ -51,15 +51,10 @@ public void DoesNotCallRewriteOutsideTheSuspendAction() [Test] [Category("Rewriter")] - public void ChecksOutAttributesRewriters() + public void TargetsAttributesCode() { - var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); - var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); - - rewriteSession.CheckOutModuleRewriter(module); - - var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); - Assert.AreEqual(CodeKind.AttributesCode, codeKind); + var rewriteSession = RewriteSession(session => true, out _); + Assert.AreEqual(CodeKind.AttributesCode, rewriteSession.TargetCodeKind); } protected override IRewriteSession RewriteSession(IParseManager parseManager, Func rewritingAllowed, out MockRewriterProvider mockProvider) diff --git a/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs b/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs index efeb565a10..ca2376a9b9 100644 --- a/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs +++ b/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs @@ -82,15 +82,10 @@ public void DoesNotRequestParseIfNoRewritersAreCheckedOut() [Test] [Category("Rewriter")] - public void ChecksOutCodePaneRewriters() + public void TargetsCodePaneCode() { - var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); - var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); - - rewriteSession.CheckOutModuleRewriter(module); - - var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); - Assert.AreEqual(CodeKind.CodePaneCode, codeKind); + var rewriteSession = RewriteSession(session => true, out _); + Assert.AreEqual(CodeKind.CodePaneCode, rewriteSession.TargetCodeKind); } protected override IRewriteSession RewriteSession(IParseManager parseManager, Func rewritingAllowed, out MockRewriterProvider mockProvider) diff --git a/RubberduckTests/Rewriter/RewriteManagerTests.cs b/RubberduckTests/Rewriter/RewriteManagerTests.cs new file mode 100644 index 0000000000..3de06d6c8e --- /dev/null +++ b/RubberduckTests/Rewriter/RewriteManagerTests.cs @@ -0,0 +1,228 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Moq; +using NUnit.Framework; +using Rubberduck.Parsing.Rewriter; +using Rubberduck.Parsing.VBA.Parsing; + +namespace RubberduckTests.Rewriter +{ + [TestFixture] + public class RewriteManagerTests + { + [Test] + [Category("Rewriter")] + public void ReturnsValidCodePaneSessions() + { + var rewritingManager = RewritingManager(out _); + var codePaneSession = rewritingManager.CheckOutCodePaneSession(); + Assert.IsFalse(codePaneSession.IsInvalidated); + } + + + [Test] + [Category("Rewriter")] + public void ReturnsValidAttributesSessions() + { + var rewritingManager = RewritingManager(out _); + var attributesSession = rewritingManager.CheckOutAttributesSession(); + Assert.IsFalse(attributesSession.IsInvalidated); + } + + + [Test] + [Category("Rewriter")] + public void InvalidateAllSessionsCallsInvalidateOnAllActiveSessions() + { + var rewritingManager = RewritingManager(out var mockFactory); + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + + rewritingManager.InvalidateAllSessions(); + + foreach (var mockSession in mockFactory.RequestedCodePaneSessions().Concat(mockFactory.RequestedAttributesSessions())) + { + mockSession.Verify(m => m.Invalidate(), Times.Once); + } + } + + [Test] + [Category("Rewriter")] + public void CallingTheRewritingAllowedCallbackFromAnActiveCodePaneSessionCallsInvalidateOnAllActiveSessions() + { + var rewritingManager = RewritingManager(out var mockFactory); + var codePaneSession = rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + + codePaneSession.Rewrite(); + + foreach (var mockSession in mockFactory.RequestedCodePaneSessions().Concat(mockFactory.RequestedAttributesSessions())) + { + mockSession.Verify(m => m.Invalidate(), Times.Once); + } + } + + [Test] + [Category("Rewriter")] + public void CallingTheRewritingAllowedCallbackFromAnActiveAttributesSessionCallsInvalidateOnAllActiveSessions() + { + var rewritingManager = RewritingManager(out var mockFactory); + rewritingManager.CheckOutCodePaneSession(); + var attributesSession = rewritingManager.CheckOutAttributesSession(); + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + + attributesSession.Rewrite(); + + foreach (var mockSession in mockFactory.RequestedCodePaneSessions().Concat(mockFactory.RequestedAttributesSessions())) + { + mockSession.Verify(m => m.Invalidate(), Times.Once); + } + } + + [Test] + [Category("Rewriter")] + public void CallingTheRewritingAllowedCallbackFromANoLongerActiveCodePaneSessionDoesNotCallInvalidateOnAnyActiveSession_InactiveDueToRewrite() + { + var rewritingManager = RewritingManager(out var mockFactory); + var codePaneSession = rewritingManager.CheckOutCodePaneSession(); + var attributesSession = rewritingManager.CheckOutAttributesSession(); + + rewritingManager.InvalidateAllSessions(); + + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + + codePaneSession.Rewrite(); + + foreach (var mockSession in mockFactory.RequestedCodePaneSessions() + .Concat(mockFactory.RequestedAttributesSessions()) + .Where(session => session.Object != codePaneSession && session.Object != attributesSession)) + { + mockSession.Verify(m => m.Invalidate(), Times.Never); + } + } + + [Test] + [Category("Rewriter")] + public void CallingTheRewritingAllowedCallbackFromANoLongerActiveAttributesSessionDoesNotCallInvalidateOnAnyActiveSession_InactiveDueToRewrite() + { + var rewritingManager = RewritingManager(out var mockFactory); + var codePaneSession = rewritingManager.CheckOutCodePaneSession(); + var attributesSession = rewritingManager.CheckOutAttributesSession(); + + rewritingManager.InvalidateAllSessions(); + + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + + codePaneSession.Rewrite(); + + foreach (var mockSession in mockFactory.RequestedCodePaneSessions() + .Concat(mockFactory.RequestedAttributesSessions()) + .Where(session => session.Object != codePaneSession && session.Object != attributesSession)) + { + mockSession.Verify(m => m.Invalidate(), Times.Never); + } + } + + [Test] + [Category("Rewriter")] + public void CallingTheRewritingAllowedCallbackFromANoLongerActiveCodePaneSessionDoesNotCallInvalidateOnAnyActiveSession_InactiveDueToInvalidateAll() + { + var rewritingManager = RewritingManager(out var mockFactory); + var codePaneSession = rewritingManager.CheckOutCodePaneSession(); + var attributesSession = rewritingManager.CheckOutAttributesSession(); + + attributesSession.Rewrite(); + + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + + codePaneSession.Rewrite(); + + foreach (var mockSession in mockFactory.RequestedCodePaneSessions() + .Concat(mockFactory.RequestedAttributesSessions()) + .Where(session => session.Object != codePaneSession && session.Object != attributesSession)) + { + mockSession.Verify(m => m.Invalidate(), Times.Never); + } + } + + [Test] + [Category("Rewriter")] + public void CallingTheRewritingAllowedCallbackFromANoLongerActiveAttributesSessionDoesNotCallInvalidateOnAnyActiveSession_InactiveDueToInvalidateAll() + { + var rewritingManager = RewritingManager(out var mockFactory); + var codePaneSession = rewritingManager.CheckOutCodePaneSession(); + var attributesSession = rewritingManager.CheckOutAttributesSession(); + + codePaneSession.Rewrite(); + + rewritingManager.CheckOutCodePaneSession(); + rewritingManager.CheckOutAttributesSession(); + + attributesSession.Rewrite(); + + foreach (var mockSession in mockFactory.RequestedCodePaneSessions() + .Concat(mockFactory.RequestedAttributesSessions()) + .Where( session => session.Object != codePaneSession && session.Object != attributesSession)) + { + mockSession.Verify(m => m.Invalidate(), Times.Never); + } + } + + private IRewritingManager RewritingManager(out MockRewriteSessionFactory mockFactory) + { + mockFactory = new MockRewriteSessionFactory(); + return new RewritingManager(mockFactory); + } + } + + public class MockRewriteSessionFactory : IRewriteSessionFactory + { + private readonly List> _requestedCodePaneSessions = new List>(); + private readonly List> _requestedAttributesSessions = new List>(); + + public IEnumerable> RequestedCodePaneSessions() + { + return _requestedCodePaneSessions; + } + + public IEnumerable> RequestedAttributesSessions() + { + return _requestedAttributesSessions; + } + + public IRewriteSession CodePaneSession(Func rewritingAllowed) + { + var mockSession = MockSession(rewritingAllowed, CodeKind.CodePaneCode); + _requestedCodePaneSessions.Add(mockSession); + return mockSession.Object; + } + + private Mock MockSession(Func rewritingAllowed, CodeKind targetCodeKind) + { + var mockSession = new Mock(); + mockSession.Setup(m => m.Rewrite()).Callback(() => rewritingAllowed.Invoke(mockSession.Object)); + var isInvalidated = false; + mockSession.Setup(m => m.IsInvalidated).Returns(() => isInvalidated); + mockSession.Setup(m => m.Invalidate()).Callback(() => isInvalidated = true); + mockSession.Setup(m => m.TargetCodeKind).Returns(targetCodeKind); + + return mockSession; + } + + public IRewriteSession AttributesSession(Func rewritingAllowed) + { + var mockSession = MockSession(rewritingAllowed, CodeKind.AttributesCode); + _requestedAttributesSessions.Add(mockSession); + return mockSession.Object; + } + } +} \ No newline at end of file diff --git a/RubberduckTests/Rewriter/RewriteSessionTestBase.cs b/RubberduckTests/Rewriter/RewriteSessionTestBase.cs index 727814dc2d..dcea529eff 100644 --- a/RubberduckTests/Rewriter/RewriteSessionTestBase.cs +++ b/RubberduckTests/Rewriter/RewriteSessionTestBase.cs @@ -168,6 +168,20 @@ public void CallsRewriteOnlyOnceForRewritersCheckedOutMultipleTimes() mockRewriter.Verify(m => m.Rewrite(), Times.Once); } + [Test] + [Category("Rewriter")] + public void ChecksOutRewritersForTheTargetCodeKind() + { + var rewriteSession = RewriteSession(session => true, out var mockRewriterProvider); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + + rewriteSession.CheckOutModuleRewriter(module); + + var expectedCodeKind = rewriteSession.TargetCodeKind; + var (qmn, actualCodeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); + Assert.AreEqual(expectedCodeKind, actualCodeKind); + } + protected IRewriteSession RewriteSession(Func rewritingAllowed, out MockRewriterProvider mockProvider) { From 88377e6f4fec931c851533ae8b50bfcd92a77be7 Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Wed, 7 Nov 2018 00:16:35 +0100 Subject: [PATCH 064/107] Fall back to clone_depth, add justification in a comment --- appveyor.yml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index f6652b8e6f..640cd79a16 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -7,8 +7,15 @@ hosts: # enforce crlf fixing init: git config --global core.autocrlf true -# we don't need history -shallow_clone: true + +# history limited to 15 commits, since we ran into trouble with a limit of 3 +# the limit can be rather +clone_depth: 15 +# explicitly do not shallow-clone. +# Line-Endings are wrong on github, because of CRLF fixing +# shallow-clone would download a zip, which doesn't fix the line-endings for unit-tests +shallow_clone: false + # ignore a certain subset of files when evaluating build-changes skip_commits: files: From 42f887fc9450116d3846bbfbd0336c7c8bf15c90 Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Wed, 7 Nov 2018 00:25:44 +0100 Subject: [PATCH 065/107] DRY the installer setup in appveyor.yml --- appveyor.yml | 44 ++++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 640cd79a16..113efb42cc 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -71,19 +71,35 @@ test_script: # when using test_script, after_test seems to not be executed - cmd: codecov -f "Rubberduck_Coverage.xml RubberduckCodeAnalysis_Coverage.xml" +# Define the installer-name depending on what branch we're building on +environment: + installer_dir: Rubberduck.Deployment\InnoSetup\Installers\ for: - - branches: - only: - - next - after_test: - - iscc /O "Rubberduck.Deployment\InnoSetup\Rubberduck.Installer.Build.iss" - - move Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.exe Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-pre.exe - - branches: - only: - - master - after_test: - - iscc /O "Rubberduck.Deployment\InnoSetup\Rubberduck.Installer.Build.iss" - - move Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.exe Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-pre.exe +- + branches: + only: + - next + environment: + installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-pre.exe +- + branches: + only: + - master + environment: + installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%.exe +- + branches: + except: + - master + - next + environment: + # fall back to calling the installer after the branch we're on + installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-%APPVEYOR_REPO_BRANCH%.exe + +# Create Installers for +after_test: + - cmd: iscc /O "Rubberduck.Deployment\InnoSetup\Rubberduck.Installer.Build.iss" + - cmd: move %INSTALLER_DIR%\Rubberduck.Setup.exe %INSTALLER_DIR%\%INSTALLER_NAME$ # grab the installers we produce and upload them to github :) artifacts: @@ -96,7 +112,7 @@ deploy: description: AppVeyor build on [master] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq - artifact: Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.$(appveyor_build_version).exe + artifact: $(installer_dir)\$(installer_name) draft: true prerelease: false on: @@ -107,7 +123,7 @@ deploy: description: AppVeyor build on [next] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq - artifact: Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.$(appveyor_build_version)-pre.exe + artifact: $(installer_dir)\$(installer_name) draft: false prerelease: true on: From 853f6de77f0e5ddff992bb10c1681926a4bc2fc2 Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Wed, 7 Nov 2018 01:06:48 +0100 Subject: [PATCH 066/107] fix embarrassing typo --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 113efb42cc..a1144433d2 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -99,7 +99,7 @@ for: # Create Installers for after_test: - cmd: iscc /O "Rubberduck.Deployment\InnoSetup\Rubberduck.Installer.Build.iss" - - cmd: move %INSTALLER_DIR%\Rubberduck.Setup.exe %INSTALLER_DIR%\%INSTALLER_NAME$ + - cmd: move %INSTALLER_DIR%\Rubberduck.Setup.exe %INSTALLER_DIR%\%INSTALLER_NAME% # grab the installers we produce and upload them to github :) artifacts: From d73230d3c9777ca44b54463e4274546b731f7705 Mon Sep 17 00:00:00 2001 From: comintern Date: Tue, 6 Nov 2018 19:52:23 -0600 Subject: [PATCH 067/107] Use Sunburst SDK for build. --- Rubberduck.API/Rubberduck.API.csproj | 2 +- .../Rubberduck.CodeAnalysis.csproj | 2 +- .../Properties/Settings.Designer.cs | 7 +-- Rubberduck.Core/Rubberduck.Core.csproj | 53 +------------------ Rubberduck.Core/UI/About/AboutControl.xaml | 2 +- .../Rubberduck.Deployment.csproj | 2 +- .../Rubberduck.Interaction.csproj | 2 +- Rubberduck.Main/Rubberduck.Main.csproj | 2 +- Rubberduck.Parsing/Rubberduck.Parsing.csproj | 2 +- .../Rubberduck.Refactorings.csproj | 2 +- .../Rubberduck.RegexAssistant.csproj | 2 +- .../Rubberduck.Resources.csproj | 9 +--- .../Rubberduck.SettingsProvider.csproj | 2 +- .../Rubberduck.SmartIndenter.csproj | 2 +- .../Rubberduck.UnitTesting.csproj | 2 +- .../Rubberduck.VBEditor.csproj | 2 +- .../Rubberduck.VBEditor.VB6.csproj | 2 +- .../Rubberduck.VBEditor.VBA.csproj | 2 +- RubberduckBaseProject.csproj | 2 +- .../RubberduckCodeAnalysis.csproj | 2 +- RubberduckTests/RubberduckTests.csproj | 2 +- .../RubberduckTestsCodeAnalysis.csproj | 2 +- 22 files changed, 25 insertions(+), 82 deletions(-) diff --git a/Rubberduck.API/Rubberduck.API.csproj b/Rubberduck.API/Rubberduck.API.csproj index 2aad7d3e2f..1019700262 100644 --- a/Rubberduck.API/Rubberduck.API.csproj +++ b/Rubberduck.API/Rubberduck.API.csproj @@ -1,5 +1,5 @@  - + Rubberduck.API Rubberduck Reflection API diff --git a/Rubberduck.CodeAnalysis/Rubberduck.CodeAnalysis.csproj b/Rubberduck.CodeAnalysis/Rubberduck.CodeAnalysis.csproj index 710227885b..08f91a0755 100644 --- a/Rubberduck.CodeAnalysis/Rubberduck.CodeAnalysis.csproj +++ b/Rubberduck.CodeAnalysis/Rubberduck.CodeAnalysis.csproj @@ -1,5 +1,5 @@  - + Rubberduck.CodeAnalysis Assembly Containing the Code Analysis features exposed by Rubberduck diff --git a/Rubberduck.Core/Properties/Settings.Designer.cs b/Rubberduck.Core/Properties/Settings.Designer.cs index b91735e4f8..9c9c23a4ea 100644 --- a/Rubberduck.Core/Properties/Settings.Designer.cs +++ b/Rubberduck.Core/Properties/Settings.Designer.cs @@ -305,7 +305,8 @@ public static Settings Default { false false 10 - 6 + false + 0 ")] public global::Rubberduck.Settings.GeneralSettings GeneralSettings { @@ -464,7 +465,7 @@ public static Settings Default { public global::Rubberduck.Settings.AutoCompleteSettings AutoCompleteSettings { get { return ((global::Rubberduck.Settings.AutoCompleteSettings)(this["AutoCompleteSettings"])); - } -} + } + } } } diff --git a/Rubberduck.Core/Rubberduck.Core.csproj b/Rubberduck.Core/Rubberduck.Core.csproj index aa0e0bf1a2..46ea79c2e7 100644 --- a/Rubberduck.Core/Rubberduck.Core.csproj +++ b/Rubberduck.Core/Rubberduck.Core.csproj @@ -1,5 +1,5 @@  - + Rubberduck Rubberduck.Core @@ -81,55 +81,4 @@ 2.0.20525 - - - - - - - - - - $([System.String]::Copy('%(Filename)').Replace('.Designer', '')).cs - - - %(Filename).cs - - - - - - - - Designer - MSBuild:Compile - - - Code - %(Filename) - - - - Resources.resx - true - true - - - Resources.Designer.cs - ResXFileCodeGenerator - - - - True - True - Settings.settings - True - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - - \ No newline at end of file diff --git a/Rubberduck.Core/UI/About/AboutControl.xaml b/Rubberduck.Core/UI/About/AboutControl.xaml index f420fff7a9..63996c942c 100644 --- a/Rubberduck.Core/UI/About/AboutControl.xaml +++ b/Rubberduck.Core/UI/About/AboutControl.xaml @@ -185,7 +185,7 @@ Brian Zenger Bruno Costa Carlos J. Quintero (MZ-Tools) Clemens Lieb -@Comintern +@Comintern, esq. Christopher McClellan @daFreeMan @Duga SE chat bot diff --git a/Rubberduck.Deployment/Rubberduck.Deployment.csproj b/Rubberduck.Deployment/Rubberduck.Deployment.csproj index a10dbe493d..7d93535d35 100644 --- a/Rubberduck.Deployment/Rubberduck.Deployment.csproj +++ b/Rubberduck.Deployment/Rubberduck.Deployment.csproj @@ -1,5 +1,5 @@  - + Rubberduck.Deployment Copyright © 2018 diff --git a/Rubberduck.Interaction/Rubberduck.Interaction.csproj b/Rubberduck.Interaction/Rubberduck.Interaction.csproj index 2b09548001..ca639854aa 100644 --- a/Rubberduck.Interaction/Rubberduck.Interaction.csproj +++ b/Rubberduck.Interaction/Rubberduck.Interaction.csproj @@ -1,5 +1,5 @@  - + Copyright © 2018 Rubberduck.Interaction diff --git a/Rubberduck.Main/Rubberduck.Main.csproj b/Rubberduck.Main/Rubberduck.Main.csproj index 0d8eb19ecf..80d1356f85 100644 --- a/Rubberduck.Main/Rubberduck.Main.csproj +++ b/Rubberduck.Main/Rubberduck.Main.csproj @@ -1,5 +1,5 @@  - + Rubberduck Rubberduck diff --git a/Rubberduck.Parsing/Rubberduck.Parsing.csproj b/Rubberduck.Parsing/Rubberduck.Parsing.csproj index 39112bf542..fff21b23a8 100644 --- a/Rubberduck.Parsing/Rubberduck.Parsing.csproj +++ b/Rubberduck.Parsing/Rubberduck.Parsing.csproj @@ -1,5 +1,5 @@  - + Rubberduck.Parsing Rubberduck.Parsing diff --git a/Rubberduck.Refactorings/Rubberduck.Refactorings.csproj b/Rubberduck.Refactorings/Rubberduck.Refactorings.csproj index 88660ec695..3010a01373 100644 --- a/Rubberduck.Refactorings/Rubberduck.Refactorings.csproj +++ b/Rubberduck.Refactorings/Rubberduck.Refactorings.csproj @@ -1,5 +1,5 @@  - + {D4B6A510-14E1-420A-A8D5-6A09890FD7D8} Rubberduck.Refactorings diff --git a/Rubberduck.RegexAssistant/Rubberduck.RegexAssistant.csproj b/Rubberduck.RegexAssistant/Rubberduck.RegexAssistant.csproj index d9a1436d37..5ebd3b9d27 100644 --- a/Rubberduck.RegexAssistant/Rubberduck.RegexAssistant.csproj +++ b/Rubberduck.RegexAssistant/Rubberduck.RegexAssistant.csproj @@ -1,5 +1,5 @@  - + Rubberduck.RegexAssistant Rubberduck.RegexAssistant diff --git a/Rubberduck.Resources/Rubberduck.Resources.csproj b/Rubberduck.Resources/Rubberduck.Resources.csproj index 88e5eb41a0..4e624ac7ca 100644 --- a/Rubberduck.Resources/Rubberduck.Resources.csproj +++ b/Rubberduck.Resources/Rubberduck.Resources.csproj @@ -1,5 +1,5 @@  - + Rubberduck.Resources Rubberduck.Resources @@ -12,12 +12,5 @@ - - PublicResXFileCodeGenerator - $([System.String]::Copy('%(FileName)')).Designer.cs - - - $([System.String]::Copy('%(Filename)').Replace('.Designer', '')).resx - \ No newline at end of file diff --git a/Rubberduck.SettingsProvider/Rubberduck.SettingsProvider.csproj b/Rubberduck.SettingsProvider/Rubberduck.SettingsProvider.csproj index e9d2c6a45f..e47f248f5b 100644 --- a/Rubberduck.SettingsProvider/Rubberduck.SettingsProvider.csproj +++ b/Rubberduck.SettingsProvider/Rubberduck.SettingsProvider.csproj @@ -1,5 +1,5 @@  - + Rubberduck.SettingsProvider Rubberduck.SettingsProvider diff --git a/Rubberduck.SmartIndenter/Rubberduck.SmartIndenter.csproj b/Rubberduck.SmartIndenter/Rubberduck.SmartIndenter.csproj index 60b66a4d56..199499db54 100644 --- a/Rubberduck.SmartIndenter/Rubberduck.SmartIndenter.csproj +++ b/Rubberduck.SmartIndenter/Rubberduck.SmartIndenter.csproj @@ -1,5 +1,5 @@  - + Rubberduck.SmartIndenter Rubberduck.SmartIndenter diff --git a/Rubberduck.UnitTesting/Rubberduck.UnitTesting.csproj b/Rubberduck.UnitTesting/Rubberduck.UnitTesting.csproj index 7b7487682e..1c2d602c06 100644 --- a/Rubberduck.UnitTesting/Rubberduck.UnitTesting.csproj +++ b/Rubberduck.UnitTesting/Rubberduck.UnitTesting.csproj @@ -1,5 +1,5 @@  - + Rubberduck.UnitTesting Rubberduck.UnitTesting diff --git a/Rubberduck.VBEEditor/Rubberduck.VBEditor.csproj b/Rubberduck.VBEEditor/Rubberduck.VBEditor.csproj index 0c61c2dbd3..4b83744329 100644 --- a/Rubberduck.VBEEditor/Rubberduck.VBEditor.csproj +++ b/Rubberduck.VBEEditor/Rubberduck.VBEditor.csproj @@ -1,5 +1,5 @@  - + Rubberduck.VBEditor Rubberduck.VBEditor diff --git a/Rubberduck.VBEditor.VB6/Rubberduck.VBEditor.VB6.csproj b/Rubberduck.VBEditor.VB6/Rubberduck.VBEditor.VB6.csproj index 9b371d17e1..b677268cc7 100644 --- a/Rubberduck.VBEditor.VB6/Rubberduck.VBEditor.VB6.csproj +++ b/Rubberduck.VBEditor.VB6/Rubberduck.VBEditor.VB6.csproj @@ -1,5 +1,5 @@  - + Rubberduck.VBEditor.VB6 Rubberduck.VBEditor.VB6 diff --git a/Rubberduck.VBEditor.VBA/Rubberduck.VBEditor.VBA.csproj b/Rubberduck.VBEditor.VBA/Rubberduck.VBEditor.VBA.csproj index b73cfd5a9e..ba9cd1de44 100644 --- a/Rubberduck.VBEditor.VBA/Rubberduck.VBEditor.VBA.csproj +++ b/Rubberduck.VBEditor.VBA/Rubberduck.VBEditor.VBA.csproj @@ -1,5 +1,5 @@  - + Rubberduck.VBEditor.VBA Rubberduck.VBEditor.VBA diff --git a/RubberduckBaseProject.csproj b/RubberduckBaseProject.csproj index 6d8f658ad9..aae613ee2a 100644 --- a/RubberduckBaseProject.csproj +++ b/RubberduckBaseProject.csproj @@ -1,4 +1,4 @@ - + Library diff --git a/RubberduckCodeAnalysis/RubberduckCodeAnalysis.csproj b/RubberduckCodeAnalysis/RubberduckCodeAnalysis.csproj index 067eb14cc7..e2e561062d 100644 --- a/RubberduckCodeAnalysis/RubberduckCodeAnalysis.csproj +++ b/RubberduckCodeAnalysis/RubberduckCodeAnalysis.csproj @@ -1,5 +1,5 @@  - + Rubberduck Code Analysis Internal Analyzer to enforce standards for Rubberduck solution's codebase diff --git a/RubberduckTests/RubberduckTests.csproj b/RubberduckTests/RubberduckTests.csproj index abd512bf3c..5ba260dd6a 100644 --- a/RubberduckTests/RubberduckTests.csproj +++ b/RubberduckTests/RubberduckTests.csproj @@ -1,5 +1,5 @@  - + RubberduckTests RubberduckTests diff --git a/RubberduckTestsCodeAnalysis/RubberduckTestsCodeAnalysis.csproj b/RubberduckTestsCodeAnalysis/RubberduckTestsCodeAnalysis.csproj index 0b465f1979..cc977e60cb 100644 --- a/RubberduckTestsCodeAnalysis/RubberduckTestsCodeAnalysis.csproj +++ b/RubberduckTestsCodeAnalysis/RubberduckTestsCodeAnalysis.csproj @@ -1,5 +1,5 @@  - + RubberduckTestsCodeAnalysis RubberduckTestsCodeAnalysis From f3f990f9218ad05be45616aca862c410ecd4cfe9 Mon Sep 17 00:00:00 2001 From: comintern Date: Tue, 6 Nov 2018 19:55:45 -0600 Subject: [PATCH 068/107] Forgot to disbar comintern. --- Rubberduck.Core/UI/About/AboutControl.xaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Rubberduck.Core/UI/About/AboutControl.xaml b/Rubberduck.Core/UI/About/AboutControl.xaml index 63996c942c..f420fff7a9 100644 --- a/Rubberduck.Core/UI/About/AboutControl.xaml +++ b/Rubberduck.Core/UI/About/AboutControl.xaml @@ -185,7 +185,7 @@ Brian Zenger Bruno Costa Carlos J. Quintero (MZ-Tools) Clemens Lieb -@Comintern, esq. +@Comintern Christopher McClellan @daFreeMan @Duga SE chat bot From 09ac9cbcfae4e98f8e0f0ac41e26d3acaf12f9b7 Mon Sep 17 00:00:00 2001 From: comintern Date: Tue, 6 Nov 2018 20:38:06 -0600 Subject: [PATCH 069/107] Remove extra whitespace. --- Rubberduck.Resources/Rubberduck.Resources.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/Rubberduck.Resources/Rubberduck.Resources.csproj b/Rubberduck.Resources/Rubberduck.Resources.csproj index 4e624ac7ca..1881eb1be9 100644 --- a/Rubberduck.Resources/Rubberduck.Resources.csproj +++ b/Rubberduck.Resources/Rubberduck.Resources.csproj @@ -7,7 +7,6 @@ {1B84B387-F7C4-4876-9BDF-C644C365359A} - From 4494b8d431af3379fa8eefb6394166925d49494f Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Wed, 7 Nov 2018 23:00:59 +0100 Subject: [PATCH 070/107] Change Rewrite to TryRewrite This change on the IRewriteSession allows the user to see whether the rewrite actually happened successfully. --- .../QuickFixes/QuickFixProvider.cs | 10 +-- .../Rewriter/AttributesRewriteSession.cs | 5 +- .../Rewriter/CodePaneRewriteSession.cs | 4 +- .../Rewriter/IRewriteSession.cs | 2 +- .../Rewriter/RewriteSessionBase.cs | 14 ++-- .../EncapsulateFieldRefactoring.cs | 2 +- .../ExtractInterfaceRefactoring.cs | 2 +- .../ImplementInterfaceRefactoring.cs | 2 +- .../IntroduceFieldRefactoring.cs | 2 +- .../IntroduceParameterRefactoring.cs | 2 +- .../MoveCloserToUsageRefactoring.cs | 2 +- .../RemoveParametersRefactoring.cs | 2 +- .../Rename/RenameRefactoring.cs | 2 +- .../ReorderParametersRefactoring.cs | 2 +- .../PostProcessing/ModuleRewriterTests.cs | 2 +- .../Rewriter/AttributesRewriteSessionTests.cs | 36 +++++++++- .../Rewriter/CodePaneRewriteSessionTests.cs | 19 +++-- .../Rewriter/RewriteManagerTests.cs | 18 ++--- .../Rewriter/RewriteSessionTestBase.cs | 72 +++++++++++++------ 19 files changed, 140 insertions(+), 60 deletions(-) diff --git a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs index 8f9bd99fee..4429adf703 100644 --- a/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs +++ b/Rubberduck.CodeAnalysis/QuickFixes/QuickFixProvider.cs @@ -78,7 +78,7 @@ public void Fix(IQuickFix fix, IInspectionResult result) var rewriteSession = RewriteSession(fix.TargetCodeKind); fix.Fix(result, rewriteSession); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); } private IRewriteSession RewriteSession(CodeKind targetCodeKind) @@ -115,7 +115,7 @@ public void FixInProcedure(IQuickFix fix, QualifiedMemberName? qualifiedMember, fix.Fix(result, rewriteSession); } - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); } public void FixInModule(IQuickFix fix, QualifiedSelection selection, Type inspectionType, IEnumerable results) @@ -137,7 +137,7 @@ public void FixInModule(IQuickFix fix, QualifiedSelection selection, Type inspec fix.Fix(result, rewriteSession); } - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); } public void FixInProject(IQuickFix fix, QualifiedSelection selection, Type inspectionType, IEnumerable results) @@ -159,7 +159,7 @@ public void FixInProject(IQuickFix fix, QualifiedSelection selection, Type inspe fix.Fix(result, rewriteSession); } - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); } public void FixAll(IQuickFix fix, Type inspectionType, IEnumerable results) @@ -181,7 +181,7 @@ public void FixAll(IQuickFix fix, Type inspectionType, IEnumerable references, Declaration method, IRewriteSession rewriteSession) diff --git a/Rubberduck.Refactorings/Rename/RenameRefactoring.cs b/Rubberduck.Refactorings/Rename/RenameRefactoring.cs index 241d556dd5..0abb562820 100644 --- a/Rubberduck.Refactorings/Rename/RenameRefactoring.cs +++ b/Rubberduck.Refactorings/Rename/RenameRefactoring.cs @@ -103,7 +103,7 @@ private void RefactorImpl(Declaration inputTarget, IRenamePresenter presenter) { var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); Rename(rewriteSession); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); } } catch (RuntimeBinderException rbEx) diff --git a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs index d97435338d..1f5bfaf4dc 100644 --- a/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs +++ b/Rubberduck.Refactorings/ReorderParameters/ReorderParametersRefactoring.cs @@ -56,7 +56,7 @@ public void Refactor() var rewriteSession = _rewritingManager.CheckOutCodePaneSession(); AdjustReferences(_model.TargetDeclaration.References, rewriteSession); AdjustSignatures(rewriteSession); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); if (oldSelection.HasValue && !pane.IsWrappingNullReference) { diff --git a/RubberduckTests/PostProcessing/ModuleRewriterTests.cs b/RubberduckTests/PostProcessing/ModuleRewriterTests.cs index f5bfb3b672..2b3eeb9fac 100644 --- a/RubberduckTests/PostProcessing/ModuleRewriterTests.cs +++ b/RubberduckTests/PostProcessing/ModuleRewriterTests.cs @@ -78,7 +78,7 @@ public void RewriterInsertsRewriterOutputAtLine1() var rewriteSession = rewritingManager.CheckOutCodePaneSession(); var rewriter = rewriteSession.CheckOutModuleRewriter(component.QualifiedModuleName); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); Assert.AreEqual(content, rewriter.GetText()); } diff --git a/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs b/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs index 94e0c78cbe..2677956788 100644 --- a/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs +++ b/RubberduckTests/Rewriter/AttributesRewriteSessionTests.cs @@ -26,7 +26,7 @@ public void UsesASuspendActionToRewrite() var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); rewriteSession.CheckOutModuleRewriter(module); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); mockParseManager.Verify(m => m.OnSuspendParser(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Once); } @@ -44,11 +44,43 @@ public void DoesNotCallRewriteOutsideTheSuspendAction() rewriteSession.CheckOutModuleRewriter(module); var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); mockRewriter.Verify(m => m.Rewrite(), Times.Never); } + [Test] + [Category("Rewriter")] + public void TryRewriteReturnsFalseIfNotInvalidatedAndParsingAllowedAndSuspensionDoesNotComplete() + { + var parseManager = new Mock(); + parseManager.Setup(m => m.OnSuspendParser(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) + .Callback((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => suspendAction()) + .Returns((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => SuspensionResult.UnexpectedError); + + var rewriteSession = RewriteSession(parseManager.Object, session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + var actual = rewriteSession.TryRewrite(); + Assert.IsFalse(actual); + } + + [Test] + [Category("Rewriter")] + public void TryRewriteReturnsTrueIfNotInvalidatedAndParsingAllowedAndSuspensionCompletes() + { + var parseManager = new Mock(); + parseManager.Setup(m => m.OnSuspendParser(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) + .Callback((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => suspendAction()) + .Returns((object requestor, IEnumerable allowedStates, Action suspendAction, int timeout) => SuspensionResult.Completed); + + var rewriteSession = RewriteSession(parseManager.Object, session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + var actual = rewriteSession.TryRewrite(); + Assert.IsTrue(actual); + } + [Test] [Category("Rewriter")] public void TargetsAttributesCode() diff --git a/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs b/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs index ca2376a9b9..a9bcab5304 100644 --- a/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs +++ b/RubberduckTests/Rewriter/CodePaneRewriteSessionTests.cs @@ -25,7 +25,7 @@ public void RequestsParseAfterRewriteIfNotInvalidatedAndParsingAllowed() rewriteSession.CheckOutModuleRewriter(module); rewriteSession.CheckOutModuleRewriter(otherModule); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Once); } @@ -44,7 +44,7 @@ public void DoesNotCallRequestsParseAfterRewriteIfInvalidated() rewriteSession.Invalidate(); rewriteSession.CheckOutModuleRewriter(otherModule); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Never); } @@ -62,7 +62,7 @@ public void DoesNotRequestsParseAfterRewriteIfNotParsingAllowed() rewriteSession.CheckOutModuleRewriter(module); rewriteSession.CheckOutModuleRewriter(otherModule); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Never); } @@ -75,11 +75,22 @@ public void DoesNotRequestParseIfNoRewritersAreCheckedOut() mockParseManager.Setup(m => m.OnParseRequested(It.IsAny())); var rewriteSession = RewriteSession(mockParseManager.Object, session => true, out _); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); mockParseManager.Verify(m => m.OnParseRequested(It.IsAny()), Times.Never); } + [Test] + [Category("Rewriter")] + public void TryRewriteReturnsTrueIfNotInvalidatedAndParsingAllowed() + { + var rewriteSession = RewriteSession(session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + var actual = rewriteSession.TryRewrite(); + Assert.IsTrue(actual); + } + [Test] [Category("Rewriter")] public void TargetsCodePaneCode() diff --git a/RubberduckTests/Rewriter/RewriteManagerTests.cs b/RubberduckTests/Rewriter/RewriteManagerTests.cs index 3de06d6c8e..08954f817a 100644 --- a/RubberduckTests/Rewriter/RewriteManagerTests.cs +++ b/RubberduckTests/Rewriter/RewriteManagerTests.cs @@ -59,7 +59,7 @@ public void CallingTheRewritingAllowedCallbackFromAnActiveCodePaneSessionCallsIn rewritingManager.CheckOutCodePaneSession(); rewritingManager.CheckOutAttributesSession(); - codePaneSession.Rewrite(); + codePaneSession.TryRewrite(); foreach (var mockSession in mockFactory.RequestedCodePaneSessions().Concat(mockFactory.RequestedAttributesSessions())) { @@ -77,7 +77,7 @@ public void CallingTheRewritingAllowedCallbackFromAnActiveAttributesSessionCalls rewritingManager.CheckOutCodePaneSession(); rewritingManager.CheckOutAttributesSession(); - attributesSession.Rewrite(); + attributesSession.TryRewrite(); foreach (var mockSession in mockFactory.RequestedCodePaneSessions().Concat(mockFactory.RequestedAttributesSessions())) { @@ -98,7 +98,7 @@ public void CallingTheRewritingAllowedCallbackFromANoLongerActiveCodePaneSession rewritingManager.CheckOutCodePaneSession(); rewritingManager.CheckOutAttributesSession(); - codePaneSession.Rewrite(); + codePaneSession.TryRewrite(); foreach (var mockSession in mockFactory.RequestedCodePaneSessions() .Concat(mockFactory.RequestedAttributesSessions()) @@ -121,7 +121,7 @@ public void CallingTheRewritingAllowedCallbackFromANoLongerActiveAttributesSessi rewritingManager.CheckOutCodePaneSession(); rewritingManager.CheckOutAttributesSession(); - codePaneSession.Rewrite(); + codePaneSession.TryRewrite(); foreach (var mockSession in mockFactory.RequestedCodePaneSessions() .Concat(mockFactory.RequestedAttributesSessions()) @@ -139,12 +139,12 @@ public void CallingTheRewritingAllowedCallbackFromANoLongerActiveCodePaneSession var codePaneSession = rewritingManager.CheckOutCodePaneSession(); var attributesSession = rewritingManager.CheckOutAttributesSession(); - attributesSession.Rewrite(); + attributesSession.TryRewrite(); rewritingManager.CheckOutCodePaneSession(); rewritingManager.CheckOutAttributesSession(); - codePaneSession.Rewrite(); + codePaneSession.TryRewrite(); foreach (var mockSession in mockFactory.RequestedCodePaneSessions() .Concat(mockFactory.RequestedAttributesSessions()) @@ -162,12 +162,12 @@ public void CallingTheRewritingAllowedCallbackFromANoLongerActiveAttributesSessi var codePaneSession = rewritingManager.CheckOutCodePaneSession(); var attributesSession = rewritingManager.CheckOutAttributesSession(); - codePaneSession.Rewrite(); + codePaneSession.TryRewrite(); rewritingManager.CheckOutCodePaneSession(); rewritingManager.CheckOutAttributesSession(); - attributesSession.Rewrite(); + attributesSession.TryRewrite(); foreach (var mockSession in mockFactory.RequestedCodePaneSessions() .Concat(mockFactory.RequestedAttributesSessions()) @@ -209,7 +209,7 @@ public IRewriteSession CodePaneSession(Func rewritingAllo private Mock MockSession(Func rewritingAllowed, CodeKind targetCodeKind) { var mockSession = new Mock(); - mockSession.Setup(m => m.Rewrite()).Callback(() => rewritingAllowed.Invoke(mockSession.Object)); + mockSession.Setup(m => m.TryRewrite()).Callback(() => rewritingAllowed.Invoke(mockSession.Object)); var isInvalidated = false; mockSession.Setup(m => m.IsInvalidated).Returns(() => isInvalidated); mockSession.Setup(m => m.Invalidate()).Callback(() => isInvalidated = true); diff --git a/RubberduckTests/Rewriter/RewriteSessionTestBase.cs b/RubberduckTests/Rewriter/RewriteSessionTestBase.cs index dcea529eff..5a38100261 100644 --- a/RubberduckTests/Rewriter/RewriteSessionTestBase.cs +++ b/RubberduckTests/Rewriter/RewriteSessionTestBase.cs @@ -30,6 +30,29 @@ public void IsInvalidatedAfterCallingInvalidate() Assert.IsTrue(rewriteSession.IsInvalidated); } + [Test] + [Category("Rewriter")] + public void DoesNotCallRewritingAllowedOnRewriteIfNoRewritersHaveBeenCheckedOut() + { + var isCalled = false; + var rewriteSession = RewriteSession(session => + { + isCalled = true; + return true; + }, out _); + rewriteSession.TryRewrite(); + Assert.IsFalse(isCalled); + } + + [Test] + [Category("Rewriter")] + public void TryRewriteReturnsFalseIfNoRewritersHaveBeenCheckedOut() + { + var rewriteSession = RewriteSession(session => true, out _); + var actual = rewriteSession.TryRewrite(); + Assert.IsFalse(actual); + } + [Test] [Category("Rewriter")] public void CallsRewritingAllowedOnRewriteIfNotInvalidatedAndRewritersHaveBeenCheckedOut() @@ -42,24 +65,10 @@ public void CallsRewritingAllowedOnRewriteIfNotInvalidatedAndRewritersHaveBeenCh }, out _); var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); rewriteSession.CheckOutModuleRewriter(module); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); Assert.IsTrue(isCalled); } - [Test] - [Category("Rewriter")] - public void DoesNotCallRewritingAllowedOnRewriteIfNoRewritersHaveBeenCheckedOut() - { - var isCalled = false; - var rewriteSession = RewriteSession(session => - { - isCalled = true; - return true; - }, out _); - rewriteSession.Rewrite(); - Assert.IsFalse(isCalled); - } - [Test] [Category("Rewriter")] public void DoesNotCallRewritingAllowedOnRewriteIfInvalidated() @@ -76,7 +85,7 @@ public void DoesNotCallRewritingAllowedOnRewriteIfInvalidated() rewriteSession.Invalidate(); rewriteSession.CheckOutModuleRewriter(otherModule); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); Assert.IsFalse(isCalled); } @@ -92,7 +101,7 @@ public void CallsRewriteOnAllCheckedOutRewritersIfNotInvalidatedAndParsingAllowe var requestedRewriters = mockRewriterProvider.RequestedRewriters(); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); foreach (var (qmn, codeKind, mockRewriter) in requestedRewriters) { @@ -100,6 +109,18 @@ public void CallsRewriteOnAllCheckedOutRewritersIfNotInvalidatedAndParsingAllowe } } + [Test] + [Category("Rewriter")] + public void TryRewriteReturnsFalseIfInvalidated() + { + var rewriteSession = RewriteSession(session => true, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + rewriteSession.Invalidate(); + var actual = rewriteSession.TryRewrite(); + Assert.IsFalse(actual); + } + [Test] [Category("Rewriter")] public void DoesNotCallRewriteOnAnyCheckedOutRewriterIfInvalidated() @@ -113,7 +134,7 @@ public void DoesNotCallRewriteOnAnyCheckedOutRewriterIfInvalidated() var requestedRewriters = mockRewriterProvider.RequestedRewriters(); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); foreach (var (qmn, codeKind, mockRewriter) in requestedRewriters) { @@ -121,6 +142,17 @@ public void DoesNotCallRewriteOnAnyCheckedOutRewriterIfInvalidated() } } + [Test] + [Category("Rewriter")] + public void TryRewriteReturnsFalseIfNotParsingAllowed() + { + var rewriteSession = RewriteSession(session => false, out _); + var module = new QualifiedModuleName("TestProject", string.Empty, "TestModule"); + rewriteSession.CheckOutModuleRewriter(module); + var actual = rewriteSession.TryRewrite(); + Assert.IsFalse(actual); + } + [Test] [Category("Rewriter")] public void DoesNotCallRewriteOnAnCheckedOutRewriterIfNotParsingAllowed() @@ -133,7 +165,7 @@ public void DoesNotCallRewriteOnAnCheckedOutRewriterIfNotParsingAllowed() var requestedRewriters = mockRewriterProvider.RequestedRewriters(); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); foreach (var (qmn, codeKind, mockRewriter) in requestedRewriters) { @@ -163,7 +195,7 @@ public void CallsRewriteOnlyOnceForRewritersCheckedOutMultipleTimes() rewriteSession.CheckOutModuleRewriter(module); var (qmn, codeKind, mockRewriter) = mockRewriterProvider.RequestedRewriters().Single(); - rewriteSession.Rewrite(); + rewriteSession.TryRewrite(); mockRewriter.Verify(m => m.Rewrite(), Times.Once); } From bd9c9c20c266b98335e3477c7f6eb3cc7a0bdb7e Mon Sep 17 00:00:00 2001 From: Max Doerner Date: Wed, 7 Nov 2018 23:17:13 +0100 Subject: [PATCH 071/107] Amend doc-comments in IModuleRewriter The Rewrite member is no longer on the interface. --- .../Rewriter/IModuleRewriter.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs b/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs index ed8da6744c..4f2a1857e8 100644 --- a/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs +++ b/Rubberduck.Parsing/Rewriter/IModuleRewriter.cs @@ -10,91 +10,91 @@ public interface IModuleRewriter bool IsDirty { get; } /// - /// Removes all tokens for specified . Use method to apply changes. + /// Removes all tokens for specified . Use to get the changed module code. /// /// The to remove. /// Removes a line that would be left empty by the removal of the declaration. void Remove(Declaration target); /// - /// Removes all tokens in specified context. Use method to apply changes. + /// Removes all tokens in specified context. Use to get the changed module code. /// /// The to remove. /// Removes a line that would be left empty by the removal of the identifier reference token. void Remove(ParserRuleContext target); /// - /// Removes all tokens for specified . Use method to apply changes. + /// Removes all tokens for specified . Use to get the changed module code. /// /// The to remove. /// Removes a line that would be left empty by the removal of the identifier reference token. void Remove(IToken target); /// - /// Removes all tokens for specified . Use method to apply changes. + /// Removes all tokens for specified . Use to get the changed module code. /// /// The to remove. /// Removes a line that would be left empty by the removal of the identifier reference token. void Remove(ITerminalNode target); /// - /// Removes all tokens for specified . Use method to apply changes. + /// Removes all tokens for specified . Use to get the changed module code. /// /// The to remove. /// Removes a line that would be left empty by the removal of the identifier reference token. void Remove(IParseTree target); /// - /// Removes all tokens from the start of the first node to the end of the second node. + /// Removes all tokens from the start of the first node to the end of the second node. Use to get the changed module code. /// /// The start index to remove. /// The end index to remove. void RemoveRange(int start, int stop); /// - /// Replaces all tokens for specified with specified content. Use method to apply changes. + /// Replaces all tokens for specified with specified content. Use to get the changed module code. /// /// The to replace. /// The literal replacement for the declaration. /// Useful for adding/removing e.g. access modifiers. void Replace(Declaration target, string content); /// - /// Replaces all tokens for specified with specified content. Use method to apply changes. + /// Replaces all tokens for specified with specified content. Use to get the changed module code. /// /// The to replace. /// The literal replacement for the expression. void Replace(ParserRuleContext target, string content); /// - /// Replaces specified token with specified content. Use method to apply changes. + /// Replaces specified token with specified content. Use to get the changed module code. /// /// The to replace. /// The literal replacement for the expression. void Replace(IToken token, string content); /// - /// Replaces specified token with specified content. Use method to apply changes. + /// Replaces specified token with specified content. Use to get the changed module code. /// /// The to replace. /// The literal replacement for the expression. void Replace(ITerminalNode target, string content); /// - /// Replaces specified token with specified content. Use method to apply changes. + /// Replaces specified token with specified content. Use to get the changed module code. /// /// The to replace. /// The literal replacement for the expression. void Replace(IParseTree target, string content); /// - /// Replaces specified interval with specified content. Use method to apply changes. + /// Replaces specified interval with specified content. Use to get the changed module code. /// /// The to replace. /// The literal replacement for the expression. void Replace(Interval tokenInterval, string content); /// - /// Inserts specified content before the specified token index in the module. Use method to apply changes. + /// Inserts specified content before the specified token index in the module. Use to get the changed module code. /// /// The index of the insertion point in the module's lexer token stream. /// The literal content to insert. void InsertBefore(int tokenIndex, string content); /// - /// Inserts specified content after the specified token index in the module. Use method to apply changes. + /// Inserts specified content after the specified token index in the module. Use to get the changed module code. /// /// The index of the insertion point in the module's lexer token stream. /// The literal content to insert. From 3746fdb548bd9bf0f0c3c57ecefac871385d02aa Mon Sep 17 00:00:00 2001 From: Mathieu Guindon Date: Wed, 7 Nov 2018 20:07:44 -0500 Subject: [PATCH 072/107] added test for matched pair deletion --- .../AutoComplete/SelfClosingPairHandlerTests.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs index 12401a27a8..3f0400d71a 100644 --- a/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs +++ b/RubberduckTests/AutoComplete/SelfClosingPairHandlerTests.cs @@ -100,8 +100,19 @@ public void GivenOpeningParenthesisOnOtherwiseNonEmptyLine_ReturnsFalseAndSwallo var info = new SelfClosingPairTestInfo(original, input, rePrettified); Assert.IsFalse(Run(info)); - Assert.IsNull(info.Result); Assert.IsTrue(info.Args.Handled); } + + [Test] + public void GivenBackspaceOnMatchedPair_DeletesMatchingTokens() + { + var input = '\b'; + var original = "foo = DateSerial(Year(|))".ToCodeString(); + var rePrettified = "foo = DateSerial(Year|)".ToCodeString(); + var info = new SelfClosingPairTestInfo(original, input, rePrettified); + + Assert.IsTrue(Run(info)); + Assert.IsNotNull(info.Result); + } } } From 3fb356818c96b08d4dd92f464a0b96d9f6d5b3ef Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Thu, 8 Nov 2018 22:50:32 +0100 Subject: [PATCH 073/107] partially revert release DRYing --- appveyor.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index a1144433d2..8b4f88ce85 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -112,7 +112,7 @@ deploy: description: AppVeyor build on [master] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq - artifact: $(installer_dir)\$(installer_name) + artifact: Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.$(appveyor_build_version).exe draft: true prerelease: false on: @@ -123,7 +123,7 @@ deploy: description: AppVeyor build on [next] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq - artifact: $(installer_dir)\$(installer_name) + artifact: Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.$(appveyor_build_version)-pre.exe draft: false prerelease: true on: From 97a6059a9327170c25cefa2e1dc5a6809c311a85 Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Thu, 8 Nov 2018 22:59:02 +0100 Subject: [PATCH 074/107] Upload Github artifacts by name instead of path --- appveyor.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 8b4f88ce85..5e494fd2fa 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -96,11 +96,11 @@ for: # fall back to calling the installer after the branch we're on installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-%APPVEYOR_REPO_BRANCH%.exe -# Create Installers for +# Create Installers to store at appveyor and upload to github after_test: - cmd: iscc /O "Rubberduck.Deployment\InnoSetup\Rubberduck.Installer.Build.iss" - cmd: move %INSTALLER_DIR%\Rubberduck.Setup.exe %INSTALLER_DIR%\%INSTALLER_NAME% - + # grab the installers we produce and upload them to github :) artifacts: - path: Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.*.exe @@ -112,7 +112,7 @@ deploy: description: AppVeyor build on [master] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq - artifact: Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.$(appveyor_build_version).exe + artifact: Rubberduck draft: true prerelease: false on: @@ -123,11 +123,12 @@ deploy: description: AppVeyor build on [next] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq - artifact: Rubberduck.Deployment\InnoSetup\Installers\Rubberduck.Setup.$(appveyor_build_version)-pre.exe + artifact: Rubberduck draft: false prerelease: true on: branch: next +# This is Duga posting stuff to the war room notifications: - provider: Webhook url: http://stats.zomis.net/GithubHookSEChatService/hooks/github/payload?roomId=14929 From 2a2496f34842a7c440218debffc93061cdcf7e0b Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Thu, 8 Nov 2018 23:31:41 +0100 Subject: [PATCH 075/107] minor cleanup --- appveyor.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 5e494fd2fa..2982483beb 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,7 +9,7 @@ init: git config --global core.autocrlf true # history limited to 15 commits, since we ran into trouble with a limit of 3 -# the limit can be rather +# the limit can be rather generous clone_depth: 15 # explicitly do not shallow-clone. # Line-Endings are wrong on github, because of CRLF fixing @@ -48,9 +48,6 @@ dotnet_csproj: file: 'RubberduckBaseProject.csproj' # ;*\Rubberduck.Core.csproj' version: '{version}' assembly_version: '{version}' - # patching fails if we try to patch properties we didn't define - #file_version: '{version}' - #informational_version: '{version}' before_build: From 399c92adcb8fe9210ef1fad43e85eeea109bcc25 Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Thu, 8 Nov 2018 23:32:05 +0100 Subject: [PATCH 076/107] Have some fun with release descriptions --- appveyor.yml | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 2982483beb..5faaccae2f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -78,12 +78,14 @@ for: - next environment: installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-pre.exe + release_name: Rubberduck v%APPVEYOR_BUILD_VERSION%-pre - branches: only: - master environment: installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%.exe + release_name: Rubberduck v%APPVEYOR_BUILD_VERSION% - branches: except: @@ -92,6 +94,7 @@ for: environment: # fall back to calling the installer after the branch we're on installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-%APPVEYOR_REPO_BRANCH%.exe + release_name: Rubberduck v%APPVEYOR_BUILD_VERSION%-%APPVEYOR_REPO_BRANCH% # Create Installers to store at appveyor and upload to github after_test: @@ -105,26 +108,30 @@ artifacts: deploy: - provider: GitHub tag: Rubberduck v$(appveyor_build_version) - release: Rubberduck v$(appveyor_build_version) - description: AppVeyor build on [master] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) + release: $(release_name) + draft: true + prerelease: false + description: "Built with :heart: by AppVeyor CI on [$(appveyor_repo_branch)] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version)" auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq artifact: Rubberduck - draft: true - prerelease: false - on: + on: branch: master - provider: GitHub tag: Rubberduck v$(appveyor_build_version) - release: Rubberduck v$(appveyor_build_version)-pre - description: AppVeyor build on [next] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) + release: $(release_name) + draft: true + prerelease: false + description: >- + AppVeyor build on [$(appveyor_repo_branch)] - https://ci.appveyor.com/project/rubberduck-vba/rubberduck/build/$(appveyor_build_version) + + Merges \#$(appveyor_pull_request_number) - $(appveyor_pull_request_title) auth_token: secure: NVAZgFRSk566SP5QDge5gYRWCaLi4NJJPTNk3QengH15wL9iVldfrFOllbzKXExq artifact: Rubberduck - draft: false - prerelease: true - on: + on: branch: next + # This is Duga posting stuff to the war room notifications: - provider: Webhook From 9a859315b73b93c03b0eca900517663c7bd9638a Mon Sep 17 00:00:00 2001 From: Clemens Lieb Date: Fri, 9 Nov 2018 00:04:48 +0100 Subject: [PATCH 077/107] Avoid naming the installer after any old branch --- appveyor.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 5faaccae2f..7a1ca14b88 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -92,8 +92,8 @@ for: - master - next environment: - # fall back to calling the installer after the branch we're on - installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-%APPVEYOR_REPO_BRANCH%.exe + # fall back to naming the installer something that shows we're in an unexpected state + installer_name: Rubberduck.Setup.%APPVEYOR_BUILD_VERSION%-unexpected.exe release_name: Rubberduck v%APPVEYOR_BUILD_VERSION%-%APPVEYOR_REPO_BRANCH% # Create Installers to store at appveyor and upload to github From 0197465a7237ba39414c862f17fd6e6a5469b3d7 Mon Sep 17 00:00:00 2001 From: Mathieu Guindon Date: Thu, 8 Nov 2018 22:01:02 -0500 Subject: [PATCH 078/107] closes #4505 --- .../Service/SelfClosingPairHandler.cs | 12 +++ .../Service/SmartConcatenationHandler.cs | 3 +- .../CodePaneSourceCodeHandler.cs | 90 +++++++++++-------- 3 files changed, 67 insertions(+), 38 deletions(-) diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs index 501f1922ef..7da83cbf80 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs @@ -41,6 +41,11 @@ public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settin } var original = CodePaneHandler.GetCurrentLogicalLine(e.Module); + if (original == null) + { + // selection spans more than a single logical line + return false; + } if (pair != null) { @@ -74,6 +79,13 @@ public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settin private bool HandleInternal(AutoCompleteEventArgs e, CodeString original, SelfClosingPair pair, out CodeString result) { + if (!original.CaretPosition.IsSingleCharacter) + { + // todo: WrapSelection? + result = null; + return false; + } + var isPresent = original.CaretLine.EndsWith($"{pair.OpeningChar}{pair.ClosingChar}"); if (!_scpService.Execute(pair, original, e.Character, out result)) diff --git a/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs b/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs index 7c120886c8..c7c88d50e0 100644 --- a/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs @@ -25,8 +25,9 @@ public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settin } var currentContent = CodePaneHandler.GetCurrentLogicalLine(e.Module); - if (!currentContent.IsInsideStringLiteral) + if (!currentContent?.IsInsideStringLiteral ?? true) { + // selection spans more than a single logical line return false; } diff --git a/Rubberduck.VBEEditor/SourceCodeHandling/CodePaneSourceCodeHandler.cs b/Rubberduck.VBEEditor/SourceCodeHandling/CodePaneSourceCodeHandler.cs index c8169b2305..a2f11f9682 100644 --- a/Rubberduck.VBEEditor/SourceCodeHandling/CodePaneSourceCodeHandler.cs +++ b/Rubberduck.VBEEditor/SourceCodeHandling/CodePaneSourceCodeHandler.cs @@ -3,6 +3,7 @@ using System.Linq; using Rubberduck.VBEditor.ComManagement; using Rubberduck.VBEditor.SafeComWrappers.Abstract; +using System.Reflection; namespace Rubberduck.VBEditor.SourceCodeHandling { @@ -165,42 +166,51 @@ private static CodeString GetPrettifiedCodeString(CodeString original, Selection return result; } + private const string LineContinuation = " _"; + public CodeString GetCurrentLogicalLine(ICodeModule module) { - const string lineContinuation = " _"; - Selection pSelection; using (var pane = module.CodePane) { pSelection = pane.Selection; } - var currentLineIndex = pSelection.StartLine; - var currentLine = module.GetLines(currentLineIndex, 1); + var selectedLines = module.GetLines(pSelection.StartLine, pSelection.LineCount).Replace("\r", string.Empty).Split('\n'); + var currentLine = selectedLines[0]; - var caretLine = (currentLineIndex, currentLine); - var lines = new List<(int Line, string Content)> {caretLine}; + var caretStartLine = (pSelection.StartLine, currentLine); + var lines = new List<(int pLine, string Content)> {caretStartLine}; - while (currentLineIndex >= 1) + // selection line may not be the only physical line in the complete logical line; accounts for line continuations. + InsertPhysicalLinesAboveSelectionStart(lines, module, pSelection.StartLine); + AppendPhysicalLinesBelowSelectionStart(lines, module, pSelection.StartLine, currentLine); + + var logicalLine = string.Join("\r\n", lines.Select(e => e.Content)); + + var zCaretLine = lines.IndexOf(caretStartLine); + var zCaretColumn = pSelection.StartColumn - 1; + var caretPosition = new Selection( + zCaretLine, zCaretColumn, zCaretLine + pSelection.LineCount - 1, pSelection.EndColumn - 1); + + var pStartLine = lines[0].pLine; + var pEndLine = lines[lines.Count - 1].pLine; + var snippetPosition = new Selection(pStartLine, 1, pEndLine, 1); + + if (lines[0].pLine < pSelection.StartLine || lines.Last().pLine > pSelection.EndLine) { - currentLineIndex--; - if (currentLineIndex >= 1) - { - currentLine = module.GetLines(currentLineIndex, 1); - if (currentLine.EndsWith(lineContinuation)) - { - lines.Insert(0, (currentLineIndex, currentLine)); - } - else - { - break; - } - } + // selection spans more than a single logical line + return null; } - currentLineIndex = pSelection.StartLine; - currentLine = caretLine.currentLine; - while (currentLineIndex <= module.CountOfLines && currentLine.EndsWith(lineContinuation)) + var result = new CodeString(logicalLine, caretPosition, snippetPosition); + return result; + } + + private void AppendPhysicalLinesBelowSelectionStart(ICollection<(int Line, string Content)> lines, ICodeModule module, int currentLineIndex, string currentLine) + { + // assumes caret line is already in the list. + while (currentLineIndex <= module.CountOfLines && currentLine.EndsWith(LineContinuation)) { currentLineIndex++; if (currentLineIndex <= module.CountOfLines) @@ -213,21 +223,27 @@ public CodeString GetCurrentLogicalLine(ICodeModule module) break; } } + } - var logicalLine = string.Join("\r\n", lines.Select(e => e.Content)); - var zCaretLine = lines.IndexOf(caretLine); - var zCaretColumn = pSelection.StartColumn - 1; - - var startLine = lines[0].Line; - var endLine = lines[lines.Count - 1].Line; - - var result = new CodeString( - logicalLine, - new Selection(zCaretLine, zCaretColumn), - new Selection(startLine, 1, endLine, 1)); - - return result; - + private void InsertPhysicalLinesAboveSelectionStart(IList<(int Line, string Content)> lines, ICodeModule module, int currentLineIndex) + { + // assumes caret line is already in the list. + while (currentLineIndex >= 1) + { + currentLineIndex--; + if (currentLineIndex >= 1) + { + var currentLine = module.GetLines(currentLineIndex, 1); + if (currentLine.EndsWith(LineContinuation)) + { + lines.Insert(0, (currentLineIndex, currentLine)); + } + else + { + break; + } + } + } } public CodeString GetCurrentLogicalLine(QualifiedModuleName module) From 8513b4847329ec85281eb2661203d03cb6d389f6 Mon Sep 17 00:00:00 2001 From: Mathieu Guindon Date: Thu, 8 Nov 2018 23:32:59 -0500 Subject: [PATCH 079/107] closes #4507 - introduces MaxLogicalLineLineCount setting --- .../Service/SelfClosingPairHandler.cs | 7 +++-- .../Service/SmartConcatenationHandler.cs | 6 ++-- Rubberduck.Core/Properties/Settings.settings | 27 +++++------------- .../Settings/AutoCompleteSettings.cs | 25 ++++++++++++++++- .../UI/Settings/AutoCompleteSettings.xaml | 3 ++ .../Settings/AutoCompleteSettingsViewModel.cs | 17 ++++++++++- Rubberduck.Core/app.config | 28 +++++-------------- .../CodePaneSourceCodeHandler.cs | 14 ++++++++-- .../SafeComWrappers/VB/CodeModule.cs | 3 ++ 9 files changed, 80 insertions(+), 50 deletions(-) diff --git a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs index 7da83cbf80..253ca22e45 100644 --- a/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SelfClosingPairHandler.cs @@ -10,6 +10,8 @@ namespace Rubberduck.AutoComplete.Service { public class SelfClosingPairHandler : AutoCompleteHandlerBase { + private const int MaximumLines = 25; + private readonly IReadOnlyList _selfClosingPairs; private readonly IDictionary _scpInputLookup; private readonly SelfClosingPairCompletionService _scpService; @@ -41,9 +43,10 @@ public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settin } var original = CodePaneHandler.GetCurrentLogicalLine(e.Module); - if (original == null) + if (original == null || original.Lines.Length == MaximumLines) { - // selection spans more than a single logical line + // selection spans more than a single logical line, or + // logical line somehow spans more than the maximum number of physical lines in a logical line of code (25). return false; } diff --git a/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs b/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs index c7c88d50e0..1f5abafff9 100644 --- a/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs +++ b/Rubberduck.Core/AutoComplete/Service/SmartConcatenationHandler.cs @@ -25,9 +25,11 @@ public override bool Handle(AutoCompleteEventArgs e, AutoCompleteSettings settin } var currentContent = CodePaneHandler.GetCurrentLogicalLine(e.Module); - if (!currentContent?.IsInsideStringLiteral ?? true) + if ((!currentContent?.IsInsideStringLiteral ?? true) + || currentContent.Lines.Length >= settings.SmartConcat.MaxLogicalLineLineCount) { - // selection spans more than a single logical line + // selection spans more than a single logical line, or spans too many lines to be legal; + // too many line continuations throws COMException if we attempt to modify. return false; } diff --git a/Rubberduck.Core/Properties/Settings.settings b/Rubberduck.Core/Properties/Settings.settings index 65cc1ca0f3..1962a7e622 100644 --- a/Rubberduck.Core/Properties/Settings.settings +++ b/Rubberduck.Core/Properties/Settings.settings @@ -268,26 +268,13 @@ <?xml version="1.0" encoding="utf-16"?> -<AutoCompleteSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IsEnabled="false" CompleteBlockOnTab="true" CompleteBlockOnEnter="true" EnableSmartConcat="true"> - <AutoCompletes> - <AutoComplete Key="AutoCompleteClosingBrace" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteClosingBracket" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteClosingParenthese" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteClosingString" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteDoBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteEnumBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteForBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteFunctionBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteIfBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteOnErrorResumeNextBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompletePrecompilerIfBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompletePropertyBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteSelectBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteSubBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteTypeBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteWhileBlock" IsEnabled="true" /> - <AutoComplete Key="AutoCompleteWithBlock" IsEnabled="true" /> - </AutoCompletes> +<AutoCompleteSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IsEnabled="false"> + <SmartConcat> + <IsEnabled>false</IsEnabled> + <ConcatVbNewLineModifier>None</ConcatVbNewLineModifier> + </SmartConcat> + <SelfClosingPairs IsEnabled="false" /> + <BlockCompletion IsEnabled="false" CompleteOnEnter="false" CompleteOnTab="false" /> </AutoCompleteSettings> diff --git a/Rubberduck.Core/Settings/AutoCompleteSettings.cs b/Rubberduck.Core/Settings/AutoCompleteSettings.cs index eb00841bc0..5c180a9f19 100644 --- a/Rubberduck.Core/Settings/AutoCompleteSettings.cs +++ b/Rubberduck.Core/Settings/AutoCompleteSettings.cs @@ -57,13 +57,36 @@ public AutoCompleteSettings() public class SmartConcatSettings : IEquatable { + private int _maxLogicalLineLineCount; + private const int MaximumLines = 25; // more than that wouldn't compile + + [XmlAttribute] public bool IsEnabled { get; set; } public ModifierKeySetting ConcatVbNewLineModifier { get; set; } + public int MaxLogicalLineLineCount + { + get => _maxLogicalLineLineCount; + set + { + if (value > MaximumLines) + { + value = MaximumLines; + } + + if (value < 5) + { + value = 5; // completely arbitrary magical value. + } + _maxLogicalLineLineCount = value; + } + } + public bool Equals(SmartConcatSettings other) => other != null && other.IsEnabled == IsEnabled && - other.ConcatVbNewLineModifier == ConcatVbNewLineModifier; + other.ConcatVbNewLineModifier == ConcatVbNewLineModifier && + other.MaxLogicalLineLineCount == MaxLogicalLineLineCount; } public class SelfClosingPairSettings : IEquatable diff --git a/Rubberduck.Core/UI/Settings/AutoCompleteSettings.xaml b/Rubberduck.Core/UI/Settings/AutoCompleteSettings.xaml index 8b22ed6052..12be94f264 100644 --- a/Rubberduck.Core/UI/Settings/AutoCompleteSettings.xaml +++ b/Rubberduck.Core/UI/Settings/AutoCompleteSettings.xaml @@ -111,6 +111,9 @@ IsChecked="{Binding ConcatVbNewLine}" Content="{Resx ResxName=Rubberduck.Resources.Settings.AutoCompletesPage, Key=ConcatVbNewLine}" /> +