Ejemplo n.º 1
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var variableDeclaration = context.GetNode <VariableDeclarationStatement>();

            if (variableDeclaration == null)
            {
                yield break;
            }
            var entryNode = FindCurrentScopeEntryNode(variableDeclaration);

            if (entryNode == null)
            {
                yield break;
            }
            var selectedInitializer = context.GetNode <VariableInitializer>();

            if (selectedInitializer != null)
            {
                if (HasDependency(context, entryNode, selectedInitializer))
                {
                    yield return(MoveDeclarationAction(context, entryNode, variableDeclaration, selectedInitializer));
                }
                else
                {
                    yield return(MoveInitializerAction(context, entryNode, variableDeclaration, selectedInitializer));
                }
            }
            else
            {
                yield return(new CodeAction(context.TranslateString("Move declaration to outer scope"), script => {
                    script.Remove(variableDeclaration);
                    script.InsertBefore(entryNode, variableDeclaration.Clone());
                }));
            }
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var invocation = context.GetNode <InvocationExpression>();

            if (invocation == null)
            {
                yield break;
            }
            var memberReference = invocation.Target as MemberReferenceExpression;

            if (memberReference == null)
            {
                yield break;
            }
            var invocationRR = context.Resolve(invocation) as CSharpInvocationResolveResult;

            if (invocationRR == null)
            {
                yield break;
            }
            if (invocationRR.IsExtensionMethodInvocation)
            {
                yield return(new CodeAction(context.TranslateString("Convert to call to static method"), script => {
                    script.Replace(invocation, ToStaticMethodInvocation(invocation, memberReference, invocationRR));
                }, invocation));
            }
        }
Ejemplo n.º 3
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var usingNode = FindUsingNodeAtCursor(context);

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

            yield return(new CodeAction(context.TranslateString("Sort usings"), script =>
            {
                var blocks = EnumerateUsingBlocks(context.RootNode);

                foreach (var block in blocks)
                {
                    var originalNodes = block.ToArray();
                    var sortedNodes = UsingHelper.SortUsingBlock(originalNodes, context).ToArray();

                    for (var i = 0; i < originalNodes.Length; ++i)
                    {
                        script.Replace(originalNodes[i], sortedNodes[i].Clone());
                    }
                }
            }, usingNode));
        }
        IEnumerable <CodeAction> GetAction <T, S> (RefactoringContext context, T decl,
                                                   Func <T, AstNodeCollection <S> > getInitializers)
            where T : AstNode
            where S : AstNode
        {
            var initializers = getInitializers(decl);

            if (initializers.Count < 2)
            {
                yield break;
            }

            yield return(new CodeAction(context.TranslateString("Split declaration list"),
                                        script =>
            {
                var emptyDecl = (T)decl.Clone();
                getInitializers(emptyDecl).Clear();

                var declList = initializers.Select(v =>
                {
                    var singleDecl = (T)emptyDecl.Clone();
                    getInitializers(singleDecl).Add((S)v.Clone());
                    return singleDecl;
                });

                foreach (var singleDecl in declList)
                {
                    script.InsertBefore(decl, singleDecl);
                }
                script.Remove(decl);
            }, decl));
        }
Ejemplo n.º 5
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            if (context.IsSomethingSelected)
            {
                yield break;
            }
            var node = context.GetNode <VariableDeclarationStatement>();

            if (node == null || node.Variables.Count != 1)
            {
                yield break;
            }
            var initializer = node.Variables.First();

            if (!initializer.NameToken.Contains(context.Location) || initializer.Initializer.IsNull)
            {
                yield break;
            }
            var resolveResult = context.Resolve(initializer) as LocalResolveResult;

            if (resolveResult == null || resolveResult.IsError)
            {
                yield break;
            }
            var unit = context.RootNode as SyntaxTree;

            if (unit == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Inline local variable"), script => {
                refFinder.FindLocalReferences(resolveResult.Variable, context.UnresolvedFile, unit, context.Compilation, (n, r) => script.Replace(n, AddParensIfRequired(n, initializer.Initializer.Clone())), default(CancellationToken));
                script.Remove(node);
            }, initializer));
        }
Ejemplo n.º 6
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var property = context.GetNode <PropertyDeclaration>();

            if (property == null || !property.NameToken.Contains(context.Location))
            {
                yield break;
            }

            var field = GetBackingField(context, property);

            if (field == null)
            {
                yield break;
            }
            // create new auto property
            var newProperty = (PropertyDeclaration)property.Clone();

            newProperty.Getter.Body = BlockStatement.Null;
            newProperty.Setter.Body = BlockStatement.Null;

            yield return(new CodeAction(context.TranslateString("Convert to auto property"), script => {
                script.Rename((IEntity)field, newProperty.Name);
                script.Remove(context.RootNode.GetNodeAt <FieldDeclaration> (field.Region.Begin));
                script.Replace(property, newProperty);
            }, property.NameToken));
        }
        protected override CodeAction GetAction(RefactoringContext context, ParameterDeclaration parameter)
        {
            BlockStatement bodyStatement;

            if (parameter.Parent is LambdaExpression)
            {
                bodyStatement = parameter.Parent.GetChildByRole(LambdaExpression.BodyRole) as BlockStatement;
            }
            else
            {
                bodyStatement = parameter.Parent.GetChildByRole(Roles.Body);
            }
            if (bodyStatement == null || bodyStatement.IsNull)
            {
                return(null);
            }
            var type = context.ResolveType(parameter.Type);

            if (type.IsReferenceType == false || HasNullCheck(parameter))
            {
                return(null);
            }

            return(new CodeAction(context.TranslateString("Add null check for parameter"), script => {
                var statement = new IfElseStatement()
                {
                    Condition = new BinaryOperatorExpression(new IdentifierExpression(parameter.Name), BinaryOperatorType.Equality, new NullReferenceExpression()),
                    TrueStatement = new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "ArgumentNullException"), new PrimitiveExpression(parameter.Name)))
                };
                script.AddTo(bodyStatement, statement);
            }, parameter.NameToken));
        }
Ejemplo n.º 8
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var catchClause = context.GetNode <CatchClause>();

            if (catchClause == null)
            {
                yield break;
            }
            if (!catchClause.Type.IsNull)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Add type specifier"), script => {
                var newIdentifier = Identifier.Create("e");
                var newType = context.CreateShortType("System", "Exception");
                script.Replace(catchClause, new CatchClause()
                {
                    Type = newType,
                    VariableNameToken = newIdentifier,
                    Body = catchClause.Body.Clone() as BlockStatement
                });
                script.Link(newType);
                script.Link(newIdentifier);
            }));
        }
Ejemplo n.º 9
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var service = (CodeGenerationService)context.GetService(typeof(CodeGenerationService));

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

            var type = context.GetNode <AstType>();

            if (type == null || type.Role != Roles.BaseType)
            {
                yield break;
            }

            var state = context.GetResolverStateBefore(type);

            if (state.CurrentTypeDefinition == null)
            {
                yield break;
            }

            var resolveResult = context.Resolve(type);

            if (resolveResult.Type.Kind != TypeKind.Interface)
            {
                yield break;
            }

            bool interfaceMissing;
            var  toImplement = CollectMembersToImplement(state.CurrentTypeDefinition, resolveResult.Type, false, out interfaceMissing);

            if (toImplement.Count == 0)
            {
                yield break;
            }

            yield return(new CodeAction(context.TranslateString("Implement interface"), script =>
                                        script.InsertWithCursor(
                                            context.TranslateString("Implement Interface"),
                                            state.CurrentTypeDefinition,
                                            (s, c) => GenerateImplementation(c, toImplement, interfaceMissing).ToList()
                                            )
                                        , type));
        }
Ejemplo n.º 10
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var property = context.GetNode <PropertyDeclaration>();
            var field    = RemoveBackingStoreAction.GetBackingField(context);

            if (field == null)
            {
                yield break;
            }
            var resolvedType = ReflectionHelper.ParseReflectionName("System.EventHandler").Resolve(context.Compilation);

            if (resolvedType == null)
            {
                yield break;
            }
            var type = (TypeDeclaration)property.Parent;

            yield return(new CodeAction(context.TranslateString("Create changed event"), script => {
                var eventDeclaration = CreateChangedEventDeclaration(context, property);
                var methodDeclaration = CreateEventInvocatorAction.CreateEventInvocator(context, type, eventDeclaration, eventDeclaration.Variables.First(), resolvedType.GetDelegateInvokeMethod(), false);
                var stmt = new ExpressionStatement(new InvocationExpression(
                                                       new IdentifierExpression(methodDeclaration.Name),
                                                       new MemberReferenceExpression(new TypeReferenceExpression(context.CreateShortType("System", "EventArgs")), "Empty")
                                                       ));
                var task = script.InsertWithCursor(
                    context.TranslateString("Create event invocator"),
                    Script.InsertPosition.After,
                    new AstNode[] { eventDeclaration, methodDeclaration }
                    );

                Action <Task> insertInvocation = delegate {
                    script.InsertBefore(property.Setter.Body.RBraceToken, stmt);
                    script.FormatText(stmt);
                };

                if (task.IsCompleted)
                {
                    insertInvocation(null);
                }
                else
                {
                    task.ContinueWith(insertInvocation, TaskScheduler.FromCurrentSynchronizationContext());
                }
            }, property.NameToken));
        }
Ejemplo n.º 11
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var type = context.GetNode <AstType>();

            if (type == null || type.Role != Roles.BaseType)
            {
                yield break;
            }
            var state = context.GetResolverStateBefore(type);

            if (state.CurrentTypeDefinition == null)
            {
                yield break;
            }

            var resolveResult = context.Resolve(type);

            if (resolveResult.Type.Kind != TypeKind.Class || resolveResult.Type.GetDefinition() == null || !resolveResult.Type.GetDefinition().IsAbstract)
            {
                yield break;
            }

            var toImplement = CollectMembersToImplement(state.CurrentTypeDefinition, resolveResult.Type);

            if (toImplement.Count == 0)
            {
                yield break;
            }

            yield return(new CodeAction(context.TranslateString("Implement abstract members"), script =>
            {
                script.InsertWithCursor(
                    context.TranslateString("Implement abstract members"),
                    state.CurrentTypeDefinition,
                    ImplementInterfaceAction.GenerateImplementation(context, toImplement.Select(m => Tuple.Create(m, false))).Select(entity => {
                    var decl = entity as EntityDeclaration;
                    if (decl != null)
                    {
                        decl.Modifiers |= Modifiers.Override;
                    }
                    return entity;
                })
                    );
            }));
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var initializer = context.GetNode <VariableInitializer>();

            if (initializer == null || !initializer.NameToken.Contains(context.Location.Line, context.Location.Column))
            {
                yield break;
            }
            var type = initializer.Parent.Parent as TypeDeclaration;

            if (type == null)
            {
                yield break;
            }
            foreach (var member in type.Members)
            {
                if (member is PropertyDeclaration && ContainsGetter((PropertyDeclaration)member, initializer))
                {
                    yield break;
                }
            }
            var field = initializer.Parent as FieldDeclaration;

            if (field == null || field.HasModifier(Modifiers.Readonly) || field.HasModifier(Modifiers.Const))
            {
                yield break;
            }
            var resolveResult = context.Resolve(initializer) as MemberResolveResult;

            if (resolveResult == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Create property"), script =>
            {
                var fieldName = context.GetNameProposal(initializer.Name, true);
                if (initializer.Name == context.GetNameProposal(initializer.Name, false))
                {
                    script.Rename(resolveResult.Member, fieldName);
                }
                script.InsertWithCursor(
                    context.TranslateString("Create property"),
                    Script.InsertPosition.After, GeneratePropertyDeclaration(context, field, fieldName));
            }));
        }
Ejemplo n.º 13
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            Expression node = context.GetNode <IdentifierExpression>();

            if (node == null)
            {
                var mr = context.GetNode <MemberReferenceExpression>();
                if (mr == null || !mr.MemberNameToken.IsInside(context.Location))
                {
                    yield break;
                }
                node = mr;
            }
            if (node == null)
            {
                yield break;
            }
            var rr = context.Resolve(node) as MethodGroupResolveResult;

            if (rr == null || rr.IsError)
            {
                yield break;
            }
            var type = TypeGuessing.GetValidTypes(context.Resolver, node).FirstOrDefault(t => t.Kind == TypeKind.Delegate);

            if (type == null)
            {
                yield break;
            }
            var invocationMethod = type.GetDelegateInvokeMethod();

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

            yield return(new CodeAction(
                             context.TranslateString("Convert to anonymous method"),
                             script => {
                var expr = new InvocationExpression(node.Clone(), invocationMethod.Parameters.Select(p => new IdentifierExpression(context.GetNameProposal(p.Name))));
                var stmt = invocationMethod.ReturnType.IsKnownType(KnownTypeCode.Void) ? (Statement)expr : new ReturnStatement(expr);
                var anonymousMethod = new AnonymousMethodExpression {
                    Body = new BlockStatement {
                        stmt
                    }
                };
                foreach (var p in invocationMethod.Parameters)
                {
                    var decl = new ParameterDeclaration(context.CreateShortType(p.Type), context.GetNameProposal(p.Name));
                    anonymousMethod.Parameters.Add(decl);
                }

                script.Replace(node, anonymousMethod);
            },
                             node
                             ));
        }
        protected override CodeAction GetAction(RefactoringContext context, InvocationExpression node)
        {
            var mRef = node.Target as MemberReferenceExpression;

            if (mRef == null)
            {
                return(null);
            }
            var rr = context.Resolve(node) as CSharpInvocationResolveResult;

            if (rr == null || rr.IsError)
            {
                return(null);
            }
            if (rr.Member.Name != "HasFlag" || rr.Member.DeclaringType.GetDefinition().KnownTypeCode != ICSharpCode.NRefactory.TypeSystem.KnownTypeCode.Enum)
            {
                return(null);
            }
            var arg = node.Arguments.First().Clone();

            if (!arg.DescendantsAndSelf.All(x => !(x is BinaryOperatorExpression) || ((BinaryOperatorExpression)x).Operator == BinaryOperatorType.BitwiseOr))
            {
                return(null);
            }
            arg = ConvertBitwiseFlagComparisonToHasFlagsAction.MakeFlatExpression(arg, BinaryOperatorType.BitwiseAnd);
            if (arg is BinaryOperatorExpression)
            {
                arg = new ParenthesizedExpression(arg);
            }
            return(new CodeAction(
                       context.TranslateString("Replace with bitwise flag comparison"),
                       script => {
                var uOp = node.Parent as UnaryOperatorExpression;
                if (uOp != null && uOp.Operator == UnaryOperatorType.Not)
                {
                    script.Replace(uOp,
                                   new BinaryOperatorExpression(
                                       new ParenthesizedExpression(new BinaryOperatorExpression(mRef.Target.Clone(), BinaryOperatorType.BitwiseAnd, arg)),
                                       BinaryOperatorType.Equality,
                                       new PrimitiveExpression(0)
                                       )
                                   );
                }
                else
                {
                    script.Replace(node,
                                   new BinaryOperatorExpression(
                                       new ParenthesizedExpression(new BinaryOperatorExpression(mRef.Target.Clone(), BinaryOperatorType.BitwiseAnd, arg)),
                                       BinaryOperatorType.InEquality,
                                       new PrimitiveExpression(0)
                                       )
                                   );
                }
            },
                       node
                       ));
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var foreachStatement = GetForeachStatement(context);

            if (foreachStatement == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Convert 'foreach' loop to 'for'"), script =>
            {
                var result = context.Resolve(foreachStatement.InExpression);
                var countProperty = GetCountProperty(result.Type);

                // TODO: use another variable name if 'i' is already in use
                var initializer = new VariableDeclarationStatement(new PrimitiveType("int"), "i", new PrimitiveExpression(0));
                var id1 = new IdentifierExpression("i");
                var id2 = id1.Clone();
                var id3 = id1.Clone();

                var variableDeclarationStatement = new VariableDeclarationStatement(
                    foreachStatement.VariableType.Clone(),
                    foreachStatement.VariableName,
                    new IndexerExpression(foreachStatement.InExpression.Clone(), id3)
                    );
                var forStatement = new ForStatement()
                {
                    Initializers = { initializer },
                    Condition = new BinaryOperatorExpression(id1, BinaryOperatorType.LessThan, new MemberReferenceExpression(foreachStatement.InExpression.Clone(), countProperty)),
                    Iterators = { new ExpressionStatement(new UnaryOperatorExpression(UnaryOperatorType.PostIncrement, id2)) },
                    EmbeddedStatement = new BlockStatement
                    {
                        variableDeclarationStatement
                    }
                };

                if (foreachStatement.EmbeddedStatement is BlockStatement)
                {
                    variableDeclarationStatement.Remove();
                    var oldBlock = (BlockStatement)foreachStatement.EmbeddedStatement.Clone();
                    if (oldBlock.Statements.Any())
                    {
                        oldBlock.Statements.InsertBefore(oldBlock.Statements.First(), variableDeclarationStatement);
                    }
                    else
                    {
                        oldBlock.Statements.Add(variableDeclarationStatement);
                    }
                    forStatement.EmbeddedStatement = oldBlock;
                }
                else
                {
                    forStatement.EmbeddedStatement.AddChild(foreachStatement.EmbeddedStatement.Clone(), BlockStatement.StatementRole);
                }
                script.Replace(foreachStatement, forStatement);
                script.Link(initializer.Variables.First().NameToken, id1, id2, id3);
            }));
        }
        protected override CodeAction GetAction(RefactoringContext context, BinaryOperatorExpression node)
        {
            if (!node.OperatorToken.IsInside(context.Location))
            {
                return(null);
            }
            if (node.Operator == BinaryOperatorType.Add ||
                node.Operator == BinaryOperatorType.BitwiseAnd ||
                node.Operator == BinaryOperatorType.BitwiseOr ||
                node.Operator == BinaryOperatorType.Divide ||
                node.Operator == BinaryOperatorType.ExclusiveOr ||
                node.Operator == BinaryOperatorType.Modulus ||
                node.Operator == BinaryOperatorType.Multiply ||
                node.Operator == BinaryOperatorType.NullCoalescing ||
                node.Operator == BinaryOperatorType.ShiftLeft ||
                node.Operator == BinaryOperatorType.ShiftRight ||
                node.Operator == BinaryOperatorType.Subtract)
            {
                return(null);
            }
            var negativeExpression = CSharpUtil.InvertCondition(node);

            if (node.Parent is ParenthesizedExpression && node.Parent.Parent is UnaryOperatorExpression)
            {
                var unaryOperatorExpression = node.Parent.Parent as UnaryOperatorExpression;
                if (unaryOperatorExpression.Operator == UnaryOperatorType.Not)
                {
                    return(new CodeAction(
                               string.Format(context.TranslateString("Invert '{0}'"), unaryOperatorExpression),
                               script => {
                        script.Replace(unaryOperatorExpression, negativeExpression);
                    }, node.OperatorToken
                               ));
                }
            }
            var newExpression = new UnaryOperatorExpression(UnaryOperatorType.Not, new ParenthesizedExpression(negativeExpression));

            return(new CodeAction(
                       string.Format(context.TranslateString("Invert '{0}'"), node),
                       script => {
                script.Replace(node, newExpression);
            }, node.OperatorToken
                       ));
        }
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var property = context.GetNode <PropertyDeclaration>();

            if (property == null || !property.NameToken.Contains(context.Location))
            {
                yield break;
            }

            if (!(!property.Getter.IsNull && !property.Setter.IsNull &&             // automatic properties always need getter & setter
                  property.Getter.Body.IsNull &&
                  property.Setter.Body.IsNull))
            {
                yield break;
            }

            yield return(new CodeAction(context.TranslateString("Create backing store"), script => {
                string backingStoreName = context.GetNameProposal(property.Name);

                // create field
                var backingStore = new FieldDeclaration();
                if (property.Modifiers.HasFlag(Modifiers.Static))
                {
                    backingStore.Modifiers |= Modifiers.Static;
                }
                backingStore.ReturnType = property.ReturnType.Clone();

                var initializer = new VariableInitializer(backingStoreName);
                backingStore.Variables.Add(initializer);

                // create new property & implement the get/set bodies
                var newProperty = (PropertyDeclaration)property.Clone();
                Expression id1;
                if (backingStoreName == "value")
                {
                    id1 = new ThisReferenceExpression().Member("value");
                }
                else
                {
                    id1 = new IdentifierExpression(backingStoreName);
                }
                Expression id2 = id1.Clone();
                newProperty.Getter.Body = new BlockStatement()
                {
                    new ReturnStatement(id1)
                };
                newProperty.Setter.Body = new BlockStatement()
                {
                    new AssignmentExpression(id2, AssignmentOperatorType.Assign, new IdentifierExpression("value"))
                };

                script.Replace(property, newProperty);
                script.InsertBefore(property, backingStore);
                script.Link(initializer, id1, id2);
            }, property.NameToken));
        }
Ejemplo n.º 18
0
 CodeAction MakeAction(RefactoringContext context, AstNode oldNode, AstNode replacementNode, IEnumerable <AstNode> toRemove)
 {
     return(new CodeAction(context.TranslateString("Convert to initializer"), script => {
         foreach (var statement in toRemove)
         {
             script.Remove(statement);
         }
         script.Replace(oldNode, replacementNode);
     }, oldNode));
 }
Ejemplo n.º 19
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            Expression node = context.GetNode <IdentifierExpression>();

            if (node == null)
            {
                var mr = context.GetNode <MemberReferenceExpression>();
                if (mr == null || !mr.MemberNameToken.IsInside(context.Location))
                {
                    yield break;
                }
                node = mr;
            }
            if (node == null)
            {
                yield break;
            }
            var rr = context.Resolve(node) as MethodGroupResolveResult;

            if (rr == null || rr.IsError)
            {
                yield break;
            }
            var type = TypeGuessing.GetValidTypes(context.Resolver, node).FirstOrDefault(t => t.Kind == TypeKind.Delegate);

            if (type == null)
            {
                yield break;
            }
            var invocationMethod = type.GetDelegateInvokeMethod();

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

            yield return(new CodeAction(
                             context.TranslateString("Convert to lambda expression"),
                             script => {
                var invocation = new InvocationExpression(node.Clone(), invocationMethod.Parameters.Select(p => new IdentifierExpression(context.GetNameProposal(p.Name))));
                var lambda = new LambdaExpression {
                    Body = invocation
                };
                lambda.Parameters.AddRange(
                    invocation.Arguments
                    .Cast <IdentifierExpression>()
                    .Select(p => new ParameterDeclaration {
                    Name = p.Identifier
                })
                    );
                script.Replace(node, lambda);
            },
                             node
                             ));
        }
Ejemplo n.º 20
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var identifier = context.GetNode <IdentifierExpression>();

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

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

            if (!(context.Resolve(identifier).IsError))
            {
                yield break;
            }
            var guessedType = TypeGuessing.GuessAstType(context, identifier);

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

            yield return(new CodeAction(context.TranslateString("Create local variable"), script => {
                var initializer = new VariableInitializer(null, identifier.Identifier);
                var decl = new VariableDeclarationStatement()
                {
                    Type = guessedType,
                    Variables = { initializer }
                };
                if (identifier.Parent is AssignmentExpression && ((AssignmentExpression)identifier.Parent).Left == identifier)
                {
                    initializer.Initializer = ((AssignmentExpression)identifier.Parent).Right.Clone();
                    if (!context.UseExplicitTypes)
                    {
                        decl.Type = new SimpleType("var");
                    }
                    script.Replace(statement, decl);
                }
                else
                {
                    script.InsertBefore(statement, decl);
                }
            }, identifier)
            {
                Severity = ICSharpCode.NRefactory.Refactoring.Severity.Error
            });
        }
Ejemplo n.º 21
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var type = context.GetNode <AstType>();

            if (type == null || type.Role != Roles.BaseType)
            {
                yield break;
            }
            var state = context.GetResolverStateBefore(type);

            if (state.CurrentTypeDefinition == null)
            {
                yield break;
            }

            var resolveResult = context.Resolve(type);

            if (resolveResult.Type.Kind != TypeKind.Interface)
            {
                yield break;
            }

            var toImplement = ImplementInterfaceAction.CollectMembersToImplement(
                state.CurrentTypeDefinition,
                resolveResult.Type,
                false
                );

            if (toImplement.Count == 0)
            {
                yield break;
            }

            yield return(new CodeAction(context.TranslateString("Implement interface explicit"), script =>
            {
                script.InsertWithCursor(
                    context.TranslateString("Implement Interface"),
                    state.CurrentTypeDefinition,
                    ImplementInterfaceAction.GenerateImplementation(context, toImplement.Select(t => Tuple.Create(t.Item1, true)))
                    );
            }));
        }
        protected override CodeAction GetAction(RefactoringContext context, MethodDeclaration node)
        {
            if (!(node.PrivateImplementationType.IsNull))
            {
                return(null);
            }

            if (!node.NameToken.Contains(context.Location))
            {
                return(null);
            }

            var method = (IMethod)((MemberResolveResult)context.Resolve(node)).Member;

            if (method.Documentation != null)
            {
                return(null);
            }

            IList <IMember> interfaceMethods = method.ImplementedInterfaceMembers;

            if (interfaceMethods.Count != 1 || method.DeclaringType.Kind == TypeKind.Interface)
            {
                return(null);
            }

            var interfaceMethod = interfaceMethods.SingleOrDefault();

            if (interfaceMethod == null)
            {
                return(null);
            }

            if (interfaceMethod.Documentation == null)
            {
                return(null);
            }

            string comments = interfaceMethod.Documentation.ToString();

            if (comments == "")
            {
                return(null);
            }

            string[] lines = comments.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            return(new CodeAction(context.TranslateString("Copy comments from interface"), script =>
            {
                foreach (string co in lines)
                {
                    script.InsertBefore(node, new Comment(co, CommentType.Documentation));
                }
            }, node));
        }
Ejemplo n.º 23
0
 CodeAction GetAction(RefactoringContext context, AstNode node, MethodDeclaration method)
 {
     return(new CodeAction(context.TranslateString("Extract anonymous method"),
                           script =>
     {
         var identifier = new IdentifierExpression("Method");
         script.Replace(node, identifier);
         script.InsertBefore(node.GetParent <EntityDeclaration> (), method);
         script.Link(method.NameToken, identifier);
     }, method.NameToken));
 }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var switchStatement = GetSwitchStatement(context);

            if (switchStatement == null)
            {
                yield break;
            }
            var result = context.Resolve(switchStatement.Expression);

            if (result.Type.Kind != TypeKind.Enum)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Create switch labels"), script =>
            {
                var type = result.Type;
                var newSwitch = (SwitchStatement)switchStatement.Clone();

                var target = new TypeReferenceExpression(context.CreateShortType(result.Type));
                foreach (var field in type.GetFields())
                {
                    if (field.IsSynthetic || !field.IsConst)
                    {
                        continue;
                    }
                    newSwitch.SwitchSections.Add(new SwitchSection()
                    {
                        CaseLabels =
                        {
                            new CaseLabel(new MemberReferenceExpression(target.Clone(), field.Name))
                        },
                        Statements =
                        {
                            new BreakStatement()
                        }
                    });
                }

                newSwitch.SwitchSections.Add(new SwitchSection()
                {
                    CaseLabels =
                    {
                        new CaseLabel()
                    },
                    Statements =
                    {
                        new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "ArgumentOutOfRangeException")))
                    }
                });

                script.Replace(switchStatement, newSwitch);
            }));
        }
Ejemplo n.º 25
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var expr = GetEmptyString(context);

            if (expr == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Use string.Empty"), script => {
                script.Replace(expr, new PrimitiveType("string").Member("Empty"));
            }, expr));
        }
Ejemplo n.º 26
0
 CodeAction CreateForConditionalExpression(RefactoringContext ctx, ReturnStatement node, ConditionalExpression conditionalExpression)
 {
     return(new CodeAction(
                ctx.TranslateString("Replace with 'if' statement"),
                script => {
         var ifStatement = new IfElseStatement(conditionalExpression.Condition.Clone(), new ReturnStatement(conditionalExpression.TrueExpression.Clone()));
         script.Replace(node, ifStatement);
         script.InsertAfter(ifStatement, new ReturnStatement(conditionalExpression.FalseExpression.Clone()));
     },
                node
                ));
 }
Ejemplo n.º 27
0
 CodeAction CreateForNullCoalesingExpression(RefactoringContext ctx, ReturnStatement node, BinaryOperatorExpression bOp)
 {
     return(new CodeAction(
                ctx.TranslateString("Replace with 'if' statement"),
                script => {
         var ifStatement = new IfElseStatement(new BinaryOperatorExpression(bOp.Left.Clone(), BinaryOperatorType.InEquality, new NullReferenceExpression()), new ReturnStatement(bOp.Left.Clone()));
         script.Replace(node, ifStatement);
         script.InsertAfter(ifStatement, new ReturnStatement(bOp.Right.Clone()));
     },
                node
                ));
 }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var expr = GetEmptyString(context);

            if (expr == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Use string.Empty"), script => {
                script.Replace(expr, new MemberReferenceExpression(new TypeReferenceExpression(new PrimitiveType("string")), "Empty"));
            }));
        }
Ejemplo n.º 29
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var ifStatement = GetIfElseStatement(context);

            if (ifStatement == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Simplify if in loops"), script => {
                GenerateNewScript(script, ifStatement);
            }, ifStatement));
        }
Ejemplo n.º 30
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var property = context.GetNode <PropertyDeclaration>();

            if (property == null || !property.NameToken.Contains(context.Location))
            {
                yield break;
            }

            var field = RemoveBackingStoreAction.GetBackingField(context, property);

            if (field == null)
            {
                yield break;
            }
            var resolvedType = ReflectionHelper.ParseReflectionName("System.EventHandler").Resolve(context.Compilation);

            if (resolvedType == null)
            {
                yield break;
            }
            var type = (TypeDeclaration)property.Parent;

            yield return(new CodeAction(context.TranslateString("Create changed event"), script => {
                var eventDeclaration = CreateChangedEventDeclaration(context, property);
                var methodDeclaration = CreateEventInvocatorAction.CreateEventInvocator(context, type, eventDeclaration, eventDeclaration.Variables.First(), resolvedType.GetDelegateInvokeMethod(), false);
                var stmt = new ExpressionStatement(new InvocationExpression(
                                                       new IdentifierExpression(methodDeclaration.Name),
                                                       context.CreateShortType("System", "EventArgs").Member("Empty")
                                                       ));
                script.InsertWithCursor(
                    context.TranslateString("Create event invocator"),
                    Script.InsertPosition.After,
                    new AstNode[] { eventDeclaration, methodDeclaration }
                    ).ContinueScript(delegate {
                    script.InsertBefore(property.Setter.Body.RBraceToken, stmt);
                    script.FormatText(stmt);
                });
            }, property.NameToken));
        }