Example #1
0
        public override IEnumerable <MonoDevelop.CodeActions.CodeAction> GetActions(MonoDevelop.Ide.Gui.Document document, TextLocation loc, CancellationToken cancellationToken)
        {
            var context = new MDRefactoringContext(document, loc);

            if (context.IsInvalid || context.RootNode == null)
            {
                yield break;
            }
            var actions = provider.GetActions(context);

            if (actions == null)
            {
                LoggingService.LogWarning(provider + " returned null actions.");
                yield break;
            }
            int num = 0;

            foreach (var action_ in actions)
            {
                var action = action_;
                if (actionId.Count <= num)
                {
                    actionId.Add(provider.GetType().FullName + "'" + num);
                }
                yield return(new NRefactoryCodeAction(actionId[num], GettextCatalog.GetString(action.Description ?? ""), action));

                num++;
            }
        }
Example #2
0
        public override void Run(Document document, TextLocation loc)
        {
            var context = new MDRefactoringContext(document, loc);

            using (var script = context.StartScript())
                act.Run(script);
        }
		public MDRefactoringScript (MDRefactoringContext context, CSharpFormattingOptions formattingOptions) : base(context.TextEditor.Document, formattingOptions, context.TextEditor.CreateNRefactoryTextEditorOptions ())
		{
			this.context = context;
			undoGroup  = this.context.TextEditor.OpenUndoGroup ();
			this.startVersion = this.context.TextEditor.Version;

		}
Example #4
0
        static void CreateNewFile(MDRefactoringContext context, TypeDeclaration type, string correctFileName)
        {
            var content = context.TextEditor.Text;

            var types = new List <EntityDeclaration> (context.Unit.GetTypes().Where(t => t.StartLocation != type.StartLocation));

            types.Sort((x, y) => y.StartLocation.CompareTo(x.StartLocation));

            foreach (var removeType in types)
            {
                var start = context.GetOffset(removeType.StartLocation);
                var end   = context.GetOffset(removeType.EndLocation);
                content = content.Remove(start, end - start);
            }

            if (context.Project != null)
            {
                string header = StandardHeaderService.GetHeader(context.Project, correctFileName, true);
                if (!string.IsNullOrEmpty(header))
                {
                    content = header + context.TextEditor.EolMarker + StripHeader(content);
                }
            }
            content = StripDoubleBlankLines(content);

            File.WriteAllText(correctFileName, content);
            context.Project.AddFile(correctFileName);
            MonoDevelop.Ide.IdeApp.ProjectOperations.Save(context.Project);
        }
		public override IEnumerable<CodeIssue> GetIssues (Document document, CancellationToken cancellationToken)
		{
			var context = new MDRefactoringContext (document, document.Editor.Caret.Location, cancellationToken);
			if (context.IsInvalid || context.RootNode == null)
				yield break;
			foreach (var action in issueProvider.GetIssues (context)) {
				if (cancellationToken.IsCancellationRequested)
					yield break;
				if (action.Actions == null) {
					LoggingService.LogError ("NRefactory actions == null in :" + Title);
					continue;
				}
				var actions = new List<MonoDevelop.CodeActions.CodeAction> ();
				foreach (var act in action.Actions) {
					if (cancellationToken.IsCancellationRequested)
						yield break;
					if (act == null) {
						LoggingService.LogError ("NRefactory issue action was null in :" + Title);
						continue;
					}
					actions.Add (new NRefactoryCodeAction (providerIdString, act.Description, act));
				}
				var issue = new CodeIssue (
					GettextCatalog.GetString (action.Description ?? ""),
					action.Start,
					action.End,
					actions
				);
				yield return issue;
			}
		}
		protected IEnumerable<MonoDevelop.CodeActions.CodeAction> GetActions (MDRefactoringContext context)
		{
			if (context.IsInvalid)
				yield break;
			var type = GetTypeDeclaration (context);
			if (type == null)
				yield break;
			if (Path.GetFileNameWithoutExtension (context.Document.FileName) == type.Name)
				yield break;
			string title;
			if (IsSingleType (context)) {
				title = String.Format (GettextCatalog.GetString ("_Rename file to '{0}'"), Path.GetFileName (GetCorrectFileName (context, type)));
			} else {
				title = String.Format (GettextCatalog.GetString ("_Move type to file '{0}'"), Path.GetFileName (GetCorrectFileName (context, type)));
			}
			yield return new MonoDevelop.CodeActions.DefaultCodeAction (title, (d, l) => {
				var ctx = new MDRefactoringContext (d, l);
				string correctFileName = GetCorrectFileName (ctx, type);
				if (IsSingleType (ctx)) {
					FileService.RenameFile (ctx.Document.FileName, correctFileName);
					if (ctx.Document.Project != null)
						ctx.Document.Project.Save (new NullProgressMonitor ());
					return;
				}
				
				CreateNewFile (ctx, type, correctFileName);
				using (var script = ctx.StartScript ()) {
					script.Remove (type);
				}
			});
		}
Example #7
0
 public MDRefactoringScript(MDRefactoringContext context, Document document, CSharpFormattingOptions formattingOptions) : base(document.Editor.Document, formattingOptions, document.Editor.CreateNRefactoryTextEditorOptions())
 {
     this.context      = context;
     this.document     = document;
     undoGroup         = this.document.Editor.OpenUndoGroup();
     this.startVersion = this.document.Editor.Version;
 }
Example #8
0
 internal static string GetCorrectFileName(MDRefactoringContext context, EntityDeclaration type)
 {
     if (type == null)
     {
         return(context.TextEditor.FileName);
     }
     return(Path.Combine(Path.GetDirectoryName(context.TextEditor.FileName), type.Name + Path.GetExtension(context.TextEditor.FileName)));
 }
		public override void BatchRun (Document document, TextLocation loc)
		{
			base.BatchRun (document, loc);
			var context = new MDRefactoringContext (document, loc);
			using (var script = context.StartScript ()) {
				foreach (var action in SiblingActions) {
					context.SetLocation (action.Start);
					action.Run (script);
				}
			}
		}
Example #10
0
        public override void DoGlobalOperationOn(IEntity entity, Action <RefactoringContext, Script, AstNode> callback, string operationName = null)
        {
            using (var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(operationName ?? GettextCatalog.GetString("Performing refactoring task..."), null)) {
                var col = ReferenceFinder.FindReferences(entity, true, monitor);

                string oldFileName          = null;
                MDRefactoringContext ctx    = null;
                MDRefactoringScript  script = null;
                TextEditorData       data   = null;
                bool hadBom = false;
                System.Text.Encoding encoding = null;
                bool isOpen = true;

                foreach (var r in col)
                {
                    var memberRef = r as CSharpReferenceFinder.CSharpMemberReference;
                    if (memberRef == null)
                    {
                        continue;
                    }

                    if (oldFileName != memberRef.FileName)
                    {
                        if (oldFileName != null && !isOpen)
                        {
                            script.Dispose();
                            Mono.TextEditor.Utils.TextFileUtility.WriteText(oldFileName, data.Text, encoding, hadBom);
                        }

                        data = TextFileProvider.Instance.GetTextEditorData(memberRef.FileName, out hadBom, out encoding, out isOpen);
                        var project = memberRef.Project;

                        ParsedDocument parsedDocument;
                        using (var reader = new StreamReader(data.OpenStream()))
                            parsedDocument = new MonoDevelop.CSharp.Parser.TypeSystemParser().Parse(true, memberRef.FileName, reader, project);
                        var resolver = new CSharpAstResolver(TypeSystemService.GetCompilation(project), memberRef.SyntaxTree, parsedDocument.ParsedFile as CSharpUnresolvedFile);

                        ctx         = new MDRefactoringContext(project as DotNetProject, data, parsedDocument, resolver, memberRef.AstNode.StartLocation, this.context.CancellationToken);
                        script      = new MDRefactoringScript(ctx, FormattingOptions);
                        oldFileName = memberRef.FileName;
                    }

                    callback(ctx, script, memberRef.AstNode);
                }

                if (oldFileName != null && !isOpen)
                {
                    script.Dispose();
                    Mono.TextEditor.Utils.TextFileUtility.WriteText(oldFileName, data.Text, encoding, hadBom);
                }
            }
        }
Example #11
0
        public override void BatchRun(Document document, TextLocation loc)
        {
            base.BatchRun(document, loc);
            var context = new MDRefactoringContext(document, loc);

            using (var script = context.StartScript()) {
                foreach (var action in SiblingActions)
                {
                    context.SetLocation(action.Start);
                    action.Run(script);
                }
            }
        }
Example #12
0
        TypeDeclaration GetTypeDeclaration(MDRefactoringContext context)
        {
            var result = context.GetNode <TypeDeclaration> ();

            if (result == null || result.Parent is TypeDeclaration)
            {
                return(null);
            }
            if (result != null && result.NameToken.Contains(context.Location))
            {
                return(result);
            }
            return(null);
        }
Example #13
0
        protected IEnumerable <MonoDevelop.CodeActions.CodeAction> GetActions(MDRefactoringContext context)
        {
            if (context.IsInvalid)
            {
                yield break;
            }
            var type = GetTypeDeclaration(context);

            if (type == null)
            {
                yield break;
            }
            if (Path.GetFileNameWithoutExtension(context.Document.FileName) == type.Name)
            {
                yield break;
            }
            string title;

            if (IsSingleType(context))
            {
                title = String.Format(GettextCatalog.GetString("_Rename file to '{0}'"), Path.GetFileName(GetCorrectFileName(context, type)));
            }
            else
            {
                title = String.Format(GettextCatalog.GetString("_Move type to file '{0}'"), Path.GetFileName(GetCorrectFileName(context, type)));
            }
            yield return(new MonoDevelop.CodeActions.DefaultCodeAction(title, (d, l) =>
            {
                var ctx = new MDRefactoringContext(d, l);
                string correctFileName = GetCorrectFileName(ctx, type);
                if (IsSingleType(ctx))
                {
                    FileService.RenameFile(ctx.Document.FileName, correctFileName);
                    if (ctx.Document.Project != null)
                    {
                        ctx.Document.Project.Save(new NullProgressMonitor());
                    }
                    return;
                }

                CreateNewFile(ctx, type, correctFileName);
                using (var script = ctx.StartScript())
                {
                    script.Remove(type);
                }
            }));
        }
        public override void BatchRun(Document document, TextLocation loc)
        {
            base.BatchRun(document, loc);
            var context = MDRefactoringContext.Create(document, loc).Result;

            if (context == null)
            {
                return;
            }
            using (var script = context.StartScript()) {
                foreach (var action in SiblingActions)
                {
                    context.SetLocation(action.DocumentRegion.Begin);
                    action.Run(context, script);
                }
            }
        }
		public override IEnumerable<MonoDevelop.CodeActions.CodeAction> GetActions (MonoDevelop.Ide.Gui.Document document, TextLocation loc, CancellationToken cancellationToken)
		{
			var context = new MDRefactoringContext (document, loc);
			if (context.IsInvalid || context.RootNode == null)
				yield break;
			var actions = provider.GetActions (context);
			if (actions == null) {
				LoggingService.LogWarning (provider + " returned null actions.");
				yield break;
			}
			int num = 0;
			foreach (var action_ in actions) {
				var action = action_;
				if (actionId.Count <= num) {
					actionId.Add (provider.GetType ().FullName + "'" + num);
				}
				yield return new NRefactoryCodeAction (actionId[num], GettextCatalog.GetString (action.Description ?? ""), action);
				num++;
			}
		}
		public override IEnumerable<CodeIssue> GetIssues (Document document, CancellationToken cancellationToken)
		{
			var context = new MDRefactoringContext (document, document.Editor.Caret.Location, cancellationToken);
			if (context.IsInvalid || context.RootNode == null)
				yield break;
			int issueNum = 0;
			foreach (var action in issueProvider.GetIssues (context)) {
				if (cancellationToken.IsCancellationRequested)
					yield break;
				if (action.Actions == null) {
					LoggingService.LogError ("NRefactory actions == null in :" + Title);
					continue;
				}
				if (actionIdList.Count <= issueNum)
					actionIdList.Add (new List<string> ());
				var actionId = actionIdList [issueNum];
				int actionNum = 0;
				
				var actions = new List<MonoDevelop.CodeActions.CodeAction> ();
				foreach (var act in action.Actions) {
					if (cancellationToken.IsCancellationRequested)
						yield break;
					if (act == null) {
						LoggingService.LogError ("NRefactory issue action was null in :" + Title);
						continue;
					}
					if (actionId.Count <= actionNum)
						actionId.Add (issueProvider.GetType ().FullName + "'" + issueNum + "'" + actionNum);
					actions.Add (new NRefactoryCodeAction (actionId[actionNum], act.Description, act));
					actionNum++;
				}
				var issue = new CodeIssue (
					GettextCatalog.GetString (action.Description ?? ""),
					action.Start,
					action.End,
					actions
				);
				yield return issue;
				issueNum ++;
			}
		}
Example #17
0
        public override void DoGlobalOperationOn(IEnumerable <IEntity> entities, Action <RefactoringContext, Script, IEnumerable <AstNode> > callback, string operationName = null)
        {
            using (var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor(operationName ?? GettextCatalog.GetString("Performing refactoring task..."), null)) {
                var col = entities.SelectMany(entity => ReferenceFinder.FindReferences(entity, true, monitor)).OfType <CSharpReferenceFinder.CSharpMemberReference> ().GroupBy(reference => reference.FileName);

                foreach (var r in col)
                {
                    string filename = r.Key;

                    bool isOpen;
                    System.Text.Encoding encoding;
                    bool hadBom;

                    var data = TextFileProvider.Instance.GetTextEditorData(filename, out hadBom, out encoding, out isOpen);

                    var firstReference = r.First();

                    var project = firstReference.Project;

                    ParsedDocument parsedDocument;
                    using (var reader = new StreamReader(data.OpenStream()))
                        parsedDocument = new MonoDevelop.CSharp.Parser.TypeSystemParser().Parse(true, filename, reader, project);

                    var resolver = new CSharpAstResolver(TypeSystemService.GetCompilation(project), firstReference.SyntaxTree, parsedDocument.ParsedFile as CSharpUnresolvedFile);

                    var ctx    = new MDRefactoringContext(project as DotNetProject, data, parsedDocument, resolver, firstReference.AstNode.StartLocation, this.context.CancellationToken);
                    var script = new MDRefactoringScript(ctx, FormattingOptions);

                    callback(ctx, script, r.Select(reference => reference.AstNode));

                    if (!isOpen)
                    {
                        script.Dispose();
                        Mono.TextEditor.Utils.TextFileUtility.WriteText(filename, data.Text, encoding, hadBom);
                    }
                }
            }
        }
		static void CreateNewFile (MDRefactoringContext context, TypeDeclaration type, string correctFileName)
		{
			var content = context.Document.Editor.Text;
			
			var types = new List<EntityDeclaration> (context.Unit.GetTypes ().Where (t => t.StartLocation != type.StartLocation));
			types.Sort ((x, y) => y.StartLocation.CompareTo (x.StartLocation));

			foreach (var removeType in types) {
				var start = context.GetOffset (removeType.StartLocation);
				var end = context.GetOffset (removeType.EndLocation);
				content = content.Remove (start, end - start);
			}
			
			if (context.Document.Project is MonoDevelop.Projects.DotNetProject) {
				string header = StandardHeaderService.GetHeader (context.Document.Project, correctFileName, true);
				if (!string.IsNullOrEmpty (header))
					content = header + context.Document.Editor.EolMarker + StripHeader (content);
			}
			content = StripDoubleBlankLines (content);
			
			File.WriteAllText (correctFileName, content);
			context.Document.Project.AddFile (correctFileName);
			MonoDevelop.Ide.IdeApp.ProjectOperations.Save (context.Document.Project);
		}
		TypeDeclaration GetTypeDeclaration (MDRefactoringContext context)
		{
			var result = context.GetNode<TypeDeclaration> ();
			if (result == null || result.Parent is TypeDeclaration)
				return null;
			if (result != null && result.NameToken.Contains (context.Location))
				return result;
			return null;
		}
		internal static string GetCorrectFileName (MDRefactoringContext context, EntityDeclaration type)
		{
			if (type == null)
				return context.Document.FileName;
			return Path.Combine (Path.GetDirectoryName (context.Document.FileName), type.Name + Path.GetExtension (context.Document.FileName));
		}
		internal IEnumerable<CodeIssue> ToMonoDevelopRepresentation (CancellationToken cancellationToken, MDRefactoringContext context, IEnumerable<ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue> issues)
		{
			var actionGroups = new Dictionary<object, IList<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction>> ();
			foreach (var issue in issues) {
				if (cancellationToken.IsCancellationRequested)
					yield break;
				if (issue.Actions == null) {
					LoggingService.LogError ("NRefactory actions == null in :" + Title);
					continue;
				}
				var actions = new List<NRefactoryCodeAction> ();
				foreach (var act in GetActions(issue, context)) {
					if (cancellationToken.IsCancellationRequested)
						yield break;
					if (act == null) {
						LoggingService.LogError ("NRefactory issue action was null in :" + Title);
						continue;
					}
					var nrefactoryCodeAction = new NRefactoryCodeAction (IdString, act.Description, act, act.SiblingKey);
					if (act.SiblingKey != null) {
						// make sure the action has a list of its siblings
						IList<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> siblingGroup;
						if (!actionGroups.TryGetValue (act.SiblingKey, out siblingGroup)) {
							siblingGroup = new List<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> ();
							actionGroups.Add (act.SiblingKey, siblingGroup);
						}
						siblingGroup.Add (act);
						nrefactoryCodeAction.SiblingActions = siblingGroup;
					}
					actions.Add (nrefactoryCodeAction);
				}
				yield return new CodeIssue (issue.IssueMarker, GettextCatalog.GetString (issue.Description ?? ""), context.TextEditor.FileName, issue.Start, issue.End, IdString, actions);
			}
		}	
		bool IsSingleType (MDRefactoringContext context)
		{
			return context.Unit.GetTypes ().Count () == 1;
		}
		internal IEnumerable<CodeIssue> ToMonoDevelopRepresentation (CancellationToken cancellationToken, MDRefactoringContext context, IEnumerable<ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue> issues)
		{
			var actionGroups = new Dictionary<object, IList<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction>> ();
			foreach (var issue in issues) {
				if (cancellationToken.IsCancellationRequested)
					yield break;
				if (issue.Actions == null) {
					LoggingService.LogError ("NRefactory actions == null in :" + Title);
					continue;
				}
				var actions = new List<NRefactoryCodeAction> ();
				foreach (var nrefactoryCodeAction in GetActions(issue, context)) {
					if (cancellationToken.IsCancellationRequested)
						yield break;
					if (nrefactoryCodeAction == null) {
						LoggingService.LogError ("NRefactory issue action was null in :" + Title);
						continue;
					}
					actions.Add (nrefactoryCodeAction);
				}
				yield return new CodeIssue (issue.IssueMarker, GettextCatalog.GetString (issue.Description ?? ""), context.TextEditor.FileName, issue.Start, issue.End, IdString, actions) {
					ActionProvider = issue.ActionProvider
				};
			}
		}	
		IEnumerable<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> GetActions (ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue issue, MDRefactoringContext context)
		{
			foreach (var action in issue.Actions)
				yield return action;
			if (boundActionProvider != null) {
				// We need to se the correct location here. Seems very fragile to do so...
				context.SetLocation (issue.Start);
				foreach (var action in boundActionProvider.GetActions (context)) {
					yield return action;
				}
			}
		}
		IEnumerable<NRefactoryCodeAction> GetActions (ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue issue, MDRefactoringContext context)
		{
			foreach (var action in issue.Actions)
				yield return new NRefactoryCodeAction (IdString, action.Description, action, action.SiblingKey);

			if (issue.ActionProvider != null) {
				foreach (var provider in issue.ActionProvider) {
					var boundActionProvider = (ICSharpCode.NRefactory.CSharp.Refactoring.CodeActionProvider)Activator.CreateInstance (provider);
					context.SetLocation (issue.Start);
					foreach (var action in boundActionProvider.GetActions (context)) {
						yield return new NRefactoryCodeAction (provider.FullName, action.Description, action, action.SiblingKey);
					}
				}
			}
			/*
			var nrefactoryCodeAction = new NRefactoryCodeAction (IdString, act.Description, act, act.SiblingKey);
			if (act.SiblingKey != null) {
				// make sure the action has a list of its siblings
				IList<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> siblingGroup;
				if (!actionGroups.TryGetValue (act.SiblingKey, out siblingGroup)) {
					siblingGroup = new List<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> ();
					actionGroups.Add (act.SiblingKey, siblingGroup);
				}
				siblingGroup.Add (act);
				nrefactoryCodeAction.SiblingActions = siblingGroup;
			}
			*/
		}
		IEnumerable<NRefactoryCodeAction> GetActions (ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue issue, MDRefactoringContext context)
		{
			foreach (var action in issue.Actions)
				yield return new NRefactoryCodeAction (IdString, action.Description, action, action.SiblingKey);

			if (issue.ActionProvider != null) {
				foreach (var provider in issue.ActionProvider) {
					var boundActionProvider = (ICSharpCode.NRefactory.CSharp.Refactoring.CodeActionProvider)Activator.CreateInstance (provider);
					context.SetLocation (issue.Start);
					foreach (var action in boundActionProvider.GetActions (context)) {
						yield return new NRefactoryCodeAction (provider.FullName, action.Description, action, action.SiblingKey);
					}
				}
			}
		}
		public override void DoGlobalOperationOn (IEnumerable<IEntity> entities, Action<RefactoringContext, Script, IEnumerable<AstNode>> callback, string operationName = null)
		{
			using (var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (operationName ?? GettextCatalog.GetString ("Performing refactoring task..."), null)) {
				var col = entities.SelectMany (entity => ReferenceFinder.FindReferences (entity, true, monitor)).OfType<CSharpReferenceFinder.CSharpMemberReference> ().GroupBy(reference => reference.FileName);

				foreach (var r in col) {
					string filename = r.Key;

					bool isOpen;
					System.Text.Encoding encoding;
					bool hadBom;

					var data = TextFileProvider.Instance.GetTextEditorData (filename, out hadBom, out encoding, out isOpen);

					var firstReference = r.First ();

					var project = firstReference.Project;

					ParsedDocument parsedDocument;
					using (var reader = new StreamReader (data.OpenStream ()))
						parsedDocument = new MonoDevelop.CSharp.Parser.TypeSystemParser ().Parse (true, filename, reader, project);

					var resolver = new CSharpAstResolver (TypeSystemService.GetCompilation (project), firstReference.SyntaxTree, parsedDocument.ParsedFile as CSharpUnresolvedFile);

					var ctx = new MDRefactoringContext (project as DotNetProject, data, parsedDocument, resolver, firstReference.AstNode.StartLocation, this.context.CancellationToken);
					var script = new MDRefactoringScript (ctx, FormattingOptions);

					callback (ctx, script, r.Select (reference => reference.AstNode));

					if (!isOpen) {
						script.Dispose ();
						Mono.TextEditor.Utils.TextFileUtility.WriteText (filename, data.Text, encoding, hadBom);
					}
				}
			}
		}
		public override void DoGlobalOperationOn (IEntity entity, Action<RefactoringContext, Script, AstNode> callback, string operationName = null)
		{
			using (var monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (operationName ?? GettextCatalog.GetString ("Performing refactoring task..."), null)) {
				var col = ReferenceFinder.FindReferences (entity, true, monitor);

				string oldFileName = null;
				MDRefactoringContext ctx = null;
				MDRefactoringScript script = null;
				TextEditorData data = null;
				bool hadBom = false;
				System.Text.Encoding encoding = null;
				bool isOpen = true;

				foreach (var r in col) {
					var memberRef = r as CSharpReferenceFinder.CSharpMemberReference;
					if (memberRef == null)
						continue;

					if (oldFileName != memberRef.FileName) {
						if (oldFileName != null && !isOpen) {
							script.Dispose ();
							Mono.TextEditor.Utils.TextFileUtility.WriteText (oldFileName, data.Text, encoding, hadBom);
						}

						data = TextFileProvider.Instance.GetTextEditorData (memberRef.FileName, out hadBom, out encoding, out isOpen);
						var project = memberRef.Project;

						ParsedDocument parsedDocument;
						using (var reader = new StreamReader (data.OpenStream ()))
							parsedDocument = new MonoDevelop.CSharp.Parser.TypeSystemParser ().Parse (true, memberRef.FileName, reader, project);
						var resolver = new CSharpAstResolver (TypeSystemService.GetCompilation (project), memberRef.SyntaxTree, parsedDocument.ParsedFile as CSharpUnresolvedFile);

						ctx = new MDRefactoringContext (project as DotNetProject, data, parsedDocument, resolver, memberRef.AstNode.StartLocation, this.context.CancellationToken);
						script = new MDRefactoringScript (ctx, FormattingOptions);
						oldFileName = memberRef.FileName;
					}

					callback (ctx, script, memberRef.AstNode);
				}

				if (oldFileName != null && !isOpen) {
					script.Dispose ();
					Mono.TextEditor.Utils.TextFileUtility.WriteText (oldFileName, data.Text, encoding, hadBom);
				}
			}
		}
		internal static string GenerateMemberCode (MDRefactoringContext ctx, TypeSystemAstBuilder builder, IMember member)
		{
			var method = builder.ConvertEntity (member) as MethodDeclaration;
			if (method != null) {
				method.Body = new BlockStatement {
					new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException")))
				};
				method.Modifiers &= ~Modifiers.Virtual;
				method.Modifiers &= ~Modifiers.Abstract;
				method.Attributes.Add (new AttributeSection {
					Attributes =  {
						GenerateExportAttribute (ctx, member)
					}
				});
				return method.ToString (ctx.FormattingOptions);
			}
			var property = builder.ConvertEntity (member) as PropertyDeclaration;
			if (property == null)
				return null;
			var p = (IProperty)member;
			property.Modifiers &= ~Modifiers.Virtual;
			property.Modifiers &= ~Modifiers.Abstract;
			if (p.CanGet) {
				property.Getter.Body = new BlockStatement {
					new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException")))
				};
				property.Getter.Attributes.Add (new AttributeSection {
					Attributes =  {
						GenerateExportAttribute (ctx, p.Getter)
					}
				});
			}
			if (p.CanSet) {
				property.Setter.Body = new BlockStatement {
					new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException")))
				};
				property.Setter.Attributes.Add (new AttributeSection {
					Attributes =  {
						GenerateExportAttribute (ctx, p.Setter)
					}
				});
			}
			return property.ToString (ctx.FormattingOptions);
		}
Example #30
0
        public override Task <Script> InsertWithCursor(string operation, ITypeDefinition parentType, Func <Script, RefactoringContext, IList <AstNode> > nodeCallback)
        {
            var tcs = new TaskCompletionSource <Script>();

            if (parentType == null)
            {
                return(tcs.Task);
            }
            var part = parentType.Parts.FirstOrDefault();

            if (part == null)
            {
                return(tcs.Task);
            }

            var loadedDocument = IdeApp.Workbench.OpenDocument(new FileOpenInformation(part.Region.FileName, null));

            loadedDocument.RunWhenLoaded(delegate {
                var editor         = loadedDocument.Editor;
                var loc            = part.Region.Begin;
                var parsedDocument = loadedDocument.UpdateParseDocument();
                var declaringType  = parsedDocument.GetInnermostTypeDefinition(loc);
                MDRefactoringScript script;

                if (loadedDocument.Editor != context.TextEditor)
                {
                    script = new MDRefactoringScript(MDRefactoringContext.Create(loadedDocument, loc, context.CancellationToken).Result, FormattingOptions);
                    startedScripts.Add(script);
                }
                else
                {
                    script = this;
                }
                var nodes = nodeCallback(script, script.context);
                var mode  = new InsertionCursorEditMode(
                    editor.Parent,
                    MonoDevelop.Ide.TypeSystem.CodeGenerationService.GetInsertionPoints(loadedDocument, declaringType));
                if (mode.InsertionPoints.Count == 0)
                {
                    MessageService.ShowError(
                        GettextCatalog.GetString("No valid insertion point can be found in type '{0}'.", declaringType.Name)
                        );
                    return;
                }
                if (declaringType.Kind == TypeKind.Enum)
                {
                    foreach (var node in nodes.Reverse())
                    {
                        var output = OutputNode(MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel(declaringType), node);
                        var point  = mode.InsertionPoints.First();
                        var offset = loadedDocument.Editor.LocationToOffset(point.Location);
                        var text   = output.Text + ",";
                        var delta  = point.Insert(editor, text);
                        output.RegisterTrackedSegments(script, delta + offset);
                    }
                    tcs.SetResult(script);
                    return;
                }

                var helpWindow       = new Mono.TextEditor.PopupWindow.InsertionCursorLayoutModeHelpWindow();
                helpWindow.TitleText = operation;
                mode.HelpWindow      = helpWindow;

                mode.CurIndex = 0;
                operationsRunning++;
                mode.StartMode();
                mode.Exited += delegate(object s, InsertionCursorEventArgs iCArgs) {
                    if (iCArgs.Success)
                    {
                        if (iCArgs.InsertionPoint.LineAfter == NewLineInsertion.None &&
                            iCArgs.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count > 1)
                        {
                            iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine;
                        }
                        foreach (var node in nodes.Reverse())
                        {
                            var output = OutputNode(MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel(declaringType), node);
                            var offset = loadedDocument.Editor.LocationToOffset(iCArgs.InsertionPoint.Location);
                            var text   = output.Text;
                            var delta  = iCArgs.InsertionPoint.Insert(editor, text);
                            output.RegisterTrackedSegments(script, delta + offset);
                        }
                        tcs.SetResult(script);
                    }
                    else
                    {
                        Rollback();
                    }
                    DisposeOnClose();
                };
            });

            return(tcs.Task);
        }
Example #31
0
 bool IsSingleType(MDRefactoringContext context)
 {
     return(context.Unit.GetTypes().Count() == 1);
 }
Example #32
0
        public override IEnumerable <MonoDevelop.CodeActions.CodeAction> GetActions(MonoDevelop.Ide.Gui.Document document, TextLocation loc, CancellationToken cancellationToken)
        {
            var context = new MDRefactoringContext(document, loc);

            return(GetActions(context));
        }
		public MonoCSharpCompletionEngine (CSharpCompletionTextEditorExtension ext, ICSharpCode.NRefactory.Editor.IDocument document, ICompletionContextProvider completionContextProvider, ICompletionDataFactory factory, ICSharpCode.NRefactory.TypeSystem.IProjectContent content, ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpTypeResolveContext ctx) : base (document, completionContextProvider, factory, content, ctx)
		{
			this.ext = ext;
			this.mdRefactoringCtx = MDRefactoringContext.Create (ext.Document, ext.Document.Editor.Caret.Location);

		}
		public MDRefactoringScript (MDRefactoringContext context, Document document, CSharpFormattingOptions formattingOptions) : base(document.Editor.Document, formattingOptions, document.Editor.CreateNRefactoryTextEditorOptions ())
		{
			this.context = context;
			this.document = document;
			undoGroup  = this.document.Editor.OpenUndoGroup ();
		}
Example #35
0
			public MonoTODOVisitor (MonoTODOIssue issue, MDRefactoringContext ctx)
			{
				this.issue = issue;
				this.ctx = ctx;
			}
		public override void Run (Document document, TextLocation loc)
		{
			var context = new MDRefactoringContext (document, loc);
			using (var script = context.StartScript ())
				act.Run (script);
		}
		public override IEnumerable<MonoDevelop.CodeActions.CodeAction> GetActions (MonoDevelop.Ide.Gui.Document document, TextLocation loc, CancellationToken cancellationToken)
		{
			var context = new MDRefactoringContext (document, loc);
			return GetActions (context);
		}
Example #38
0
        public override IEnumerable <MonoDevelop.CodeActions.CodeAction> GetActions(MonoDevelop.Ide.Gui.Document document, object refactoringContext, TextLocation loc, CancellationToken cancellationToken)
        {
            MDRefactoringContext context = (MDRefactoringContext)refactoringContext;

            if (context.IsInvalid)
            {
                yield break;
            }

            VariableInitializer currentVariable = context.GetNode <VariableInitializer>();

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

            FieldDeclaration currentField = currentVariable.Parent as FieldDeclaration;

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

            if (!currentField.Modifiers.HasFlag(Modifiers.Const))
            {
                yield break;
            }

            PrimitiveType baseType = TypeToIntegerPrimitive(context, currentField.ReturnType);

            if (baseType == null)
            {
                //Can't make enums of these types
                yield break;
            }

            TypeDeclaration containerType = currentVariable.GetParent <TypeDeclaration>();

            //Get all the fields/variables that the enum can possibly cover
            //Don't check the name just yet. That'll come later.

            var constFields = containerType.Members.OfType <FieldDeclaration>()
                              .Where(field => field.GetParent <TypeDeclaration>() == containerType && field.HasModifier(Modifiers.Const)).ToList();

            var constVariables = constFields.SelectMany(field => field.Variables).ToList();

            //Now, it's time to check the name of the selected variable
            //We'll use this to search for prefixes later

            var    names       = constVariables.Select(variable => variable.Name).ToList();
            string currentName = currentVariable.Name;

            //Now, find the common name prefixes
            //If the variable is called 'A_B_C_D', then 'A', 'A_B' and 'A_B_C' are
            //the potentially available prefixes.
            //Note that the common prefixes are the ones that more than one variable
            //has.
            //Each prefix has an associated action.

            foreach (var prefix in GetCommonPrefixes(currentName, names))
            {
                string title = string.Format(GettextCatalog.GetString("Create enum '{0}'"), prefix);

                yield return(new DefaultCodeAction(title, (ctx, script) => {
                    PrepareToRunAction(prefix, baseType, containerType, constVariables, cancellationToken, ctx, script);
                }));
            }
        }
			protected override IEnumerable<string> GenerateCode (List<object> includedMembers)
			{
				var generator = Options.CreateCodeGenerator ();
				generator.AutoIndent = false;
				var ctx = new MDRefactoringContext (Options.Document, Options.Document.Editor.Caret.Location);
				var builder = ctx.CreateTypeSystemAstBuilder ();

				foreach (IMember member in includedMembers) {
					var method = builder.ConvertEntity (member) as MethodDeclaration;
					method.Body = new BlockStatement () {
						new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException")))
					};
					var astType = ctx.CreateShortType ("MonoTouch.Foundation", "ExportAttribute");
					if (astType is SimpleType) {
						astType = new SimpleType ("Export");
					} else {
						astType = new MemberType (new MemberType (new SimpleType ("MonoTouch"), "Foundation"), "Export");
					}

					var attr = new ICSharpCode.NRefactory.CSharp.Attribute {
						Type = astType,
					};
					method.Modifiers &= ~Modifiers.Virtual;
					var exportAttribute = member.GetAttribute (new FullTypeName (new TopLevelTypeName ("MonoTouch.Foundation", "ExportAttribute"))); 
					attr.Arguments.Add (new PrimitiveExpression (exportAttribute.PositionalArguments.First ().ConstantValue)); 
					method.Attributes.Add (new AttributeSection {
						Attributes = { attr }
					}); 
					yield return method.ToString ();
				}
			}