void CheckSegments(IList <IFormatStringSegment> segments, TextLocation formatStart, IList <Expression> formatArguments, AstNode anchor) { int argumentCount = formatArguments.Count; foreach (var segment in segments) { var errors = segment.Errors.ToList(); var formatItem = segment as FormatItem; if (formatItem != null) { var segmentEnd = new TextLocation(formatStart.Line, formatStart.Column + segment.EndLocation + 1); var segmentStart = new TextLocation(formatStart.Line, formatStart.Column + segment.StartLocation + 1); if (formatItem.Index >= argumentCount) { var outOfBounds = context.TranslateString("The index '{0}' is out of bounds of the passed arguments"); AddIssue(new CodeIssue(segmentStart, segmentEnd, string.Format(outOfBounds, formatItem.Index))); } if (formatItem.HasErrors) { var errorMessage = string.Join(Environment.NewLine, errors.Select(error => error.Message).ToArray()); string messageFormat; if (errors.Count > 1) { messageFormat = context.TranslateString("Multiple:\n{0}"); } else { messageFormat = context.TranslateString("{0}"); } AddIssue(new CodeIssue(segmentStart, segmentEnd, string.Format(messageFormat, errorMessage))); } } else if (segment.HasErrors) { foreach (var error in errors) { var errorStart = new TextLocation(formatStart.Line, formatStart.Column + error.StartLocation + 1); var errorEnd = new TextLocation(formatStart.Line, formatStart.Column + error.EndLocation + 1); AddIssue(new CodeIssue(errorStart, errorEnd, error.Message)); } } } }
protected override IEnumerable <CodeAction> GetFixes(BaseRefactoringContext context, Node env, string variableName) { var containingStatement = env.ContainingStatement; // we don't give a fix for these cases since the general fix may not work // lambda in while/do-while/for condition if (containingStatement is WhileStatement || containingStatement is DoWhileStatement || containingStatement is ForStatement) { yield break; } // lambda in for initializer/iterator if (containingStatement.Parent is ForStatement && ((ForStatement)containingStatement.Parent).EmbeddedStatement != containingStatement) { yield break; } Action <Script> action = script => { var newName = LocalVariableNamePicker.PickSafeName( containingStatement.GetParent <EntityDeclaration> (), Enumerable.Range(1, 100).Select(i => variableName + i)); var variableDecl = new VariableDeclarationStatement(new SimpleType("var"), newName, new IdentifierExpression(variableName)); if (containingStatement.Parent is BlockStatement || containingStatement.Parent is SwitchSection) { script.InsertBefore(containingStatement, variableDecl); } else { var offset = script.GetCurrentOffset(containingStatement.StartLocation); script.InsertBefore(containingStatement, variableDecl); script.InsertText(offset, "{"); script.InsertText(script.GetCurrentOffset(containingStatement.EndLocation), "}"); script.FormatText(containingStatement.Parent); } var textNodes = new List <AstNode> (); textNodes.Add(variableDecl.Variables.First().NameToken); foreach (var reference in env.GetAllReferences()) { var identifier = new IdentifierExpression(newName); script.Replace(reference.AstNode, identifier); textNodes.Add(identifier); } script.Link(textNodes.ToArray()); }; yield return(new CodeAction(context.TranslateString("Copy to local variable"), action, env.AstNode)); }
CodeAction GetAction(BaseRefactoringContext context, Expression targetExpression, IMember member) { var builder = context.CreateTypeSystemAstBuilder(targetExpression); var newType = builder.ConvertType(member.DeclaringType); string description = string.Format("{0} '{1}'", context.TranslateString("Use base qualifier"), newType.ToString()); return(new CodeAction(description, script => { script.Replace(targetExpression, newType); }, targetExpression)); }
public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) { base.VisitVariableDeclarationStatement(variableDeclarationStatement); var rootNode = variableDeclarationStatement.Parent as BlockStatement; if (rootNode == null) { // We are somewhere weird, like a the ResourceAquisition of a using statement return; } // TODO: Handle declarations with more than one variable? if (variableDeclarationStatement.Variables.Count > 1) { return; } var variableInitializer = variableDeclarationStatement.Variables.First(); var identifiers = GetIdentifiers(rootNode.Descendants, variableInitializer.Name).ToList(); if (identifiers.Count == 0) { // variable is not used return; } if (!CheckForInvocations(variableInitializer.Initializer)) { return; } AstNode deepestCommonAncestor = GetDeepestCommonAncestor(rootNode, identifiers); var path = GetPath(rootNode, deepestCommonAncestor); // The node that will follow the moved declaration statement AstNode anchorNode = GetInitialAnchorNode(rootNode, identifiers, path); // Restrict path to only those where the initializer has not changed var pathToCheck = path.Skip(1).ToList(); var firstInitializerChangeNode = GetFirstInitializerChange(variableDeclarationStatement, pathToCheck, variableInitializer.Initializer); if (firstInitializerChangeNode != null) { // The node changing the initializer expression may not be on the path // to the actual usages of the variable, so we need to merge the paths // so we get the part of the paths that are common between them var pathToChange = GetPath(rootNode, firstInitializerChangeNode); var deepestCommonIndex = GetLowestCommonAncestorIndex(path, pathToChange); anchorNode = pathToChange [deepestCommonIndex + 1]; path = pathToChange.Take(deepestCommonIndex).ToList(); } // Restrict to locations outside of blacklisted node types var firstBlackListedNode = path.FirstOrDefault(node => moveTargetBlacklist.Contains(node.GetType())); if (firstBlackListedNode != null) { path = GetPath(rootNode, firstBlackListedNode.Parent); anchorNode = firstBlackListedNode; } anchorNode = GetInsertionPoint(anchorNode); if (anchorNode != null && anchorNode != rootNode && anchorNode.Parent != rootNode) { AddIssue(new CodeIssue(variableDeclarationStatement, context.TranslateString("Variable could be moved to a nested scope"), GetActions(variableDeclarationStatement, (Statement)anchorNode))); } }
public override void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) { base.VisitObjectCreateExpression(objectCreateExpression); Expression paramNode; Expression altParamNode; bool canAddParameterName; if (!CheckExceptionType(objectCreateExpression, out paramNode, out altParamNode, out canAddParameterName)) { return; } var paramName = GetArgumentParameterName(paramNode); if (paramName == null) { return; } var validNames = GetValidParameterNames(objectCreateExpression); if (!validNames.Contains(paramName)) { // Case 1: Parameter name is swapped var altParamName = GetArgumentParameterName(altParamNode); if (altParamName != null && validNames.Contains(altParamName)) { AddIssue(new CodeIssue( paramNode, string.Format(context.TranslateString("The parameter '{0}' can't be resolved"), paramName), context.TranslateString("Swap parameter."), script => { var newAltNode = paramNode.Clone(); script.Replace(paramNode, altParamNode.Clone()); script.Replace(altParamNode, newAltNode); } )); AddIssue(new CodeIssue( altParamNode, context.TranslateString("The parameter name is on the wrong argument."), context.TranslateString("Swap parameter."), script => { var newAltNode = paramNode.Clone(); script.Replace(paramNode, altParamNode.Clone()); script.Replace(altParamNode, newAltNode); } )); return; } var guessName = GuessParameterName(objectCreateExpression, validNames); if (guessName != null) { var actions = new List <CodeAction>(); actions.Add(new CodeAction( string.Format(context.TranslateString("Replace with '\"{0}\"'."), guessName), script => { script.Replace(paramNode, new PrimitiveExpression(guessName)); }, paramNode )); if (canAddParameterName) { actions.Add(new CodeAction( string.Format(context.TranslateString("Add '\"{0}\"' parameter."), guessName), script => { var oce = (ObjectCreateExpression)objectCreateExpression.Clone(); oce.Arguments.Clear(); oce.Arguments.Add(new PrimitiveExpression(guessName)); oce.Arguments.Add(objectCreateExpression.Arguments.First().Clone()); script.Replace(objectCreateExpression, oce); }, paramNode )); } AddIssue(new CodeIssue( paramNode, string.Format(context.TranslateString("The parameter '{0}' can't be resolved"), paramName), actions )); return; } // General case: mark only AddIssue(new CodeIssue( paramNode, string.Format(context.TranslateString("The parameter '{0}' can't be resolved"), paramName) )); } }
static CodeAction HandleNegatedCase(BaseRefactoringContext ctx, IfElseStatement ifElseStatement, Match match, out IsExpression isExpression, out int foundCastCount) { foundCastCount = 0; var outerIs = match.Get <Expression>("isExpression").Single(); isExpression = AlUtil.GetInnerMostExpression(outerIs) as IsExpression; var obj = AlUtil.GetInnerMostExpression(isExpression.Expression); var castToType = isExpression.Type; var cast = new Choice { PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastTo(castToType.Clone())), PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastAs(castToType.Clone())) }; var rr = ctx.Resolve(castToType); if (rr == null || rr.IsError || rr.Type.IsReferenceType == false) { return(null); } var foundCasts = ifElseStatement.GetParent <BlockStatement>().DescendantNodes(n => n.StartLocation >= ifElseStatement.StartLocation && !cast.IsMatch(n)).Where(n => cast.IsMatch(n)).ToList(); foundCastCount = foundCasts.Count; return(new CodeAction(ctx.TranslateString("Use 'as' and check for null"), script => { var varName = ctx.GetNameProposal(CreateMethodDeclarationAction.GuessNameFromType(rr.Type), ifElseStatement.StartLocation); var varDec = new VariableDeclarationStatement(new PrimitiveType("var"), varName, new AsExpression(obj.Clone(), castToType.Clone())); var binaryOperatorIdentifier = new IdentifierExpression(varName); var binaryOperatorExpression = new BinaryOperatorExpression(binaryOperatorIdentifier, BinaryOperatorType.Equality, new NullReferenceExpression()); var linkedNodes = new List <AstNode>(); linkedNodes.Add(varDec.Variables.First().NameToken); linkedNodes.Add(binaryOperatorIdentifier); if (IsEmbeddedStatement(ifElseStatement)) { var block = new BlockStatement(); block.Add(varDec); var newIf = (IfElseStatement)ifElseStatement.Clone(); newIf.Condition = binaryOperatorExpression; foreach (var node in newIf.DescendantNodesAndSelf(n => !cast.IsMatch(n)).Where(n => cast.IsMatch(n))) { var id = new IdentifierExpression(varName); linkedNodes.Add(id); node.ReplaceWith(id); } block.Add(newIf); script.Replace(ifElseStatement, block); } else { script.InsertBefore(ifElseStatement, varDec); script.Replace(ifElseStatement.Condition, binaryOperatorExpression); foreach (var c in foundCasts) { var id = new IdentifierExpression(varName); linkedNodes.Add(id); script.Replace(c, id); } } script.Link(linkedNodes); }, isExpression.IsToken)); }
public GatherVisitor(BaseRefactoringContext context, SyntaxTree unit, AccessToClosureIssue qualifierDirectiveEvidentIssueProvider) : base(context, qualifierDirectiveEvidentIssueProvider) { this.title = context.TranslateString(qualifierDirectiveEvidentIssueProvider.Title); }
public string GetErrorMessage(BaseRefactoringContext ctx, string name, out IList <string> suggestedNames) { suggestedNames = new List <string>(); string id = name; string errorMessage = null; bool missingRequiredPrefix = false; bool missingRequiredSuffix = false; string requiredPrefix = null; string allowedPrefix = null; string suffix = null; if (AllowedPrefixes != null && AllowedPrefixes.Length > 0) { allowedPrefix = AllowedPrefixes.FirstOrDefault(p => id.StartsWith(p, StringComparison.Ordinal)); if (allowedPrefix != null) { id = id.Substring(allowedPrefix.Length); } } if (RequiredPrefixes != null && RequiredPrefixes.Length > 0) { requiredPrefix = RequiredPrefixes.FirstOrDefault(p => id.StartsWith(p, StringComparison.Ordinal)); if (requiredPrefix == null) { errorMessage = string.Format(ctx.TranslateString("Name should have prefix '{0}'. (Rule '{1}')."), RequiredPrefixes [0], Name); missingRequiredPrefix = true; } else { id = id.Substring(requiredPrefix.Length); } } else if (ForbiddenPrefixes != null && ForbiddenPrefixes.Length > 0) { requiredPrefix = ForbiddenPrefixes.FirstOrDefault(p => id.StartsWith(p, StringComparison.Ordinal)); if (requiredPrefix != null) { errorMessage = string.Format(ctx.TranslateString("Name has forbidden prefix '{0}'. (Rule '{1}')"), requiredPrefix, Name); id = id.Substring(requiredPrefix.Length); } } if (RequiredSuffixes != null && RequiredSuffixes.Length > 0) { suffix = RequiredSuffixes.FirstOrDefault(s => id.EndsWith(s, StringComparison.Ordinal)); if (suffix == null) { errorMessage = string.Format(ctx.TranslateString("Name should have suffix '{0}'. (Rule '{1}')"), RequiredSuffixes [0], Name); missingRequiredSuffix = true; } else { id = id.Substring(0, id.Length - suffix.Length); } } else if (ForbiddenSuffixes != null && ForbiddenSuffixes.Length > 0) { suffix = ForbiddenSuffixes.FirstOrDefault(p => id.EndsWith(p, StringComparison.Ordinal)); if (suffix != null) { errorMessage = string.Format(ctx.TranslateString("Name has forbidden suffix '{0}'. (Rule '{1}')"), suffix, Name); id = id.Substring(0, id.Length - suffix.Length); } } switch (NamingStyle) { case NamingStyle.AllLower: if (id.Any(ch => char.IsLetter(ch) && char.IsUpper(ch))) { errorMessage = string.Format(ctx.TranslateString("'{0}' contains upper case letters. (Rule '{1}')"), name, Name); suggestedNames.Add(LowerCaseIdentifier(WordParser.BreakWords(id))); } else { suggestedNames.Add(id); } break; case NamingStyle.AllUpper: if (id.Any(ch => char.IsLetter(ch) && char.IsLower(ch))) { errorMessage = string.Format(ctx.TranslateString("'{0}' contains lower case letters. (Rule '{1}')"), name, Name); suggestedNames.Add(UpperCaseIdentifier(WordParser.BreakWords(id))); } else { suggestedNames.Add(id); } break; case NamingStyle.CamelCase: if (id.Length > 0 && !char.IsLower(id [0])) { errorMessage = string.Format(ctx.TranslateString("'{0}' should start with a lower case letter. (Rule '{1}')"), name, Name); } else if (!CheckUnderscore(id, UnderscoreHandling.Forbid)) { errorMessage = string.Format(ctx.TranslateString("'{0}' should not separate words with an underscore. (Rule '{1}')"), name, Name); } else { suggestedNames.Add(id); break; } suggestedNames.Add(CamelCaseIdentifier(id)); break; case NamingStyle.CamelCaseWithLowerLetterUnderscore: if (id.Length > 0 && !char.IsLower(id [0])) { errorMessage = string.Format(ctx.TranslateString("'{0}' should start with a lower case letter. (Rule '{1}')"), name, Name); } else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithLowerStartingLetter)) { errorMessage = string.Format(ctx.TranslateString("after '_' a lower letter should follow. (Rule '{0}')"), Name); } else { suggestedNames.Add(id); break; } suggestedNames.Add(CamelCaseWithLowerLetterUnderscore(id)); break; case NamingStyle.CamelCaseWithUpperLetterUnderscore: if (id.Length > 0 && !char.IsLower(id [0])) { errorMessage = string.Format(ctx.TranslateString("'{0}' should start with a lower case letter. (Rule '{1}')"), name, Name); } else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithUpperStartingLetter)) { errorMessage = string.Format(ctx.TranslateString("after '_' an upper letter should follow. (Rule '{0}')"), Name); } else { suggestedNames.Add(id); break; } suggestedNames.Add(CamelCaseWithUpperLetterUnderscore(id)); break; case NamingStyle.PascalCase: if (id.Length > 0 && !char.IsUpper(id [0])) { errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name); } else if (!CheckUnderscore(id, UnderscoreHandling.Forbid)) { errorMessage = string.Format(ctx.TranslateString("'{0}' should not separate words with an underscore. (Rule '{1}')"), name, Name); } else { suggestedNames.Add(id); break; } suggestedNames.Add(PascalCaseIdentifier(id)); break; case NamingStyle.PascalCaseWithLowerLetterUnderscore: if (id.Length > 0 && !char.IsUpper(id [0])) { errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name); } else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithLowerStartingLetter)) { errorMessage = string.Format(ctx.TranslateString("after '_' a lower letter should follow. (Rule '{0}')"), Name); } else { suggestedNames.Add(id); break; } suggestedNames.Add(PascalCaseWithLowerLetterUnderscore(id)); break; case NamingStyle.PascalCaseWithUpperLetterUnderscore: if (id.Length > 0 && !char.IsUpper(id [0])) { errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name); } else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithUpperStartingLetter)) { errorMessage = string.Format(ctx.TranslateString("after '_' an upper letter should follow. (Rule '{0}')"), Name); } else { suggestedNames.Add(id); break; } suggestedNames.Add(PascalCaseWithUpperLetterUnderscore(id)); break; case NamingStyle.FirstUpper: if (id.Length > 0 && !char.IsUpper(id [0])) { errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name); } else if (id.Take(1).Any(ch => char.IsLetter(ch) && char.IsUpper(ch))) { errorMessage = string.Format(ctx.TranslateString("'{0}' contains an upper case letter after the first. (Rule '{1}')"), name, Name); } else { suggestedNames.Add(id); break; } suggestedNames.Add(FirstUpperIdentifier(WordParser.BreakWords(id))); break; } if (requiredPrefix != null) { for (int i = 0; i < suggestedNames.Count; i++) { suggestedNames [i] = requiredPrefix + suggestedNames [i]; } } else if (allowedPrefix != null) { int count = suggestedNames.Count; for (int i = 0; i < count; i++) { suggestedNames.Add(suggestedNames [i]); suggestedNames [i] = allowedPrefix + suggestedNames [i]; } } else if (missingRequiredPrefix) { for (int i = 0; i < suggestedNames.Count; i++) { var n = suggestedNames [i]; bool first = true; foreach (var p in RequiredPrefixes) { if (first) { first = false; suggestedNames [i] = p + n; } else { suggestedNames.Add(p + n); } } } } if (suffix != null) { for (int i = 0; i < suggestedNames.Count; i++) { suggestedNames [i] = ApplySuffix(suggestedNames [i], suffix); } } else if (missingRequiredSuffix) { for (int i = 0; i < suggestedNames.Count; i++) { var n = suggestedNames [i]; bool first = true; foreach (var s in RequiredSuffixes) { if (first) { first = false; suggestedNames [i] = ApplySuffix(n, s); } else { suggestedNames.Add(ApplySuffix(n, s)); } } } } return(errorMessage // should never happen. ?? "no known errors."); }