Ejemplo n.º 1
0
        private void AddItems(IEnumerable <Declaration> 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);
        }
        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 static void AddByRefIdentifier(IModuleRewriter rewriter, VBAParser.ArgContext context)
 {
     if (context.BYREF() == null)
     {
         rewriter.InsertBefore(context.unrestrictedIdentifier().Start.TokenIndex, "ByRef ");
     }
 }
 private void UpdateCondition(VBAParser.RelationalOpContext condition, IModuleRewriter rewriter)
 {
     if (condition.EQ() != null)
     {
         rewriter.Replace(condition.EQ(), "<>");
     }
     if (condition.NEQ() != null)
     {
         rewriter.Replace(condition.NEQ(), "=");
     }
     if (condition.LT() != null)
     {
         rewriter.Replace(condition.LT(), ">=");
     }
     if (condition.GT() != null)
     {
         rewriter.Replace(condition.GT(), "<=");
     }
     if (condition.LEQ() != null)
     {
         rewriter.Replace(condition.LEQ(), ">");
     }
     if (condition.GEQ() != null)
     {
         rewriter.Replace(condition.GEQ(), "<");
     }
     if (condition.IS() != null || condition.LIKE() != null)
     {
         UpdateCondition((ParserRuleContext)condition, rewriter);
     }
 }
Ejemplo n.º 5
0
        private void PromoteVariable(IModuleRewriter rewriter, Declaration target)
        {
            if (new[] { DeclarationType.ClassModule, DeclarationType.ProceduralModule }.Contains(target.ParentDeclaration.DeclarationType))
            {
                _messageBox.Show(RubberduckUI.PromoteVariable_InvalidSelection, RubberduckUI.IntroduceParameter_Caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            QualifiedSelection?oldSelection = null;

            if (_vbe.ActiveCodePane != null)
            {
                oldSelection = _vbe.ActiveCodePane.CodeModule.GetQualifiedSelection();
            }

            rewriter.Remove(target);
            AddField(rewriter, target);

            if (oldSelection.HasValue)
            {
                var module = oldSelection.Value.QualifiedName.Component.CodeModule;
                var pane   = module.CodePane;
                {
                    pane.Selection = oldSelection.Value.Selection;
                }
            }

            rewriter.Rewrite();
        }
        /// <summary>
        /// Removes variable declaration and subsequent <c>VBAParser.EndOfStatementContext</c>
        /// depending on the <paramref name="removeEndOfStmtContext"/> flag.
        /// This function is intended to be called only once per rewriter within a given <c>ModuleRewriteSession</c>.
        /// </summary>
        /// <remarks>
        /// Calling this function with <paramref name="removeEndOfStmtContext"/> defaulted to <c>true</c>
        /// avoids leaving residual newlines between the deleted declaration and the next declaration.
        /// The one-time call constraint is required for scenarios where variables to delete are declared in a list.  Specifically,
        /// the use case where all the variables in the list are to be removed.
        /// If the variables to remove are not declared in a list, then this function can be called multiple times.
        /// </remarks>
        public static void RemoveVariables(this IModuleRewriter rewriter, IEnumerable <VariableDeclaration> toRemove, bool removeEndOfStmtContext = true)
        {
            if (!toRemove.Any())
            {
                return;
            }

            var fieldsToDeleteByListContext = toRemove.Distinct()
                                              .ToLookup(f => f.Context.GetAncestor <VBAParser.VariableListStmtContext>());

            foreach (var fieldsToDelete in fieldsToDeleteByListContext)
            {
                var variableList = fieldsToDelete.Key.children.OfType <VBAParser.VariableSubStmtContext>();

                if (variableList.Count() == fieldsToDelete.Count())
                {
                    if (fieldsToDelete.First().ParentDeclaration.DeclarationType.HasFlag(DeclarationType.Module))
                    {
                        rewriter.RemoveDeclarationContext <VBAParser.ModuleDeclarationsElementContext>(fieldsToDelete.First(), removeEndOfStmtContext);
                    }
                    else
                    {
                        rewriter.RemoveDeclarationContext <VBAParser.BlockStmtContext>(fieldsToDelete.First(), removeEndOfStmtContext);
                    }
                    continue;
                }

                foreach (var target in fieldsToDelete)
                {
                    rewriter.Remove(target);
                }
            }
        }
 public static void MakeImplicitDeclarationTypeExplicit(this IModuleRewriter rewriter, Declaration element)
 {
     if (!element.Context.TryGetChildContext <VBAParser.AsTypeClauseContext>(out _))
     {
         rewriter.InsertAfter(element.Context.Stop.TokenIndex, $" {Tokens.As} {element.AsTypeName}");
     }
 }
Ejemplo n.º 8
0
 private void RemoveReturnStatements(IInspectionResult result, IModuleRewriter rewriter)
 {
     foreach (var returnStatement in GetReturnStatements(result.Target))
     {
         rewriter.Remove(returnStatement);
     }
 }
Ejemplo n.º 9
0
 private void RemoveReturnStatements(ModuleBodyElementDeclaration member, IModuleRewriter rewriter)
 {
     foreach (var returnStatement in GetReturnStatements(member))
     {
         rewriter.Remove(returnStatement);
     }
 }
Ejemplo n.º 10
0
        private void UpdateContext(VBAParser.IfStmtContext context, IModuleRewriter rewriter)
        {
            var elseBlock   = context.elseBlock();
            var elseIfBlock = context.elseIfBlock().FirstOrDefault();

            if (BlockHasDeclaration(context.block()))
            {
                rewriter.InsertBefore(context.Start.TokenIndex, AdjustedBlockText(context.block()));
            }

            if (elseIfBlock != null)
            {
                rewriter.RemoveRange(context.IF().Symbol.TokenIndex, context.block()?.Stop.TokenIndex ?? context.endOfStatement().Stop.TokenIndex);
                rewriter.Replace(elseIfBlock.ELSEIF(), "If");
            }
            else if (elseBlock != null)
            {
                if (!string.IsNullOrEmpty(context.block()?.GetText()))
                {
                    rewriter.RemoveRange(context.block().Start.TokenIndex, elseBlock.ELSE().Symbol.TokenIndex);
                }
                else
                {
                    rewriter.Remove(elseBlock.ELSE());
                }

                Debug.Assert(context.booleanExpression().children.Count == 1);
                UpdateCondition((dynamic)context.booleanExpression().children[0], rewriter);
            }
            else
            {
                rewriter.Remove(context);
            }
        }
Ejemplo n.º 11
0
 private void ReplaceAssignedByValParameterReferences(IModuleRewriter rewriter, Declaration target, string localIdentifier)
 {
     foreach (var identifierReference in target.References)
     {
         rewriter.Replace(identifierReference.Context, localIdentifier);
     }
 }
Ejemplo n.º 12
0
        private static void RemoveAnnotationMarker(VBAParser.AnnotationListContext annotationList,
                                                   IAnnotation annotation, IModuleRewriter rewriter)
        {
            var index = Array.IndexOf(annotationList.annotation(), annotation.Context);

            rewriter.Remove(annotationList.AT(index));
        }
        public override void Fix(IInspectionResult result)
        {
            IModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName);

            //dynamic used since it's not known at run-time
            UpdateContext((dynamic)result.Context, rewriter);
        }
Ejemplo n.º 14
0
        private static void RemoveAnnotationMarker(IModuleRewriter rewriter, VBAParser.AnnotationContext annotationContext)
        {
            var endOfAnnotationMarker   = annotationContext.start.TokenIndex - 1;
            var startOfAnnotationMarker = endOfAnnotationMarker - ParseTreeAnnotation.ANNOTATION_MARKER.Length + 1;

            rewriter.RemoveRange(startOfAnnotationMarker, endOfAnnotationMarker);
        }
Ejemplo n.º 15
0
        public void AddAttributesRewriter(QualifiedModuleName module, IModuleRewriter attributesRewriter)
        {
            var key = module;

            _moduleStates[key].SetAttributesRewriter(attributesRewriter);
            _moduleStates[key].SetModuleContentHashCode(key.ContentHashCode);
        }
Ejemplo n.º 16
0
        public override void Fix(IInspectionResult result)
        {
            IModuleRewriter rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName);
            var             context  = result.Context;

            rewriter.Remove(context);
        }
        private void MakeReferenceUnqualified(IdentifierReference reference, IModuleRewriter rewriter)
        {
            var memberAccessContext = reference.Context.GetAncestor <VBAParser.MemberAccessExprContext>();

            if (memberAccessContext == null)
            {
                return;
            }

            // member access might be to something unrelated to the rewritten target.
            // check we're not accidentally overwriting some other member-access who just happens to be a parent context
            if (memberAccessContext.unrestrictedIdentifier()?.GetText() != _target.IdentifierName)
            {
                return;
            }
            var qualification = memberAccessContext.lExpression().GetText();

            if (!qualification.Equals(_target.ComponentName, StringComparison.InvariantCultureIgnoreCase) &&
                !qualification.Equals(_target.ProjectName, StringComparison.InvariantCultureIgnoreCase) &&
                !qualification.Equals($"{_target.QualifiedModuleName.ProjectName}.{_target.ComponentName}", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            rewriter.Replace(memberAccessContext, reference.IdentifierName);
        }
 private void SetFieldToPrivate(IModuleRewriter rewriter)
 {
     if (_model.TargetDeclaration.Accessibility != Accessibility.Private)
     {
         rewriter.Remove(_model.TargetDeclaration);
     }
 }
Ejemplo n.º 19
0
        private void PromoteVariable(IModuleRewriter rewriter, Declaration target)
        {
            if (new[] { DeclarationType.ClassModule, DeclarationType.ProceduralModule }.Contains(target.ParentDeclaration.DeclarationType))
            {
                _messageBox.NotifyWarn(RubberduckUI.PromoteVariable_InvalidSelection, RubberduckUI.IntroduceParameter_Caption);
                return;
            }

            var oldSelection = _vbe.GetActiveSelection();

            rewriter.Remove(target);
            AddField(rewriter, target);

            if (oldSelection.HasValue)
            {
                using (var module = _state.ProjectsProvider.Component(oldSelection.Value.QualifiedName).CodeModule)
                {
                    using (var pane = module.CodePane)
                    {
                        pane.Selection = oldSelection.Value.Selection;
                    }
                }
            }

            rewriter.Rewrite();
        }
Ejemplo n.º 20
0
 private static void RemoveByRefIdentifier(IModuleRewriter rewriter, VBAParser.ArgContext context)
 {
     if (context.BYREF() != null)
     {
         rewriter.Remove(context.BYREF());
         rewriter.Remove(context.whiteSpace().First());
     }
 }
        private void ImplementMissingMembers(IModuleRewriter rewriter)
        {
            var interfaceMembers      = GetInterfaceMembers();
            var implementedMembers    = GetImplementedMembers();
            var nonImplementedMembers = GetNonImplementedMembers(interfaceMembers, implementedMembers);

            AddItems(nonImplementedMembers, rewriter, _targetInterface.IdentifierName);
        }
 private static void RemoveArgumentRange(
     int startArgumentIndex,
     int stopArgumentIndex,
     VBAParser.ArgumentListContext argumentList,
     IModuleRewriter rewriter)
 {
     var(startTokenIndex, stopTokenIndex) = TokenIndexRange(startArgumentIndex, stopArgumentIndex, argumentList.argument());
     rewriter.RemoveRange(startTokenIndex, stopTokenIndex);
 }
Ejemplo n.º 23
0
        private static void UpdateAttributeValues(IModuleRewriter rewriter, AttributeNode nodeToUpdate, IEnumerable <string> values)
        {
            var statementContext    = nodeToUpdate.Context;
            var firstIndexToReplace = statementContext.EQ().Symbol.TokenIndex + 1;
            var lastIndexToReplace  = statementContext.stop.TokenIndex;
            var replacementText     = $" {AttributeValuesText(values)}";

            rewriter.Replace(new Interval(firstIndexToReplace, lastIndexToReplace), replacementText);
        }
        private void UpdateContext(VBAParser.ElseBlockContext context, IModuleRewriter rewriter)
        {
            var elseBlock = context.block();

            if (elseBlock.ChildCount == 0)
            {
                rewriter.Remove(context);
            }
        }
        public override void Fix(IInspectionResult result)
        {
            IModuleRewriter    rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName);
            ForNextStmtContext context  = result.Context as ForNextStmtContext;

            int toExpressionEnd = this.GetToExpressionEnd(context);

            rewriter.InsertAfter(toExpressionEnd, " Step 1");
        }
        public static void InsertAtEndOfFile(this IModuleRewriter rewriter, string content)
        {
            if (content == string.Empty)
            {
                return;
            }

            rewriter.InsertBefore(rewriter.TokenStream.Size - 1, content);
        }
        public static void Rename(this IModuleRewriter rewriter, Declaration target, string newName)
        {
            if (!(target.Context is IIdentifierContext context))
            {
                throw new ArgumentException();
            }

            rewriter.Replace(context.IdentifierTokens, newName);
        }
Ejemplo n.º 28
0
        private void UpdateContext(VBAParser.ElseIfBlockContext context, IModuleRewriter rewriter)
        {
            if (BlockHasDeclaration(context.block()))
            {
                rewriter.InsertBefore(((VBAParser.IfStmtContext)context.Parent).Start.TokenIndex, AdjustedBlockText(context.block()));
            }

            rewriter.Remove(context);
        }
Ejemplo n.º 29
0
        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)
                          .Where(item => item.DeclarationType.HasFlag(DeclarationType.Member))
                          .OrderByDescending(item => item.Selection);

            var firstMember = members.FirstOrDefault();

            rewriter.InsertBefore(firstMember?.Context.Start.TokenIndex ?? 0, content);
        }
Ejemplo n.º 30
0
 private void UpdateCondition(VBAParser.LogicalNotOpContext condition, IModuleRewriter rewriter)
 {
     if (condition.whiteSpace() != null)
     {
         rewriter.RemoveRange(condition.NOT().Symbol.TokenIndex, condition.whiteSpace().Stop.TokenIndex);
     }
     else
     {
         rewriter.Remove(condition.NOT());
     }
 }