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));
        }
Exemple #2
0
            CodeAction GetAction(BaseRefactoringContext context, Expression targetExpression,
                                 IMember member)
            {
                var    builder     = context.CreateTypeSytemAstBuilder(targetExpression);
                var    newType     = builder.ConvertType(member.DeclaringType);
                string description = string.Format("{0} '{1}'", context.TranslateString("Use base class"), newType.GetText());

                return(new CodeAction(description, script => {
                    script.Replace(targetExpression, newType);
                }, targetExpression));
            }
            public override void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
            {
                var parameters = objectCreateExpression.Arguments;

                if (parameters.Count != 2)
                {
                    return;
                }
                var firstParam  = parameters.FirstOrNullObject() as PrimitiveExpression;
                var secondParam = parameters.LastOrNullObject() as PrimitiveExpression;

                if (firstParam == null || !(firstParam.Value is string) ||
                    secondParam == null || !(secondParam.Value is string))
                {
                    return;
                }
                var type = context.Resolve(objectCreateExpression.Type) as TypeResolveResult;

                if (type == null)
                {
                    return;
                }
                var leftLength  = (firstParam.Value as string).Length;
                var rightLength = (secondParam.Value as string).Length;

                Func <int, int, bool> func;

                if (!rules.TryGetValue(type.Type.FullName, out func))
                {
                    return;
                }
                if (!func(leftLength, rightLength))
                {
                    AddIssue(objectCreateExpression,
                             context.TranslateString("The parameters are in the wrong order"),
                             GetAction(objectCreateExpression, firstParam, secondParam));
                }
            }
Exemple #4
0
            public override void VisitInvocationExpression(InvocationExpression invocationExpression)
            {
                base.VisitInvocationExpression(invocationExpression);
                if (!IsCallDependentOnCurrentInstance(invocationExpression))
                {
                    // Call within current class scope without 'this' or 'base'
                    return;
                }
                var targetMethod = context.Resolve(invocationExpression) as InvocationResolveResult;

                if (targetMethod == null)
                {
                    return;
                }
                if (targetMethod.IsVirtualCall)
                {
                    AddIssue(invocationExpression,
                             context.TranslateString("Constructors should not call virtual members"));
                }
            }
			CodeAction GetAction(BaseRefactoringContext context, Expression targetExpression,
			                                   IMember member)
			{
				var builder = context.CreateTypeSytemAstBuilder(targetExpression);
				var newType = builder.ConvertType(member.DeclaringType);
				string description = string.Format("{0} '{1}'", context.TranslateString("Use base class"), newType.GetText());
				return new CodeAction(description, script => {
					script.Replace(targetExpression, newType);
				});
			}
		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);
		}
            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.Where(node => moveTargetBlacklist.Contains(node.GetType())).FirstOrDefault();

                if (firstBlackListedNode != null)
                {
                    path       = GetPath(rootNode, firstBlackListedNode.Parent);
                    anchorNode = firstBlackListedNode;
                }

                anchorNode = GetInsertionPoint(anchorNode);

                if (anchorNode != null && anchorNode != rootNode && anchorNode.Parent != rootNode)
                {
                    AddIssue(variableDeclarationStatement, context.TranslateString("Variable could be moved to a nested scope"),
                             GetActions(variableDeclarationStatement, (Statement)anchorNode));
                }
            }
//		static bool NoUnderscoreWithoutNumber(string id)
//		{
//			int idx = id.IndexOf('_');
//			while (idx >= 0 && idx < id.Length) {
//				if ((idx + 2 >= id.Length || !char.IsDigit(id [idx + 1])) && (idx == 0 || !char.IsDigit(id [idx - 1]))) {
//					return false;
//				}
//				idx = id.IndexOf('_', idx + 1);
//			}
//			return true;
//		}


        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}'."), RequiredPrefixes [0]);
                    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}'."), requiredPrefix);
                    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}'."), RequiredSuffixes [0]);
                    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}'."), suffix);
                    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."), 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."), name);
                    suggestedNames.Add(UpperCaseIdentifier(WordParser.BreakWords(id)));
                }
                else
                {
                    suggestedNames.Add(id);
                }
                break;

            case NamingStyle.CamelCase:
                if (id.Length > 0 && char.IsUpper(id [0]))
                {
                    errorMessage = string.Format(ctx.TranslateString("'{0}' should start with a lower case letter."), name);
                }
                else if (!NoUnderscore(id))
                {
                    errorMessage = string.Format(ctx.TranslateString("'{0}' should not separate words with an underscore."), name);
                }
                else
                {
                    suggestedNames.Add(id);
                    break;
                }
                suggestedNames.Add(CamelCaseIdentifier(WordParser.BreakWords(id)));
                break;

            case NamingStyle.PascalCase:
                if (id.Length > 0 && char.IsLower(id [0]))
                {
                    errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter."), name);
                }
                else if (!NoUnderscore(id))
                {
                    errorMessage = string.Format(ctx.TranslateString("'{0}' should not separate words with an underscore."), name);
                }
                else
                {
                    suggestedNames.Add(id);
                    break;
                }
                suggestedNames.Add(PascalCaseIdentifier(WordParser.BreakWords(id)));
                break;

            case NamingStyle.FirstUpper:
                if (id.Length > 0 && char.IsLower(id [0]))
                {
                    errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter."), 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."), 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] = 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] = n + s;
                        }
                        else
                        {
                            suggestedNames.Add(n + s);
                        }
                    }
                }
            }

            return(errorMessage
                   // should never happen.
                   ?? "no known errors.");
        }
 public GatherVisitor(BaseRefactoringContext context, SyntaxTree unit,
                      AccessToClosureIssue issueProvider)
     : base(context, issueProvider)
 {
     this.title = context.TranslateString(issueProvider.Title);
 }