public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var createExpression = context.GetNode <ObjectCreateExpression>();

            if (createExpression == null)
            {
                yield break;
            }

            var resolveResult = context.Resolve(createExpression) as CSharpInvocationResolveResult;

            if (resolveResult == null || !resolveResult.IsError || resolveResult.Member.DeclaringTypeDefinition == null || resolveResult.Member.DeclaringTypeDefinition.IsSealed || resolveResult.Member.DeclaringTypeDefinition.Region.IsEmpty)
            {
                yield break;
            }

            yield return(new CodeAction(context.TranslateString("Create constructor"), script => {
                var decl = new ConstructorDeclaration()
                {
                    Name = resolveResult.Member.DeclaringTypeDefinition.Name,
                    Modifiers = Modifiers.Public,
                    Body = new BlockStatement()
                    {
                        new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                    }
                };
                decl.Parameters.AddRange(CreateMethodDeclarationAction.GenerateParameters(context, createExpression.Arguments));

                script.InsertWithCursor(context.TranslateString("Create constructor"), decl, resolveResult.Member.DeclaringTypeDefinition);
            }));
        }
Exemple #2
0
        static TypeDeclaration CreateClassFromObjectCreation(RefactoringContext context, ObjectCreateExpression createExpression)
        {
            TypeDeclaration result;
            string          className = createExpression.Type.GetText();

            if (!createExpression.Arguments.Any())
            {
                result = new TypeDeclaration()
                {
                    Name = className
                };
            }
            else
            {
                var decl = new ConstructorDeclaration()
                {
                    Name      = className,
                    Modifiers = Modifiers.Public,
                    Body      = new BlockStatement()
                    {
                        new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                    }
                };
                result = new TypeDeclaration()
                {
                    Name    = className,
                    Members =
                    {
                        decl
                    }
                };
                decl.Parameters.AddRange(CreateMethodDeclarationAction.GenerateParameters(context, createExpression.Arguments));
            }
            var guessedType = CreateFieldAction.GuessType(context, createExpression);

            if (guessedType.Kind == TypeKind.Interface || guessedType.Kind == TypeKind.Class && guessedType.GetDefinition().IsAbstract)
            {
                result.BaseTypes.Add(context.CreateShortType(guessedType));
                AddImplementation(context, result, guessedType);
            }

            return(result);
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var pexpr = context.GetNode <PrimitiveExpression>();

            if (pexpr == null)
            {
                yield break;
            }
            var statement = context.GetNode <Statement>();

            if (statement == null)
            {
                yield break;
            }

            var resolveResult = context.Resolve(pexpr);

            yield return(new CodeAction(context.TranslateString("Create local constant"), script => {
                string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                if (service != null)
                {
                    name = service.CheckName(context, name, AffectedEntity.LocalConstant);
                }

                var initializer = new VariableInitializer(name, pexpr.Clone());
                var decl = new VariableDeclarationStatement()
                {
                    Type = context.CreateShortType(resolveResult.Type),
                    Modifiers = Modifiers.Const,
                    Variables = { initializer }
                };

                script.InsertBefore(statement, decl);
                var variableUsage = new IdentifierExpression(name);
                script.Replace(pexpr, variableUsage);
                script.Link(initializer.NameToken, variableUsage);
            }));

            yield return(new CodeAction(context.TranslateString("Create constant field"), script => {
                string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                if (service != null)
                {
                    name = service.CheckName(context, name, AffectedEntity.ConstantField);
                }

                var initializer = new VariableInitializer(name, pexpr.Clone());

                var decl = new FieldDeclaration()
                {
                    ReturnType = context.CreateShortType(resolveResult.Type),
                    Modifiers = Modifiers.Const,
                    Variables = { initializer }
                };

                var variableUsage = new IdentifierExpression(name);
                script.Replace(pexpr, variableUsage);
//				script.Link(initializer.NameToken, variableUsage);
                script.InsertWithCursor(context.TranslateString("Create constant"), decl, Script.InsertPosition.Before);
            }));
        }
Exemple #4
0
        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 = CSharpUtil.GetInnerMostExpression(outerIs) as IsExpression;
            var obj        = CSharpUtil.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));
        }
Exemple #5
0
        protected override CodeAction GetAction(RefactoringContext ctx, IfElseStatement ifElseStatement)
        {
            var isExpr = ctx.GetNode <IsExpression>();

            if (isExpr == null || !isExpr.IsToken.Contains(ctx.Location))
            {
                return(null);
            }

            int foundCasts;
            var action = ScanIfElse(ctx, ifElseStatement, out isExpr, out foundCasts);

            if (action != null)
            {
                return(action);
            }

            isExpr = ctx.GetNode <IsExpression>();
            var node = isExpr.Parent;

            while (node is ParenthesizedExpression)
            {
                node = node.Parent;
            }
            var uOp = node as UnaryOperatorExpression;

            if (uOp != null && uOp.Operator == UnaryOperatorType.Not)
            {
                var rr = ctx.Resolve(isExpr.Type);
                if (rr == null || rr.IsError || rr.Type.IsReferenceType == false)
                {
                    return(null);
                }

                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(isExpr.Expression.Clone(), isExpr.Type.Clone()));
                    var binaryOperatorIdentifier = new IdentifierExpression(varName);
                    var binaryOperatorExpression = new BinaryOperatorExpression(binaryOperatorIdentifier, BinaryOperatorType.Equality, new NullReferenceExpression());
                    if (IsEmbeddedStatement(ifElseStatement))
                    {
                        var block = new BlockStatement();
                        block.Add(varDec);
                        var newIf = (IfElseStatement)ifElseStatement.Clone();
                        newIf.Condition = binaryOperatorExpression;
                        block.Add(newIf);
                        script.Replace(ifElseStatement, block);
                    }
                    else
                    {
                        script.InsertBefore(ifElseStatement, varDec);
                        script.Replace(uOp, binaryOperatorExpression);
                    }
                }, isExpr.IsToken));
            }

            var obj        = isExpr.Expression;
            var castToType = isExpr.Type;

            var cast = new Choice {
                PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastTo(castToType.Clone())),
                PatternHelper.OptionalParentheses(PatternHelper.OptionalParentheses(obj.Clone()).CastAs(castToType.Clone()))
            };

            var rr2 = ctx.Resolve(castToType);

            if (rr2 == null || rr2.IsError || rr2.Type.IsReferenceType == false)
            {
                return(null);
            }
            var foundCasts2 = isExpr.GetParent <Statement>().DescendantNodesAndSelf(n => !cast.IsMatch(n)).Where(n => isExpr.StartLocation < n.StartLocation && cast.IsMatch(n)).ToList();

            return(new CodeAction(ctx.TranslateString("Use 'as' and check for null"), script => {
                var varName = ctx.GetNameProposal(CreateMethodDeclarationAction.GuessNameFromType(rr2.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.InEquality, 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 node2 in newIf.DescendantNodesAndSelf(n => !cast.IsMatch(n)).Where(n => cast.IsMatch(n)))
                    {
                        var id = new IdentifierExpression(varName);
                        linkedNodes.Add(id);
                        node2.ReplaceWith(id);
                    }
                    block.Add(newIf);
                    script.Replace(ifElseStatement, block);
                }
                else
                {
                    script.InsertBefore(ifElseStatement, varDec);
                    script.Replace(isExpr, binaryOperatorExpression);
                    foreach (var c in foundCasts2)
                    {
                        var id = new IdentifierExpression(varName);
                        linkedNodes.Add(id);
                        script.Replace(c, id);
                    }
                }
                script.Link(linkedNodes);
            }, isExpr.IsToken));
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            if (!context.IsSomethingSelected)
            {
                yield break;
            }
            var selected = new List <AstNode>(context.GetSelectedNodes());

            if (selected.Count != 1 || !(selected [0] is Expression))
            {
                yield break;
            }
            var expr    = selected [0] as Expression;
            var visitor = new SearchNodeVisitior(expr);

            var node = context.GetNode <BlockStatement>();

            if (node != null)
            {
                node.AcceptVisitor(visitor);
            }

            yield return(new CodeAction(context.TranslateString("Declare local variable"), script => {
                var resolveResult = context.Resolve(expr);
                var guessedType = resolveResult.Type;
                if (resolveResult is MethodGroupResolveResult)
                {
                    guessedType = GetDelegateType(context, ((MethodGroupResolveResult)resolveResult).Methods.First(), expr);
                }
                var name = CreateMethodDeclarationAction.CreateBaseName(expr, guessedType);
                var type = context.UseExplicitTypes ? context.CreateShortType(guessedType) : new SimpleType("var");
                var varDecl = new VariableDeclarationStatement(type, name, expr.Clone());
                var replaceNode = visitor.Matches.First() as Expression;
                if (replaceNode.Parent is ExpressionStatement)
                {
                    script.Replace(replaceNode.Parent, varDecl);
                    script.Select(varDecl.Variables.First().NameToken);
                }
                else
                {
                    var containing = replaceNode.Parent;
                    while (!(containing.Parent is BlockStatement))
                    {
                        containing = containing.Parent;
                    }

                    script.InsertBefore(containing, varDecl);
                    var identifierExpression = new IdentifierExpression(name);
                    script.Replace(replaceNode, identifierExpression);
                    script.Link(varDecl.Variables.First().NameToken, identifierExpression);
                }
            }, expr));

            if (visitor.Matches.Count > 1)
            {
                yield return(new CodeAction(string.Format(context.TranslateString("Declare local variable (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
                    var resolveResult = context.Resolve(expr);
                    var guessedType = resolveResult.Type;
                    if (resolveResult is MethodGroupResolveResult)
                    {
                        guessedType = GetDelegateType(context, ((MethodGroupResolveResult)resolveResult).Methods.First(), expr);
                    }
                    var linkedNodes = new List <AstNode>();
                    var name = CreateMethodDeclarationAction.CreateBaseName(expr, guessedType);
                    var type = context.UseExplicitTypes ? context.CreateShortType(guessedType) : new SimpleType("var");
                    var varDecl = new VariableDeclarationStatement(type, name, expr.Clone());
                    linkedNodes.Add(varDecl.Variables.First().NameToken);
                    var first = visitor.Matches [0];
                    if (first.Parent is ExpressionStatement)
                    {
                        script.Replace(first.Parent, varDecl);
                    }
                    else
                    {
                        var containing = first.Parent;
                        while (!(containing.Parent is BlockStatement))
                        {
                            containing = containing.Parent;
                        }

                        script.InsertBefore(containing, varDecl);
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(first, identifierExpression);
                    }
                    for (int i = 1; i < visitor.Matches.Count; i++)
                    {
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(visitor.Matches [i], identifierExpression);
                    }
                    script.Link(linkedNodes.ToArray());
                }, expr));
            }
        }
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var pexpr = context.GetNode <PrimitiveExpression>();

            if (pexpr == null)
            {
                yield break;
            }

            var visitor = new DeclareLocalVariableAction.SearchNodeVisitior(pexpr);

            if (pexpr.Parent is VariableInitializer)
            {
                var varDec = pexpr.Parent.Parent as VariableDeclarationStatement;
                if (varDec != null && (varDec.Modifiers & Modifiers.Const) != 0)
                {
                    yield break;
                }
                var fieldDecl = pexpr.Parent.Parent as FieldDeclaration;
                if (fieldDecl != null && (fieldDecl.Modifiers & Modifiers.Const) != 0)
                {
                    yield break;
                }
            }

            var node = context.GetNode <BlockStatement>();

            if (node != null)
            {
                node.AcceptVisitor(visitor);
            }

            var resolveResult = context.Resolve(pexpr);
            var statement     = context.GetNode <Statement>();

            if (statement != null)
            {
                yield return(new CodeAction(context.TranslateString("Create local constant"), script => {
                    string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                    var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                    if (service != null)
                    {
                        name = service.CheckName(context, name, AffectedEntity.LocalConstant);
                    }

                    var initializer = new VariableInitializer(name, pexpr.Clone());
                    var decl = new VariableDeclarationStatement()
                    {
                        Type = context.CreateShortType(resolveResult.Type),
                        Modifiers = Modifiers.Const,
                        Variables = { initializer }
                    };

                    script.InsertBefore(statement, decl);
                    var variableUsage = new IdentifierExpression(name);
                    script.Replace(pexpr, variableUsage);
                    script.Link(initializer.NameToken, variableUsage);
                }, pexpr));
            }

            yield return(new CodeAction(context.TranslateString("Create constant field"), script => {
                string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                if (service != null)
                {
                    name = service.CheckName(context, name, AffectedEntity.ConstantField);
                }

                var initializer = new VariableInitializer(name, pexpr.Clone());

                var decl = new FieldDeclaration()
                {
                    ReturnType = context.CreateShortType(resolveResult.Type),
                    Modifiers = Modifiers.Const,
                    Variables = { initializer }
                };

                var variableUsage = new IdentifierExpression(name);
                script.Replace(pexpr, variableUsage);
                //				script.Link(initializer.NameToken, variableUsage);
                script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
            }, pexpr));

            if (visitor.Matches.Count > 1)
            {
                yield return(new CodeAction(string.Format(context.TranslateString("Create local constant (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
                    string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                    var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                    if (service != null)
                    {
                        name = service.CheckName(context, name, AffectedEntity.LocalConstant);
                    }

                    var initializer = new VariableInitializer(name, pexpr.Clone());
                    var decl = new VariableDeclarationStatement()
                    {
                        Type = context.CreateShortType(resolveResult.Type),
                        Modifiers = Modifiers.Const,
                        Variables = { initializer }
                    };

                    script.InsertBefore(statement, decl);

                    var linkedNodes = new List <AstNode>();
                    linkedNodes.Add(initializer.NameToken);
                    for (int i = 0; i < visitor.Matches.Count; i++)
                    {
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(visitor.Matches [i], identifierExpression);
                    }
                    script.Link(linkedNodes.ToArray());
                }, pexpr));

                yield return(new CodeAction(string.Format(context.TranslateString("Create constant field (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
                    string name = CreateMethodDeclarationAction.CreateBaseName(pexpr, resolveResult.Type);
                    var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
                    if (service != null)
                    {
                        name = service.CheckName(context, name, AffectedEntity.ConstantField);
                    }

                    var initializer = new VariableInitializer(name, pexpr.Clone());

                    var decl = new FieldDeclaration()
                    {
                        ReturnType = context.CreateShortType(resolveResult.Type),
                        Modifiers = Modifiers.Const,
                        Variables = { initializer }
                    };

                    var linkedNodes = new List <AstNode>();
                    linkedNodes.Add(initializer.NameToken);
                    for (int i = 0; i < visitor.Matches.Count; i++)
                    {
                        var identifierExpression = new IdentifierExpression(name);
                        linkedNodes.Add(identifierExpression);
                        script.Replace(visitor.Matches [i], identifierExpression);
                    }
                    script.InsertWithCursor(context.TranslateString("Create constant"), Script.InsertPosition.Before, decl);
                }, pexpr));
            }
        }
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var indexer = context.GetNode <IndexerExpression>();

            if (indexer == null)
            {
                yield break;
            }
            if (!(context.Resolve(indexer).IsError))
            {
                yield break;
            }

            var state = context.GetResolverStateBefore(indexer);

            if (state.CurrentTypeDefinition == null)
            {
                yield break;
            }
            var guessedType = TypeGuessing.GuessAstType(context, indexer);

            bool          createInOtherType   = false;
            ResolveResult targetResolveResult = null;

            targetResolveResult = context.Resolve(indexer.Target);
            createInOtherType   = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());

            bool isStatic;

            if (createInOtherType)
            {
                if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
                {
                    yield break;
                }
                isStatic = targetResolveResult is TypeResolveResult;
                if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
                {
                    yield break;
                }
            }
            else
            {
                isStatic = indexer.Target is IdentifierExpression && state.CurrentMember.IsStatic;
            }

            yield return(new CodeAction(context.TranslateString("Create indexer"), script => {
                var decl = new IndexerDeclaration()
                {
                    ReturnType = guessedType,
                    Getter = new Accessor()
                    {
                        Body = new BlockStatement()
                        {
                            new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                        }
                    },
                    Setter = new Accessor()
                    {
                        Body = new BlockStatement()
                        {
                            new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                        }
                    },
                };
                decl.Parameters.AddRange(CreateMethodDeclarationAction.GenerateParameters(context, indexer.Arguments));
                if (isStatic)
                {
                    decl.Modifiers |= Modifiers.Static;
                }

                if (createInOtherType)
                {
                    if (targetResolveResult.Type.Kind == TypeKind.Interface)
                    {
                        decl.Getter.Body = null;
                        decl.Setter.Body = null;
                        decl.Modifiers = Modifiers.None;
                    }
                    else
                    {
                        decl.Modifiers |= Modifiers.Public;
                    }

                    script.InsertWithCursor(context.TranslateString("Create indexer"), targetResolveResult.Type.GetDefinition(), (s, c) => decl);
                    return;
                }

                script.InsertWithCursor(context.TranslateString("Create indexer"), Script.InsertPosition.Before, decl);
            }, indexer)
            {
                Severity = ICSharpCode.NRefactory.Refactoring.Severity.Error
            });
        }