Skip to content

Commit

Permalink
Merge branch 'next' into SelectiveReferenceResolving
Browse files Browse the repository at this point in the history
Incorporating recent changes.
  • Loading branch information
MDoerner committed Mar 1, 2017
2 parents 5550154 + 427ef60 commit 2971896
Show file tree
Hide file tree
Showing 38 changed files with 1,441 additions and 952 deletions.
38 changes: 38 additions & 0 deletions RetailCoder.VBE/Common/CodeModuleExtensions.cs
@@ -0,0 +1,38 @@
using Antlr4.Runtime;
using Rubberduck.Parsing.Symbols;
using Rubberduck.VBEditor.SafeComWrappers.Abstract;

namespace Rubberduck.Common
{
public static class CodeModuleExtensions
{
public static void ReplaceToken(this ICodeModule module, IToken token, string replacement)
{
var original = module.GetLines(token.Line, 1);
var result = ReplaceStringAtIndex(original, token.Text, replacement, token.Column);
module.ReplaceLine(token.Line, result);
}

public static void ReplaceIdentifierReferenceName(this ICodeModule module, IdentifierReference identifierReference, string replacement)
{
var original = module.GetLines(identifierReference.Selection.StartLine, 1);
var result = ReplaceStringAtIndex(original, identifierReference.IdentifierName, replacement, identifierReference.Context.Start.Column);
module.ReplaceLine(identifierReference.Selection.StartLine, result);
}

public static void InsertLines(this ICodeModule module, int startLine, string[] lines)
{
int lineNumber = startLine;
for ( int idx = 0; idx < lines.Length; idx++ )
{
module.InsertLines(lineNumber, lines[idx]);
lineNumber++;
}
}
private static string ReplaceStringAtIndex(string original, string toReplace, string replacement, int startIndex)
{
var modifiedContent = original.Remove(startIndex, toReplace.Length);
return modifiedContent.Insert(startIndex, replacement);
}
}
}
21 changes: 11 additions & 10 deletions RetailCoder.VBE/Inspections/Abstract/InspectionBase.cs
Expand Up @@ -116,28 +116,29 @@ protected bool IsIgnoringInspectionResultFor(IVBComponent component, int line)

protected bool IsIgnoringInspectionResultFor(Declaration declaration, string inspectionName)
{
var module = Declaration.GetModuleParent(declaration);
if (module == null) { return false; }

var isIgnoredAtModuleLevel = module.Annotations
.Any(annotation => annotation.AnnotationType == AnnotationType.IgnoreModule
&& ((IgnoreModuleAnnotation) annotation).IsIgnored(inspectionName));


if (declaration.DeclarationType == DeclarationType.Parameter)
{
return declaration.ParentDeclaration.Annotations.Any(annotation =>
return isIgnoredAtModuleLevel || declaration.ParentDeclaration.Annotations.Any(annotation =>
annotation.AnnotationType == AnnotationType.Ignore
&& ((IgnoreAnnotation)annotation).IsIgnored(inspectionName));
}

return declaration.Annotations.Any(annotation =>
return isIgnoredAtModuleLevel || declaration.Annotations.Any(annotation =>
annotation.AnnotationType == AnnotationType.Ignore
&& ((IgnoreAnnotation)annotation).IsIgnored(inspectionName));
}

protected bool IsIgnoringInspectionResultFor(IdentifierReference reference, string inspectionName)
{
if (reference == null)
{
return false;
}

return reference.Annotations.Any(annotation =>
annotation.AnnotationType == AnnotationType.Ignore
&& ((IgnoreAnnotation)annotation).IsIgnored(inspectionName));
return reference != null && reference.IsIgnoringInspectionResultFor(inspectionName);
}

public int CompareTo(IInspection other)
Expand Down
Expand Up @@ -3,18 +3,21 @@
using Rubberduck.Inspections.Abstract;
using Rubberduck.Inspections.Resources;
using Rubberduck.Inspections.Results;
using Rubberduck.Parsing.Grammar;
using Rubberduck.Parsing.Symbols;
using Rubberduck.Parsing.VBA;
using Rubberduck.UI.Refactorings;

namespace Rubberduck.Inspections
{
public sealed class AssignedByValParameterInspection : InspectionBase
{
public AssignedByValParameterInspection(RubberduckParserState state)
private readonly IAssignedByValParameterQuickFixDialogFactory _dialogFactory;
public AssignedByValParameterInspection(RubberduckParserState state, IAssignedByValParameterQuickFixDialogFactory dialogFactory)
: base(state)
{
Severity = DefaultSeverity;
_dialogFactory = dialogFactory;

}

public override string Meta { get { return InspectionsUI.AssignedByValParameterInspectionMeta; } }
Expand All @@ -31,7 +34,7 @@ public override IEnumerable<InspectionResultBase> GetInspectionResults()
.ToList();

return parameters
.Select(param => new AssignedByValParameterInspectionResult(this, param))
.Select(param => new AssignedByValParameterInspectionResult(this, param, _dialogFactory))
.ToList();
}
}
Expand Down
@@ -0,0 +1,191 @@
using Rubberduck.Inspections.Abstract;
using System.Linq;
using Rubberduck.VBEditor;
using Rubberduck.Inspections.Resources;
using Rubberduck.Parsing.Grammar;
using Rubberduck.Parsing.Symbols;
using System.Windows.Forms;
using Rubberduck.UI.Refactorings;
using Rubberduck.Common;
using Antlr4.Runtime;
using System.Collections.Generic;
using Antlr4.Runtime.Tree;

namespace Rubberduck.Inspections.QuickFixes
{
public class AssignedByValParameterMakeLocalCopyQuickFix : QuickFixBase
{
private readonly Declaration _target;
private readonly IAssignedByValParameterQuickFixDialogFactory _dialogFactory;
private readonly IEnumerable<string> _forbiddenNames;
private string _localCopyVariableName;

public AssignedByValParameterMakeLocalCopyQuickFix(Declaration target, QualifiedSelection selection, IAssignedByValParameterQuickFixDialogFactory dialogFactory)
: base(target.Context, selection, InspectionsUI.AssignedByValParameterMakeLocalCopyQuickFix)
{
_target = target;
_dialogFactory = dialogFactory;
_forbiddenNames = GetIdentifierNamesAccessibleToProcedureContext(target.Context.Parent.Parent);
_localCopyVariableName = ComputeSuggestedName();
}

public override bool CanFixInModule { get { return false; } }
public override bool CanFixInProject { get { return false; } }

public override void Fix()
{
RequestLocalCopyVariableName();

if (!VariableNameIsValid(_localCopyVariableName) || IsCancelled)
{
return;
}

ReplaceAssignedByValParameterReferences();

InsertLocalVariableDeclarationAndAssignment();
}

private void RequestLocalCopyVariableName()
{
using( var view = _dialogFactory.Create(_target.IdentifierName, _target.DeclarationType.ToString(), _forbiddenNames))
{
view.NewName = _localCopyVariableName;
view.ShowDialog();
IsCancelled = view.DialogResult == DialogResult.Cancel;
if (!IsCancelled)
{
_localCopyVariableName = view.NewName;
}
}
}

private string ComputeSuggestedName()
{
var newName = "local" + _target.IdentifierName.CapitalizeFirstLetter();
if (VariableNameIsValid(newName))
{
return newName;
}

for ( var attempt = 2; attempt < 10; attempt++)
{
var result = newName + attempt;
if (VariableNameIsValid(result))
{
return result;
}
}
return newName;
}

private bool VariableNameIsValid(string variableName)
{
return VariableNameValidator.IsValidName(variableName)
&& !_forbiddenNames.Any(name => name.Equals(variableName, System.StringComparison.InvariantCultureIgnoreCase));
}

private void ReplaceAssignedByValParameterReferences()
{
var module = Selection.QualifiedName.Component.CodeModule;
foreach (var identifierReference in _target.References)
{
module.ReplaceIdentifierReferenceName(identifierReference, _localCopyVariableName);
}
}

private void InsertLocalVariableDeclarationAndAssignment()
{
var block = QuickFixHelper.GetBlockStmtContextsForContext(_target.Context.Parent.Parent).FirstOrDefault();
if (block == null)
{
return;
}

string[] lines = { BuildLocalCopyDeclaration(), BuildLocalCopyAssignment() };
var module = Selection.QualifiedName.Component.CodeModule;
module.InsertLines(block.Start.Line, lines);
}

private string BuildLocalCopyDeclaration()
{
return Tokens.Dim + " " + _localCopyVariableName + " " + Tokens.As + " " + _target.AsTypeName;
}

private string BuildLocalCopyAssignment()
{
return (_target.AsTypeDeclaration is ClassModuleDeclaration ? Tokens.Set + " " : string.Empty)
+ _localCopyVariableName + " = " + _target.IdentifierName;
}

private IEnumerable<string> GetIdentifierNamesAccessibleToProcedureContext(RuleContext ruleContext)
{
var allIdentifiers = new HashSet<string>();

var blocks = QuickFixHelper.GetBlockStmtContextsForContext(ruleContext);

var blockStmtIdentifiers = GetIdentifierNames(blocks);
allIdentifiers.UnionWith(blockStmtIdentifiers);

var args = QuickFixHelper.GetArgContextsForContext(ruleContext);

var potentiallyUnreferencedParameters = GetIdentifierNames(args);
allIdentifiers.UnionWith(potentiallyUnreferencedParameters);

//TODO: add module and global scope variableNames to the list.

return allIdentifiers.ToArray();
}

private IEnumerable<string> GetIdentifierNames(IEnumerable<RuleContext> ruleContexts)
{
var identifiers = new HashSet<string>();
foreach (var identifiersForThisContext in ruleContexts.Select(GetIdentifierNames))
{
identifiers.UnionWith(identifiersForThisContext);
}
return identifiers;
}

private static HashSet<string> GetIdentifierNames(RuleContext ruleContext)
{
// note: this looks like something that's already handled somewhere else...

//Recursively work through the tree to get all IdentifierContexts
var results = new HashSet<string>();
var tokenValues = typeof(Tokens).GetFields().Select(item => item.GetValue(null)).Cast<string>().Select(item => item).ToArray();
var children = GetChildren(ruleContext);

foreach (var child in children)
{
var context = child as VBAParser.IdentifierContext;
if (context != null)
{
var childName = Identifier.GetName(context);
if (!tokenValues.Contains(childName))
{
results.Add(childName);
}
}
else
{
if (!(child is TerminalNodeImpl))
{
results.UnionWith(GetIdentifierNames((RuleContext)child));
}
}
}
return results;
}

private static IEnumerable<IParseTree> GetChildren(IParseTree tree)
{
var result = new List<IParseTree>();
for (var index = 0; index < tree.ChildCount; index++)
{
result.Add(tree.GetChild(index));
}
return result;
}
}
}

0 comments on commit 2971896

Please sign in to comment.