private void ConvertPropertyGet(IInspectionResult result, VBAParser.PropertyGetStmtContext propertyGetContext) { var rewriter = _state.GetRewriter(result.Target); var asTypeContext = ParserRuleContextHelper.GetChild <VBAParser.AsTypeClauseContext>(propertyGetContext); if (asTypeContext != null) { rewriter.Remove(asTypeContext); rewriter.Remove(propertyGetContext.children.ElementAt(propertyGetContext.children.IndexOf(asTypeContext) - 1) as ParserRuleContext); } if (result.Target.TypeHint != null) { rewriter.Remove(ParserRuleContextHelper.GetDescendent <VBAParser.TypeHintContext>(propertyGetContext)); } rewriter.Replace(propertyGetContext.PROPERTY_GET(), Tokens.Sub); rewriter.Replace(propertyGetContext.END_PROPERTY(), "End Sub"); foreach (var returnStatement in GetReturnStatements(result.Target)) { rewriter.Remove(returnStatement); } }
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); }
public override void ExitIfStmt(VBAParser.IfStmtContext context) { if (context.elseIfBlock() != null && context.elseIfBlock().Any()) { return; } if (context.elseBlock() == null) { return; } if (!IsSingleBooleanAssignment(context.block()) || !IsSingleBooleanAssignment(context.elseBlock().block())) { return; } // make sure the assignments are the opposite if (!(ParserRuleContextHelper.GetDescendent <VBAParser.BooleanLiteralIdentifierContext>(context.block()).GetText() == Tokens.True ^ ParserRuleContextHelper.GetDescendent <VBAParser.BooleanLiteralIdentifierContext>(context.elseBlock().block()).GetText() == Tokens.True)) { return; } if (ParserRuleContextHelper.GetDescendent <VBAParser.LetStmtContext>(context.block()).lExpression().GetText().ToLowerInvariant() != ParserRuleContextHelper.GetDescendent <VBAParser.LetStmtContext>(context.elseBlock().block()).lExpression().GetText().ToLowerInvariant()) { return; } _contexts.Add(new QualifiedContext <ParserRuleContext>(CurrentModuleName, context)); }
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); } }
/// <remarks> /// Interface implementation members are private, they're not called from an object /// variable reference of the type of the procedure's class, and whether they're called or not, /// they have to be implemented anyway, so removing them would break the code. /// Best just ignore them. /// </remarks> private bool IsInterfaceMember(IEnumerable <Declaration> declarations, IEnumerable <Declaration> classes, Declaration procedure) { // get the procedure's parent module var enumerable = classes as IList <Declaration> ?? classes.ToList(); var parent = enumerable.Where(item => item.ProjectId == procedure.ProjectId) .SingleOrDefault(item => item.IdentifierName == procedure.ComponentName); if (parent == null) { return(false); } var interfaces = enumerable.Where(item => item.References.Any(reference => ParserRuleContextHelper.HasParent <VBAParser.ImplementsStmtContext>(reference.Context.Parent))); if (interfaces.Select(i => i.ComponentName).Contains(procedure.ComponentName)) { return(true); } var result = GetImplementedInterfaceMembers(declarations, enumerable, procedure.ComponentName) .Contains(procedure.IdentifierName); return(result); }
public override IExpression VisitCcIfBlock([NotNull] VBAConditionalCompilationParser.CcIfBlockContext context) { var ifCondTokens = new ConstantExpression(new TokensValue(ParserRuleContextHelper.GetTokens(context.ccIf(), _tokenStream))); var ifCond = Visit(context.ccIf().ccExpression()); var ifBlock = Visit(context.ccBlock()); var elseIfCodeCondBlocks = context .ccElseIfBlock() .Select(elseIf => Tuple.Create <IExpression, IExpression, IExpression>( new ConstantExpression(new TokensValue(ParserRuleContextHelper.GetTokens(elseIf.ccElseIf(), _tokenStream))), Visit(elseIf.ccElseIf().ccExpression()), Visit(elseIf.ccBlock()))) .ToList(); IExpression elseCondTokens = null; IExpression elseBlock = null; if (context.ccElseBlock() != null) { elseCondTokens = new ConstantExpression(new TokensValue(ParserRuleContextHelper.GetTokens(context.ccElseBlock().ccElse(), _tokenStream))); elseBlock = Visit(context.ccElseBlock().ccBlock()); } var endIfTokens = new ConstantExpression(new TokensValue(ParserRuleContextHelper.GetTokens(context.ccEndIf(), _tokenStream))); return(new ConditionalCompilationIfExpression( ifCondTokens, ifCond, ifBlock, elseIfCodeCondBlocks, elseCondTokens, elseBlock, endIfTokens)); }
private IExpression VisitLibraryFunction(VBAConditionalCompilationParser.CcExpressionContext context) { var intrinsicFunction = context.intrinsicFunction(); var functionName = ParserRuleContextHelper.GetText(intrinsicFunction.intrinsicFunctionName(), _stream); var argument = Visit(intrinsicFunction.ccExpression()); return(VBALibrary.CreateLibraryFunction(functionName, argument)); }
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 IExpression VisitCcConst([NotNull] VBAConditionalCompilationParser.CcConstContext context) { return(new ConditionalCompilationConstantExpression( new ConstantExpression(new TokensValue(ParserRuleContextHelper.GetTokens(context, _tokenStream))), new ConstantExpression(new StringValue(Identifier.GetName(context.ccVarLhs().name()))), Visit(context.ccExpression()), _symbolTable)); }
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); }
private IEnumerable <string> GetImplementedInterfaceMembers(IEnumerable <Declaration> declarations, IEnumerable <Declaration> classes, string componentName) { var interfaces = classes.Where(item => item.References.Any(reference => ParserRuleContextHelper.HasParent <VBAParser.ImplementsStmtContext>(reference.Context.Parent) && reference.QualifiedModuleName.Component.Name == componentName)); var members = interfaces.SelectMany(declarations.InScope) .Select(member => member.ComponentName + "_" + member.IdentifierName); return(members); }
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); }
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, ")"); }
private bool IsSingleBooleanAssignment(VBAParser.BlockContext block) { if (block.ChildCount != 2) { return(false); } var mainBlockStmtContext = ParserRuleContextHelper.GetDescendent <VBAParser.MainBlockStmtContext>(block); return(mainBlockStmtContext.children.FirstOrDefault() is VBAParser.LetStmtContext letStmt && letStmt.expression() is VBAParser.LiteralExprContext literal && ParserRuleContextHelper.GetDescendent <VBAParser.BooleanLiteralIdentifierContext>(literal) != null); }
public override void Fix(IInspectionResult result) { if (!string.IsNullOrWhiteSpace(result.Target.TypeHint)) { var rewriter = _state.GetRewriter(result.Target); var typeHintContext = ParserRuleContextHelper.GetDescendent <VBAParser.TypeHintContext>(result.Context); rewriter.Remove(typeHintContext); var asTypeClause = ' ' + Tokens.As + ' ' + SymbolList.TypeHintToTypeName[result.Target.TypeHint]; switch (result.Target.DeclarationType) { case DeclarationType.Variable: var variableContext = (VBAParser.VariableSubStmtContext)result.Target.Context; rewriter.InsertAfter(variableContext.identifier().Stop.TokenIndex, asTypeClause); break; case DeclarationType.Constant: var constantContext = (VBAParser.ConstSubStmtContext)result.Target.Context; rewriter.InsertAfter(constantContext.identifier().Stop.TokenIndex, asTypeClause); break; case DeclarationType.Parameter: var parameterContext = (VBAParser.ArgContext)result.Target.Context; rewriter.InsertAfter(parameterContext.unrestrictedIdentifier().Stop.TokenIndex, asTypeClause); break; case DeclarationType.Function: var functionContext = (VBAParser.FunctionStmtContext)result.Target.Context; rewriter.InsertAfter(functionContext.argList().Stop.TokenIndex, asTypeClause); break; case DeclarationType.PropertyGet: var propertyContext = (VBAParser.PropertyGetStmtContext)result.Target.Context; rewriter.InsertAfter(propertyContext.argList().Stop.TokenIndex, asTypeClause); break; } } foreach (var reference in result.Target.References) { var rewriter = _state.GetRewriter(reference.QualifiedModuleName); var context = ParserRuleContextHelper.GetDescendent <VBAParser.TypeHintContext>(reference.Context); if (context != null) { rewriter.Remove(context); } } }
public override void Fix(IInspectionResult result) { var ifContext = (VBAParser.IfStmtContext)result.Context; var letStmt = ParserRuleContextHelper.GetDescendent <VBAParser.LetStmtContext>(ifContext.block()); var conditional = ifContext.booleanExpression().GetText(); if (letStmt.expression().GetText() == Tokens.False) { conditional = $"Not ({conditional})"; } var rewriter = _state.GetRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(result.Context, $"{letStmt.lExpression().GetText()} = {conditional}"); }
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)); }
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)); }
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))); }
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 IExpression Visit(VBAConditionalCompilationParser.LiteralContext context) { if (context.HEXLITERAL() != null) { return(VisitHexLiteral(context)); } else if (context.OCTLITERAL() != null) { return(VisitOctLiteral(context)); } else if (context.DATELITERAL() != null) { return(VisitDateLiteral(context)); } else if (context.FLOATLITERAL() != null) { return(VisitFloatLiteral(context)); } else if (context.INTEGERLITERAL() != null) { return(VisitIntegerLiteral(context)); } else if (context.STRINGLITERAL() != null) { return(VisitStringLiteral(context)); } else if (context.TRUE() != null) { return(new ConstantExpression(new BoolValue(true))); } else if (context.FALSE() != null) { return(new ConstantExpression(new BoolValue(false))); } else if (context.NOTHING() != null || context.NULL() != null) { return(new ConstantExpression(null)); } else if (context.EMPTY() != null) { return(new ConstantExpression(EmptyValue.Value)); } throw new Exception(string.Format("Unexpected literal encountered: {0}", ParserRuleContextHelper.GetText(context, _stream))); }
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))); }
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))); }
public override IExpression VisitPhysicalLine([NotNull] VBAConditionalCompilationParser.PhysicalLineContext context) { return(new ConstantExpression(new TokensValue(ParserRuleContextHelper.GetTokens(context, _tokenStream)))); }
private static void ReplaceTypeHint(RuleContext context, IModuleRewriter rewriter) { var typeHintContext = ParserRuleContextHelper.GetDescendent <VBAParser.TypeHintContext>(context); rewriter.Replace(typeHintContext, "&"); }
public override void Fix(IInspectionResult result) { var rewriter = _state.GetRewriter(result.Target); rewriter.Replace(ParserRuleContextHelper.GetDescendent <VBAParser.VisibilityContext>(result.Context.Parent.Parent), Tokens.Public); }
private bool IsTypeOfExpression(IdentifierReference usage) { return(ParserRuleContextHelper.HasParent <VBAParser.TypeofexprContext>(usage.Context)); }