private void UpdateSignature(Declaration targetVariable, IRewriteSession rewriteSession) { var functionDeclaration = _selectedDeclarationProvider.SelectedMember(targetVariable.QualifiedSelection); var paramList = functionDeclaration.Context.GetChild <VBAParser.ArgListContext>(); if (functionDeclaration.DeclarationType.HasFlag(DeclarationType.Property)) { UpdateProperties(functionDeclaration, targetVariable, rewriteSession); } else { AddParameter(functionDeclaration, targetVariable, paramList, rewriteSession); } var interfaceImplementation = functionDeclaration.InterfaceMemberImplemented; if (interfaceImplementation == null) { return; } UpdateSignature(interfaceImplementation, targetVariable, rewriteSession); var interfaceImplementations = _declarationFinderProvider.DeclarationFinder.FindInterfaceImplementationMembers(functionDeclaration.InterfaceMemberImplemented) .Where(member => !ReferenceEquals(member, functionDeclaration)); foreach (var implementation in interfaceImplementations) { UpdateSignature(implementation, targetVariable, rewriteSession); } }
public override void Refactor(ImplicitTypeToExplicitModel model, IRewriteSession rewriteSession) { if (!(model.Target.Context is VBAParser.VariableSubStmtContext || model.Target.Context is VBAParser.ConstSubStmtContext || model.Target.Context is VBAParser.ArgContext)) { throw new ArgumentException($"Invalid target {model.Target.IdentifierName}"); } var identifierNode = model.Target.Context.GetChild <VBAParser.IdentifierContext>() ?? model.Target.Context.GetChild <VBAParser.UnrestrictedIdentifierContext>() as ParserRuleContext; var insertAfterTarget = model.Target.IsArray ? model.Target.Context.Stop.TokenIndex : identifierNode.Stop.TokenIndex; var asTypeName = Tokens.Variant; if (!model.ForceVariantAsType) { var resolver = new ImplicitAsTypeNameResolver(_declarationFinderProvider, _parseTreeValueFactory, model.Target); asTypeName = InferAsTypeNameForInspectionResult(model.Target, resolver, new AsTypeNamesResultsHandler()); } var rewriter = rewriteSession.CheckOutModuleRewriter(model.Target.QualifiedModuleName); rewriter.InsertAfter(insertAfterTarget, $" {Tokens.As} {asTypeName}"); }
public override void Refactor(AnnotateDeclarationModel model, IRewriteSession rewriteSession) { if (model.AdjustAttribute && rewriteSession.TargetCodeKind != CodeKind.AttributesCode && model.Annotation is IAttributeAnnotation) { throw new AttributeRewriteSessionRequiredException(); } var targetDeclaration = model.Target; if (rewriteSession.TargetCodeKind == CodeKind.AttributesCode && targetDeclaration.AttributesPassContext == null && !targetDeclaration.DeclarationType.HasFlag(DeclarationType.Module)) { throw new AttributeRewriteSessionNotSupportedException(); } var arguments = model.Arguments.Select(ToCode).ToList(); if (model.AdjustAttribute && model.Annotation is IAttributeAnnotation attributeAnnotation) { var baseAttribute = attributeAnnotation.Attribute(arguments); var attribute = targetDeclaration.DeclarationType.HasFlag(DeclarationType.Module) ? baseAttribute : Attributes.MemberAttributeName(baseAttribute, targetDeclaration.IdentifierName); var attributeValues = attributeAnnotation.AnnotationToAttributeValues(arguments); _attributesUpdater.AddOrUpdateAttribute(rewriteSession, targetDeclaration, attribute, attributeValues); } _annotationUpdater.AddAnnotation(rewriteSession, targetDeclaration, model.Annotation, arguments); }
private void InsertNewDeclaration(IRewriteSession rewriteSession) { var subscripts = _target.Context.GetDescendent <VBAParser.SubscriptsContext>()?.GetText() ?? string.Empty; var identifier = _target.IsArray ? $"{_target.IdentifierName}({subscripts})" : _target.IdentifierName; var newVariable = _target.AsTypeContext is null ? $"{Tokens.Dim} {identifier} {Tokens.As} {Tokens.Variant}{Environment.NewLine}" : $"{Tokens.Dim} {identifier} {Tokens.As} {(_target.IsSelfAssigned ? Tokens.New + " " : string.Empty)}{_target.AsTypeNameWithoutArrayDesignator}{Environment.NewLine}"; var firstReference = _target.References.OrderBy(r => r.Selection.StartLine).First(); RuleContext expression = firstReference.Context; while (!(expression is VBAParser.BlockStmtContext)) { expression = expression.Parent; } var insertionIndex = (expression as ParserRuleContext).Start.TokenIndex; int indentLength; using (var pane = _vbe.ActiveCodePane) { using (var codeModule = pane.CodeModule) { var firstReferenceLine = codeModule.GetLines((expression as ParserRuleContext).Start.Line, 1); indentLength = firstReferenceLine.Length - firstReferenceLine.TrimStart().Length; } } var padding = new string(' ', indentLength); var rewriter = rewriteSession.CheckOutModuleRewriter(firstReference.QualifiedModuleName); rewriter.InsertBefore(insertionIndex, newVariable + padding); }
private void Apply(IRewriteSession rewriteSession) { if (!rewriteSession.TryRewrite()) { _failureNotifier.NotifyQuickFixExecutionFailure(rewriteSession.Status); } }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.RemCommentContext)result.Context; rewriter.Replace(context.REM(), "'"); }
private void RenameMember(RenameModel model, IRewriteSession rewriteSession) { if (model.Target.DeclarationType.HasFlag(DeclarationType.Property)) { var members = _declarationFinderProvider.DeclarationFinder.MatchName(model.Target.IdentifierName) .Where(item => item.ProjectId == model.Target.ProjectId && item.ComponentName == model.Target.ComponentName && item.DeclarationType.HasFlag(DeclarationType.Property)); foreach (var member in members) { RenameStandardElements(member, model.NewName, rewriteSession); } } else { RenameStandardElements(model.Target, model.NewName, rewriteSession); } if (!model.IsInterfaceMemberRename) { return; } var implementations = _declarationFinderProvider.DeclarationFinder.FindAllInterfaceImplementingMembers() .Where(impl => ReferenceEquals(model.Target.ParentDeclaration, impl.InterfaceImplemented) && impl.InterfaceMemberImplemented.IdentifierName.Equals(model.Target.IdentifierName)); RenameDefinedFormatMembers(model, implementations.ToList(), PrependUnderscoreFormat, rewriteSession); }
protected override void Refactor(IntroduceParameterModel model, IRewriteSession rewriteSession) { var target = model.Target; UpdateSignature(target, model.EnclosingMember, rewriteSession); RemoveTarget(target, rewriteSession); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = result.Context; rewriter.Remove(context); }
private void UpdateSignature(Declaration target, ParameterDeclaration arg, IRewriteSession rewriteSession) { var subStmt = (VBAParser.SubStmtContext)target.Context; var argContext = (VBAParser.ArgContext)arg.Context; var rewriter = rewriteSession.CheckOutModuleRewriter(target.QualifiedModuleName); rewriter.Replace(subStmt.SUB(), Tokens.Function); rewriter.Replace(subStmt.END_SUB(), "End Function"); rewriter.InsertAfter(subStmt.argList().Stop.TokenIndex, $" As {arg.AsTypeName}"); if (arg.IsByRef) { rewriter.Replace(argContext.BYREF(), Tokens.ByVal); } else if (arg.IsImplicitByRef) { rewriter.InsertBefore(argContext.unrestrictedIdentifier().Start.TokenIndex, Tokens.ByVal); } var returnStmt = $" {subStmt.subroutineName().GetText()} = {argContext.unrestrictedIdentifier().GetText()}{Environment.NewLine}"; rewriter.InsertBefore(subStmt.END_SUB().Symbol.TokenIndex, returnStmt); }
private void AdjustReferences(IEnumerable <IdentifierReference> references, IRewriteSession rewriteSession) { foreach (var reference in references.Where(item => item.Context != _model.TargetDeclaration.Context)) { VBAParser.ArgumentListContext argumentList = null; var callStmt = reference.Context.GetAncestor <VBAParser.CallStmtContext>(); if (callStmt != null) { argumentList = CallStatement.GetArgumentList(callStmt); } if (argumentList == null) { var indexExpression = reference.Context.GetAncestor <VBAParser.IndexExprContext>(); if (indexExpression != null) { argumentList = indexExpression.GetChild <VBAParser.ArgumentListContext>(); } } if (argumentList == null) { continue; } var module = reference.QualifiedModuleName; RewriteCall(argumentList, module, rewriteSession); } }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var context = (VBAParser.ErrorStmtContext)result.Context; rewriter.Replace(context.ERROR(), "Err.Raise"); }
public override void Refactor(ModifyUserDefinedTypeModel model, IRewriteSession rewriteSession) { var newMembers = new List <string>(); foreach ((Declaration Prototype, string Identifier) in model.MembersToAdd) { _codeBuilder.TryBuildUDTMemberDeclaration(Prototype, Identifier, out var udtMemberDeclaration); newMembers.Add(udtMemberDeclaration); } var scratchPad = _rewritingManager.CheckOutCodePaneSession().CheckOutModuleRewriter(model.Target.QualifiedModuleName); scratchPad.InsertBefore(model.InsertionIndex, $"{Environment.NewLine}{string.Join(Environment.NewLine, newMembers)}"); foreach (var member in model.MembersToRemove) { scratchPad.Remove(member); } var udtDeclarationContext = model.Target.Context as VBAParser.UdtDeclarationContext; var newBlock = scratchPad.GetText(udtDeclarationContext.Start.TokenIndex, udtDeclarationContext.Stop.TokenIndex); var udtLines = newBlock.Split(new string[] { Environment.NewLine }, StringSplitOptions.None) .Where(ul => !string.IsNullOrEmpty(ul.Trim())); var rewriter = rewriteSession.CheckOutModuleRewriter(model.Target.QualifiedModuleName); rewriter.Replace(udtDeclarationContext, string.Join(Environment.NewLine, _codeBuilder.Indenter.Indent(udtLines))); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); if (result.Context.Parent.Parent is VBAParser.WithStmtContext withContext) { var lines = withContext.GetText().Replace("\r", string.Empty).Split('\n'); // Assume that the End With is at the appropriate indentation level for the block. Note that this could // over-indent or under-indent some lines if statement separators are being used, but meh. var padding = new string(' ', lines.Last().IndexOf(Tokens.End, StringComparison.Ordinal)); var replacement = new List <string> { $"{Tokens.CommentMarker}TODO - {result.Description}", $"{Tokens.CommentMarker}{padding}{lines.First()}" }; replacement.AddRange(lines.Skip(1) .Select(line => Tokens.CommentMarker + line)); rewriter.Replace(withContext, string.Join(Environment.NewLine, replacement)); return; } var assignmentContext = result.Context.GetAncestor <VBAParser.LetStmtContext>() ?? (ParserRuleContext)result.Context.GetAncestor <VBAParser.CallStmtContext>(); rewriter.Remove(assignmentContext); }
public void UpdateAnnotation(IRewriteSession rewriteSession, IParseTreeAnnotation annotation, IAnnotation annotationInfo, IReadOnlyList <string> newValues = null) { var newAnnotationValues = newValues ?? new List <string>(); if (annotation == null) { _logger.Warn("Tried to replace an annotation that is null."); _logger.Trace($"Tried to replace an annotation that is null with an annotation {annotationInfo.Name} with values {AnnotationValuesText(newAnnotationValues)}."); return; } if (rewriteSession.TargetCodeKind != CodeKind.CodePaneCode && rewriteSession.TargetCodeKind != CodeKind.AttributesCode) { _logger.Warn($"Tried to update an annotation with a rewriter not suitable for annotationss. (target code kind = {rewriteSession.TargetCodeKind})"); _logger.Trace($"Tried to update annotation {annotation.Annotation.Name} at {annotation.QualifiedSelection.Selection} in module {annotation.QualifiedSelection.QualifiedName} with annotation {annotationInfo.Name} with values {AnnotationValuesText(newAnnotationValues)} using a rewriter not suitable for annotations."); return; } //If there are no common flags, the annotations cannot apply to the same target. if ((annotation.Annotation.Target & annotationInfo.Target) == 0) { _logger.Warn("Tried to replace an annotation with an annotation without common flags."); _logger.Trace($"Tried to replace an annotation {annotation.Annotation.Name} with values {AnnotationValuesText(newValues)} at {annotation.QualifiedSelection.Selection} in module {annotation.QualifiedSelection.QualifiedName} with an annotation {annotationInfo.Name} with values {AnnotationValuesText(newAnnotationValues)}, which does not have any common flags."); return; } var context = annotation.Context; var whitespaceAtEnd = context.whiteSpace()?.GetText() ?? string.Empty; var codeReplacement = $"{AnnotationBaseText(annotationInfo.Name, newAnnotationValues)}{whitespaceAtEnd}"; var rewriter = rewriteSession.CheckOutModuleRewriter(annotation.QualifiedSelection.QualifiedName); rewriter.Replace(annotation.Context, codeReplacement); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { if (!(result.Target is ParameterDeclaration parameter)) { return; } AddByRefIdentifier(rewriteSession, parameter); var finder = _declarationFinderProvider.DeclarationFinder; var parentDeclaration = parameter.ParentDeclaration; if (parentDeclaration is ModuleBodyElementDeclaration enclosingMember && enclosingMember.IsInterfaceMember) { var parameterIndex = ParameterIndex(parameter, enclosingMember); AddByRefIdentifierToImplementations(enclosingMember, parameterIndex, finder, rewriteSession); } if (parentDeclaration is EventDeclaration enclosingEvent) { var parameterIndex = ParameterIndex(parameter, enclosingEvent); AddByRefIdentifierToHandlers(enclosingEvent, parameterIndex, finder, rewriteSession); } }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); var duplicateAnnotations = result.Target.Annotations .Where(annotation => annotation.AnnotationType == result.Properties.AnnotationType) .OrderBy(annotation => annotation.Context.Start.StartIndex) .Skip(1) .ToList(); var duplicatesPerAnnotationList = duplicateAnnotations .Select(annotation => (VBAParser.AnnotationListContext)annotation.Context.Parent) .Distinct() .ToDictionary(list => list, _ => 0); foreach (var annotation in duplicateAnnotations) { var annotationList = (VBAParser.AnnotationListContext)annotation.Context.Parent; RemoveAnnotationMarker(annotationList, annotation, rewriter); rewriter.Remove(annotation.Context); duplicatesPerAnnotationList[annotationList]++; } foreach (var pair in duplicatesPerAnnotationList) { if (OnlyQuoteRemainedFromAnnotationList(pair)) { rewriter.Remove(pair.Key); rewriter.Remove(((VBAParser.CommentOrAnnotationContext)pair.Key.Parent).NEWLINE()); } } }
public override void Refactor(MoveFolderModel model, IRewriteSession rewriteSession) { var sourceFolderParent = model.FolderToMove.ParentFolder(); var changeFolderModel = new ChangeFolderModel(sourceFolderParent, model.ModulesToMove, model.TargetFolder); _changeFolder.Refactor(changeFolderModel, rewriteSession); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { IParseTreeAnnotation oldAnnotation = result.Properties.Annotation; string attributeName = result.Properties.AttributeName; IReadOnlyList <string> attributeValues = result.Properties.AttributeValues; var declaration = result.Target; if (declaration.DeclarationType.HasFlag(DeclarationType.Module)) { var componentType = declaration.QualifiedModuleName.ComponentType; if (IsDefaultAttribute(componentType, attributeName, attributeValues)) { _annotationUpdater.RemoveAnnotation(rewriteSession, oldAnnotation); } else { var(newAnnotation, newAnnotationValues) = _attributeAnnotationProvider.ModuleAttributeAnnotation(attributeName, attributeValues); _annotationUpdater.UpdateAnnotation(rewriteSession, oldAnnotation, newAnnotation, newAnnotationValues); } } else { var attributeBaseName = AttributeBaseName(attributeName, declaration); var(newAnnotation, newAnnotationValues) = _attributeAnnotationProvider.MemberAttributeAnnotation(attributeBaseName, attributeValues); _annotationUpdater.UpdateAnnotation(rewriteSession, oldAnnotation, newAnnotation, newAnnotationValues); } }
public void RemoveAttribute(IRewriteSession rewriteSession, Declaration declaration, string attribute, IReadOnlyList <string> values = null) { if (string.IsNullOrEmpty(attribute)) { return; } if (declaration == null) { _logger.Warn("Tried to remove an attribute from a declaration that is null."); _logger.Trace($"Tried to remove attribute {attribute} {(values != null ? $"with values {AttributeValuesText(values)} " : string.Empty)}from a declaration that is null."); return; } if (rewriteSession.TargetCodeKind != CodeKind.AttributesCode) { _logger.Warn($"Tried to remove an attribute with a rewriter not suitable for attributes. (target code kind = {rewriteSession.TargetCodeKind})"); _logger.Trace($"Tried to remove attribute {attribute} {(values != null ? $"with values {AttributeValuesText(values)} " : string.Empty)}from {declaration.QualifiedModuleName} using a rewriter not suitable for attributes."); return; } var attributeNodes = ApplicableAttributeNodes(declaration, attribute, values); if (!attributeNodes.Any()) { return; } var rewriter = rewriteSession.CheckOutModuleRewriter(declaration.QualifiedModuleName); RemoveNodes(rewriter, attributeNodes); }
private void UpdateOtherModules(IRewriteSession rewriteSession) { QualifiedSelection?oldSelection = null; using (var pane = _vbe.ActiveCodePane) { if (!pane.IsWrappingNullReference) { oldSelection = pane.GetQualifiedSelection(); } var newTarget = _state.DeclarationFinder.MatchName(_target.IdentifierName).FirstOrDefault( item => item.ComponentName == _target.ComponentName && item.ParentScope == _target.ParentScope && item.ProjectId == _target.ProjectId && Equals(item.Selection, _target.Selection)); if (newTarget != null) { UpdateCallsToOtherModule(newTarget.References.ToList(), rewriteSession); } if (oldSelection.HasValue) { pane.Selection = oldSelection.Value.Selection; } } }
public void AddOrUpdateAttribute( IRewriteSession rewriteSession, Declaration declaration, string attribute, IReadOnlyList <string> values) { var attributeNodes = ApplicableAttributeNodes(declaration, attribute); if (!attributeNodes.Any()) { AddAttribute(rewriteSession, declaration, attribute, values); return; } if (attribute.Equals("VB_Ext_Key")) { var newKey = values.First(); var matchingExtKeyAttribute = attributeNodes.FirstOrDefault(node => newKey.Equals(node.Values.FirstOrDefault(), StringComparison.InvariantCultureIgnoreCase)); if (matchingExtKeyAttribute == null) { AddAttribute(rewriteSession, declaration, attribute, values); return; } var oldValues = matchingExtKeyAttribute.Values; UpdateAttribute(rewriteSession, declaration, attribute, values, oldValues); return; } UpdateAttribute(rewriteSession, declaration, attribute, values); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { if (!(result is IWithInspectionResultProperties <(IParseTreeAnnotation Annotation, string AttributeName, IReadOnlyList <string> AttributeValues)> resultProperties)) { return; } var declaration = result.Target; var(oldParseTreeAnnotation, attributeBaseName, attributeValues) = resultProperties.Properties; if (declaration.DeclarationType.HasFlag(DeclarationType.Module)) { var componentType = declaration.QualifiedModuleName.ComponentType; if (IsDefaultAttribute(componentType, attributeBaseName, attributeValues)) { _annotationUpdater.RemoveAnnotation(rewriteSession, oldParseTreeAnnotation); } else { var(newAnnotation, newAnnotationValues) = _attributeAnnotationProvider.ModuleAttributeAnnotation(attributeBaseName, attributeValues); _annotationUpdater.UpdateAnnotation(rewriteSession, oldParseTreeAnnotation, newAnnotation, newAnnotationValues); } } else { var(newAnnotation, newAnnotationValues) = _attributeAnnotationProvider.MemberAttributeAnnotation(attributeBaseName, attributeValues); _annotationUpdater.UpdateAnnotation(rewriteSession, oldParseTreeAnnotation, newAnnotation, newAnnotationValues); } }
private void AddModuleAnnotation(IRewriteSession rewriteSession, Declaration declaration, IAnnotation annotationInfo, IReadOnlyList <string> annotationValues) { if (!annotationInfo.Target.HasFlag(AnnotationTarget.Module)) { _logger.Warn("Tried to add an annotation without the module annotation flag to a module."); _logger.Trace($"Tried to add the annotation {annotationInfo.Name} with values {AnnotationValuesText(annotationValues)} to the module {declaration.QualifiedModuleName}."); return; } if (rewriteSession.TargetCodeKind != CodeKind.CodePaneCode && rewriteSession.TargetCodeKind != CodeKind.AttributesCode) { _logger.Warn($"Tried to add an annotation to a module with a rewriter not suitable for annotations. (target code kind = {rewriteSession.TargetCodeKind})"); _logger.Trace($"Tried to add annotation {annotationInfo.Name} with values {AnnotationValuesText(annotationValues)} to the module {declaration.QualifiedModuleName} using a rewriter not suitable for annotations."); return; } var codeToAdd = AnnotationText(annotationInfo, annotationValues); var rewriter = rewriteSession.CheckOutModuleRewriter(declaration.QualifiedModuleName); if (rewriteSession.TargetCodeKind == CodeKind.AttributesCode) { InsertAfterLastModuleAttribute(rewriter, declaration.QualifiedModuleName, codeToAdd); } else { var codeToInsert = codeToAdd + Environment.NewLine; rewriter.InsertBefore(0, codeToInsert); } }
private void UpdateSignature(Declaration targetVariable, IRewriteSession rewriteSession) { var functionDeclaration = (ModuleBodyElementDeclaration)_declarations.FindTarget(targetVariable.QualifiedSelection, ValidDeclarationTypes); var proc = (dynamic)functionDeclaration.Context; var paramList = (VBAParser.ArgListContext)proc.argList(); if (functionDeclaration.DeclarationType.HasFlag(DeclarationType.Property)) { UpdateProperties(functionDeclaration, targetVariable, rewriteSession); } else { AddParameter(functionDeclaration, targetVariable, paramList, rewriteSession); } var interfaceImplementation = functionDeclaration.InterfaceMemberImplemented; if (interfaceImplementation == null) { return; } UpdateSignature(interfaceImplementation, targetVariable, rewriteSession); var interfaceImplementations = _state.DeclarationFinder.FindInterfaceImplementationMembers(functionDeclaration.InterfaceMemberImplemented) .Where(member => !ReferenceEquals(member, functionDeclaration)); foreach (var implementation in interfaceImplementations) { UpdateSignature(implementation, targetVariable, rewriteSession); } }
public void AddAnnotation(IRewriteSession rewriteSession, IdentifierReference reference, IAnnotation annotationInfo, IReadOnlyList <string> values = null) { var annotationValues = values ?? new List <string>(); if (reference == null) { _logger.Warn("Tried to add an annotation to an identifier reference that is null."); _logger.Trace($"Tried to add annotation {annotationInfo.Name} with values {AnnotationValuesText(annotationValues)} to an identifier reference that is null."); return; } if (!annotationInfo.Target.HasFlag(AnnotationTarget.Identifier)) { _logger.Warn("Tried to add an annotation without the identifier reference annotation flag to an identifier reference."); _logger.Trace($"Tried to add annotation {annotationInfo.Name} with values {AnnotationValuesText(annotationValues)} to the identifier reference to {reference.Declaration.QualifiedName} at {reference.Selection} in module {reference.QualifiedModuleName}."); return; } if (rewriteSession.TargetCodeKind != CodeKind.CodePaneCode) { _logger.Warn($"Tried to add an annotation to an identifier reference with a rewriter not suitable for annotations to references. (target code kind = {rewriteSession.TargetCodeKind})"); _logger.Trace($"Tried to add annotation {annotationInfo.Name} with values {AnnotationValuesText(annotationValues)} to the the identifier reference {reference.IdentifierName} at {reference.Selection} in module {reference.QualifiedModuleName} using a rewriter not suitable for annotations."); return; } AddAnnotation(rewriteSession, new QualifiedContext(reference.QualifiedModuleName, reference.Context), annotationInfo, annotationValues); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var rewriter = rewriteSession.CheckOutModuleRewriter(result.Target.QualifiedModuleName); const string asTypeClause = " As Variant"; switch (result.Target.DeclarationType) { case DeclarationType.Variable: var variableContext = (VBAParser.VariableSubStmtContext)result.Target.Context; rewriter.InsertAfter(variableContext.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.LibraryFunction: var declareContext = (VBAParser.DeclareStmtContext)result.Target.Context; rewriter.InsertAfter(declareContext.argList().Stop.TokenIndex, asTypeClause); break; case DeclarationType.PropertyGet: var propertyContext = (VBAParser.PropertyGetStmtContext)result.Target.Context; rewriter.InsertAfter(propertyContext.argList().Stop.TokenIndex, asTypeClause); break; } }
public void RemoveAnnotation(IRewriteSession rewriteSession, IParseTreeAnnotation annotation) { if (annotation == null) { _logger.Warn("Tried to remove an annotation that is null."); return; } if (rewriteSession.TargetCodeKind != CodeKind.CodePaneCode) { _logger.Warn($"Tried to remove an annotation with a rewriter not suitable for annotationss. (target code kind = {rewriteSession.TargetCodeKind})"); _logger.Trace($"Tried to remove annotation {annotation.Annotation.Name} at {annotation.QualifiedSelection.Selection} in module {annotation.QualifiedSelection.QualifiedName} using a rewriter not suitable for annotations."); return; } var annotationContext = annotation.Context; var annotationList = (VBAParser.AnnotationListContext)annotationContext.Parent; var rewriter = rewriteSession.CheckOutModuleRewriter(annotation.QualifiedSelection.QualifiedName); var annotations = annotationList.annotation(); if (annotations.Length == 1) { RemoveSingleAnnotation(rewriter, annotationContext, annotationList); } RemoveAnnotationMarker(rewriter, annotationContext); rewriter.Remove(annotationContext); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { var context = result.Context is VBAParser.ConstStmtContext ? result.Context : (ParserRuleContext)result.Context.Parent; string declarationsText; switch (context) { case VBAParser.ConstStmtContext consts: declarationsText = GetDeclarationsText(consts); break; case VBAParser.VariableStmtContext variables: declarationsText = GetDeclarationsText(variables); break; default: throw new NotSupportedException(); } var rewriter = rewriteSession.CheckOutModuleRewriter(result.QualifiedSelection.QualifiedName); rewriter.Replace(context, declarationsText); }
public override void Fix(IInspectionResult result, IRewriteSession rewriteSession) { if (!(result is IWithInspectionResultProperties <(IParseTreeAnnotation Annotation, string AttributeName, IReadOnlyList <string> AttributeValues)> resultProperties)) { return; } var declaration = result.Target; var(parseTreeAnnotation, attributeBaseName, attributeValues) = resultProperties.Properties; var attributeName = declaration.DeclarationType.HasFlag(DeclarationType.Module) ? attributeBaseName : Attributes.MemberAttributeName(attributeBaseName, declaration.IdentifierName); if (!(parseTreeAnnotation.Annotation is IAttributeAnnotation attributeAnnotation)) { var message = $"Tried to adjust values of attribute {attributeName} to values of non-attribute annotation {parseTreeAnnotation.Annotation.Name} in component {declaration.QualifiedModuleName}."; Logger.Warn(message); Debug.Fail(message); return; } var attributeValuesFromAnnotation = attributeAnnotation.AttributeValues(parseTreeAnnotation); _attributesUpdater.UpdateAttribute(rewriteSession, declaration, attributeName, attributeValuesFromAnnotation, oldValues: attributeValues); }