public override void Execute(EditorRefactoringContext context)
		{
			CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;
			if (parseInformation != null) {
				SyntaxTree st = parseInformation.SyntaxTree;
				Identifier identifier = (Identifier) st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
				if (identifier == null)
					return;
				TypeDeclaration interfaceTypeDeclaration = identifier.Parent as TypeDeclaration;
				if (interfaceTypeDeclaration != null) {
					// Generate abstract class from interface and abstract members from interface members
					TypeDeclaration abstractClassTypeNode = (TypeDeclaration) interfaceTypeDeclaration.Clone();
					abstractClassTypeNode.ClassType = ClassType.Class;
					abstractClassTypeNode.Modifiers |= Modifiers.Abstract;
					foreach (var entity in abstractClassTypeNode.Children.OfType<EntityDeclaration>()) {
						entity.Modifiers |= Modifiers.Abstract | Modifiers.Public;
					}
					
					var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
					using (Script script = refactoringContext.StartScript()) {
						// Replace interface node with node of abstract class
						script.Replace(interfaceTypeDeclaration, abstractClassTypeNode);
					}
				}
			}
		}
Ejemplo n.º 2
0
        public override void Execute(EditorRefactoringContext context)
        {
            AlFullParseInformation parseInformation = context.GetParseInformation() as AlFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return;
                }
                TypeDeclaration interfaceTypeDeclaration = identifier.Parent as TypeDeclaration;
                if (interfaceTypeDeclaration != null)
                {
                    // Generate abstract class from interface and abstract members from interface members
                    TypeDeclaration abstractClassTypeNode = (TypeDeclaration)interfaceTypeDeclaration.Clone();
                    abstractClassTypeNode.ClassType  = ClassType.Class;
                    abstractClassTypeNode.Modifiers |= Modifiers.Abstract;
                    foreach (var entity in abstractClassTypeNode.Children.OfType <EntityDeclaration>())
                    {
                        entity.Modifiers |= Modifiers.Abstract | Modifiers.Public;
                    }

                    var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
                    using (Script script = refactoringContext.StartScript()) {
                        // Replace interface node with node of abstract class
                        script.Replace(interfaceTypeDeclaration, abstractClassTypeNode);
                    }
                }
            }
        }
 public ContextActionCommand(IContextAction action, EditorRefactoringContext context)
 {
     if (action == null)
         throw new ArgumentNullException("action");
     this.action = action;
     this.context = context;
 }
        public override async void Execute(EditorRefactoringContext context)
        {
            SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);

            ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false);

            CSharpFullParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false) as CSharpFullParseInformation;

            EntityDeclaration node     = (EntityDeclaration)st.GetNodeAt(context.CaretLocation, n => n is TypeDeclaration || n is DelegateDeclaration);
            IDocument         document = context.Editor.Document;

            FileName newFileName = FileName.Create(Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(node.Name)));
            string   header      = CopyFileHeader(document, info);
            string   footer      = CopyFileEnd(document, info);

            AstNode newNode = node.Clone();

            foreach (var ns in node.Ancestors.OfType <NamespaceDeclaration>())
            {
                var newNS = new NamespaceDeclaration(ns.Name);
                newNS.Members.AddRange(ns.Children.Where(ch => ch is UsingDeclaration ||
                                                         ch is UsingAliasDeclaration ||
                                                         ch is ExternAliasDeclaration).Select(usingDecl => usingDecl.Clone()));
                newNS.AddMember(newNode);
                newNode = newNS;
            }

            var topLevelUsings = st.Children.Where(ch => ch is UsingDeclaration ||
                                                   ch is UsingAliasDeclaration ||
                                                   ch is ExternAliasDeclaration);
            StringBuilder       newCode = new StringBuilder(header);
            CSharpOutputVisitor visitor = new CSharpOutputVisitor(new StringWriter(newCode), FormattingOptionsFactory.CreateSharpDevelop());

            foreach (var topLevelUsing in topLevelUsings)
            {
                topLevelUsing.AcceptVisitor(visitor);
            }

            newNode.AcceptVisitor(visitor);

            newCode.AppendLine(footer);

            IViewContent viewContent = FileService.NewFile(newFileName, newCode.ToString());

            viewContent.PrimaryFile.SaveToDisk(newFileName);
            // now that the code is saved in the other file, remove it from the original document
            RemoveExtractedNode(context, node);

            IProject project = (IProject)compilation.GetProject();

            if (project != null)
            {
                FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile);
                projectItem.FileName = newFileName;
                ProjectService.AddProjectItem(project, projectItem);
                FileService.FireFileCreated(newFileName, false);
                project.Save();
                ProjectBrowserPad.RefreshViewAsync();
            }
        }
Ejemplo n.º 5
0
        public override async Task <bool> IsAvailableAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
        {
            SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);

            Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);

            if (identifier == null)
            {
                return(false);
            }
            if (MakeValidFileName(identifier.Name).Equals(Path.GetFileName(context.FileName), StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }
            if (identifier.Parent.Parent is TypeDeclaration)
            {
                return(false);
            }
            ParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false);

            if (info.UnresolvedFile.TopLevelTypeDefinitions.Count == 1)
            {
                return(false);
            }
            return(identifier.Parent is TypeDeclaration || identifier.Parent is DelegateDeclaration);
        }
Ejemplo n.º 6
0
            public Task <IContextAction[]> GetAvailableActionsAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
            {
                ITextEditor editor = context.Editor;
                // grab SelectionStart/SelectionLength while we're still on the main thread
                int selectionStart  = editor.SelectionStart;
                int selectionLength = editor.SelectionLength;

                return(Task.Run(
                           async delegate {
                    try {
                        if (!CreateCodeActionProvider())
                        {
                            return new IContextAction[0];
                        }
                        AlAstResolver resolver = await context.GetAstResolverAsync().ConfigureAwait(false);
                        var refactoringContext = new SDRefactoringContext(context.TextSource, resolver, context.CaretLocation, selectionStart, selectionLength, cancellationToken);
                        return codeActionProvider.GetActions(refactoringContext).Select(Wrap).ToArray();
                    } catch (OperationCanceledException) {
                        throw;                                 // don't catch cancellations
                    } catch (Exception ex) {
                        SD.Log.WarnFormatted("AlContextActionProviderWrapper crashed: {0}", ex);
                        SD.AnalyticsMonitor.TrackException(ex);
                        return new IContextAction[0];
                    }
                }, cancellationToken));
            }
Ejemplo n.º 7
0
        public override async Task <bool> IsAvailableAsync(EditorRefactoringContext context, System.Threading.CancellationToken cancellationToken)
        {
            SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);

            Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);

            if (identifier == null)
            {
                return(false);
            }
            ParameterDeclaration parameterDeclaration = identifier.Parent as ParameterDeclaration;

            if (parameterDeclaration == null)
            {
                return(false);
            }
            ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false);

            ITypeReference typeRef = parameterDeclaration.Type.ToTypeReference();

            if (typeRef == null)
            {
                return(false);
            }
            IType type = typeRef.Resolve(compilation);

            if (type == null)
            {
                return(false);
            }
            return(type.HasRange());
        }
Ejemplo n.º 8
0
		async Task<IContextAction[]> IContextActionProvider.GetAvailableActionsAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			if (await IsAvailableAsync(context, cancellationToken).ConfigureAwait(false))
				return new IContextAction[] { this };
			else
				return new IContextAction[0];
		}
Ejemplo n.º 9
0
        void RemoveExtractedNode(EditorRefactoringContext context, EntityDeclaration node)
        {
            IDocument document = context.Editor.Document;
            int       start    = document.GetOffset(node.StartLocation);
            int       end      = document.GetOffset(node.EndLocation);

            document.Remove(start, end - start);
        }
		public ContextActionViewModel(IContextAction action, EditorRefactoringContext context)
		{
			if (action == null)
				throw new ArgumentNullException("action");
			this.IsVisible = true;
			this.context = context;
			this.Action = action;
		}
Ejemplo n.º 11
0
		public override void Run(ResolveResult symbol)
		{
			ITextEditor editor = SD.GetActiveViewContentService<ITextEditor>();
			if(editor == null)
				return;
			
			EditorRefactoringContext context = new EditorRefactoringContext(editor);
			MakePopupWithClipboardOptions(context).OpenAtCaretAndFocus();
		}
		public override async Task<bool> IsAvailableAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
		{
			SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);
			Identifier identifier = (Identifier) st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
			if (identifier == null)
				return false;
			TypeDeclaration typeDeclaration = identifier.Parent as TypeDeclaration;
			return (typeDeclaration != null) && (typeDeclaration.ClassType == ClassType.Interface);
		}
 public ContextActionCommand(IContextAction action, EditorRefactoringContext context)
 {
     if (action == null)
     {
         throw new ArgumentNullException("action");
     }
     this.action  = action;
     this.context = context;
 }
Ejemplo n.º 14
0
        public override void Execute(EditorRefactoringContext context)
        {
            AlFullParseInformation parseInformation = context.GetParseInformation() as AlFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return;
                }
                ParameterDeclaration parameterDeclaration = identifier.Parent as ParameterDeclaration;
                if (parameterDeclaration == null)
                {
                    return;
                }

                AstNode grandparent = identifier.Parent.Parent;
                if ((grandparent is MethodDeclaration) || (grandparent is ConstructorDeclaration))
                {
                    // Range check condition
                    var rangeCheck = new IfElseStatement(
                        new BinaryOperatorExpression(
                            new BinaryOperatorExpression(new IdentifierExpression(identifier.Name), BinaryOperatorType.LessThan, new IdentifierExpression("lower")),
                            BinaryOperatorType.ConditionalOr,
                            new BinaryOperatorExpression(new IdentifierExpression(identifier.Name), BinaryOperatorType.GreaterThan, new IdentifierExpression("upper"))
                            ),
                        new ThrowStatement(
                            new ObjectCreateExpression(
                                new SimpleType("ArgumentOutOfRangeException"),
                                new List <Expression>()
                    {
                        new PrimitiveExpression(identifier.Name, '"' + identifier.Name + '"'), new IdentifierExpression(identifier.Name), new BinaryOperatorExpression(new PrimitiveExpression("Value must be between "), BinaryOperatorType.Add, new BinaryOperatorExpression(new IdentifierExpression("lower"), BinaryOperatorType.Add, new BinaryOperatorExpression(new PrimitiveExpression(" and "), BinaryOperatorType.Add, new IdentifierExpression("upper"))))
                    }
                                )
                            )
                        );

                    // Add range check as first statement in method's/constructor's body
                    var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
                    using (Script script = refactoringContext.StartScript()) {
                        if (grandparent is MethodDeclaration)
                        {
                            var methodDeclaration = (MethodDeclaration)grandparent;
                            script.AddTo(methodDeclaration.Body, rangeCheck);
                        }
                        else if (grandparent is ConstructorDeclaration)
                        {
                            var ctorDeclaration = (ConstructorDeclaration)grandparent;
                            script.AddTo(ctorDeclaration.Body, rangeCheck);
                        }
                    }
                }
            }
        }
Ejemplo n.º 15
0
		public EditorActionsProvider(EditorRefactoringContext editorContext, IList<IContextActionProvider> providers)
		{
			if (editorContext == null)
				throw new ArgumentNullException("editorContext");
			if (providers == null)
				throw new ArgumentNullException("providers");
			LoadProviderVisibilities(providers);
			this.providers = providers;
			this.editorContext = editorContext;
		}
 public ContextActionViewModel(IContextAction action, EditorRefactoringContext context)
 {
     if (action == null)
     {
         throw new ArgumentNullException("action");
     }
     this.IsVisible = true;
     this.context   = context;
     this.Action    = action;
 }
		public void Execute(EditorRefactoringContext context)
		{
			var resolver = context.GetAstResolverAsync().Result;
			var refactoringContext = new SDRefactoringContext(context.Editor, resolver, context.CaretLocation);
			var action = getUpdatedCodeAction(refactoringContext);
			if (action != null) {
				using (var script = refactoringContext.StartScript()) {
					action.Run(script);
				}
			}
		}
Ejemplo n.º 18
0
		public void Execute(EditorRefactoringContext context)
		{
			/* insert to editor */
			ITextEditor editor = context.Editor;
			editor.Document.Insert(context.CaretOffset, this.Text);
			
			/* update clipboard ring */
			var clipboardRing = ICSharpCode.SharpDevelop.Gui.TextEditorSideBar.Instance;
			if (clipboardRing != null) {
				clipboardRing.PutInClipboardRing(this.Text);
			}
		}
Ejemplo n.º 19
0
		static ObservableCollection<ContextActionViewModel> BuildClipboardRingData(EditorRefactoringContext context)
		{
			var clipboardRing = ICSharpCode.SharpDevelop.Gui.TextEditorSideBar.Instance;
			var clipboardRingItems = clipboardRing.GetClipboardRingItems();
			
			var list = new ObservableCollection<ContextActionViewModel>();
			foreach (var item in clipboardRingItems) {
				list.Add(new ContextActionViewModel(new ClipboardRingAction(item), context));
			}
			
			return list;
		}
Ejemplo n.º 20
0
            public override void Execute(EditorRefactoringContext context)
            {
                SD.AnalyticsMonitor.TrackFeature(typeof(SuppressIssueContextAction), issueName);
                var lineNo   = context.CaretLocation.Line;
                var document = context.Editor.Document;

                var    line        = document.GetLineByNumber(lineNo);
                string indentation = DocumentUtilities.GetIndentation(document, lineNo);
                string newLine     = DocumentUtilities.GetLineTerminator(document, lineNo);

                document.Insert(line.Offset, indentation + "// disable once " + issueName + newLine);
            }
		public override async void Execute(EditorRefactoringContext context)
		{
			SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);
			ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false);
			CSharpFullParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false) as CSharpFullParseInformation;
			EntityDeclaration node = (EntityDeclaration)st.GetNodeAt(context.CaretLocation, n => n is TypeDeclaration || n is DelegateDeclaration);
			IDocument document = context.Editor.Document;
			
			FileName newFileName = FileName.Create(Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(node.Name)));
			string header = CopyFileHeader(document, info);
			string footer = CopyFileEnd(document, info);
			
			AstNode newNode = node.Clone();
			
			foreach (var ns in node.Ancestors.OfType<NamespaceDeclaration>()) {
				var newNS = new NamespaceDeclaration(ns.Name);
				newNS.Members.AddRange(ns.Children.Where(ch => ch is UsingDeclaration
				                                         || ch is UsingAliasDeclaration
				                                         || ch is ExternAliasDeclaration).Select(usingDecl => usingDecl.Clone()));
				newNS.AddMember(newNode);
				newNode = newNS;
			}
			
			var topLevelUsings = st.Children.Where(ch => ch is UsingDeclaration
			                                       || ch is UsingAliasDeclaration
			                                       || ch is ExternAliasDeclaration);
			StringBuilder newCode = new StringBuilder(header);
			var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(compilation.GetProject());
			CSharpOutputVisitor visitor = new CSharpOutputVisitor(new StringWriter(newCode), formattingOptions.OptionsContainer.GetEffectiveOptions());
			
			foreach (var topLevelUsing in topLevelUsings)
				topLevelUsing.AcceptVisitor(visitor);
			
			newNode.AcceptVisitor(visitor);
			
			newCode.AppendLine(footer);
			
			IViewContent viewContent = FileService.NewFile(newFileName, newCode.ToString());
			viewContent.PrimaryFile.SaveToDisk(newFileName);
			// now that the code is saved in the other file, remove it from the original document
			RemoveExtractedNode(context, node);
			
			IProject project = (IProject)compilation.GetProject();
			if (project != null) {
				FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile);
				projectItem.FileName = newFileName;
				ProjectService.AddProjectItem(project, projectItem);
				FileService.FireFileCreated(newFileName, false);
				project.Save();
				ProjectBrowserPad.RefreshViewAsync();
			}
		}
        public void Execute(EditorRefactoringContext context)
        {
            var resolver           = context.GetAstResolverAsync().Result;
            var refactoringContext = new SDRefactoringContext(context.Editor, resolver, context.CaretLocation);
            var action             = getUpdatedCodeAction(refactoringContext);

            if (action != null)
            {
                using (var script = refactoringContext.StartScript()) {
                    action.Run(script);
                }
            }
        }
Ejemplo n.º 23
0
            public override void Execute(EditorRefactoringContext context)
            {
                var myContext   = SDRefactoringContext.Create(context.Editor, default(CancellationToken));
                var currentNode = myContext.RootNode.GetNodeAt <Statement>(context.CaretLocation);

                if (currentNode == null)
                {
                    return;
                }
                using (var script = myContext.StartScript()) {
                    script.InsertBefore(currentNode, new Comment(string.Format(" disable{1}{0}", issueName, type == SuppressType.Once ? " once " : " ")));
                }
            }
Ejemplo n.º 24
0
        public static async Task <SyntaxTree> GetSyntaxTreeAsync(this EditorRefactoringContext editorContext)
        {
            var parseInfo = (await editorContext.GetParseInformationAsync().ConfigureAwait(false)) as CSharpFullParseInformation;

            if (parseInfo != null)
            {
                return(parseInfo.SyntaxTree);
            }
            else
            {
                return(new SyntaxTree());
            }
        }
Ejemplo n.º 25
0
        public override void Run(ResolveResult symbol)
        {
            ITextEditor editor = SD.GetActiveViewContentService <ITextEditor>();

            if (editor == null)
            {
                return;
            }

            EditorRefactoringContext context = new EditorRefactoringContext(editor);

            MakePopupWithClipboardOptions(context).OpenAtCaretAndFocus();
        }
Ejemplo n.º 26
0
		static ContextActionsPopup MakePopupWithClipboardOptions(EditorRefactoringContext context)
		{
			var popupViewModel = new ContextActionsPopupViewModel();
			var actions = BuildClipboardRingData(context);
			
			string labelSource = "${res:SharpDevelop.Refactoring.ClipboardRing}";
			if (actions == null || actions.Count == 0) 
				labelSource = "${res:SharpDevelop.Refactoring.ClipboardRingEmpty}";
			
			popupViewModel.Title = MenuService.ConvertLabel(StringParser.Parse(labelSource));
			popupViewModel.Actions = actions;
			return new ClipboardRingPopup { Actions = popupViewModel };
		}
Ejemplo n.º 27
0
        static ObservableCollection <ContextActionViewModel> BuildClipboardRingData(EditorRefactoringContext context)
        {
            var clipboardRing      = ICSharpCode.SharpDevelop.Gui.TextEditorSideBar.Instance;
            var clipboardRingItems = clipboardRing.GetClipboardRingItems();

            var list = new ObservableCollection <ContextActionViewModel>();

            foreach (var item in clipboardRingItems)
            {
                list.Add(new ContextActionViewModel(new ClipboardRingAction(item), context));
            }

            return(list);
        }
		public override async Task<bool> IsAvailableAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
		{
			SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);
			Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
			if (identifier == null) return false;
			if (MakeValidFileName(identifier.Name).Equals(Path.GetFileName(context.FileName), StringComparison.OrdinalIgnoreCase))
				return false;
			if (identifier.Parent.Parent is TypeDeclaration)
				return false;
			ParseInformation info = await context.GetParseInformationAsync().ConfigureAwait(false);
			if (info.UnresolvedFile.TopLevelTypeDefinitions.Count == 1)
				return false;
			return identifier.Parent is TypeDeclaration || identifier.Parent is DelegateDeclaration;
		}
Ejemplo n.º 29
0
        public override async Task <bool> IsAvailableAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
        {
            SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);

            Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);

            if (identifier == null)
            {
                return(false);
            }
            TypeDeclaration typeDeclaration = identifier.Parent as TypeDeclaration;

            return((typeDeclaration != null) && (typeDeclaration.ClassType == ClassType.Interface));
        }
Ejemplo n.º 30
0
 public EditorActionsProvider(EditorRefactoringContext editorContext, IList <IContextActionProvider> providers)
 {
     if (editorContext == null)
     {
         throw new ArgumentNullException("editorContext");
     }
     if (providers == null)
     {
         throw new ArgumentNullException("providers");
     }
     LoadProviderVisibilities(providers);
     this.providers     = providers;
     this.editorContext = editorContext;
 }
		public override string GetDisplayName(EditorRefactoringContext context)
		{
			CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;
			if (parseInformation != null) {
				SyntaxTree st = parseInformation.SyntaxTree;
				Identifier identifier = (Identifier) st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
				if (identifier == null)
					return DisplayName;
				
				return StringParser.Parse("${res:SharpDevelop.Refactoring.MoveClassToFile}",
				                          new StringTagPair("FileName", MakeValidFileName(identifier.Name)));
			}
			
			return DisplayName;
		}
Ejemplo n.º 32
0
        public void Execute(EditorRefactoringContext context)
        {
            /* insert to editor */
            ITextEditor editor = context.Editor;

            editor.Document.Insert(context.CaretOffset, this.Text);

            /* update clipboard ring */
            var clipboardRing = ICSharpCode.SharpDevelop.Gui.TextEditorSideBar.Instance;

            if (clipboardRing != null)
            {
                clipboardRing.PutInClipboardRing(this.Text);
            }
        }
		public override void Execute(EditorRefactoringContext context)
		{
			CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;
			if (parseInformation != null) {
				SyntaxTree st = parseInformation.SyntaxTree;
				Identifier identifier = (Identifier) st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
				if (identifier == null)
					return;
				
				ICompilation compilation = context.GetCompilation();
				IProject project = compilation.GetProject();
				RenameFile(project, context.FileName, Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(identifier.Name)));
				if (project != null) {
					project.Save();
				}
			}
		}
		public override async Task<bool> IsAvailableAsync(EditorRefactoringContext context, System.Threading.CancellationToken cancellationToken)
		{
			SyntaxTree st = await context.GetSyntaxTreeAsync().ConfigureAwait(false);
			Identifier identifier = (Identifier) st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
			if (identifier == null)
				return false;
			ParameterDeclaration parameterDeclaration = identifier.Parent as ParameterDeclaration;
			if (parameterDeclaration == null)
				return false;
			ICompilation compilation = await context.GetCompilationAsync().ConfigureAwait(false);
			ITypeReference typeRef = parameterDeclaration.Type.ToTypeReference();
			if (typeRef == null)
				return false;
			IType type = typeRef.Resolve(compilation);
			if (type == null)
				return false;
			return type.HasRange();
		}
Ejemplo n.º 35
0
 public static Task <CSharpAstResolver> GetAstResolverAsync(this EditorRefactoringContext editorContext)
 {
     return(editorContext.GetCachedAsync(
                async ec => {
         var parseInfo = (await ec.GetParseInformationAsync().ConfigureAwait(false)) as CSharpFullParseInformation;
         var compilation = await ec.GetCompilationAsync().ConfigureAwait(false);
         if (parseInfo != null)
         {
             return parseInfo.GetResolver(compilation);
         }
         else
         {
             return new CSharpAstResolver(compilation, new SyntaxTree(), new CSharpUnresolvedFile {
                 FileName = ec.FileName
             });
         }
     }));
 }
Ejemplo n.º 36
0
        static ContextActionsPopup MakePopupWithClipboardOptions(EditorRefactoringContext context)
        {
            var popupViewModel = new ContextActionsPopupViewModel();
            var actions        = BuildClipboardRingData(context);

            string labelSource = "${res:SharpDevelop.SideBar.ClipboardRing}";

            if (actions == null || actions.Count == 0)
            {
                labelSource = "${res:SharpDevelop.Refactoring.ClipboardRingEmpty}";
            }

            popupViewModel.Title   = MenuService.ConvertLabel(StringParser.Parse(labelSource));
            popupViewModel.Actions = actions;
            return(new ClipboardRingPopup {
                Actions = popupViewModel
            });
        }
Ejemplo n.º 37
0
        Task <IContextAction[]> IContextActionProvider.GetAvailableActionsAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
        {
            List <IContextAction> result = new List <IContextAction>();

            if (existingResults != null)
            {
                var markers = markerService.GetMarkersAtOffset(context.CaretOffset);
                foreach (var tag in markers.Select(m => m.Tag).OfType <InspectionTag>())
                {
                    result.AddRange(tag.Actions);
                    string issueName;
                    if (CanSuppress(tag, out issueName))
                    {
                        result.Add(new SuppressIssueContextAction(issueName));
                    }
                }
            }
            return(Task.FromResult(result.ToArray()));
        }
		public override void Execute(EditorRefactoringContext context)
		{
			CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;
			if (parseInformation != null) {
				SyntaxTree st = parseInformation.SyntaxTree;
				Identifier identifier = (Identifier) st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
				if (identifier == null)
					return;
				ParameterDeclaration parameterDeclaration = identifier.Parent as ParameterDeclaration;
				if (parameterDeclaration == null)
					return;
				
				AstNode grandparent = identifier.Parent.Parent;
				if ((grandparent is MethodDeclaration) || (grandparent is ConstructorDeclaration)) {
					// Range check condition
					var rangeCheck = new IfElseStatement(
						new BinaryOperatorExpression(
							new BinaryOperatorExpression(new IdentifierExpression(identifier.Name), BinaryOperatorType.LessThan, new IdentifierExpression("lower")),
							BinaryOperatorType.ConditionalOr,
							new BinaryOperatorExpression(new IdentifierExpression(identifier.Name), BinaryOperatorType.GreaterThan, new IdentifierExpression("upper"))
						),
						new ThrowStatement(
							new ObjectCreateExpression(
								new SimpleType("ArgumentOutOfRangeException"),
								new List<Expression>() { new PrimitiveExpression(identifier.Name, '"' + identifier.Name + '"'), new IdentifierExpression(identifier.Name), new BinaryOperatorExpression(new PrimitiveExpression("Value must be between "), BinaryOperatorType.Add, new BinaryOperatorExpression(new IdentifierExpression("lower"), BinaryOperatorType.Add, new BinaryOperatorExpression(new PrimitiveExpression(" and "), BinaryOperatorType.Add, new IdentifierExpression("upper")))) }
							)
						)
					);
					
					// Add range check as first statement in method's/constructor's body
					var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
					using (Script script = refactoringContext.StartScript()) {
						if (grandparent is MethodDeclaration) {
							var methodDeclaration = (MethodDeclaration) grandparent;
							script.AddTo(methodDeclaration.Body, rangeCheck);
						} else if (grandparent is ConstructorDeclaration) {
							var ctorDeclaration = (ConstructorDeclaration) grandparent;
							script.AddTo(ctorDeclaration.Body, rangeCheck);
						}
					}
				}
			}
		}
Ejemplo n.º 39
0
        public override string GetDisplayName(EditorRefactoringContext context)
        {
            CSharpFullParseInformation parseInformation = context.GetParseInformation() as CSharpFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return(DisplayName);
                }

                return(StringParser.Parse("${res:SharpDevelop.Refactoring.MoveClassToFile}",
                                          new StringTagPair("FileName", MakeValidFileName(identifier.Name))));
            }

            return(DisplayName);
        }
Ejemplo n.º 40
0
        public override void Execute(EditorRefactoringContext context)
        {
            AlFullParseInformation parseInformation = context.GetParseInformation() as AlFullParseInformation;

            if (parseInformation != null)
            {
                SyntaxTree st         = parseInformation.SyntaxTree;
                Identifier identifier = (Identifier)st.GetNodeAt(context.CaretLocation, node => node.Role == Roles.Identifier);
                if (identifier == null)
                {
                    return;
                }

                ICompilation compilation = context.GetCompilation();
                IProject     project     = compilation.GetProject();
                RenameFile(project, context.FileName, Path.Combine(Path.GetDirectoryName(context.FileName), MakeValidFileName(identifier.Name)));
                if (project != null)
                {
                    project.Save();
                }
            }
        }
Ejemplo n.º 41
0
 public void Execute(EditorRefactoringContext context)
 {
     SD.FileService.JumpToFilePosition(new FileName(target.FileName), target.BeginLine, target.BeginColumn);
 }
Ejemplo n.º 42
0
 public string GetDisplayName(EditorRefactoringContext context)
 {
     return(DisplayName);
 }
Ejemplo n.º 43
0
 public void Execute(EditorRefactoringContext context)
 {
     SD.FileService.JumpToFilePosition(new FileName(target.FileName), target.BeginLine, target.BeginColumn);
 }
Ejemplo n.º 44
0
		public string GetDisplayName(EditorRefactoringContext context)
		{
			return DisplayName;
		}
			public Task<IContextAction[]> GetAvailableActionsAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
			{
				ITextEditor editor = context.Editor;
				// grab SelectionStart/SelectionLength while we're still on the main thread
				int selectionStart = editor.SelectionStart;
				int selectionLength = editor.SelectionLength;
				return Task.Run(
					async delegate {
						try {
							if (!CreateCodeActionProvider())
								return new IContextAction[0];
							CSharpAstResolver resolver = await context.GetAstResolverAsync().ConfigureAwait(false);
							var refactoringContext = new SDRefactoringContext(context.TextSource, resolver, context.CaretLocation, selectionStart, selectionLength, cancellationToken);
							return codeActionProvider.GetActions(refactoringContext).Select(Wrap).ToArray();
						} catch (Exception ex) {
							SD.Log.WarnFormatted("CSharpContextActionProviderWrapper crashed: {0}", ex);
							SD.AnalyticsMonitor.TrackException(ex);
							return new IContextAction[0];
						}
					}, cancellationToken);
			}
Ejemplo n.º 46
0
			public override Task<bool> IsAvailableAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
			{
				return Task.FromResult(true);
			}
Ejemplo n.º 47
0
 public override Task <bool> IsAvailableAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
 {
     return(Task.FromResult(true));
 }
Ejemplo n.º 48
0
		/// <summary>
		/// Gets whether this context action is available in the given context.
		/// </summary>
		/// <remarks><inheritdoc cref="IContextActionsProvider.GetAvailableActionsAsync"/></remarks>
		public abstract Task<bool> IsAvailableAsync(EditorRefactoringContext context, CancellationToken cancellationToken);
Ejemplo n.º 49
0
		public abstract void Execute(EditorRefactoringContext context);
Ejemplo n.º 50
0
		Task<IContextAction[]> IContextActionProvider.GetAvailableActionsAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
		{
			List<IContextAction> result = new List<IContextAction>();
			if (existingResults != null) {
				var markers = markerService.GetMarkersAtOffset(context.CaretOffset);
				foreach (var tag in markers.Select(m => m.Tag).OfType<InspectionTag>()) {
					result.AddRange(tag.Actions);
				}
			}
			return Task.FromResult(result.ToArray());
		}
Ejemplo n.º 51
0
 public string GetDisplayName(EditorRefactoringContext context)
 {
     return(Path.GetFileName(target.FileName));
 }
Ejemplo n.º 52
0
 public string GetDisplayName(EditorRefactoringContext context)
 {
     return Path.GetFileName(target.FileName);
 }
Ejemplo n.º 53
0
			public override void Execute(EditorRefactoringContext context)
			{
				SD.AnalyticsMonitor.TrackFeature(typeof(SuppressIssueContextAction), issueName);
				var lineNo = context.CaretLocation.Line;
				var document = context.Editor.Document;
				
				var line = document.GetLineByNumber(lineNo);
				string indentation = DocumentUtilities.GetIndentation(document, lineNo);
				string newLine = DocumentUtilities.GetLineTerminator(document, lineNo);
				document.Insert(line.Offset, indentation + "// disable once " + issueName + newLine);
			}
			public Task<IContextAction[]> GetAvailableActionsAsync(EditorRefactoringContext context, CancellationToken cancellationToken)
			{
				ITextEditor editor = context.Editor;
				// grab SelectionStart/SelectionLength while we're still on the main thread
				int selectionStart = editor.SelectionStart;
				int selectionLength = editor.SelectionLength;
				return Task.Run(
					async delegate {
						if (!CreateCodeActionProvider())
							return new IContextAction[0];
						CSharpAstResolver resolver = await context.GetAstResolverAsync().ConfigureAwait(false);
						var refactoringContext = new SDRefactoringContext(context.TextSource, resolver, context.CaretLocation, selectionStart, selectionLength, cancellationToken);
						return codeActionProvider.GetActions(refactoringContext).Select(Wrap).ToArray();
					}, cancellationToken);
			}
Ejemplo n.º 55
0
 public void Execute(EditorRefactoringContext context)
 {
     NavigationService.NavigateTo(this.Entity);
 }
		void RemoveExtractedNode(EditorRefactoringContext context, EntityDeclaration node)
		{
			IDocument document = context.Editor.Document;
			int start = document.GetOffset(node.StartLocation);
			int end   = document.GetOffset(node.EndLocation);
			document.Remove(start, end - start);
		}
Ejemplo n.º 57
0
			public override void Execute(EditorRefactoringContext context)
			{
				var myContext = SDRefactoringContext.Create(context.Editor, default(CancellationToken));
				var currentNode = myContext.RootNode.GetNodeAt<Statement>(context.CaretLocation);
				if (currentNode == null)
					return;
				using (var script = myContext.StartScript()) {
					script.InsertBefore(currentNode, new Comment(string.Format(" disable{1}{0}", issueName, type == SuppressType.Once ? " once " : " ")));
				}
			}
Ejemplo n.º 58
0
		public void Execute(EditorRefactoringContext context)
		{
			NavigationService.NavigateTo(this.Entity);
		}