Example #1
0
        public void FindReferences_SearchOptionsArePassed()
        {
            var fileIOMock       = new Mock <IFileIO>();
            var moduleLoaderMock = new Mock <IModuleLoader>();
            var cut = new ReferenceFinder(fileIOMock.Object, moduleLoaderMock.Object,
                                          options => { options.SearchOption = SearchOption.AllDirectories; });

            cut.FindReferences(out _);

            fileIOMock.Verify(f => f.GetFilePaths(It.IsAny <string>(), "*.dll", SearchOption.AllDirectories));
        }
Example #2
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 #3
0
    public void Execute()
    {
        var nullGuardAttribute = ModuleDefinition.GetNullGuardAttribute();

        if (nullGuardAttribute == null)
        {
            nullGuardAttribute = ModuleDefinition.Assembly.GetNullGuardAttribute();
        }

        if (nullGuardAttribute != null)
        {
            ValidationFlags = (ValidationFlags)nullGuardAttribute.ConstructorArguments[0].Value;
        }

        ReferenceFinder.FindReferences(AssemblyResolver, ModuleDefinition);
        var types = new List <TypeDefinition>(ModuleDefinition.GetTypes());

        CheckForBadAttributes(types);
        ProcessAssembly(types);
        RemoveAttributes(types);
        RemoveReference();
    }
        public static void RenameNamespace(INamespace ns, string newName)
        {
            using (var monitor = new NullProgressMonitor()) {
                var col = ReferenceFinder.FindReferences(ns, true, monitor);

                List <Change> result = new List <Change> ();
                foreach (var memberRef in col)
                {
                    var change = new TextReplaceChange();
                    change.FileName     = memberRef.FileName;
                    change.Offset       = memberRef.Offset;
                    change.RemovedChars = memberRef.Length;
                    change.InsertedText = newName;
                    change.Description  = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), memberRef.GetName(), newName);
                    result.Add(change);
                }
                if (result.Count > 0)
                {
                    RefactoringService.AcceptChanges(monitor, result);
                }
            }
        }
Example #5
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);
                    }
                }
            }
        }
        public override List <Change> PerformChanges(RefactoringOptions options, object prop)
        {
            RenameProperties properties       = (RenameProperties)prop;
            List <Change>    result           = new List <Change> ();
            IEnumerable <MemberReference> col = null;

            using (var monitor = new MessageDialogProgressMonitor(true, false, false, true)) {
                col = ReferenceFinder.FindReferences(options.SelectedItem, properties.IncludeOverloads, monitor);
                if (col == null)
                {
                    return(result);
                }

                if (properties.RenameFile && options.SelectedItem is IType)
                {
                    var cls            = ((IType)options.SelectedItem).GetDefinition();
                    int currentPart    = 1;
                    var alreadyRenamed = new HashSet <string> ();
                    foreach (var part in cls.Parts)
                    {
                        if (alreadyRenamed.Contains(part.Region.FileName))
                        {
                            continue;
                        }
                        alreadyRenamed.Add(part.Region.FileName);

                        string oldFileName = System.IO.Path.GetFileNameWithoutExtension(part.Region.FileName);
                        string newFileName;
                        var    newName = properties.NewName;
                        if (string.IsNullOrEmpty(oldFileName) || string.IsNullOrEmpty(newName))
                        {
                            continue;
                        }
                        if (oldFileName.ToUpper() == newName.ToUpper() || oldFileName.ToUpper().EndsWith("." + newName.ToUpper(), StringComparison.Ordinal))
                        {
                            continue;
                        }
                        int idx = oldFileName.IndexOf(cls.Name, StringComparison.Ordinal);
                        if (idx >= 0)
                        {
                            newFileName = oldFileName.Substring(0, idx) + newName + oldFileName.Substring(idx + cls.Name.Length);
                        }
                        else
                        {
                            newFileName = currentPart != 1 ? newName + currentPart : newName;
                            currentPart++;
                        }

                        int t = 0;
                        while (System.IO.File.Exists(GetFullFileName(newFileName, part.Region.FileName, t)))
                        {
                            t++;
                        }
                        result.Add(new RenameFileChange(part.Region.FileName, GetFullFileName(newFileName, part.Region.FileName, t)));
                    }
                }

                foreach (var memberRef in col)
                {
                    TextReplaceChange change = new TextReplaceChange();
                    change.FileName     = memberRef.FileName;
                    change.Offset       = memberRef.Offset;
                    change.RemovedChars = memberRef.Length;
                    change.InsertedText = properties.NewName;
                    change.Description  = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), memberRef.GetName(), properties.NewName);
                    result.Add(change);
                }
            }
            return(result);
        }
        public override void Run(RefactoringOptions options)
        {
            if (options.SelectedItem is IVariable)
            {
                var field = options.SelectedItem as IField;
                if (field != null && (field.Accessibility != Accessibility.Private || field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Parts.Count > 1))
                {
                    MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
                    return;
                }

                var par = options.SelectedItem as IParameter;
                if (par != null && par.Owner != null && (par.Owner.Accessibility != Accessibility.Private || par.Owner.DeclaringTypeDefinition != null && par.Owner.DeclaringTypeDefinition.Parts.Count > 1))
                {
                    MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
                    return;
                }

                var col = ReferenceFinder.FindReferences(options.SelectedItem, true);
                if (col == null)
                {
                    return;
                }
                var data = options.Document != null?options.GetTextEditorData() : IdeApp.Workbench.ActiveDocument.Editor;

                var editor = data.Parent;
                if (editor == null)
                {
                    MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
                    return;
                }

                var links      = new List <TextLink> ();
                var link       = new TextLink("name");
                int baseOffset = Int32.MaxValue;
                foreach (var r in col)
                {
                    baseOffset = Math.Min(baseOffset, r.Offset);
                }
                foreach (MemberReference r in col)
                {
                    var segment = new TextSegment(r.Offset - baseOffset, r.Length);
                    if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset)
                    {
                        link.Links.Insert(0, segment);
                    }
                    else
                    {
                        link.AddLink(segment);
                    }
                }

                links.Add(link);
                if (editor.CurrentMode is TextLinkEditMode)
                {
                    ((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode();
                }
                TextLinkEditMode tle = new TextLinkEditMode(editor, baseOffset, links);
                tle.SetCaretPosition  = false;
                tle.SelectPrimaryLink = true;
                if (tle.ShouldStartTextLinkMode)
                {
                    var helpWindow = new TableLayoutModeHelpWindow();
                    helpWindow.TitleText = options.SelectedItem is IVariable?GettextCatalog.GetString("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString("<b>Parameter -- Renaming</b>");

                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Key</b>"), GettextCatalog.GetString("<b>Behavior</b>")));
                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Return</b>"), GettextCatalog.GetString("<b>Accept</b> this refactoring.")));
                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Esc</b>"), GettextCatalog.GetString("<b>Cancel</b> this refactoring.")));
                    tle.HelpWindow = helpWindow;
                    tle.Cancel    += delegate {
                        if (tle.HasChangedText)
                        {
                            editor.Document.Undo();
                        }
                    };
                    tle.OldMode = data.CurrentMode;
                    tle.StartMode();
                    data.CurrentMode = tle;
                }
            }
            else
            {
                MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
            }
        }
Example #8
0
        public override void Run(RefactoringOptions options)
        {
            if (options.SelectedItem is LocalVariable || options.SelectedItem is IParameter)
            {
                var col = ReferenceFinder.FindReferences(options.SelectedItem);
                if (col == null)
                {
                    return;
                }
                TextEditorData             data   = options.GetTextEditorData();
                Mono.TextEditor.TextEditor editor = data.Parent;
                if (editor == null)
                {
                    MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
                    return;
                }

                List <TextLink> links      = new List <TextLink> ();
                TextLink        link       = new TextLink("name");
                int             baseOffset = Int32.MaxValue;
                foreach (MemberReference r in col)
                {
                    baseOffset = Math.Min(baseOffset, data.Document.LocationToOffset(r.Line, r.Column));
                }
                foreach (MemberReference r in col)
                {
                    Segment segment = new Segment(data.Document.LocationToOffset(r.Line, r.Column) - baseOffset, r.Name.Length);
                    if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset)
                    {
                        link.Links.Insert(0, segment);
                    }
                    else
                    {
                        link.AddLink(segment);
                    }
                }

                links.Add(link);
                if (editor.CurrentMode is TextLinkEditMode)
                {
                    ((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode();
                }
                TextLinkEditMode tle = new TextLinkEditMode(editor, baseOffset, links);
                tle.SetCaretPosition  = false;
                tle.SelectPrimaryLink = true;
                if (tle.ShouldStartTextLinkMode)
                {
                    ModeHelpWindow helpWindow = new ModeHelpWindow();
                    helpWindow.TransientFor = IdeApp.Workbench.RootWindow;
                    helpWindow.TitleText    = options.SelectedItem is LocalVariable?GettextCatalog.GetString("<b>Local Variable -- Renaming</b>") : GettextCatalog.GetString("<b>Parameter -- Renaming</b>");

                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Key</b>"), GettextCatalog.GetString("<b>Behavior</b>")));
                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Return</b>"), GettextCatalog.GetString("<b>Accept</b> this refactoring.")));
                    helpWindow.Items.Add(new KeyValuePair <string, string> (GettextCatalog.GetString("<b>Esc</b>"), GettextCatalog.GetString("<b>Cancel</b> this refactoring.")));
                    tle.HelpWindow = helpWindow;
                    tle.Cancel    += delegate {
                        editor.Document.Undo();
                    };
                    tle.OldMode = data.CurrentMode;
                    tle.StartMode();
                    data.CurrentMode = tle;
                }
            }
            else
            {
                MessageService.ShowCustomDialog(new RenameItemDialog(options, this));
            }
        }
Example #9
0
        public override List <Change> PerformChanges(RefactoringOptions options, object prop)
        {
            List <Change>          result        = new List <Change> ();
            TextEditorData         data          = options.GetTextEditorData();
            MemberResolveResult    resolveResult = options.ResolveResult as MemberResolveResult;
            IProperty              property      = resolveResult.ResolvedMember as IProperty;
            INRefactoryASTProvider astProvider   = options.GetASTProvider();
            string backingStoreName = RetrieveBackingStore(options, astProvider, property);

            int    backinStoreStart;
            int    backinStoreEnd;
            IField backingStore = GetBackingStoreField(options, backingStoreName, out backinStoreStart, out backinStoreEnd);

            if (backingStore != null)
            {
                using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true, true)) {
                    foreach (MemberReference memberRef in ReferenceFinder.FindReferences(backingStore, monitor))
                    {
                        result.Add(new TextReplaceChange()
                        {
                            FileName     = memberRef.FileName,
                            Offset       = memberRef.Position,
                            RemovedChars = memberRef.Name.Length,
                            InsertedText = property.Name
                        });
                    }
                }

                result.RemoveAll(c => backinStoreStart <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= backinStoreEnd);
                result.Add(new TextReplaceChange()
                {
                    FileName     = options.Document.FileName,
                    Offset       = backinStoreStart,
                    RemovedChars = backinStoreEnd - backinStoreStart
                });
            }

            if (property.HasGet)
            {
                int startOffset = data.Document.LocationToOffset(property.GetRegion.Start.ToDocumentLocation(data.Document));
                int endOffset   = data.Document.LocationToOffset(property.GetRegion.End.ToDocumentLocation(data.Document));

                string text = astProvider.OutputNode(options.Dom, new PropertyGetRegion(null, null), options.GetIndent(property) + "\t").Trim();

                result.RemoveAll(c => startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= endOffset);
                result.Add(new TextReplaceChange()
                {
                    FileName     = options.Document.FileName,
                    Offset       = startOffset,
                    RemovedChars = endOffset - startOffset,
                    InsertedText = text
                });
            }

            int setStartOffset;
            int setEndOffset;
            PropertySetRegion setRegion = new PropertySetRegion(null, null);
            string            setText;

            if (property.HasSet)
            {
                setStartOffset = data.Document.LocationToOffset(property.SetRegion.Start.ToDocumentLocation(data.Document));
                setEndOffset   = data.Document.LocationToOffset(property.SetRegion.End.ToDocumentLocation(data.Document));
                setText        = astProvider.OutputNode(options.Dom, setRegion, options.GetIndent(property) + "\t").Trim();
            }
            else
            {
                setEndOffset       = setStartOffset = data.Document.LocationToOffset(property.GetRegion.End.ToDocumentLocation(data.Document));
                setRegion.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.Private;
                setText            = Environment.NewLine + astProvider.OutputNode(options.Dom, setRegion, options.GetIndent(property) + "\t").TrimEnd();
            }
            result.RemoveAll(c => setStartOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= setEndOffset);
            result.Add(new TextReplaceChange()
            {
                FileName     = options.Document.FileName,
                Offset       = setStartOffset,
                RemovedChars = setEndOffset - setStartOffset,
                InsertedText = setText
            });
            return(result);
        }
Example #10
0
        public override void Run(RefactoringOptions options)
        {
            if (options.SelectedItem is IVariable)
            {
                var field = options.SelectedItem as IField;
                if (field != null && (field.Accessibility != Accessibility.Private || field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Parts.Count > 1))
                {
                    using (var dlg = new RenameItemDialog(options, this))
                        MessageService.ShowCustomDialog(dlg);
                    return;
                }

                var par = options.SelectedItem as IParameter;
                if (par != null && par.Owner != null && (par.Owner.Accessibility != Accessibility.Private || par.Owner.DeclaringTypeDefinition != null && par.Owner.DeclaringTypeDefinition.Parts.Count > 1))
                {
                    using (var dlg = new RenameItemDialog(options, this))
                        MessageService.ShowCustomDialog(dlg);
                    return;
                }

                var col = ReferenceFinder.FindReferences(options.SelectedItem, true);
                if (col == null)
                {
                    return;
                }
                var data = options.Document != null?options.GetTextEditorData() : IdeApp.Workbench.ActiveDocument.Editor;

                var editor = data.Parent;
                if (editor == null)
                {
                    using (var dlg = new RenameItemDialog(options, this))
                        MessageService.ShowCustomDialog(dlg);
                    return;
                }

                var links      = new List <TextLink> ();
                var link       = new TextLink("name");
                int baseOffset = Int32.MaxValue;
                foreach (var r in col)
                {
                    baseOffset = Math.Min(baseOffset, r.Offset);
                }
                foreach (MemberReference r in col)
                {
                    var segment = new TextSegment(r.Offset - baseOffset, r.Length);
                    if (segment.Offset <= data.Caret.Offset - baseOffset && data.Caret.Offset - baseOffset <= segment.EndOffset)
                    {
                        link.Links.Insert(0, segment);
                    }
                    else
                    {
                        link.AddLink(segment);
                    }
                }

                links.Add(link);
                if (editor.CurrentMode is TextLinkEditMode)
                {
                    ((TextLinkEditMode)editor.CurrentMode).ExitTextLinkMode();
                }
                TextLinkEditMode tle = new TextLinkEditMode(editor, baseOffset, links);
                tle.SetCaretPosition  = false;
                tle.SelectPrimaryLink = true;
                if (tle.ShouldStartTextLinkMode)
                {
                    tle.Cancel += delegate {
                        if (tle.HasChangedText)
                        {
                            editor.Document.Undo();
                        }
                    };
                    tle.OldMode = data.CurrentMode;
                    tle.StartMode();
                    data.CurrentMode = tle;
                }
            }
            else
            {
                using (var dlg = new RenameItemDialog(options, this))
                    MessageService.ShowCustomDialog(dlg);
            }
        }