Ejemplo n.º 1
0
        public Declaration FindSelectedDeclaration(QualifiedSelection selection, IEnumerable<DeclarationType> types, Func<Declaration,Selection> selector = null)
        {
            var userDeclarations = _declarations.Where(item => !item.IsBuiltIn);
            var declarations = userDeclarations.Where(item => types.Contains(item.DeclarationType)
                && item.QualifiedName.QualifiedModuleName == selection.QualifiedName).ToList();

            var declaration = declarations.SingleOrDefault(item => 
                selector == null
                    ? item.Selection.Contains(selection.Selection)
                    : selector(item).Contains(selection.Selection));

            if (declaration != null)
            {
                return declaration;
            }

            // if we haven't returned yet, then we must be on an identifier reference.
            declaration = _declarations.SingleOrDefault(item => !item.IsBuiltIn
                && types.Contains(item.DeclarationType)
                && item.References.Any(reference =>
                reference.QualifiedModuleName == selection.QualifiedName
                && reference.Selection.Contains(selection.Selection)));

            return declaration;
        }
Ejemplo n.º 2
0
 public IgnoreOnceQuickFix(ParserRuleContext context, QualifiedSelection selection, string inspectionName) 
     : base(context, selection, InspectionsUI.IgnoreOnce)
 {
     _inspectionName = inspectionName;
     _annotationText = "'" + Parsing.Grammar.Annotations.AnnotationMarker +
                       Parsing.Grammar.Annotations.IgnoreInspection + ' ' + inspectionName;
 }
 private void AcquireTarget(QualifiedSelection selection)
 {
     TargetDeclaration = Declarations.FindTarget(selection, ValidDeclarationTypes);
     TargetDeclaration = PromptIfTargetImplementsInterface();
     TargetDeclaration = GetEvent();
     TargetDeclaration = GetGetter();
 }
 public RenameProjectQuickFix(ParserRuleContext context, QualifiedSelection selection, Declaration target, RubberduckParserState state, ICodePaneWrapperFactory wrapperFactory)
     : base(context, selection, string.Format(RubberduckUI.Rename_DeclarationType, RubberduckUI.ResourceManager.GetString("DeclarationType_" + DeclarationType.Project, RubberduckUI.Culture)))
 {
     _target = target;
     _state = state;
     _wrapperFactory = wrapperFactory;
 }
 public RemoveUnusedParameterQuickFix(ParserRuleContext context, QualifiedSelection selection, 
     RemoveParametersRefactoring quickFixRefactoring, RubberduckParserState parseResult)
     : base(context, selection, InspectionsUI.RemoveUnusedParameterQuickFix)
 {
     _quickFixRefactoring = quickFixRefactoring;
     _parseResult = parseResult;
 }
 public MoveFieldCloserToUsageQuickFix(ParserRuleContext context, QualifiedSelection selection, Declaration target, RubberduckParserState parseResult, ICodePaneWrapperFactory wrapperFactory, IMessageBox messageBox)
     : base(context, selection, string.Format(InspectionsUI.MoveFieldCloserToUsageInspectionResultFormat, target.IdentifierName))
 {
     _target = target;
     _parseResult = parseResult;
     _wrapperFactory = wrapperFactory;
     _messageBox = messageBox;
 }
        public EncapsulateFieldModel(RubberduckParserState parseResult, QualifiedSelection selection)
        {
            IList<Declaration> declarations = parseResult.AllDeclarations
                                                        .Where(d => !d.IsBuiltIn && d.DeclarationType == DeclarationType.Variable)
                                                        .ToList();

            TargetDeclaration = declarations.FindVariable(selection);
        }
Ejemplo n.º 8
0
        public ExtractMethodModel(IActiveCodePaneEditor editor, IEnumerable<Declaration> declarations, QualifiedSelection selection)
        {
            var items = declarations.ToList();

            _sourceMember = items.FindSelectedDeclaration(selection, DeclarationExtensions.ProcedureTypes, d => ((ParserRuleContext)d.Context.Parent).GetSelection());
            if (_sourceMember == null)
            {
                throw new InvalidOperationException("Invalid selection.");
            }

            _extractedMethod = new ExtractedMethod();

            _selection = selection;
            _selectedCode = editor.GetLines(selection.Selection);

            var inScopeDeclarations = items.Where(item => item.ParentScope == _sourceMember.Scope).ToList();

            var inSelection = inScopeDeclarations.SelectMany(item => item.References)
                .Where(item => selection.Selection.Contains(item.Selection))
                .ToList();

            var usedInSelection = new HashSet<Declaration>(inScopeDeclarations.Where(item =>
                selection.Selection.Contains(item.Selection) ||
                item.References.Any(reference => inSelection.Contains(reference))));

            var usedBeforeSelection = new HashSet<Declaration>(inScopeDeclarations.Where(item =>
                item.Selection.StartLine < selection.Selection.StartLine ||
                item.References.Any(reference => reference.Selection.StartLine < selection.Selection.StartLine)));

            var usedAfterSelection = new HashSet<Declaration>(inScopeDeclarations.Where(item =>
                item.Selection.StartLine > selection.Selection.StartLine ||
                item.References.Any(reference => reference.Selection.StartLine > selection.Selection.EndLine)));

            // identifiers used inside selection and before selection (or if it's a parameter) are candidates for parameters:
            var input = inScopeDeclarations.Where(item =>
                usedInSelection.Contains(item) && (usedBeforeSelection.Contains(item) || item.DeclarationType == DeclarationType.Parameter)).ToList();

            // identifiers used inside selection and after selection are candidates for return values:
            var output = inScopeDeclarations.Where(item =>
                usedInSelection.Contains(item) && usedAfterSelection.Contains(item))
                .ToList();

            // identifiers used only inside and/or after selection are candidates for locals:
            _locals = inScopeDeclarations.Where(item => item.DeclarationType != DeclarationType.Parameter && (
                item.References.All(reference => inSelection.Contains(reference))
                || (usedAfterSelection.Contains(item) && (!usedBeforeSelection.Contains(item)))))
                .ToList();

            // locals that are only used in selection are candidates for being moved into the new method:
            _declarationsToMove = _locals.Where(item => !usedAfterSelection.Contains(item)).ToList();

            _output = output.Select(declaration =>
                new ExtractedParameter(declaration.AsTypeName, ExtractedParameter.PassedBy.ByRef, declaration.IdentifierName));

            _input = input.Where(declaration => !output.Contains(declaration))
                .Select(declaration =>
                    new ExtractedParameter(declaration.AsTypeName, ExtractedParameter.PassedBy.ByVal, declaration.IdentifierName));
        }
Ejemplo n.º 9
0
        private void AcquireTarget(out Declaration target, QualifiedSelection selection)
        {
            target = _declarations
                .Where(item => !item.IsBuiltIn && item.DeclarationType != DeclarationType.ModuleOption)
                .FirstOrDefault(item => item.IsSelected(selection)
                                      || item.References.Any(r => r.IsSelected(selection)));

            PromptIfTargetImplementsInterface(ref target);
        }
Ejemplo n.º 10
0
 public ToDoItem(TodoPriority priority, string description, QualifiedSelection qualifiedSelection)
 {
     _priority = priority;
     _description = description;
     _selection = qualifiedSelection;
     _projectName = qualifiedSelection.QualifiedName.Project.Name;
     _moduleName = qualifiedSelection.QualifiedName.Component.Name;
     _lineNumber = qualifiedSelection.Selection.StartLine;
 }
        public void QuickFix(VBProjectParseResult parseResult, QualifiedSelection selection)
        {
            _model = new RemoveParametersModel(parseResult, selection);
            var target = _model.Declarations.FindSelection(selection, new[] { DeclarationType.Parameter });

            // ReSharper disable once PossibleUnintendedReferenceComparison
            _model.Parameters.Find(param => param.Declaration == target).IsRemoved = true;
            RemoveParameters();
        }
Ejemplo n.º 12
0
        public RenameModel(VBE vbe, VBProjectParseResult parseResult, QualifiedSelection selection)
        {
            _vbe = vbe;
            _parseResult = parseResult;
            _declarations = parseResult.Declarations;
            _selection = selection;

            AcquireTarget(out _target, Selection);
        }
        public RemoveParametersModel(VBProjectParseResult parseResult, QualifiedSelection selection)
        {
            _parseResult = parseResult;
            _declarations = parseResult.Declarations;

            AcquireTarget(selection);

            Parameters = new List<Parameter>();
            LoadParameters();
        }
Ejemplo n.º 14
0
        public RenameModel(VBE vbe, RubberduckParserState parseResult, QualifiedSelection selection, IMessageBox messageBox)
        {
            _vbe = vbe;
            _parseResult = parseResult;
            _declarations = parseResult.AllDeclarations.ToList();
            _selection = selection;
            _messageBox = messageBox;

            AcquireTarget(out _target, Selection);
        }
        public ReorderParametersModel(RubberduckParserState parseResult, QualifiedSelection selection, IMessageBox messageBox)
        {
            _parseResult = parseResult;
            _declarations = parseResult.AllUserDeclarations;
            _messageBox = messageBox;

            AcquireTarget(selection);

            Parameters = new List<Parameter>();
            LoadParameters();
        }
Ejemplo n.º 16
0
 public FolderAnnotation(
     QualifiedSelection qualifiedSelection,
     IEnumerable<string> parameters)
     : base(AnnotationType.Folder, qualifiedSelection)
 {
     if (parameters.Count() != 1)
     {
         throw new InvalidAnnotationArgumentException(string.Format("{0} expects exactly one argument, the folder, but none or more than one were passed.", this.GetType().Name));
     }
     _folderName = parameters.First();
 }
Ejemplo n.º 17
0
        public void EncapsulatePublicField_WithLetter()
        {
            //Input
            const string inputCode =
@"Public fizz As Integer";
            var selection = new Selection(1, 1, 1, 1);

            //Expectation
            const string expectedCode =
@"Private fizz As Integer

Public Property Get Name() As Integer
    Name = fizz
End Property

Public Property Let Name(ByVal value As Integer)
    fizz = value
End Property
";

            //Arrange
            var builder = new MockVbeBuilder();
            VBComponent component;
            var vbe = builder.BuildFromSingleStandardModule(inputCode, out component);
            var project = vbe.Object.VBProjects.Item(0);
            var module = project.VBComponents.Item(0).CodeModule;
            var codePaneFactory = new CodePaneWrapperFactory();
            var mockHost = new Mock<IHostApplication>();
            mockHost.SetupAllProperties();
            var parser = MockParser.Create(vbe.Object, new RubberduckParserState());

            parser.Parse();
            if (parser.State.Status == ParserState.Error) { Assert.Inconclusive("Parser Error"); }

            var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

            var model = new EncapsulateFieldModel(parser.State, qualifiedSelection)
            {
                ImplementLetSetterType = true,
                ImplementSetSetterType = false,
                ParameterName = "value",
                PropertyName = "Name"
            };

            //SetupFactory
            var factory = SetupFactory(model);

            //Act
            var refactoring = new EncapsulateFieldRefactoring(factory.Object, new ActiveCodePaneEditor(vbe.Object, codePaneFactory));
            refactoring.Refactor(qualifiedSelection);

            //Assert
            Assert.AreEqual(expectedCode, module.Lines());
        }
Ejemplo n.º 18
0
 public IgnoreAnnotation(
     QualifiedSelection qualifiedSelection,
     IEnumerable<string> parameters)
     : base(AnnotationType.Ignore, qualifiedSelection)
 {
     if (!parameters.Any())
     {
         throw new InvalidAnnotationArgumentException(string.Format("{0} expects at least one argument but none were given.", this.GetType().Name));
     }
     _inspectionNames = parameters.ToList();
 }
        public override void Execute(object parameter)
        {
            if (Vbe.ActiveCodePane == null)
            {
                return;
            }
            var codePane = _wrapperWrapperFactory.Create(Vbe.ActiveCodePane);
            var selection = new QualifiedSelection(new QualifiedModuleName(codePane.CodeModule.Parent), codePane.Selection);

            var refactoring = new IntroduceFieldRefactoring(_state, Editor, new MessageBox());
            refactoring.Refactor(selection);
        }
Ejemplo n.º 20
0
        public void ExtractMethod_PrivateFunction()
        {
            const string inputCode = @"
Private Sub Foo()
    Dim x As Integer
    x = 1 + 2
End Sub";

            const string expectedCode = @"
Private Sub Foo()
    x = Bar()
End Sub

Private Function Bar() As Integer
    Dim x As Integer
    x = 1 + 2
    Bar = x
End Function

";

            var codePaneFactory = new CodePaneWrapperFactory();

            var builder = new MockVbeBuilder();
            VBComponent component;
            var vbe = builder.BuildFromSingleStandardModule(inputCode, out component);
            var module = component.CodeModule;

            var mockHost = new Mock<IHostApplication>();
            mockHost.SetupAllProperties();
            var editor = new ActiveCodePaneEditor(module.VBE, codePaneFactory);
            var parser = MockParser.Create(vbe.Object, new RubberduckParserState());

            parser.Parse();
            if (parser.State.Status == ParserState.Error) { Assert.Inconclusive("Parser Error"); }

            var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(module.Parent), new Selection(4, 1, 4, 20));
            var model = new ExtractMethodModel(editor, parser.State.AllDeclarations, qualifiedSelection);
            model.Method.Accessibility = Accessibility.Private;
            model.Method.MethodName = "Bar";
            model.Method.ReturnValue = new ExtractedParameter("Integer", ExtractedParameter.PassedBy.ByVal, "x");
            model.Method.Parameters = new List<ExtractedParameter>();

            var factory = SetupFactory(model);

            //act
            var refactoring = new ExtractMethodRefactoring(factory.Object, editor);
            refactoring.Refactor(qualifiedSelection);

            //assert
            Assert.AreEqual(expectedCode, module.Lines());
        }
Ejemplo n.º 21
0
        public void ConstructorWorks_IsNotNull()
        {
            // arange
            var symbolSelection = new Selection(1, 1, 2, 2);
            var qualifiedSelection = new QualifiedSelection(_module, symbolSelection);

            //act
            //var presenter = new RenamePresenter(_vbe.Object, _view.Object, _declarations, qualifiedSelection);
            Assert.Inconclusive("This test is broken");

            //assert
            //Assert.IsNotNull(presenter, "Successfully initialized");
        }
        public void Refactor(QualifiedSelection selection)
        {
            var target = _declarations.FindVariable(selection);

            if (target == null)
            {
                _messageBox.Show(RubberduckUI.MoveCloserToUsage_InvalidSelection, RubberduckUI.IntroduceParameter_Caption,
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            MoveCloserToUsage(target);
        }
 public ChangeProcedureToFunction(RubberduckParserState state,
                                  QualifiedContext<VBAParser.ArgListContext> argListQualifiedContext,
                                  QualifiedContext<VBAParser.SubStmtContext> subStmtQualifiedContext,
                                  QualifiedSelection selection)
     : base(subStmtQualifiedContext.Context, selection, InspectionsUI.ProcedureShouldBeFunctionInspectionQuickFix)
 {
     _state = state;
     _argListQualifiedContext = argListQualifiedContext;
     _subStmtQualifiedContext = subStmtQualifiedContext;
     _argQualifiedContext = new QualifiedContext<VBAParser.ArgContext>(_argListQualifiedContext.ModuleName,
         _argListQualifiedContext.Context.arg()
             .First(a => a.BYREF() != null || (a.BYREF() == null && a.BYVAL() == null)));
 }
        public override void Execute(object parameter)
        {
            if (Vbe.ActiveCodePane == null)
            {
                return;
            }
            var codePane = _wrapperWrapperFactory.Create(Vbe.ActiveCodePane);
            var selection = new QualifiedSelection(new QualifiedModuleName(codePane.CodeModule.Parent), codePane.Selection);

            using (var view = new ReorderParametersDialog())
            {
                var factory = new ReorderParametersPresenterFactory(Editor, view, _state, new MessageBox());
                var refactoring = new ReorderParametersRefactoring(factory, Editor, new MessageBox());
                refactoring.Refactor(selection);
            }
        }
 public IAnnotation Create(VBAParser.AnnotationContext context, QualifiedSelection qualifiedSelection)
 {
     string annotationName = context.annotationName().GetText();
     List<string> parameters = new List<string>();
     var argList = context.annotationArgList();
     if (argList != null)
     {
         parameters.AddRange(argList.annotationArg().Select(arg => arg.GetText()));
     }
     Type annotationCLRType = null;
     if (_creators.TryGetValue(annotationName.ToUpperInvariant(), out annotationCLRType))
     {
         return (IAnnotation)Activator.CreateInstance(annotationCLRType, qualifiedSelection, parameters);
     }
     return null;
 }
        public void Refactor(QualifiedSelection selection)
        {
            _targetInterface = _declarations.FindInterface(selection);

            _targetClass = _declarations.SingleOrDefault(d =>
                        !d.IsBuiltIn && d.DeclarationType == DeclarationType.Class &&
                        d.QualifiedSelection.QualifiedName.Equals(selection.QualifiedName));

            if (_targetClass == null || _targetInterface == null)
            {
                _messageBox.Show(RubberduckUI.ImplementInterface_InvalidSelectionMessage, RubberduckUI.ImplementInterface_Caption,
                    System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
                return;
            }

            ImplementMissingMembers();
        }
Ejemplo n.º 27
0
        public void RenameRefactoring_RenameSub()
        {
            //Input
            const string inputCode =
@"Private Sub Foo()
End Sub";
            var selection = new Selection(1, 15, 1, 15);

            //Expectation
            const string expectedCode =
@"Private Sub Goo()
End Sub";

            //Arrange
            var builder = new MockVbeBuilder();
            VBComponent component;
            var vbe = builder.BuildFromSingleStandardModule(inputCode, out component);
            var project = vbe.Object.VBProjects.Item(0);
            var module = project.VBComponents.Item(0).CodeModule;
            var codePaneFactory = new CodePaneWrapperFactory();
            var mockHost = new Mock<IHostApplication>();
            mockHost.SetupAllProperties();
            var parser = MockParser.Create(vbe.Object, new RubberduckParserState());

            parser.Parse();
            if (parser.State.Status == ParserState.Error) { Assert.Inconclusive("Parser Error"); }

            var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

            var model = new RenameModel(vbe.Object, parser.State, qualifiedSelection, null) { NewName = "Goo" };

            //SetupFactory
            var factory = SetupFactory(model);

            //Act
            var refactoring = new RenameRefactoring(factory.Object, new ActiveCodePaneEditor(vbe.Object, codePaneFactory), null, parser.State);
            refactoring.Refactor(qualifiedSelection);

            //Assert
            var actual = module.Lines();
            Assert.AreEqual(expectedCode, actual);
        }
        public void ReorderParams_SwapPositions()
        {
            //Input
            const string inputCode =
@"Private Sub Foo(ByVal arg1 As Integer, ByVal arg2 As String)
End Sub";
            var selection = new Selection(1, 23, 1, 27);

            //Expectation
            const string expectedCode =
@"Private Sub Foo(ByVal arg2 As String, ByVal arg1 As Integer)
End Sub";

            //Arrange
            var builder = new MockVbeBuilder();
            VBComponent component;
            var vbe = builder.BuildFromSingleStandardModule(inputCode, out component);
            var project = vbe.Object.VBProjects.Item(0);
            var module = project.VBComponents.Item(0).CodeModule;
            var codePaneFactory = new CodePaneWrapperFactory();
            var mockHost = new Mock<IHostApplication>();
            mockHost.SetupAllProperties();
            var parser = MockParser.Create(vbe.Object, new RubberduckParserState());

            parser.Parse();
            if (parser.State.Status == ParserState.Error) { Assert.Inconclusive("Parser Error"); }

            var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

            //set up model
            var model = new ReorderParametersModel(parser.State, qualifiedSelection, null);
            model.Parameters.Reverse();

            var factory = SetupFactory(model);

            //act
            var refactoring = new ReorderParametersRefactoring(factory.Object, new ActiveCodePaneEditor(vbe.Object, codePaneFactory), null);
            refactoring.Refactor(qualifiedSelection);

            //assert
            Assert.AreEqual(expectedCode, module.Lines());
        }
        public void MoveCloserToUsageRefactoring_Field()
        {
            //Input
            const string inputCode =
@"Private bar As Boolean
Private Sub Foo()
    bar = True
End Sub";
            var selection = new Selection(1, 1, 1, 1);

            //Expectation
            const string expectedCode =
@"Private Sub Foo()

    Dim bar As Boolean
    bar = True
End Sub";

            //Arrange
            var builder = new MockVbeBuilder();
            VBComponent component;
            var vbe = builder.BuildFromSingleStandardModule(inputCode, out component);
            var project = vbe.Object.VBProjects.Item(0);
            var module = project.VBComponents.Item(0).CodeModule;
            var codePaneFactory = new CodePaneWrapperFactory();
            var mockHost = new Mock<IHostApplication>();
            mockHost.SetupAllProperties();
            var parser = MockParser.Create(vbe.Object, new RubberduckParserState());

            parser.Parse();
            if (parser.State.Status == ParserState.Error) { Assert.Inconclusive("Parser Error"); }

            var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(component), selection);

            //Act
            var refactoring = new MoveCloserToUsageRefactoring(parser.State, new ActiveCodePaneEditor(vbe.Object, codePaneFactory), null);
            refactoring.Refactor(qualifiedSelection);

            //Assert
            Assert.AreEqual(expectedCode, module.Lines());
        }
 public RemoveTypeHintsQuickFix(ParserRuleContext context, QualifiedSelection selection, Declaration declaration)
     : base(context, selection, InspectionsUI.RemoveTypeHintsQuickFix)
 {
     _declaration = declaration;
 }
 public void SetSelection(QualifiedSelection selection)
 {
     _vbe.ActiveCodePane = selection.QualifiedName.Component.CodeModule.CodePane;
     SetSelection(selection.Selection);
 }