public IDeclaredElement GetDeclaredElement()
        {
            var typeElement = GetTypeElement();

            if (typeElement == null)
            {
                return(null);
            }

            using (CompilationContextCookie.GetOrCreate(myProject.GetResolveContext()))
            {
                foreach (var member in typeElement.EnumerateMembers(myMethodName, typeElement.CaseSensitiveName))
                {
                    var method = member as IMethod;
                    if (method == null)
                    {
                        continue;
                    }
                    if (method.IsAbstract)
                    {
                        continue;
                    }
                    if (method.TypeParameters.Count > 0)
                    {
                        continue;
                    }

                    return(member);
                }
                return(null);
            }
        }
Пример #2
0
        private List <IGenerator> GetApplicableGeneratorsFromProvider()
        {
            var result = new List <IGenerator>();

            foreach (IGenerator generator in _generatorsProvider.GetAllGenerators())
            {
                if (generator.Visible)
                {
                    generator.DataProvider = _generatorDataProvider;

                    using (CompilationContextCookie.GetOrCreate(generator.DataProvider.PsiFile.GetResolveContext()))
                    {
                        bool generatorAvailable = false;

                        try
                        {
                            generatorAvailable = generator.IsAvailable();
                        }
                        catch (Exception e)
                        {
                            // Pass to exceptions.
                        }

                        if (generatorAvailable)
                        {
                            result.Add(generator);
                        }
                    }
                }
            }

            return(result);
        }
Пример #3
0
        public void NavigateToMethod(MethodReference methodReference)
        {
            var declaredElement = MethodDeclaredElement(methodReference);

            using (ReadLockCookie.Create())
            {
                using (CompilationContextCookie.GetOrCreate(UniversalModuleReferenceContext.Instance))
                {
                    declaredElement.Navigate(true);
                }
            }
        }
Пример #4
0
 private void InvalidateReferencingModules(IPsiModule psiModule)
 {
     using (CompilationContextCookie.GetOrCreate(psiModule.GetContextFromModule()))
     {
         var resolveContext = CompilationContextCookie.GetContext();
         foreach (var psiModuleReference in PsiModules.GetReverseModuleReferences(psiModule, resolveContext))
         {
             if (myPsiModules.TryGetValue(psiModuleReference.Module, out var moduleSymbols))
             {
                 moduleSymbols.Invalidate();
             }
         }
     }
 }
        protected override void DoTest(Lifetime lifetime, IProject testProject)
        {
            var position = GetCaretPosition();

            IProjectFile item;

            if (position == null)
            {
                item = testProject.GetSubItemsRecursively().OfType <IProjectFile>().First("No project file");
            }
            else
            {
                item = (IProjectFile)testProject.FindProjectItemsByLocation(position.FileName)
                       .Single("No project file", "More than one project file");
            }

            var swea = SolutionAnalysisService.GetInstance(Solution);

            Assert.IsTrue(item.Kind == ProjectItemKind.PHYSICAL_FILE);
            using (TestPresentationMap.Cookie())
                using (swea.RunAnalysisCookie())
                {
                    using (var definition = Lifetime.Define(lifetime))
                    {
                        var boundstore = ChangeSettingsTemporarily(definition.Lifetime).BoundStore;
                        boundstore.SetValue(HighlightingSettingsAccessor.CalculateUnusedTypeMembers, InplaceUsageAnalysis);

                        ITextControl textControl = position != null
                        ? OpenTextControl(definition.Lifetime, position)
                        : OpenTextControl(definition.Lifetime, item);

                        {
                            swea.ReanalyzeFile(item.ToSourceFile());
                            using (CompilationContextCookie.GetOrCreate(textControl.GetContext(Solution)))
                            {
                                ExecuteWithGold(item, writer =>
                                {
                                    var highlightings = GetHighlightings(textControl);

                                    DumpQuickFixesAvailability(writer, highlightings, textControl, Solution);
                                });
                            }
                        }
                    }
                }
        }
        public IEnumerable <IProject> GetProjectDependencies(IT4File file)
        {
            file.AssertContainsNoIncludeContext();
            var sourceFile     = file.LogicalPsiSourceFile.NotNull();
            var projectFile    = sourceFile.ToProjectFile().NotNull();
            var psiModule      = sourceFile.PsiModule;
            var resolveContext = projectFile.SelectResolveContext();

            using (CompilationContextCookie.GetOrCreate(resolveContext))
            {
                return(PsiModules
                       .GetModuleReferences(psiModule)
                       .Select(it => it.Module)
                       .OfType <IProjectPsiModule>()
                       .Select(it => it.Project)
                       .AsList());
            }
        }
Пример #7
0
        public void NavigateToClass(UClass uClass)
        {
            var classSymbol = GetClassSymbol(uClass.Name.Data);

            if (classSymbol == null)
            {
                return;
            }
            var declaredElement = new CppParserSymbolDeclaredElement(_psiServices, classSymbol);

            using (ReadLockCookie.Create())
            {
                using (CompilationContextCookie.GetOrCreate(UniversalModuleReferenceContext.Instance))
                {
                    declaredElement.Navigate(true);
                }
            }
        }
        private void InvalidateReferencingModules(IPsiModule psiModule)
        {
            if (PsiModulesCaches.IsEmpty())
            {
                return;
            }

            // todo: reuse FcsProjectProvider references
            using (CompilationContextCookie.GetOrCreate(psiModule.GetContextFromModule()))
            {
                var resolveContext = CompilationContextCookie.GetContext();
                foreach (var psiModuleReference in PsiModules.GetReverseModuleReferences(psiModule, resolveContext))
                {
                    if (PsiModulesCaches.TryGetValue(psiModuleReference.Module, out var moduleSymbols))
                    {
                        moduleSymbols.Invalidate();
                    }
                }
            }
        }
        public static bool TryExecuteGenerator(IGenerator generator, Action executeAction)
        {
            using (CompilationContextCookie.GetOrCreate(generator.DataProvider.PsiFile.GetResolveContext()))
            {
                try
                {
                    executeAction();
                    return(true);
                }
                catch (GeneratorErrorException e)
                {
                    MessageBox.ShowError(e.Message);
                }
                catch (Exception e)
                {
                    MessageBox.ShowError(e.ToString());
                }
            }

            return(false);
        }
Пример #10
0
        protected override void AugmentQuickInfoSessionCore(
            IQuickInfoSession session,
            IList <object> quickInfoContent,
            IDocumentMarkup documentMarkup,
            TooltipFormattingProvider tooltipFormattingProvider,
            out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;

            ITextSnapshot textSnapshot = TextBuffer.CurrentSnapshot;
            TextRange     textRange    = GetCurrentTextRange(session, textSnapshot);
            IShellLocks   shellLocks   = Shell.Instance.GetComponent <IShellLocks>();
            Span?         finalSpan    = null;

            void GetEnhancedTooltips()
            {
                using (shellLocks.UsingReadLock()) {
                    IDocument document  = documentMarkup.Document;
                    var       presenter = new MultipleTooltipContentPresenter(tooltipFormattingProvider.GetTooltipFormatting(), document);
                    IContextBoundSettingsStore settings = document.GetSettings();
                    ISolution solution = TryGetCurrentSolution();
                    bool      hasIdentifierTooltipContent = false;

                    var resolveContext = solution != null?document.GetContext(solution) : UniversalModuleReferenceContext.Instance;

                    using (CompilationContextCookie.GetOrCreate(resolveContext)) {
                        if (solution != null)
                        {
                            DocumentRange          documentRange = textRange.CreateDocumentRange(document);
                            IdentifierContentGroup contentGroup  = GetIdentifierContentGroup(documentRange, solution, settings);
                            if (contentGroup != null)
                            {
                                foreach (IdentifierTooltipContent content in contentGroup.Identifiers)
                                {
                                    presenter.AddIdentifierTooltipContent(content);
                                    finalSpan = content.TrackingRange.ToSpan().Union(finalSpan);
                                    hasIdentifierTooltipContent = true;
                                }
                                if (contentGroup.ArgumentRole != null)
                                {
                                    presenter.AddArgumentRoleTooltipContent(contentGroup.ArgumentRole);
                                    if (finalSpan == null)
                                    {
                                        // Only track the argument role if we have nothing else displayed.
                                        // See https://github.com/MrJul/ReSharper.EnhancedTooltip/issues/70
                                        finalSpan = contentGroup.ArgumentRole.TrackingRange.ToSpan();
                                    }
                                }
                            }
                        }

                        List <Vs10Highlighter> highlighters = documentMarkup.GetHighlightersOver(textRange).OfType <Vs10Highlighter>().ToList();
                        foreach (Vs10Highlighter highlighter in highlighters)
                        {
                            IEnumerable <IReSharperTooltipContent> contents = GetTooltipContents(highlighter, highlighter.Range, documentMarkup, solution, hasIdentifierTooltipContent);
                            foreach (IReSharperTooltipContent content in contents)
                            {
                                if (presenter.TryAddReSharperContent(content))
                                {
                                    finalSpan = content.TrackingRange.ToSpan().Union(finalSpan);
                                }
                            }
                        }
                    }

                    var vsSquiggleContents = session.RetrieveVsSquiggleContents()
                                             .OfType <string>()
                                             .ToSet();

                    bool ignoredFirstVsElement = false;
                    foreach (object content in quickInfoContent)
                    {
                        if (content == null)
                        {
                            continue;
                        }

                        // ignore existing R# elements
                        if (content is IQuickInfoContent)
                        {
                            continue;
                        }

                        var contentFullName = content.GetType().FullName;

                        // ignore the first VS element, as it's the identifier tooltip and we already have one
                        if (hasIdentifierTooltipContent && !ignoredFirstVsElement)
                        {
                            if (contentFullName == VsFullTypeNames.ContainerElement ||                          /* VS 2017 >= 15.8 */
                                contentFullName == VsFullTypeNames.QuickInfoDisplayPanel ||                         /* VS 2015 and VS 2017 < 15.8 */
                                content is ITextBuffer /* VS2012 and VS2013 */)
                            {
                                ignoredFirstVsElement = true;
                                continue;
                            }
                        }

                        // ignore Roslyn's bulb info placeholder (interactive tooltip "press ctrl+.")
                        if (contentFullName == VsFullTypeNames.LightBulbQuickInfoPlaceHolder)
                        {
                            continue;
                        }

                        if (contentFullName == VsFullTypeNames.QuickInfoDisplayPanel)
                        {
                            presenter.AddVsIdentifierContent(new VsIdentifierContent(content));
                        }
                        else if (content is string stringContent && vsSquiggleContents.Contains(stringContent))
                        {
                            presenter.AddVsSquiggleContent(new VsSquiggleContent(stringContent));
                        }
Пример #11
0
        protected override void DoTest(IProject testProject)
        {
            var positionsToCheck = GetCaretPositions().DefaultIfEmpty(GetCaretPosition()).ToList();

            Assert.IsNotEmpty(positionsToCheck, "Nothing to check - put {caret} where necessary");

            var reparsedNodes = new List <ITreeNode>();

            ShellInstance.GetComponent <TestIdGenerator>().Reset();
            var psiFiles = Solution.GetPsiServices().Files;

            void PsiChanged(ITreeNode node, PsiChangedElementType type)
            {
                if (node != null)
                {
                    reparsedNodes.Add(node);
                }
            }

            psiFiles.AfterPsiChanged += PsiChanged;

            try
            {
                var textControl = OpenTextControl();
                {
                    using (CompilationContextCookie.GetOrCreate(testProject.GetResolveContext()))
                    {
                        // number of original files
                        var originalFiles = new Dictionary <IPsiSourceFile, int>();
                        foreach (var caretPosition in positionsToCheck)
                        {
                            var projectFile = GetProjectFile(testProject, caretPosition.FileName);
                            Assert.NotNull(projectFile);

                            foreach (var psiSourceFile in projectFile.ToSourceFiles())
                            {
                                originalFiles.Add(psiSourceFile, GetPsiFiles(psiSourceFile).Count);
                            }
                        }

                        var checkAll = GetSetting(textControl.Document.Buffer, "CHECKALL");

                        // change text
                        var actions = GetSettings(textControl.Document.Buffer, "ACTION");
                        if (actions.Count == 0)
                        {
                            throw new Exception("No actions found");
                        }
                        foreach (var action in actions)
                        {
                            if (action.Length == 0)
                            {
                                continue;
                            }
                            var text = action.Substring(1).Replace("{LEFT}", "{").Replace("{RIGHT}", "}");
                            switch (action.ToCharArray()[0])
                            {
                            case '+':
                                textControl.Document.InsertText(textControl.Caret.Offset(), text);
                                break;

                            case '-':
                                textControl.Document.DeleteText(TextRange.FromLength(textControl.Caret.Offset(), Convert.ToInt32(text)));
                                break;

                            case '>':
                                textControl.Caret.MoveTo(textControl.Caret.Offset() + Convert.ToInt32(text),
                                                         CaretVisualPlacement.Generic);
                                break;

                            case '<':
                                textControl.Caret.MoveTo(textControl.Caret.Offset() - Convert.ToInt32(text),
                                                         CaretVisualPlacement.Generic);
                                break;

                            default:
                                var actionManager = ShellInstance.GetComponent <IActionManager>();
                                actionManager.Defs.GetActionDefById(TextControlActions.Composition.Compose(action, false))
                                .EvaluateAndExecute(actionManager);
                                break;
                            }

                            if (String.Equals(checkAll, "true", StringComparison.InvariantCultureIgnoreCase))
                            {
                                foreach (var data in originalFiles)
                                {
                                    GetPsiFiles(data.Key);
                                }
                            }
                        }

                        foreach (var data in originalFiles)
                        {
                            var psiSourceFile = data.Key;

                            Assert.IsTrue(psiSourceFile.IsValid());

                            // get reparsed files
                            var reparsedFiles = GetPsiFiles(psiSourceFile);

                            Assert.AreEqual(reparsedFiles.Count, data.Value, "Reparsed psi files count mismatch for {0}", psiSourceFile);

                            // check reparsed element
                            ExecuteWithGold(psiSourceFile, writer =>
                            {
                                if (reparsedNodes.IsEmpty())
                                {
                                    writer.Write("Fully reparsed");
                                }
                                else
                                {
                                    reparsedNodes.Sort((n1, n2) => String.CompareOrdinal(n1.Language.Name, n2.Language.Name));
                                    foreach (var reparsedNode in reparsedNodes)
                                    {
                                        if (reparsedNode is IFile)
                                        {
                                            writer.WriteLine("{0}: Fully reparsed", reparsedNode.Language);
                                        }
                                        else
                                        {
                                            var nodeType = reparsedNode.GetType();
                                            writer.WriteLine("{0}: reparsed node type: {1}, text: {2}", reparsedNode.Language,
                                                             PresentNodeType(nodeType), reparsedNode.GetText());
                                        }
                                    }
                                }
                                if (DoDumpRanges)
                                {
                                    DumpRanges <PsiLanguageType>(psiSourceFile, writer);
                                }
                            });

                            // drop psi files cache
                            WriteLockCookie.Execute(() => psiFiles.MarkAsDirty(psiSourceFile));

                            var files = GetPsiFiles(psiSourceFile);
                            Assert.AreEqual(files.Count, reparsedFiles.Count, "Psi files count mismatch");

                            foreach (var pair in files)
                            {
                                var language = pair.Key;
                                Assert.IsTrue(reparsedFiles.TryGetValue(language, out var reparsedFile), "Failed to find psi file for {0}", language);

                                CompareTrees(pair.Value, reparsedFile);
                            }
                        }
                    }
                }
            }
            finally
            {
                psiFiles.AfterPsiChanged -= PsiChanged;
                reparsedNodes.Clear();
            }
        }