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;
            }

            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)
             *      );
             * });*/
        }
		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);
		}
Ejemplo n.º 3
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var identifier = context.GetNode <IdentifierExpression>();

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

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

            if (guessedType == null)
            {
                yield break;
            }
            var state = context.GetResolverStateBefore(identifier);

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

            bool isStatic = state.CurrentMember.IsStatic | state.CurrentTypeDefinition.IsStatic;

//			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(identifier.Identifier, AffectedEntity.Field, Modifiers.Private, isStatic)) {
//				yield break;
//			}

            yield return(new CodeAction(context.TranslateString("Create field"), script => {
                var decl = new FieldDeclaration()
                {
                    ReturnType = guessedType,
                    Variables = { new VariableInitializer(identifier.Identifier) }
                };
                if (isStatic)
                {
                    decl.Modifiers |= Modifiers.Static;
                }
                script.InsertWithCursor(context.TranslateString("Create field"), decl, Script.InsertPosition.Before);
            }));
        }
Ejemplo n.º 4
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var expr = GetCreatePropertyOrFieldNode(context);

            if (expr == null)
            {
                yield break;
            }
            if (!(expr is MemberReferenceExpression))
            {
                yield break;
            }
            var propertyName = CreatePropertyAction.GetPropertyName(expr);

            if (propertyName == null)
            {
                yield break;
            }
            if (IsInvocationTarget(expr))
            {
                yield break;
            }
            var statement = expr.GetParent <Statement>();

            if (statement == null)
            {
                yield break;
            }
            if (!(context.Resolve(expr).IsError))
            {
                yield break;
            }
            var guessedType = TypeGuessing.GuessType(context, expr);

            if (guessedType == null || guessedType.Kind != TypeKind.Enum)
            {
                yield break;
            }
            var state = context.GetResolverStateBefore(expr);

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

            yield return(new CodeAction(context.TranslateString("Create enum value"), script => {
                var decl = new EnumMemberDeclaration {
                    Name = propertyName
                };
                script.InsertWithCursor(context.TranslateString("Create enum value"), guessedType.GetDefinition(), (s, c) => decl);
            }, expr)
            {
                Severity = ICSharpCode.NRefactory.Refactoring.Severity.Error
            });
        }
        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 = ImplementInterfaceAction.CollectMembersToImplement(
                state.CurrentTypeDefinition,
                resolveResult.Type,
                false,
                out interfaceMissing
                );

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

            yield return(new CodeAction(context.TranslateString("Implement interface explicit"), script =>
                                        script.InsertWithCursor(
                                            context.TranslateString("Implement Interface"),
                                            state.CurrentTypeDefinition,
                                            (s, c) => ImplementInterfaceAction.GenerateImplementation(c, toImplement.Select(t => Tuple.Create(t.Item1, true)), interfaceMissing).ToList()
                                            )
                                        , type));
        }
Ejemplo n.º 6
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var loop = GetForeachStatement(context);

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

            if (context.GetResolverStateBefore(loop)
                .LookupSimpleNameOrTypeName("Enumerable", new List <IType>(), NameLookupMode.Type)
                .Type.FullName != "System.Linq.Enumerable")
            {
                yield break;
            }

            var outputStatement = GetTransformedAssignmentExpression(context, loop);

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

            yield return(new CodeAction(context.TranslateString("Convert foreach loop to LINQ expression"), script => {
                var prevSibling = loop.GetPrevSibling(node => node is Statement);

                Expression leftSide = outputStatement.Left;
                Expression rightSide = outputStatement.Right;

                Expression expressionToReplace = GetExpressionToReplace(prevSibling, leftSide);

                if (expressionToReplace != null)
                {
                    Expression replacementExpression = rightSide.Clone();
                    if (!IsZeroPrimitive(expressionToReplace))
                    {
                        replacementExpression = new BinaryOperatorExpression(ParenthesizeIfNeeded(expressionToReplace).Clone(),
                                                                             BinaryOperatorType.Add,
                                                                             replacementExpression);
                    }

                    script.Replace(expressionToReplace, replacementExpression);
                    script.Remove(loop);
                }
                else
                {
                    script.Replace(loop, new ExpressionStatement(outputStatement));
                }
            }, loop));
        }
        IEnumerable <CodeAction> GetActionsFromIdentifier(RefactoringContext context, IdentifierExpression identifier)
        {
            if (!(context.Resolve(identifier).IsError))
            {
                yield break;
            }
            var methodName  = identifier.Identifier;
            var guessedType = TypeGuessing.GuessType(context, identifier);

            if (guessedType.Kind != TypeKind.Delegate)
            {
                yield break;
            }
            var invocationMethod = guessedType.GetDelegateInvokeMethod();

            if (invocationMethod == null)
            {
                yield break;
            }
            var state = context.GetResolverStateBefore(identifier);

            if (state.CurrentMember == null || state.CurrentTypeDefinition == null)
            {
                yield break;
            }
            bool isStatic = state.CurrentMember.IsStatic || state.CurrentTypeDefinition.IsStatic;

            var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));

            if (service != null && !service.IsValidName(methodName, AffectedEntity.Method, Modifiers.Private, isStatic))
            {
                yield break;
            }

            yield return(CreateAction(
                             context,
                             identifier,
                             methodName,
                             context.CreateShortType(invocationMethod.ReturnType),
                             invocationMethod.Parameters.Select(parameter => new ParameterDeclaration(context.CreateShortType(parameter.Type), parameter.Name)
            {
                ParameterModifier = GetModifiers(parameter)
            }),
                             false,
                             isStatic,
                             null));
        }
Ejemplo n.º 8
0
        static IEnumerable <string> GetNameProposals(RefactoringContext context, QueryExpression query, string baseName)
        {
            var    resolver = context.GetResolverStateBefore(query);
            int    current  = -1;
            string nameProposal;

            for (;;)
            {
                do
                {
                    ++current;
                    nameProposal = baseName + (current == 0 ? string.Empty : current.ToString());
                } while (IsNameUsed(resolver, query, nameProposal));

                yield return(nameProposal);
            }
        }
Ejemplo n.º 9
0
        IEnumerable <CodeAction> GetActionsForAddNamespaceUsing(RefactoringContext context, AstNode node)
        {
            var nrr = context.Resolve(node) as NamespaceResolveResult;

            if (nrr == null)
            {
                return(EmptyList <CodeAction> .Instance);
            }

            var trr = context.Resolve(node.Parent) as TypeResolveResult;

            if (trr == null)
            {
                return(EmptyList <CodeAction> .Instance);
            }
            ITypeDefinition typeDef = trr.Type.GetDefinition();

            if (typeDef == null)
            {
                return(EmptyList <CodeAction> .Instance);
            }

            IList <IType>     typeArguments;
            ParameterizedType parameterizedType = trr.Type as ParameterizedType;

            if (parameterizedType != null)
            {
                typeArguments = parameterizedType.TypeArguments;
            }
            else
            {
                typeArguments = EmptyList <IType> .Instance;
            }

            var resolver = context.GetResolverStateBefore(node.Parent);

            if (resolver.ResolveSimpleName(typeDef.Name, typeArguments) is UnknownIdentifierResolveResult)
            {
                // It's possible to remove the explicit namespace usage and introduce a using instead
                return(new[] { NewUsingAction(context, node, typeDef.Namespace) });
            }
            return(EmptyList <CodeAction> .Instance);
        }
Ejemplo n.º 10
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)))
                    );
            }));
        }
Ejemplo n.º 11
0
        public IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var foreachStatement = GetForeachStatement(context);

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

            var    state = context.GetResolverStateBefore(foreachStatement.EmbeddedStatement);
            string name  = GetName(state, VariableNames);

            if (name == null)             // very unlikely, but just in case ...
            {
                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"), name, new PrimitiveExpression(0));
                var id1 = new IdentifierExpression(name);
                var id2 = id1.Clone();
                var id3 = id1.Clone();
                var inExpression = foreachStatement.InExpression;
                Statement declarationStatement = null;
                if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression)
                {
                    string listName = GetName(state, CollectionNames) ?? "col";
                    declarationStatement = new VariableDeclarationStatement(
                        new PrimitiveType("var"),
                        listName,
                        inExpression.Clone()
                        );
                    inExpression = new IdentifierExpression(listName);
                }

                var variableDeclarationStatement = new VariableDeclarationStatement(
                    foreachStatement.VariableType.Clone(),
                    foreachStatement.VariableName,
                    new IndexerExpression(inExpression.Clone(), id3)
                    );
                var forStatement = new ForStatement()
                {
                    Initializers = { initializer },
                    Condition = new BinaryOperatorExpression(id1, BinaryOperatorType.LessThan, new MemberReferenceExpression(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);
                }
                if (declarationStatement != null)
                {
                    script.InsertBefore(foreachStatement, declarationStatement);
                }
                script.Replace(foreachStatement, forStatement);
                script.Link(initializer.Variables.First().NameToken, id1, id2, id3);
            }, foreachStatement));
        }
Ejemplo n.º 12
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var identifier = CreateFieldAction.GetCreatePropertyOrFieldNode(context);

            if (identifier == null)
            {
                yield break;
            }
            if (CreateFieldAction.IsInvocationTarget(identifier))
            {
                yield break;
            }

            var propertyName = GetPropertyName(identifier);

            if (propertyName == null)
            {
                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;
            }
            var state = context.GetResolverStateBefore(identifier);

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

            bool          createInOtherType   = false;
            ResolveResult targetResolveResult = null;

            if (identifier is MemberReferenceExpression)
            {
                targetResolveResult = context.Resolve(((MemberReferenceExpression)identifier).Target);
                if (targetResolveResult.Type.GetDefinition() == null || targetResolveResult.Type.GetDefinition().Region.IsEmpty)
                {
                    yield break;
                }
                createInOtherType = !state.CurrentTypeDefinition.Equals(targetResolveResult.Type.GetDefinition());
            }

            bool isStatic = targetResolveResult is TypeResolveResult;

            if (createInOtherType)
            {
                if (isStatic && targetResolveResult.Type.Kind == TypeKind.Interface || targetResolveResult.Type.Kind == TypeKind.Enum)
                {
                    yield break;
                }
            }
            else
            {
                if (state.CurrentMember == null)
                {
                    yield break;
                }
                isStatic |= state.CurrentTypeDefinition.IsStatic;
                if (targetResolveResult == null)
                {
                    isStatic |= state.CurrentMember.IsStatic;
                }
            }
            isStatic &= !(identifier is NamedExpression);

            //			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(propertyName, AffectedEntity.Property, Modifiers.Private, isStatic)) {
//				yield break;
//			}

            yield return(new CodeAction(context.TranslateString("Create property"), script => {
                var decl = new PropertyDeclaration()
                {
                    ReturnType = guessedType,
                    Name = propertyName,
                    Getter = new Accessor(),
                    Setter = new Accessor()
                };
                if (isStatic)
                {
                    decl.Modifiers |= Modifiers.Static;
                }

                if (createInOtherType)
                {
                    if (targetResolveResult.Type.Kind == TypeKind.Interface)
                    {
                        decl.Modifiers = Modifiers.None;
                    }
                    else
                    {
                        decl.Modifiers |= Modifiers.Public;
                    }
                    script.InsertWithCursor(
                        context.TranslateString("Create property"),
                        targetResolveResult.Type.GetDefinition(),
                        (s, c) => decl);

                    return;
                }

                script.InsertWithCursor(context.TranslateString("Create property"), Script.InsertPosition.Before, decl);
            }, identifier.GetNodeAt(context.Location) ?? identifier)
            {
                Severity = ICSharpCode.NRefactory.Refactoring.Severity.Error
            });
        }
Ejemplo n.º 13
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            bool hasIndexAccess;
            var  foreachStatement = GetForeachStatement(context, out hasIndexAccess);

            if (foreachStatement == null || foreachStatement.EmbeddedStatement.IsNull)
            {
                yield break;
            }
            var    state = context.GetResolverStateBefore(foreachStatement.EmbeddedStatement);
            string name  = GetName(state, VariableNames);

            if (name == null)             // very unlikely, but just in case ...
            {
                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);
                var inExpression = foreachStatement.InExpression;

                var initializer = hasIndexAccess ? new VariableDeclarationStatement(new PrimitiveType("int"), name, new PrimitiveExpression(0)) :
                                  new VariableDeclarationStatement(new SimpleType("var"), name, new InvocationExpression(new MemberReferenceExpression(inExpression.Clone(), "GetEnumerator")));
                var id1 = new IdentifierExpression(name);
                var id2 = id1.Clone();
                var id3 = id1.Clone();
                Statement declarationStatement = null;
                if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression)
                {
                    string listName = GetName(state, CollectionNames) ?? "col";
                    declarationStatement = new VariableDeclarationStatement(
                        new PrimitiveType("var"),
                        listName,
                        inExpression.Clone()
                        );
                    inExpression = new IdentifierExpression(listName);
                }

                var variableDeclarationStatement = new VariableDeclarationStatement(
                    foreachStatement.VariableType.Clone(),
                    foreachStatement.VariableName,
                    hasIndexAccess ? (Expression) new IndexerExpression(inExpression.Clone(), id3) : new MemberReferenceExpression(id1, "Current")
                    );

                var forStatement = new ForStatement {
                    Initializers = { initializer },
                    Condition = hasIndexAccess ? (Expression) new BinaryOperatorExpression(id1, BinaryOperatorType.LessThan, new MemberReferenceExpression(inExpression.Clone(), countProperty)) :
                                new InvocationExpression(new MemberReferenceExpression(id2, "MoveNext")),
                    EmbeddedStatement = new BlockStatement {
                        variableDeclarationStatement
                    }
                };

                if (hasIndexAccess)
                {
                    forStatement.Iterators.Add(new UnaryOperatorExpression(UnaryOperatorType.PostIncrement, id2));
                }

                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);
                }
                if (declarationStatement != null)
                {
                    script.InsertBefore(foreachStatement, declarationStatement);
                }
                script.Replace(foreachStatement, forStatement);
                if (hasIndexAccess)
                {
                    script.Link(initializer.Variables.First().NameToken, id1, id2, id3);
                }
                else
                {
                    script.Link(initializer.Variables.First().NameToken, id1, id2);
                }
            }, foreachStatement));

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

                var initializer = new VariableDeclarationStatement(new PrimitiveType("int"), name, new PrimitiveExpression(0));
                var id1 = new IdentifierExpression(name);
                var id2 = id1.Clone();
                var id3 = id1.Clone();
                var inExpression = foreachStatement.InExpression;
                Statement declarationStatement = null;
                if (inExpression is ObjectCreateExpression || inExpression is ArrayCreateExpression)
                {
                    string listName = GetName(state, CollectionNames) ?? "col";
                    declarationStatement = new VariableDeclarationStatement(
                        new PrimitiveType("var"),
                        listName,
                        inExpression.Clone()
                        );
                    inExpression = new IdentifierExpression(listName);
                }

                var variableDeclarationStatement = new VariableDeclarationStatement(
                    foreachStatement.VariableType.Clone(),
                    foreachStatement.VariableName,
                    new IndexerExpression(inExpression.Clone(), id3)
                    );

                string optimizedUpperBound = GetBoundName(inExpression) + countProperty;
                initializer.Variables.Add(new VariableInitializer(optimizedUpperBound, new MemberReferenceExpression(inExpression.Clone(), countProperty)));
                var forStatement = new ForStatement {
                    Initializers = { initializer },
                    Condition = new BinaryOperatorExpression(id1, BinaryOperatorType.LessThan, new IdentifierExpression(optimizedUpperBound)),
                    Iterators = { 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);
                }
                if (declarationStatement != null)
                {
                    script.InsertBefore(foreachStatement, declarationStatement);
                }
                script.Replace(foreachStatement, forStatement);
                script.Link(initializer.Variables.First().NameToken, id1, id2, id3);
            }, foreachStatement));
        }
Ejemplo n.º 14
0
        public override IEnumerable <CodeAction> GetActions(RefactoringContext context)
        {
            var expr = GetCreatePropertyOrFieldNode(context);

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

            if (expr is MemberReferenceExpression && !(((MemberReferenceExpression)expr).Target is ThisReferenceExpression))
            {
                yield break;
            }

            var propertyName = CreatePropertyAction.GetPropertyName(expr);

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

            if (IsInvocationTarget(expr))
            {
                yield break;
            }
            var statement = expr.GetParent <Statement>();

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

            if (guessedType == null)
            {
                yield break;
            }
            var state = context.GetResolverStateBefore(expr);

            if (state.CurrentMember == null || state.CurrentTypeDefinition == null)
            {
                yield break;
            }
            bool isStatic = !(expr is NamedExpression) && (state.CurrentMember.IsStatic | state.CurrentTypeDefinition.IsStatic);

//			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(identifier.Identifier, AffectedEntity.Field, Modifiers.Private, isStatic)) {
//				yield break;
//			}

            yield return(new CodeAction(context.TranslateString("Create field"), script => {
                var decl = new FieldDeclaration {
                    ReturnType = guessedType,
                    Variables = { new VariableInitializer(propertyName) }
                };
                if (isStatic)
                {
                    decl.Modifiers |= Modifiers.Static;
                }
                script.InsertWithCursor(context.TranslateString("Create field"), Script.InsertPosition.Before, decl);
            }, expr.GetNodeAt(context.Location) ?? expr)
            {
                Severity = ICSharpCode.NRefactory.Refactoring.Severity.Error
            });
        }
Ejemplo n.º 15
0
        IEnumerable <CodeAction> GetActionsFromMemberReferenceExpression(RefactoringContext context, MemberReferenceExpression invocation)
        {
            if (!(context.Resolve(invocation).IsError))
            {
                yield break;
            }

            var methodName  = invocation.MemberName;
            var guessedType = CreateFieldAction.GuessType(context, invocation);

            if (guessedType.Kind != TypeKind.Delegate)
            {
                yield break;
            }
            var invocationMethod = guessedType.GetDelegateInvokeMethod();
            var state            = context.GetResolverStateBefore(invocation);

            if (state.CurrentTypeDefinition == null)
            {
                yield break;
            }
            ResolveResult targetResolveResult = context.Resolve(invocation.Target);
            bool          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
            {
                if (state.CurrentMember == null)
                {
                    yield break;
                }
                isStatic = state.CurrentMember.IsStatic || state.CurrentTypeDefinition.IsStatic;
            }

//			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(methodName, AffectedEntity.Method, Modifiers.Private, isStatic)) {
//				yield break;
//			}

            yield return(CreateAction(
                             context,
                             methodName,
                             context.CreateShortType(invocationMethod.ReturnType),
                             invocationMethod.Parameters.Select(parameter => new ParameterDeclaration(context.CreateShortType(parameter.Type), parameter.Name)
            {
                ParameterModifier = GetModifiers(parameter)
            }),
                             createInOtherType,
                             isStatic,
                             targetResolveResult));
        }
Ejemplo n.º 16
0
        IEnumerable <CodeAction> GetActionsFromInvocation(RefactoringContext context, InvocationExpression invocation)
        {
            if (!(context.Resolve(invocation.Target).IsError))
            {
                yield break;
            }

            var methodName = GetMethodName(invocation);

            if (methodName == null)
            {
                yield break;
            }
            var state = context.GetResolverStateBefore(invocation);

            if (state.CurrentMember == null || state.CurrentTypeDefinition == null)
            {
                yield break;
            }
            var guessedType = invocation.Parent is ExpressionStatement ? new PrimitiveType("void") : CreateFieldAction.GuessAstType(context, invocation);

            bool          createInOtherType   = false;
            ResolveResult targetResolveResult = null;

            if (invocation.Target is MemberReferenceExpression)
            {
                targetResolveResult = context.Resolve(((MemberReferenceExpression)invocation.Target).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 = state.CurrentMember.IsStatic || state.CurrentTypeDefinition.IsStatic;
            }

//			var service = (NamingConventionService)context.GetService(typeof(NamingConventionService));
//			if (service != null && !service.IsValidName(methodName, AffectedEntity.Method, Modifiers.Private, isStatic)) {
//				yield break;
//			}


            yield return(CreateAction(
                             context,
                             methodName,
                             guessedType,
                             GenerateParameters(context, invocation.Arguments),
                             createInOtherType,
                             isStatic,
                             targetResolveResult));
        }
Ejemplo n.º 17
0
        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
            });
        }