Exemplo n.º 1
0
        public static Declaration FindInterface(this IEnumerable <Declaration> declarations, QualifiedSelection selection)
        {
            foreach (var declaration in declarations.FindInterfaces())
            {
                foreach (var reference in declaration.References)
                {
                    var implementsStmt = ParserRuleContextHelper.GetParent <VBAParser.ImplementsStmtContext>(reference.Context);

                    if (implementsStmt == null)
                    {
                        continue;
                    }

                    var completeSelection = new Selection(implementsStmt.GetSelection().StartLine,
                                                          implementsStmt.GetSelection().StartColumn, reference.Selection.EndLine,
                                                          reference.Selection.EndColumn);

                    if (reference.QualifiedModuleName.Equals(selection.QualifiedName) &&
                        completeSelection.Contains(selection.Selection))
                    {
                        return(declaration);
                    }
                }
            }

            return(null);
        }
        private void AdjustReferences(IEnumerable <IdentifierReference> references, Declaration method)
        {
            foreach (var reference in references.Where(item => item.Context != method.Context))
            {
                var module = reference.QualifiedModuleName.Component.CodeModule;
                VBAParser.ArgumentListContext argumentList = null;
                var callStmt = ParserRuleContextHelper.GetParent <VBAParser.CallStmtContext>(reference.Context);
                if (callStmt != null)
                {
                    argumentList = CallStatement.GetArgumentList(callStmt);
                }

                if (argumentList == null)
                {
                    var indexExpression = ParserRuleContextHelper.GetParent <VBAParser.IndexExprContext>(reference.Context);
                    if (indexExpression != null)
                    {
                        argumentList = ParserRuleContextHelper.GetChild <VBAParser.ArgumentListContext>(indexExpression);
                    }
                }

                if (argumentList == null)
                {
                    continue;
                }
                RemoveCallParameter(argumentList, module);
            }
        }
        private bool FlagIfObjectVariableNotSet(IdentifierReference reference)
        {
            var allrefs        = reference.Declaration.References;
            var letStmtContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(reference.Context);

            return(reference.IsAssignment && (letStmtContext != null ||
                                              allrefs.Where(r => r.IsAssignment).All(r => ParserRuleContextHelper.GetParent <VBAParser.SetStmtContext>(r.Context)?.expression()?.GetText().Equals(Tokens.Nothing, StringComparison.InvariantCultureIgnoreCase) ?? false)));
        }
        public override void Fix(IInspectionResult result)
        {
            var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName);

            var assignmentContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(result.Context) ??
                                    (ParserRuleContext)ParserRuleContextHelper.GetParent <VBAParser.CallStmtContext>(result.Context);

            rewriter.Remove(assignmentContext);
        }
Exemplo n.º 5
0
        private bool IsSet(IdentifierReference usage)
        {
            var setStmt = ParserRuleContextHelper.GetParent <VBAParser.SetStmtContext>(usage.Context);

            if (setStmt == null)
            {
                return(false);
            }
            bool isSetAssignmentTarget = setStmt == usage.Context;

            return(isSetAssignmentTarget);
        }
Exemplo n.º 6
0
        private void UpdateCall(IdentifierReference reference, int argIndex)
        {
            var rewriter        = _state.GetRewriter(reference.QualifiedModuleName);
            var callStmtContext = ParserRuleContextHelper.GetParent <VBAParser.CallStmtContext>(reference.Context);
            var argListContext  = ParserRuleContextHelper.GetChild <VBAParser.ArgumentListContext>(callStmtContext);

            var arg     = argListContext.argument()[argIndex];
            var argName = arg.positionalArgument()?.argumentExpression() ?? arg.namedArgument().argumentExpression();

            rewriter.InsertBefore(callStmtContext.Start.TokenIndex, $"{argName.GetText()} = ");
            rewriter.Replace(callStmtContext.whiteSpace(), "(");
            rewriter.InsertAfter(argListContext.Stop.TokenIndex, ")");
        }
Exemplo n.º 7
0
        private bool IsIndexExprContext(IdentifierReference usage)
        {
            var indexExpr = ParserRuleContextHelper.GetParent <VBAParser.IndexExprContext>(usage.Context);

            if (indexExpr == null)
            {
                return(false);
            }
            var argumentList = indexExpr.argumentList();

            if (argumentList == null)
            {
                return(true);
            }
            return(!ParserRuleContextHelper.HasParent(usage.Context, argumentList));
        }
Exemplo n.º 8
0
        private bool IsCallStmt(IdentifierReference usage)
        {
            var callStmt = ParserRuleContextHelper.GetParent <VBAParser.CallStmtContext>(usage.Context);

            if (callStmt == null)
            {
                return(false);
            }
            var argumentList = CallStatement.GetArgumentList(callStmt);

            if (argumentList == null)
            {
                return(true);
            }
            return(!ParserRuleContextHelper.HasParent(usage.Context, argumentList));
        }
Exemplo n.º 9
0
        private static bool ObjectOrVariantRequiresSetAssignment(IdentifierReference objectOrVariantRef, IEnumerable <Declaration> variantAndObjectDeclarations)
        {
            //Not an assignment...nothing to evaluate
            if (!objectOrVariantRef.IsAssignment)
            {
                return(false);
            }

            if (IsAlreadyAssignedUsingSet(objectOrVariantRef) ||
                objectOrVariantRef.Declaration.AsTypeName != Tokens.Variant)
            {
                return(true);
            }

            //Variants can be assigned with or without 'Set' depending...
            var letStmtContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(objectOrVariantRef.Context);

            //A potential error is only possible for let statements: rset, lset and other type specific assignments are always let assignments;
            //assignemts in for each loop statements are do not require the set keyword.
            if (letStmtContext == null)
            {
                return(false);
            }

            //You can only new up objects.
            if (RHSUsesNew(letStmtContext))
            {
                return(true);
            }

            if (RHSIsLiteral(letStmtContext))
            {
                if (RHSIsObjectLiteral(letStmtContext))
                {
                    return(true);
                }
                //All literals but the object literal potentially do not need a set assignment.
                //We cannot get more information from the RHS and do not want false positives.
                return(false);
            }

            //If the RHS is the identifierName of one of the 'interesting' declarations, we need to use 'Set'
            //unless the 'interesting' declaration is also a Variant
            var rhsIdentifier = GetRHSIdentifierExpressionText(letStmtContext);

            return(variantAndObjectDeclarations.Any(dec => dec.IdentifierName == rhsIdentifier && dec.AsTypeName != Tokens.Variant));
        }
        public override IEnumerable <InspectionResultBase> GetInspectionResults()
        {
            var interestingDeclarations =
                State.AllDeclarations.Where(item =>
                                            item.AsTypeDeclaration != null &&
                                            ClassModuleDeclaration.HasDefaultMember(item.AsTypeDeclaration));

            var interestingReferences = interestingDeclarations
                                        .SelectMany(declaration => declaration.References)
                                        .Where(reference =>
            {
                var letStmtContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(reference.Context);
                return(reference.IsAssignment && letStmtContext != null && letStmtContext.LET() == null);
            });

            return(interestingReferences.Select(reference => new ImplicitDefaultMemberAssignmentInspectionResult(this, reference)));
        }
Exemplo n.º 11
0
        private void RenameModule()
        {
            RequestParseAfterRename = false;

            RenameReferences(_model.Target, _model.NewName);

            if (_model.Target.DeclarationType.HasFlag(DeclarationType.ClassModule))
            {
                foreach (var reference in _model.Target.References)
                {
                    var ctxt = ParserRuleContextHelper.GetParent <VBAParser.ImplementsStmtContext>(reference.Context);
                    if (ctxt != null)
                    {
                        RenameDefinedFormatMembers(_state.DeclarationFinder.FindInterfaceMembersForImplementsContext(ctxt), _appendUnderscoreFormat);
                    }
                }
            }

            var component = _model.Target.QualifiedName.QualifiedModuleName.Component;

            if (component.Type == ComponentType.Document)
            {
                var properties = component.Properties;
                var property   = properties["_CodeName"];
                {
                    property.Value = _model.NewName;
                }
            }
            else if (component.Type == ComponentType.UserForm)
            {
                var properties = component.Properties;
                var property   = properties["Caption"];
                {
                    if ((string)property.Value == _model.Target.IdentifierName)
                    {
                        property.Value = _model.NewName;
                    }
                    component.Name = _model.NewName;
                }
            }
            else
            {
                Debug.Assert(!component.CodeModule.IsWrappingNullReference, "input validation fail: Attempting to rename an ICodeModule wrapping a null reference");
                component.CodeModule.Name = _model.NewName;
            }
        }
 private void AdjustReferences(IEnumerable <IdentifierReference> references)
 {
     foreach (var reference in references.Where(item => item.Context != _model.TargetDeclaration.Context))
     {
         dynamic proc   = reference.Context;
         var     module = reference.QualifiedModuleName.Component.CodeModule;
         VBAParser.ArgumentListContext argumentList = null;
         var callStmt = ParserRuleContextHelper.GetParent <VBAParser.CallStmtContext>(reference.Context);
         if (callStmt != null)
         {
             argumentList = CallStatement.GetArgumentList(callStmt);
         }
         if (argumentList == null)
         {
             continue;
         }
         RewriteCall(argumentList, module);
     }
 }
        protected override IEnumerable <IInspectionResult> DoGetInspectionResults()
        {
            var interestingDeclarations =
                State.AllDeclarations.Where(item =>
                                            item.AsTypeDeclaration != null &&
                                            ClassModuleDeclaration.HasDefaultMember(item.AsTypeDeclaration));

            var interestingReferences = interestingDeclarations
                                        .SelectMany(declaration => declaration.References)
                                        .Where(reference =>
            {
                var letStmtContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(reference.Context);
                return(reference.IsAssignment && letStmtContext != null && letStmtContext.LET() == null);
            });

            return(interestingReferences.Select(reference => new IdentifierReferenceInspectionResult(this,
                                                                                                     string.Format(InspectionsUI.ImplicitDefaultMemberAssignmentInspectionResultFormat,
                                                                                                                   reference.Declaration.IdentifierName,
                                                                                                                   reference.Declaration.AsTypeDeclaration.IdentifierName),
                                                                                                     State,
                                                                                                     reference)));
        }
        public override IEnumerable <InspectionResultBase> GetInspectionResults()
        {
            var interestingDeclarations =
                State.AllUserDeclarations.Where(item =>
                                                !item.IsSelfAssigned &&
                                                !item.IsArray &&
                                                !SymbolList.ValueTypes.Contains(item.AsTypeName) &&
                                                (item.AsTypeDeclaration == null || (!ClassModuleDeclaration.HasDefaultMember(item.AsTypeDeclaration) &&
                                                                                    item.AsTypeDeclaration.DeclarationType != DeclarationType.Enumeration &&
                                                                                    item.AsTypeDeclaration.DeclarationType != DeclarationType.UserDefinedType)) &&
                                                (item.DeclarationType == DeclarationType.Variable ||
                                                 item.DeclarationType == DeclarationType.Parameter));

            var interestingMembers =
                State.AllUserDeclarations.Where(item =>
                                                (item.DeclarationType == DeclarationType.Function || item.DeclarationType == DeclarationType.PropertyGet) &&
                                                !item.IsArray &&
                                                item.IsTypeSpecified &&
                                                !SymbolList.ValueTypes.Contains(item.AsTypeName) &&
                                                (item.AsTypeDeclaration == null || // null if unresolved (e.g. in unit tests)
                                                 (item.AsTypeDeclaration.DeclarationType != DeclarationType.Enumeration && item.AsTypeDeclaration.DeclarationType != DeclarationType.UserDefinedType &&
                                                  item.AsTypeDeclaration != null &&
                                                  !ClassModuleDeclaration.HasDefaultMember(item.AsTypeDeclaration))));

            var interestingReferences = interestingDeclarations
                                        .Union(interestingMembers.SelectMany(item =>
                                                                             item.References.Where(reference => reference.ParentScoping.Equals(item) && reference.IsAssignment)
                                                                             .Select(reference => reference.Declaration)))
                                        .SelectMany(declaration =>
                                                    declaration.References.Where(reference =>
            {
                var letStmtContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(reference.Context);
                return(reference.IsAssignment && letStmtContext != null && letStmtContext.LET() == null);
            })
                                                    );


            return(interestingReferences.Select(reference => new ObjectVariableNotSetInspectionResult(this, reference)));
        }
Exemplo n.º 15
0
        public override IEnumerable <InspectionResultBase> GetInspectionResults()
        {
            var interestingDeclarations =
                State.AllUserDeclarations.Where(item =>
                                                !item.IsSelfAssigned &&
                                                !ValueTypes.Contains(item.AsTypeName) &&
                                                (item.AsTypeDeclaration == null ||
                                                 item.AsTypeDeclaration.DeclarationType != DeclarationType.Enumeration &&
                                                 item.AsTypeDeclaration.DeclarationType != DeclarationType.UserDefinedType) &&
                                                (item.DeclarationType == DeclarationType.Variable ||
                                                 item.DeclarationType == DeclarationType.Parameter));

            var interestingReferences = interestingDeclarations
                                        .SelectMany(declaration =>
                                                    declaration.References.Where(reference =>
            {
                var setStmtContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(reference.Context);
                return(reference.IsAssignment && setStmtContext != null && setStmtContext.LET() == null);
            }));


            return(interestingReferences.Select(reference => new ObjectVariableNotSetInspectionResult(this, reference)));
        }
Exemplo n.º 16
0
        private static bool IsLetAssignment(IdentifierReference reference)
        {
            var letStmtContext = ParserRuleContextHelper.GetParent <VBAParser.LetStmtContext>(reference.Context);

            return(reference.IsAssignment && letStmtContext != null);
        }
Exemplo n.º 17
0
        private static bool IsAlreadyAssignedUsingSet(IdentifierReference reference)
        {
            var setStmtContext = ParserRuleContextHelper.GetParent <VBAParser.SetStmtContext>(reference.Context);

            return(reference.IsAssignment && setStmtContext != null && setStmtContext.SET() != null);
        }
        private void UpdateCalls()
        {
            var procedureName = Identifier.GetName(_subStmtQualifiedContext.Context.subroutineName().identifier());

            var procedure =
                _state.AllDeclarations.SingleOrDefault(d =>
                                                       !d.IsBuiltIn &&
                                                       d.IdentifierName == procedureName &&
                                                       d.Context is VBAParser.SubStmtContext &&
                                                       d.QualifiedName.QualifiedModuleName.Equals(_subStmtQualifiedContext.ModuleName));

            if (procedure == null)
            {
                return;
            }

            foreach (var reference in procedure.References.OrderByDescending(o => o.Selection.StartLine).ThenByDescending(d => d.Selection.StartColumn))
            {
                var startLine = reference.Selection.StartLine;

                if (procedure.ComponentName == reference.QualifiedModuleName.ComponentName && procedure.Selection.EndLine < reference.Selection.StartLine)
                {
                    startLine += _lineOffset;
                }

                var module = reference.QualifiedModuleName.Component.CodeModule;

                var referenceParent = ParserRuleContextHelper.GetParent <VBAParser.CallStmtContext>(reference.Context);
                if (referenceParent == null)
                {
                    continue;
                }
                VBAParser.ArgumentListContext argList = CallStatement.GetArgumentList(referenceParent);
                List <string> paramNames     = new List <string>();
                string        argsCall       = string.Empty;
                int           argsCallOffset = 0;
                if (argList != null)
                {
                    argsCallOffset = argList.GetSelection().EndColumn - reference.Context.GetSelection().EndColumn;
                    argsCall       = argList.GetText();
                    if (argList.positionalOrNamedArgumentList().positionalArgumentOrMissing() != null)
                    {
                        paramNames.AddRange(argList.positionalOrNamedArgumentList().positionalArgumentOrMissing().Select(p =>
                        {
                            if (p is VBAParser.SpecifiedPositionalArgumentContext)
                            {
                                return(((VBAParser.SpecifiedPositionalArgumentContext)p).positionalArgument().GetText());
                            }
                            else
                            {
                                return(string.Empty);
                            }
                        }).ToList());
                    }
                    if (argList.positionalOrNamedArgumentList().namedArgumentList() != null)
                    {
                        paramNames.AddRange(argList.positionalOrNamedArgumentList().namedArgumentList().namedArgument().Select(p => p.GetText()).ToList());
                    }
                    if (argList.positionalOrNamedArgumentList().requiredPositionalArgument() != null)
                    {
                        paramNames.Add(argList.positionalOrNamedArgumentList().requiredPositionalArgument().GetText());
                    }
                }
                var referenceText = reference.Context.GetText();
                var newCall       = paramNames.ToList().ElementAt(_argListQualifiedContext.Context.arg().ToList().IndexOf(_argQualifiedContext.Context)) +
                                    " = " + _subStmtQualifiedContext.Context.subroutineName().GetText() +
                                    "(" + argsCall + ")";

                var oldLines = module.Lines[startLine, reference.Selection.LineCount];

                var newText = oldLines.Remove(reference.Selection.StartColumn - 1, referenceText.Length + argsCallOffset)
                              .Insert(reference.Selection.StartColumn - 1, newCall);

                module.DeleteLines(startLine, reference.Selection.LineCount);
                module.InsertLines(startLine, newText);
            }
        }