Skip to content

Commit

Permalink
Remove use of dynamic
Browse files Browse the repository at this point in the history
Adds guard clause to constrain refactoring action to the finite set of supported types.
  • Loading branch information
BZngr committed Dec 4, 2020
1 parent f5d2cd3 commit 01de2f1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
@@ -1,7 +1,7 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;
using Rubberduck.Parsing;
using Rubberduck.Parsing.Grammar;
using Rubberduck.Parsing.Rewriter;
Expand All @@ -27,10 +27,15 @@ public class ImplicitTypeToExplicitRefactoringAction : CodeOnlyRefactoringAction

public override void Refactor(ImplicitTypeToExplicitModel model, IRewriteSession rewriteSession)
{
ParserRuleContext identifierNode =
model.Target.Context is VBAParser.VariableSubStmtContext || model.Target.Context is VBAParser.ConstSubStmtContext || model.Target.Context is VBAParser.FunctionStmtContext
? model.Target.Context.children[0]
: ((dynamic)model.Target.Context).unrestrictedIdentifier();
if (!(model.Target.Context is VBAParser.VariableSubStmtContext
|| model.Target.Context is VBAParser.ConstSubStmtContext
|| model.Target.Context is VBAParser.ArgContext))
{
throw new ArgumentException($"Invalid target {model.Target.IdentifierName}");
}

var identifierNode = model.Target.Context.GetChild<VBAParser.IdentifierContext>()
?? model.Target.Context.GetChild<VBAParser.UnrestrictedIdentifierContext>() as ParserRuleContext;

var insertAfterTarget = model.Target.IsArray
? model.Target.Context.Stop.TokenIndex
Expand Down
Expand Up @@ -3,6 +3,7 @@
using Rubberduck.Refactorings.ImplicitTypeToExplicit;
using Rubberduck.VBEditor.SafeComWrappers;
using RubberduckTests.Mocks;
using System;
using System.Collections.Generic;

namespace RubberduckTests.Refactoring.ImplicitTypeToExplicit
Expand Down Expand Up @@ -52,6 +53,20 @@ Dim var1
StringAssert.Contains($"{targetName} As Variant", refactoredCode);
}

[Test]
[Category("Refactorings")]
[Category(nameof(ImplicitTypeToExplicitRefactoringAction))]
public void InvalidTarget_ThrowsArgumentException()
{
var targetName = "Foo";
var inputCode =
$@"Sub Foo()
End Sub";

Assert.Throws<ArgumentException>( () => RefactoredCode(inputCode,
state => TestModel(state, (targetName, DeclarationType.Procedure), (model) => model)));
}

[TestCase("var1 = 42", "Long", "Long")]
[TestCase("var1 = 42.55", "Long", "Double")]
[Category("Refactorings")]
Expand Down

0 comments on commit 01de2f1

Please sign in to comment.