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));
            }
        }
        protected override CodeAction GetAction(RefactoringContext context, CastExpression node)
        {
            if (node.Expression.Contains(context.Location))
            {
                return(null);
            }
            // only works on reference and nullable types
            var type       = context.ResolveType(node.Type);
            var typeDef    = type.GetDefinition();
            var isNullable = typeDef != null && typeDef.KnownTypeCode == KnownTypeCode.NullableOfT;

            if (type.IsReferenceType == true || isNullable)
            {
                return(new CodeAction(context.TranslateString("Convert cast to 'as'"), script => {
                    var asExpr = new AsExpression(node.Expression.Clone(), node.Type.Clone());
                    // if parent is an expression, clone parent and replace the case expression with asExpr,
                    // so that we can inset parentheses
                    var parentExpr = node.Parent.Clone() as Expression;
                    if (parentExpr != null)
                    {
                        var castExpr = parentExpr.GetNodeContaining(node.StartLocation, node.EndLocation);
                        castExpr.ReplaceWith(asExpr);
                        parentExpr.AcceptVisitor(insertParentheses);
                        script.Replace(node.Parent, parentExpr);
                    }
                    else
                    {
                        script.Replace(node, asExpr);
                    }
                }, node));
            }
            return(null);
        }
        CodeAction ActionFromVariableInitializer(RefactoringContext context)
        {
            var initializer = context.GetNode <VariableInitializer>();

            if (initializer == null || initializer.Parent.Parent is ForStatement)
            {
                return(null);
            }
            var initializerRR = context.Resolve(initializer) as LocalResolveResult;

            if (initializerRR == null)
            {
                return(null);
            }
            var elementType = GetElementType(initializerRR, context);

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

            return(new CodeAction(context.TranslateString("Iterate via foreach"), script => {
                var iterator = MakeForeach(new IdentifierExpression(initializer.Name), elementType, context);
                script.InsertAfter(context.GetNode <Statement>(), iterator);
            }));
        }
        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));
        }
Пример #5
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;
                })
                    );
            }, type));
        }
        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));
            }));
        }
Пример #7
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);
     }));
 }
Пример #8
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);
     }));
 }
Пример #9
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)))
                    );
            }));
        }
Пример #10
0
        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);
            }));
        }
        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"));
            }, expr));
        }
        public 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 = CreateFieldAction.GuessAstType(context, identifier);

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

            yield return(new CodeAction(context.TranslateString("Create local variable"), script => {
                var initializer = new VariableInitializer(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);
                }
            }));
        }
Пример #13
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var property = context.GetNode <PropertyDeclaration>();

            if (!(property != null &&
                  !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));
        }
Пример #14
0
        static IEnumerable <CodeAction> GetActions(RefactoringContext context, SimpleType node)
        {
            var resolveResult = context.Resolve(node) as UnknownIdentifierResolveResult;

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

            yield return(new CodeAction(context.TranslateString("Create delegate"), script => {
                script.CreateNewType(CreateType(context, node));
            }));
        }
Пример #15
0
        static CodeAction CreateAction(RefactoringContext context, string methodName, AstType returnType, IEnumerable <ParameterDeclaration> parameters, bool createInOtherType, bool isStatic, ResolveResult targetResolveResult)
        {
            return(new CodeAction(context.TranslateString("Create method"), script => {
                var decl = new MethodDeclaration()
                {
                    ReturnType = returnType,
                    Name = methodName,
                    Body = new BlockStatement()
                    {
                        new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
                    }
                };
                decl.Parameters.AddRange(parameters);

                if (isStatic)
                {
                    decl.Modifiers |= Modifiers.Static;
                }

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

                    script.InsertWithCursor(context.TranslateString("Create method"), targetResolveResult.Type.GetDefinition(), decl);
                    return;
                }

                script.InsertWithCursor(context.TranslateString("Create method"), Script.InsertPosition.Before, decl);
            }));
        }
Пример #16
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            VariableInitializer initializer;
            var eventDeclaration = GetEventDeclaration(context, out initializer);

            if (eventDeclaration == null)
            {
                yield break;
            }
            var type = (TypeDeclaration)eventDeclaration.Parent;
            var proposedHandlerName = GetNameProposal(initializer);

            if (type.Members.Any(m => m is MethodDeclaration && m.Name == proposedHandlerName))
            {
                yield break;
            }
            var resolvedType = context.Resolve(eventDeclaration.ReturnType).Type;

            if (resolvedType.Kind == TypeKind.Unknown)
            {
                yield break;
            }
            var invokeMethod = resolvedType.GetDelegateInvokeMethod();

            if (invokeMethod == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Create event invocator"), script => {
                var methodDeclaration = CreateEventInvocator(context, type, eventDeclaration, initializer, invokeMethod, UseExplictType);
                script.InsertWithCursor(
                    context.TranslateString("Create event invocator"),
                    Script.InsertPosition.After,
                    methodDeclaration
                    );
            }, initializer));
        }
Пример #17
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var binop = GetBinaryOperatorExpression(context);

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


            yield return(new CodeAction(string.Format(context.TranslateString("Flip '{0}' operator arguments"), binop.OperatorToken.GetText()), script => {
                script.Replace(binop.Left, binop.Right.Clone());
                script.Replace(binop.Right, binop.Left.Clone());
            }));
        }
Пример #18
0
        static CodeAction MoveDeclarationAction(RefactoringContext context, AstNode insertAnchor,
                                                VariableDeclarationStatement declarationStatement, VariableInitializer initializer)
        {
            var type = declarationStatement.Type.Clone();
            var name = initializer.Name;

            return(new CodeAction(context.TranslateString("Move declaration to outer scope"), script => {
                script.InsertBefore(declarationStatement, new ExpressionStatement()
                {
                    Expression = new AssignmentExpression(new IdentifierExpression(name), initializer.Initializer.Clone())
                });
                script.Remove(declarationStatement);
                script.InsertBefore(insertAnchor, new VariableDeclarationStatement(type, name, Expression.Null));
            }));
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var pdecl = GetPropertyDeclaration(context);

            if (pdecl == null || !pdecl.Getter.IsNull && !pdecl.Setter.IsNull)
            {
                yield break;
            }

            var type = pdecl.Parent as TypeDeclaration;

            if (type != null && type.ClassType == ClassType.Interface)
            {
                yield break;
            }
            yield return(new CodeAction(pdecl.Setter.IsNull ? context.TranslateString("Add setter") : context.TranslateString("Add getter"), script => {
                Statement accessorStatement = null;

                var accessor = new Accessor();
                if (!pdecl.Getter.IsNull && !pdecl.Getter.Body.IsNull || !pdecl.Setter.IsNull && !pdecl.Setter.Body.IsNull)
                {
                    accessorStatement = BuildAccessorStatement(context, pdecl);
                    accessor.Body = new BlockStatement {
                        accessorStatement
                    };
                }

                accessor.Role = pdecl.Setter.IsNull ? PropertyDeclaration.SetterRole : PropertyDeclaration.GetterRole;

                if (pdecl.Setter.IsNull && !pdecl.Getter.IsNull)
                {
                    script.InsertAfter(pdecl.Getter, accessor);
                }
                else if (pdecl.Getter.IsNull && !pdecl.Setter.IsNull)
                {
                    script.InsertBefore(pdecl.Setter, accessor);
                }
                else
                {
                    script.InsertBefore(pdecl.Getter, accessor);
                }
                if (accessorStatement != null)
                {
                    script.Select(accessorStatement);
                }
                script.FormatText(pdecl);
            }, pdecl.NameToken));
        }
Пример #20
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            // if (condition) {CodeBlock();}else { return|break|continue;}
            // will be reduced to:
            //if (!condition) return|break|continue;
            //CodeBlock();

            var ifStatement = GetIfElseStatement(context);

            if (ifStatement == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Simplify if in loops"), script => GenerateNewScript(
                                            script, ifStatement), ifStatement));
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            // TODO: Invert if without else
            // ex. if (cond) DoSomething () == if (!cond) return; DoSomething ()
            // beware of loop contexts return should be continue then.
            var ifStatement = GetIfElseStatement(context);

            if (ifStatement == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Invert if"), script =>
            {
                GenerateNewScript(script, ifStatement);
            }, ifStatement));
        }
        CodeAction GetAction <T> (RefactoringContext context, IfElseStatement ifElseStatement,
                                  Func <Statement, T> extractor, Func <T, T, Statement> getReplaceStatement,
                                  bool findImplicitFalseStatement = false)
            where T : AstNode
        {
            var node1 = GetNode(ifElseStatement.TrueStatement, extractor);

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

            var falseStatement = ifElseStatement.FalseStatement;

            // try next statement if there is no FalseStatement
            if (falseStatement.IsNull && findImplicitFalseStatement)
            {
                falseStatement = ifElseStatement.GetNextSibling(n => n is Statement) as Statement;
            }

            var node2 = GetNode(falseStatement, extractor);

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

            var replacement = getReplaceStatement(node1, node2);

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

            return(new CodeAction(context.TranslateString("Convert 'if' to '?:'"),
                                  script =>
            {
                script.Replace(ifElseStatement, replacement);
                // remove implicit false statement
                if (falseStatement != ifElseStatement.FalseStatement)
                {
                    script.Remove(falseStatement);
                }
            },
                                  ifElseStatement
                                  ));
        }
Пример #23
0
        static CodeAction MoveInitializerAction(RefactoringContext context, AstNode insertAnchor,
                                                VariableDeclarationStatement declaration, VariableInitializer initializer)
        {
            var type = declaration.Type.Clone();
            var name = initializer.Name;

            return(new CodeAction(context.TranslateString("Move initializer to outer scope"), script => {
                if (declaration.Variables.Count != 1)
                {
                    var innerDeclaration = RemoveInitializer(declaration, initializer);
                    script.InsertBefore(declaration, innerDeclaration);
                }
                script.Remove(declaration);
                var outerDeclaration = new VariableDeclarationStatement(type, name, initializer.Initializer.Clone());
                script.InsertBefore(insertAnchor, outerDeclaration);
            }));
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            if (!context.IsSomethingSelected)
            {
                yield break;
            }
            var pexpr = context.GetNode <PrimitiveExpression>();

            if (pexpr == null || !(pexpr.Value is string))
            {
                yield break;
            }
            if (pexpr.LiteralValue.StartsWith("@", StringComparison.Ordinal))
            {
                if (!(pexpr.StartLocation < new TextLocation(context.Location.Line, context.Location.Column - 1) && new TextLocation(context.Location.Line, context.Location.Column + 1) < pexpr.EndLocation))
                {
                    yield break;
                }
            }
            else
            {
                if (!(pexpr.StartLocation < context.Location && context.Location < pexpr.EndLocation))
                {
                    yield break;
                }
            }

            yield return(new CodeAction(context.TranslateString("Introduce format item"), script => {
                var invocation = context.GetNode <InvocationExpression>();
                if (invocation != null && invocation.Target.IsMatch(PrototypeFormatReference))
                {
                    AddFormatCallToInvocation(context, script, pexpr, invocation);
                    return;
                }

                var arg = CreateFormatArgument(context);
                var newInvocation = new InvocationExpression(PrototypeFormatReference.Clone())
                {
                    Arguments = { CreateFormatString(context, pexpr, 0), arg }
                };

                script.Replace(pexpr, newInvocation);
                script.Select(arg);
            }));
        }
Пример #25
0
        protected override CodeAction GetAction(RefactoringContext context, LambdaExpression node)
        {
            if (context.Location < node.StartLocation || context.Location >= node.Body.StartLocation)
            {
                return(null);
            }

            var lambdaResolveResult = context.Resolve(node) as LambdaResolveResult;

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

            return(new CodeAction(context.TranslateString("Convert to anonymous delegate"), script => {
                BlockStatement newBody;
                if (node.Body is BlockStatement)
                {
                    newBody = (BlockStatement)node.Body.Clone();
                }
                else
                {
                    var expression = (Expression)node.Body.Clone();

                    Statement statement;
                    if (RequireReturnStatement(context, node))
                    {
                        statement = new ReturnStatement(expression);
                    }
                    else
                    {
                        statement = new ExpressionStatement(expression);
                    }

                    newBody = new BlockStatement {
                        Statements =
                        {
                            statement
                        }
                    };
                }
                var method = new AnonymousMethodExpression(newBody, GetParameters(lambdaResolveResult.Parameters, context));
                script.Replace(node, method);
            }, node));
        }
Пример #26
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var pexpr = context.GetNode <PrimitiveExpression>();

            if (pexpr == null || !pexpr.LiteralValue.StartsWith("0X", System.StringComparison.OrdinalIgnoreCase))
            {
                yield break;
            }
            if (!((pexpr.Value is int) || (pexpr.Value is long) || (pexpr.Value is short) || (pexpr.Value is sbyte) ||
                  (pexpr.Value is uint) || (pexpr.Value is ulong) || (pexpr.Value is ushort) || (pexpr.Value is byte)))
            {
                yield break;
            }

            yield return(new CodeAction(context.TranslateString("Convert hex to dec"), script => {
                script.Replace(pexpr, new PrimitiveExpression(pexpr.Value));
            }));
        }
Пример #27
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var directive = GetDirective(context);

            if (directive == null)
            {
                yield break;
            }
            var endDirective = DirectiveSearcher.GetEndRegion(context.RootNode, directive);

            if (endDirective == null)
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Remove region"), script => {
                script.Remove(directive);
                script.Remove(endDirective);
            }, directive));
        }
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            // TODO: Invert if without else
            // ex. if (cond) DoSomething () == if (!cond) return; DoSomething ()
            // beware of loop contexts return should be continue then.

            var ifStatement = GetIfElseStatement(context);

            if (!(ifStatement != null && !ifStatement.TrueStatement.IsNull && !ifStatement.FalseStatement.IsNull))
            {
                yield break;
            }
            yield return(new CodeAction(context.TranslateString("Invert if"), script => {
                script.Replace(ifStatement.Condition, CSharpUtil.InvertCondition(ifStatement.Condition.Clone()));
                script.Replace(ifStatement.TrueStatement, ifStatement.FalseStatement.Clone());
                script.Replace(ifStatement.FalseStatement, ifStatement.TrueStatement.Clone());
                script.FormatText(ifStatement);
            }));
        }
        CodeAction ActionFromUsingStatement(RefactoringContext context)
        {
            var initializer = context.GetNode <VariableInitializer>();

            if (initializer == null)
            {
                return(null);
            }
            var initializerRR = context.Resolve(initializer) as LocalResolveResult;

            if (initializerRR == null)
            {
                return(null);
            }
            var elementType = GetElementType(initializerRR, context);

            if (elementType == null)
            {
                return(null);
            }
            var usingStatement = initializer.Parent.Parent as UsingStatement;

            if (usingStatement == null)
            {
                return(null);
            }
            return(new CodeAction(context.TranslateString("Iterate via foreach"), script => {
                var iterator = MakeForeach(new IdentifierExpression(initializer.Name), elementType, context);
                if (usingStatement.EmbeddedStatement is EmptyStatement)
                {
                    var blockStatement = new BlockStatement();
                    blockStatement.Statements.Add(iterator);
                    script.Replace(usingStatement.EmbeddedStatement, blockStatement);
                    script.FormatText((AstNode)blockStatement);
                }
                else if (usingStatement.EmbeddedStatement is BlockStatement)
                {
                    var anchorNode = usingStatement.EmbeddedStatement.FirstChild;
                    script.InsertAfter(anchorNode, iterator);
                    script.FormatText(usingStatement.EmbeddedStatement);
                }
            }, initializer));
        }
        protected override CodeAction GetAction(RefactoringContext context, IfElseStatement node)
        {
            if (!node.IfToken.Contains(context.Location))
            {
                return(null);
            }

            IfElseStatement outerIfStatement;
            IfElseStatement innerIfStatement = GetInnerIfStatement(node);

            if (innerIfStatement != null)
            {
                if (!innerIfStatement.FalseStatement.IsNull)
                {
                    return(null);
                }
                outerIfStatement = node;
            }
            else
            {
                outerIfStatement = GetOuterIfStatement(node);
                if (outerIfStatement == null || !outerIfStatement.FalseStatement.IsNull)
                {
                    return(null);
                }
                innerIfStatement = node;
            }

            return(new CodeAction(context.TranslateString("Merge nested 'if's"),
                                  script =>
            {
                var mergedIfStatement = new IfElseStatement
                {
                    Condition = new BinaryOperatorExpression(outerIfStatement.Condition.Clone(),
                                                             BinaryOperatorType.ConditionalAnd,
                                                             innerIfStatement.Condition.Clone()),
                    TrueStatement = innerIfStatement.TrueStatement.Clone()
                };
                mergedIfStatement.Condition.AcceptVisitor(insertParenthesesVisitor);
                script.Replace(outerIfStatement, mergedIfStatement);
            }, node));
        }