Beispiel #1
0
 void GetAllSeverities()
 {
     foreach (var node in RefactoringService.GetInspectors(mimeType))
     {
         severities [node] = node.GetSeverity();
     }
 }
Beispiel #2
0
 public void FillInspectors(string filter)
 {
     categories.Clear();
     treeStore.Clear();
     foreach (var node in RefactoringService.GetInspectors(mimeType))
     {
         if (!string.IsNullOrEmpty(filter) && node.Title.IndexOf(filter, StringComparison.OrdinalIgnoreCase) < 0)
         {
             continue;
         }
         Gtk.TreeIter iter;
         if (!categories.TryGetValue(node.Category, out iter))
         {
             iter = treeStore.AppendValues("<b>" + node.Category + "</b>");
             categories [node.Category] = iter;
         }
         var title = node.Title;
         if (!string.IsNullOrEmpty(filter))
         {
             var idx = title.IndexOf(filter, StringComparison.OrdinalIgnoreCase);
             title = title.Substring(0, idx) + "<span bgcolor=\"yellow\">" + title.Substring(idx, filter.Length) + "</span>" + title.Substring(idx + filter.Length);
         }
         treeStore.AppendValues(iter, title, node.GetSeverity(), node);
     }
     treeviewInspections.ExpandAll();
 }
        void AnalyzeFile(ProjectFile file, IProjectContent content)
        {
            var me    = new object();
            var owner = processedFiles.AddOrUpdate(file.Name, me, (key, old) => old);

            if (me != owner)
            {
                return;
            }

            if (file.BuildAction != BuildAction.Compile || tokenSource.IsCancellationRequested)
            {
                return;
            }

            TextEditorData editor;

            try {
                editor = TextFileProvider.Instance.GetReadOnlyTextEditorData(file.FilePath);
            } catch (FileNotFoundException) {
                // Swallow exception and ignore this file
                return;
            }
            var document = TypeSystemService.ParseFile(file.Project, editor);

            if (document == null)
            {
                return;
            }

            var compilation = content.AddOrUpdateFiles(document.ParsedFile).CreateCompilation();

            CSharpAstResolver resolver;

            using (var timer = ExtensionMethods.ResolveCounter.BeginTiming()) {
                resolver = new CSharpAstResolver(compilation, document.GetAst <SyntaxTree> (), document.ParsedFile as ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpUnresolvedFile);
                resolver.ApplyNavigator(new ExtensionMethods.ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Resolve, null));
            }
            var context = document.CreateRefactoringContextWithEditor(editor, resolver, tokenSource.Token);

            CodeIssueProvider[] codeIssueProvider = RefactoringService.GetInspectors(editor.MimeType).ToArray();
            foreach (var provider in codeIssueProvider)
            {
                var severity = provider.GetSeverity();
                if (severity == Severity.None || tokenSource.IsCancellationRequested)
                {
                    return;
                }
                try {
                    foreach (var issue in provider.GetIssues(context, tokenSource.Token))
                    {
                        AddIssue(file, provider, issue);
                    }
                } catch (OperationCanceledException) {
                    // The operation was cancelled, no-op as the user-visible parts are
                    // handled elsewhere
                }
            }
        }
Beispiel #4
0
        static IList <CodeIssueProvider> GetInspectors(IReadonlyTextDocument editor, ICollection <string> inspectorIds)
        {
            var inspectors = RefactoringService.GetInspectors(editor.MimeType).ToList();

            return(inspectors
                   .Where(inspector => inspectorIds.Contains(inspector.IdString))
                   .ToList());
        }
        public static IEnumerable <Result> Check(Document input, CancellationToken cancellationToken)
        {
            if (!QuickTaskStrip.EnableFancyFeatures)
            {
                return(Enumerable.Empty <Result> ());
            }

//			var now = DateTime.Now;

            var editor = input.Editor;

            if (editor == null)
            {
                return(Enumerable.Empty <Result> ());
            }
            var loc    = editor.Caret.Location;
            var result = new BlockingCollection <Result> ();

            var codeIssueProvider = RefactoringService.GetInspectors(editor.Document.MimeType).ToArray();
            var context           = input.ParsedDocument.CreateRefactoringContext != null?
                                    input.ParsedDocument.CreateRefactoringContext(input, cancellationToken) : null;

//			Console.WriteLine ("start check:"+ (DateTime.Now - now).TotalMilliseconds);
            Parallel.ForEach(codeIssueProvider, (provider) => {
                try {
                    var severity = provider.GetSeverity();
                    if (severity == Severity.None)
                    {
                        return;
                    }
//					var now2 = DateTime.Now;
                    foreach (var r in provider.GetIssues(input, context, cancellationToken))
                    {
                        var fixes = new List <GenericFix> (r.Actions.Where(a => a != null).Select(a => new GenericFix(a.Title, new System.Action(() => a.Run(input, loc)))));
                        result.Add(new InspectorResults(
                                       provider,
                                       r.Region,
                                       r.Description,
                                       severity,
                                       provider.IssueMarker,
                                       fixes.ToArray()
                                       ));
                    }

/*					var ms = (DateTime.Now - now2).TotalMilliseconds;
 *                                      if (ms > 1000)
 *                                              Console.WriteLine (ms +"\t\t"+ provider.Title);*/
                } catch (OperationCanceledException) {
                    //ignore
                } catch (Exception e) {
                    LoggingService.LogError("CodeAnalysis: Got exception in inspector '" + provider + "'", e);
                }
            });
//			Console.WriteLine ("END check:"+ (DateTime.Now - now).TotalMilliseconds);
            return(result);
        }
Beispiel #6
0
 public IEnumerable <BaseCodeIssueProvider> GetIssueProviders(ProjectFile file)
 {
     return(RefactoringService.GetInspectors(DesktopService.GetMimeTypeForUri(file.Name))
            .Where(provider => {
         var severity = provider.GetSeverity();
         if (severity == Severity.None || !provider.GetIsEnabled())
         {
             return false;
         }
         return true;
     }));
 }
Beispiel #7
0
 void GetAllSeverities()
 {
     foreach (var node in RefactoringService.GetInspectors(mimeType))
     {
         severities [node] = node.GetSeverity();
         if (node.HasSubIssues)
         {
             foreach (var subIssue in node.SubIssues)
             {
                 severities [subIssue] = subIssue.GetSeverity();
             }
         }
     }
 }
        public static IEnumerable <Result> Check(Document input, CancellationToken cancellationToken)
        {
            if (!QuickTaskStrip.EnableFancyFeatures)
            {
                return(Enumerable.Empty <Result> ());
            }
            var editor = input.Editor;

            if (editor == null)
            {
                return(Enumerable.Empty <Result> ());
            }
            var loc               = editor.Caret.Location;
            var result            = new BlockingCollection <Result> ();
            var codeIssueProvider = RefactoringService.GetInspectors(editor.Document.MimeType);

            Parallel.ForEach(codeIssueProvider, (provider) =>
            {
                try {
                    var severity = provider.GetSeverity();
                    if (severity == Severity.None)
                    {
                        return;
                    }
                    foreach (var r in provider.GetIssues(input, cancellationToken))
                    {
                        var fixes = new List <GenericFix> (r.Actions.Where(a => a != null).Select(a => new GenericFix(a.Title, new System.Action(() => a.Run(input, loc)))));
                        result.Add(new InspectorResults(
                                       provider,
                                       r.Region,
                                       r.Description,
                                       severity,
                                       provider.IssueMarker,
                                       fixes.ToArray()
                                       ));
                    }
                }
                catch (Exception e)
                {
                    LoggingService.LogError("CodeAnalysis: Got exception in inspector '" + provider + "'", e);
                }
            });
            return(result);
        }
        public void PopulateFixes(Gtk.Menu menu, ref int items)
        {
            int mnemonic = 1;

            foreach (var fix_ in fixes.OrderByDescending(i => GetUsage(i.IdString)))
            {
                var fix          = fix_;
                var escapedLabel = fix.Title.Replace("_", "__");
                var label        = (mnemonic <= 10)
                                        ? "_" + (mnemonic++ % 10).ToString() + " " + escapedLabel
                                                : "  " + escapedLabel;
                var menuItem = new Gtk.MenuItem(label);
                menuItem.Activated += new ContextActionRunner(fix, document, loc).Run;
                menuItem.Activated += delegate {
                    ConfirmUsage(fix.IdString);
                    menu.Destroy();
                };
                menu.Add(menuItem);
                items++;
            }
            var first           = true;
            var alreadyInserted = new HashSet <CodeIssueProvider> ();

            foreach (var analysisFix_ in fixes.OfType <AnalysisContextActionProvider.AnalysisCodeAction>().Where(f => f.Result is InspectorResults))
            {
                var analysisFix = analysisFix_;
                var ir          = analysisFix.Result as InspectorResults;
                if (ir == null)
                {
                    continue;
                }

                if (first)
                {
                    menu.Add(new Gtk.SeparatorMenuItem());
                    first = false;
                }
                if (alreadyInserted.Contains(ir.Inspector))
                {
                    continue;
                }
                alreadyInserted.Add(ir.Inspector);

                var label    = GettextCatalog.GetString("_Inspection options for \"{0}\"", ir.Inspector.Title);
                var menuItem = new Gtk.MenuItem(label);
                menuItem.Activated += analysisFix.ShowOptions;
                menuItem.Activated += delegate {
                    menu.Destroy();
                };
                menu.Add(menuItem);
                items++;
            }

            foreach (var fix_ in fixes.Where(f => f.BoundToIssue != null))
            {
                var fix = fix_;
                foreach (var inspector_ in RefactoringService.GetInspectors(document.Editor.MimeType).Where(i => i.GetSeverity() != ICSharpCode.NRefactory.CSharp.Severity.None))
                {
                    var inspector = inspector_;

                    if (inspector.IdString.IndexOf(fix.BoundToIssue.FullName, StringComparison.Ordinal) < 0)
                    {
                        continue;
                    }
                    if (first)
                    {
                        menu.Add(new Gtk.SeparatorMenuItem());
                        first = false;
                    }
                    if (alreadyInserted.Contains(inspector))
                    {
                        continue;
                    }
                    alreadyInserted.Add(inspector);

                    var label    = GettextCatalog.GetString("_Inspection options for \"{0}\"", inspector.Title);
                    var menuItem = new Gtk.MenuItem(label);
                    menuItem.Activated += delegate {
                        MessageService.RunCustomDialog(new CodeIssueOptionsDialog(inspector), MessageService.RootWindow);
                        menu.Destroy();
                    };
                    menu.Add(menuItem);
                    break;
                }

                items++;
            }
        }
Beispiel #10
0
        public static IEnumerable <Result> Check(Document input, CancellationToken cancellationToken)
        {
            if (!QuickTaskStrip.EnableFancyFeatures || input.Project == null)
            {
                return(Enumerable.Empty <Result> ());
            }

                        #if PROFILE
            var runList = new List <Tuple <long, string> > ();
                        #endif
            var editor = input.Editor;
            if (editor == null)
            {
                return(Enumerable.Empty <Result> ());
            }
            var loc    = editor.Caret.Location;
            var result = new BlockingCollection <Result> ();

            var codeIssueProvider = RefactoringService.GetInspectors(editor.Document.MimeType).ToArray();
            var context           = input.ParsedDocument.CreateRefactoringContext != null?
                                    input.ParsedDocument.CreateRefactoringContext(input, cancellationToken) : null;

            Parallel.ForEach(codeIssueProvider, (parentProvider) => {
                try {
                                        #if PROFILE
                    var clock = new Stopwatch();
                    clock.Start();
                                        #endif
                    foreach (var provider in EnumerateProvider(parentProvider))
                    {
                        var severity = provider.GetSeverity();
                        if (severity == Severity.None || !provider.GetIsEnabled())
                        {
                            continue;
                        }
                        foreach (var r in provider.GetIssues(context, cancellationToken))
                        {
                            var fixes = r.Actions == null ? new List <GenericFix> () : new List <GenericFix> (r.Actions.Where(a => a != null).Select(a => {
                                Action batchAction = null;
                                if (a.SupportsBatchRunning)
                                {
                                    batchAction = () => a.BatchRun(input, loc);
                                }
                                return(new GenericFix(
                                           a.Title,
                                           () => {
                                    using (var script = context.CreateScript()) {
                                        a.Run(context, script);
                                    }
                                },
                                           batchAction)
                                {
                                    DocumentRegion = new DocumentRegion(r.Region.Begin, r.Region.End),
                                    IdString = a.IdString
                                });
                            }));
                            result.Add(new InspectorResults(
                                           provider,
                                           r.Region,
                                           r.Description,
                                           severity,
                                           r.IssueMarker,
                                           fixes.ToArray()
                                           ));
                        }
                    }
                                        #if PROFILE
                    clock.Stop();
                    lock (runList) {
                        runList.Add(Tuple.Create(clock.ElapsedMilliseconds, parentProvider.Title));
                    }
                                        #endif
                } catch (OperationCanceledException) {
                    //ignore
                } catch (Exception e) {
                    LoggingService.LogError("CodeAnalysis: Got exception in inspector '" + parentProvider + "'", e);
                }
            });
#if PROFILE
            runList.Sort();
            foreach (var item in runList)
            {
                Console.WriteLine(item.Item1 + "ms\t: " + item.Item2);
            }
#endif
            return(result);
        }
Beispiel #11
0
        public void PopulateFixes(Gtk.Menu menu, ref int items)
        {
            int mnemonic = 1;

            foreach (var fix_ in fixes.OrderByDescending(i => GetUsage(i.IdString)))
            {
                var fix          = fix_;
                var escapedLabel = fix.Title.Replace("_", "__");
                var label        = (mnemonic <= 10)
                                        ? "_" + (mnemonic++ % 10).ToString() + " " + escapedLabel
                                                : "  " + escapedLabel;
                var thisInstanceMenuItem = new Gtk.MenuItem(label);
                thisInstanceMenuItem.Activated += new ContextActionRunner(fix, document, loc).Run;
                thisInstanceMenuItem.Activated += delegate {
                    ConfirmUsage(fix.IdString);
                    menu.Destroy();
                };
                menu.Add(thisInstanceMenuItem);
                items++;
            }
            var first           = true;
            var alreadyInserted = new HashSet <BaseCodeIssueProvider> ();

            foreach (var analysisFix_ in fixes.OfType <AnalysisContextActionProvider.AnalysisCodeAction>().Where(f => f.Result is InspectorResults))
            {
                var analysisFix = analysisFix_;
                var ir          = analysisFix.Result as InspectorResults;
                if (ir == null)
                {
                    continue;
                }

                if (first)
                {
                    menu.Add(new Gtk.SeparatorMenuItem());
                    first = false;
                }
                if (alreadyInserted.Contains(ir.Inspector))
                {
                    continue;
                }
                alreadyInserted.Add(ir.Inspector);

                var subMenu = new Gtk.Menu();
                if (analysisFix.SupportsBatchRunning)
                {
                    var batchRunMenuItem = new Gtk.MenuItem(GettextCatalog.GetString("Fix all in this file"));
                    batchRunMenuItem.Activated += delegate {
                        ConfirmUsage(analysisFix.IdString);
                        menu.Destroy();
                    };
                    batchRunMenuItem.Activated += new ContextActionRunner(analysisFix, document, loc).BatchRun;
                    subMenu.Add(batchRunMenuItem);
                    subMenu.Add(new Gtk.SeparatorMenuItem());
                }

                var inspector = ir.Inspector;
                if (inspector.CanDisableWithPragma)
                {
                    var menuItem = new Gtk.MenuItem(GettextCatalog.GetString("_Suppress with #pragma"));
                    menuItem.Activated += delegate {
                        inspector.DisableWithPragma(document, loc);
                    };
                    subMenu.Add(menuItem);
                }

                if (inspector.CanDisableOnce)
                {
                    var menuItem = new Gtk.MenuItem(GettextCatalog.GetString("_Disable once with comment"));
                    menuItem.Activated += delegate {
                        inspector.DisableOnce(document, loc);
                    };
                    subMenu.Add(menuItem);
                }

                if (inspector.CanDisableAndRestore)
                {
                    var menuItem = new Gtk.MenuItem(GettextCatalog.GetString("Disable _and restore with comments"));
                    menuItem.Activated += delegate {
                        inspector.DisableAndRestore(document, loc);
                    };
                    subMenu.Add(menuItem);
                }
                var label       = GettextCatalog.GetString("_Options for \"{0}\"", InspectorResults.GetTitle(ir.Inspector));
                var subMenuItem = new Gtk.MenuItem(label);

                var optionsMenuItem = new Gtk.MenuItem(GettextCatalog.GetString("_Configure inspection severity"));
                optionsMenuItem.Activated += analysisFix.ShowOptions;
                optionsMenuItem.Activated += delegate {
                    menu.Destroy();
                };
                subMenu.Add(optionsMenuItem);
                subMenuItem.Submenu = subMenu;
                menu.Add(subMenuItem);
                items++;
            }

            foreach (var fix_ in fixes.Where(f => f.BoundToIssue != null))
            {
                var fix = fix_;
                foreach (var inspector_ in RefactoringService.GetInspectors(document.Editor.MimeType).Where(i => i.GetSeverity() != Severity.None))
                {
                    var inspector = inspector_;

                    if (inspector.IdString.IndexOf(fix.BoundToIssue.FullName, StringComparison.Ordinal) < 0)
                    {
                        continue;
                    }
                    if (first)
                    {
                        menu.Add(new Gtk.SeparatorMenuItem());
                        first = false;
                    }
                    if (alreadyInserted.Contains(inspector))
                    {
                        continue;
                    }
                    alreadyInserted.Add(inspector);

                    var      label       = GettextCatalog.GetString("_Options for \"{0}\"", InspectorResults.GetTitle(inspector));
                    var      subMenuItem = new Gtk.MenuItem(label);
                    Gtk.Menu subMenu     = new Gtk.Menu();
                    if (inspector.CanSuppressWithAttribute)
                    {
                        var menuItem = new Gtk.MenuItem(GettextCatalog.GetString("_Suppress with attribute"));
                        menuItem.Activated += delegate {
                            inspector.SuppressWithAttribute(document, loc);
                        };
                        subMenu.Add(menuItem);
                    }

                    if (inspector.CanDisableWithPragma)
                    {
                        var menuItem = new Gtk.MenuItem(GettextCatalog.GetString("_Suppress with #pragma"));
                        menuItem.Activated += delegate {
                            inspector.DisableWithPragma(document, loc);
                        };
                        subMenu.Add(menuItem);
                    }

                    if (inspector.CanDisableOnce)
                    {
                        var menuItem = new Gtk.MenuItem(GettextCatalog.GetString("_Disable once with comment"));
                        menuItem.Activated += delegate {
                            inspector.DisableOnce(document, loc);
                        };
                        subMenu.Add(menuItem);
                    }

                    if (inspector.CanDisableAndRestore)
                    {
                        var menuItem = new Gtk.MenuItem(GettextCatalog.GetString("Disable _and restore with comments"));
                        menuItem.Activated += delegate {
                            inspector.DisableAndRestore(document, loc);
                        };
                        subMenu.Add(menuItem);
                    }

                    var confItem = new Gtk.MenuItem(GettextCatalog.GetString("_Configure inspection severity"));
                    confItem.Activated += delegate {
                        MessageService.RunCustomDialog(new CodeIssueOptionsDialog(inspector), MessageService.RootWindow);
                        menu.Destroy();
                    };
                    subMenu.Add(confItem);

                    subMenuItem.Submenu = subMenu;
                    subMenu.ShowAll();
                    menu.Add(subMenuItem);
                    break;
                }

                items++;
            }
        }
        public InspectionPanelWidget(string mimeType)
        {
            this.Build();
//			this.mimeType = mimeType;


            treeviewInspections.AppendColumn("Title", new CellRendererText(), "text", 0);


            var comboRenderer = new CellRendererCombo();
            var col           = treeviewInspections.AppendColumn("Severity", comboRenderer);

            var comboBoxStore = new ListStore(typeof(string), typeof(QuickTaskSeverity));

            comboBoxStore.AppendValues(GetDescription(QuickTaskSeverity.None), QuickTaskSeverity.None);
            comboBoxStore.AppendValues(GetDescription(QuickTaskSeverity.Error), QuickTaskSeverity.Error);
            comboBoxStore.AppendValues(GetDescription(QuickTaskSeverity.Warning), QuickTaskSeverity.Warning);
            comboBoxStore.AppendValues(GetDescription(QuickTaskSeverity.Hint), QuickTaskSeverity.Hint);
            comboBoxStore.AppendValues(GetDescription(QuickTaskSeverity.Suggestion), QuickTaskSeverity.Suggestion);
            comboRenderer.Model      = comboBoxStore;
            comboRenderer.Mode       = CellRendererMode.Activatable;
            comboRenderer.TextColumn = 0;
            comboRenderer.Editable   = true;
            comboRenderer.HasEntry   = false;

            comboRenderer.Edited += delegate(object o, Gtk.EditedArgs args) {
                Gtk.TreeIter iter;
                if (!treeStore.GetIterFromString(out iter, args.Path))
                {
                    return;
                }

                Gtk.TreeIter storeIter;
                if (!comboBoxStore.GetIterFirst(out storeIter))
                {
                    return;
                }
                Console.WriteLine("new text:" + args.NewText);
                do
                {
                    if ((string)comboBoxStore.GetValue(storeIter, 0) == args.NewText)
                    {
                        treeStore.SetValue(iter, 1, (QuickTaskSeverity)comboBoxStore.GetValue(storeIter, 1));
                        return;
                    }
                } while (comboBoxStore.IterNext(ref storeIter));
            };

            col.SetCellDataFunc(comboRenderer, delegate(Gtk.TreeViewColumn tree_column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) {
                var severity       = (QuickTaskSeverity)treeStore.GetValue(iter, 1);
                comboRenderer.Text = GetDescription(severity);
            });
            treeviewInspections.HeadersVisible     = false;
            treeviewInspections.Model              = treeStore;
            treeviewInspections.Selection.Changed += HandleSelectionChanged;

            foreach (var node in RefactoringService.GetInspectors(mimeType))
            {
                treeStore.AppendValues(node.Title, node.GetSeverity(), node);
            }
        }
Beispiel #13
0
        void StartAnalyzation(object sender, EventArgs e)
        {
            var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;

            if (solution == null)
            {
                return;
            }
            runButton.Sensitive = false;
            store.Clear();
            var rootNode = store.AddNode();

            rootNode.SetValue(text, "Analyzing...");
            ThreadPool.QueueUserWorkItem(delegate {
                using (var monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor("Analyzing solution", null, false)) {
                    int work = 0;
                    foreach (var project in solution.GetAllProjects())
                    {
                        work += project.Files.Count(f => f.BuildAction == BuildAction.Compile);
                    }
                    monitor.BeginTask("Analyzing solution", work);
                    int allIssues           = 0;
                    TypeSystemParser parser = null;
                    string lastMime         = null;
                    CodeIssueProvider[] codeIssueProvider = null;
                    foreach (var project in solution.GetAllProjects())
                    {
                        var compilation             = TypeSystemService.GetCompilation(project);
                        List <CodeIssue> codeIssues = new List <CodeIssue> ();
                        Parallel.ForEach(project.Files, file => {
                            if (file.BuildAction != BuildAction.Compile)
                            {
                                return;
                            }

                            var editor = TextFileProvider.Instance.GetReadOnlyTextEditorData(file.FilePath);

                            if (lastMime != editor.MimeType || parser == null)
                            {
                                parser = TypeSystemService.GetParser(editor.MimeType);
                            }
                            if (parser == null)
                            {
                                return;
                            }
                            var reader   = new StreamReader(editor.OpenStream());
                            var document = parser.Parse(true, editor.FileName, reader, project);
                            reader.Close();
                            if (document == null)
                            {
                                return;
                            }

                            var resolver = new CSharpAstResolver(compilation, document.GetAst <SyntaxTree> (), document.ParsedFile as CSharpUnresolvedFile);
                            var context  = document.CreateRefactoringContextWithEditor(editor, resolver, CancellationToken.None);

                            if (lastMime != editor.MimeType || codeIssueProvider == null)
                            {
                                codeIssueProvider = RefactoringService.GetInspectors(editor.MimeType).ToArray();
                            }
                            Parallel.ForEach(codeIssueProvider, (provider) => {
                                var severity = provider.GetSeverity();
                                if (severity == Severity.None)
                                {
                                    return;
                                }
                                try {
                                    foreach (var r in provider.GetIssues(context, CancellationToken.None))
                                    {
                                        lock (codeIssues) {
                                            codeIssues.Add(r);
                                        }
                                    }
                                } catch (Exception ex) {
                                    LoggingService.LogError("Error while running code issue on:" + editor.FileName, ex);
                                }
                            });
                            lastMime = editor.MimeType;
                            monitor.Step(1);
                        });
                        Application.Invoke(delegate {
                            var projectNode = store.AddNode();
                            projectNode.SetValue(text, project.Name + "( " + codeIssues.Count + " issues)");
                            foreach (var issue in codeIssues)
                            {
                                var child = projectNode.AddChild();
                                child.SetValue(text, issue.Description + " - " + issue.Region);
                                child.SetValue(region, issue.Region);
                                child.MoveToParent();
                            }
                            projectNode.MoveToParent();
                            allIssues += codeIssues.Count;
                        });
                    }
                    Application.Invoke(delegate {
                        rootNode.SetValue(text, "Found issues :" + allIssues);
                        runButton.Sensitive = true;
                    });
                    monitor.EndTask();
                }
            });
        }
        protected override void Run()
        {
            var lang = "text/x-csharp";

            OpenFileDialog dlg = new OpenFileDialog("Export Rules", MonoDevelop.Components.FileChooserAction.Save);

            dlg.InitialFileName = "rules.html";
            if (!dlg.Run())
            {
                return;
            }

            Dictionary <BaseCodeIssueProvider, Severity> severities = new Dictionary <BaseCodeIssueProvider, Severity> ();

            foreach (var node in RefactoringService.GetInspectors(lang))
            {
                severities [node] = node.GetSeverity();
                if (node.HasSubIssues)
                {
                    foreach (var subIssue in node.SubIssues)
                    {
                        severities [subIssue] = subIssue.GetSeverity();
                    }
                }
            }

            var grouped = severities.Keys.OfType <CodeIssueProvider> ()
                          .GroupBy(node => node.Category)
                          .OrderBy(g => g.Key, StringComparer.Ordinal);

            using (var sw = new StreamWriter(dlg.SelectedFile)) {
                sw.WriteLine("<h1>Code Rules</h1>");
                foreach (var g in grouped)
                {
                    sw.WriteLine("<h2>" + g.Key + "</h2>");
                    sw.WriteLine("<table border='1'>");

                    foreach (var node in g.OrderBy(n => n.Title, StringComparer.Ordinal))
                    {
                        var title = node.Title;
                        var desc  = node.Description != title ? node.Description : "";
                        sw.WriteLine("<tr><td>" + title + "</td><td>" + desc + "</td><td>" + node.GetSeverity() + "</td></tr>");
                        if (node.HasSubIssues)
                        {
                            foreach (var subIssue in node.SubIssues)
                            {
                                title = subIssue.Title;
                                desc  = subIssue.Description != title ? subIssue.Description : "";
                                sw.WriteLine("<tr><td> - " + title + "</td><td>" + desc + "</td><td>" + subIssue.GetSeverity() + "</td></tr>");
                            }
                        }
                    }
                    sw.WriteLine("</table>");
                }

                Dictionary <CodeActionProvider, bool> providerStates = new Dictionary <CodeActionProvider, bool> ();
                string disabledNodes = PropertyService.Get("ContextActions." + lang, "");
                foreach (var node in RefactoringService.ContextAddinNodes.Where(n => n.MimeType == lang))
                {
                    providerStates [node] = disabledNodes.IndexOf(node.IdString, StringComparison.Ordinal) < 0;
                }

                sw.WriteLine("<h1>Code Actions</h1>");
                sw.WriteLine("<table border='1'>");
                var sortedAndFiltered = providerStates.Keys.OrderBy(n => n.Title, StringComparer.Ordinal);
                foreach (var node in sortedAndFiltered)
                {
                    var desc = node.Title != node.Description ? node.Description : "";
                    sw.WriteLine("<tr><td>" + node.Title + "</td><td>" + desc + "</td></tr>");
                }
                sw.WriteLine("</table>");
            }
        }
Beispiel #15
0
        public void StartAnalysis(WorkspaceItem solution)
        {
            lock (_lock) {
                tokenSource = new CancellationTokenSource();
                ThreadPool.QueueUserWorkItem(delegate {
                    State = AnalysisState.Running;

                    using (var monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor("Analyzing solution", null, false)) {
                        int work = 0;
                        foreach (var project in solution.GetAllProjects())
                        {
                            work += project.Files.Count(f => f.BuildAction == BuildAction.Compile);
                        }
                        monitor.BeginTask("Analyzing solution", work);
                        var processedFiles = new ConcurrentDictionary <string, object> ();
                        foreach (var project in solution.GetAllProjects())
                        {
                            if (tokenSource.IsCancellationRequested)
                            {
                                break;
                            }
                            var content = TypeSystemService.GetProjectContext(project);
                            Parallel.ForEach(project.Files, file => {
                                var me    = new object();
                                var owner = processedFiles.AddOrUpdate(file.Name, me, (key, old) => old);
                                if (me != owner)
                                {
                                    return;
                                }
                                if (file.BuildAction != BuildAction.Compile || tokenSource.IsCancellationRequested)
                                {
                                    return;
                                }

                                var editor   = TextFileProvider.Instance.GetReadOnlyTextEditorData(file.FilePath);
                                var document = TypeSystemService.ParseFile(project, editor);
                                if (document == null)
                                {
                                    return;
                                }

                                var compilation = content.AddOrUpdateFiles(document.ParsedFile).CreateCompilation();
                                var resolver    = new CSharpAstResolver(compilation, document.GetAst <SyntaxTree> (), document.ParsedFile as ICSharpCode.NRefactory.CSharp.TypeSystem.CSharpUnresolvedFile);
                                var context     = document.CreateRefactoringContextWithEditor(editor, resolver, tokenSource.Token);

                                CodeIssueProvider[] codeIssueProvider = RefactoringService.GetInspectors(editor.MimeType).ToArray();
                                Parallel.ForEach(codeIssueProvider, (provider) => {
                                    var severity = provider.GetSeverity();
                                    if (severity == Severity.None || tokenSource.IsCancellationRequested)
                                    {
                                        return;
                                    }
                                    try {
                                        foreach (var issue in provider.GetIssues(context, tokenSource.Token))
                                        {
                                            AddIssue(file, provider, issue);
                                        }
                                    } catch (OperationCanceledException) {
                                        // The operation was cancelled, no-op as the user-visible parts are
                                        // handled elsewhere
                                    } catch (Exception ex) {
                                        LoggingService.LogError("Error while running code issue on:" + editor.FileName, ex);
                                    }
                                });
                                //lastMime = editor.MimeType;
                                monitor.Step(1);
                            });
                        }
                        // Cleanup
                        AnalysisState oldState;
                        AnalysisState newState;
                        lock (_lock) {
                            oldState = state;
                            if (tokenSource.IsCancellationRequested)
                            {
                                newState = AnalysisState.Cancelled;
                            }
                            else
                            {
                                newState = AnalysisState.Completed;
                            }
                            state       = newState;
                            tokenSource = null;
                        }
                        OnAnalysisStateChanged(new AnalysisStateChangeEventArgs(oldState, newState));
                        monitor.EndTask();
                    }
                });
            }
        }