Пример #1
0
        private bool FileIsValid()
        {
            PsiManager manager = PsiManager.GetInstance(this.daemonProcess.Solution);

            if (this.daemonProcess.ProjectFile == null)
            {
                return(false);
            }

            if (!this.daemonProcess.ProjectFile.IsValid)
            {
                return(false);
            }

            IFile file = manager.GetPsiFile(this.daemonProcess.ProjectFile, PsiLanguageType.GetByProjectFile(this.daemonProcess.ProjectFile));

            if (file == null)
            {
                return(false);
            }

            bool hasErrorElements = new RecursiveElementCollector <ErrorElement>().ProcessElement(file).GetResults().Any();

            StyleCopTrace.Info("File has error elements = {0}", hasErrorElements);

            return(!hasErrorElements);
        }
        protected ICSharpFile GetCodeFile(string fileName)
        {
            PsiManager   manager     = PsiManager.GetInstance(Solution);
            IProjectFile projectFile = Project.GetAllProjectFiles(file => file.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

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

            IPsiSourceFile psiSourceFile = projectFile.ToSourceFile();

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

#if SDK70
            var cSharpFile = manager.GetPsiFile(psiSourceFile, CSharpLanguage.Instance,
                                                new DocumentRange(psiSourceFile.Document, psiSourceFile.Document.DocumentRange)) as ICSharpFile;
#else
            var cSharpFile = manager.GetPsiFile(psiSourceFile, CSharpLanguage.Instance) as ICSharpFile;
#endif
            if (cSharpFile == null || string.IsNullOrEmpty(cSharpFile.GetText()))
            {
                Assert.Fail("Unable to open the file '{0}', or the file is empty", fileName);
            }

            return(cSharpFile);
        }
        public override IDeclaredElement GetDeclaredElement()
        {
            PsiManager         manager           = PsiManager.GetInstance(GetSolution());
            IDeclarationsCache declarationsCache = manager.GetDeclarationsCache(DeclarationsScopeFactory.ModuleScope(PsiModuleManager.GetInstance(GetSolution()).GetPrimaryPsiModule(GetProject()), false), true);

            return(declarationsCache.GetTypeElementByCLRName(GetTypeClrName()));
        }
Пример #4
0
        /// <summary>
        /// Process clean-up on file.
        /// </summary>
        /// <param name="projectFile">
        /// The project file to process.
        /// </param>
        /// <param name="rangeMarker">
        /// The range marker to process.
        /// </param>
        /// <param name="profile">
        /// The code cleanup settings to use.
        /// </param>
        /// <param name="progressIndicator">
        /// The progress indicator.
        /// </param>
        public void Process(
            IPsiSourceFile projectFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, JB::JetBrains.Application.Progress.IProgressIndicator progressIndicator)
        {
            if (projectFile == null)
            {
                return;
            }

            if (!this.IsAvailable(projectFile))
            {
                return;
            }

            ISolution solution = projectFile.GetSolution();

            ICSharpFile file = projectFile.GetPsiFile <CSharpLanguage>() as ICSharpFile;

            if (file == null)
            {
                return;
            }

            PsiManager.GetInstance(solution).DoTransaction(() => this.InternalProcess(profile, file), "Code cleanup");

            StyleCopTrace.Out();
        }
Пример #5
0
        public void Execute(Action <DaemonStageResult> commiter)
        {
            PsiManager  manager = PsiManager.GetInstance(myDaemonProcess.Solution);
            ICSharpFile file    = manager.GetPsiFile(myDaemonProcess.SourceFile, CSharpLanguage.Instance) as ICSharpFile;

            if (file == null)
            {
                return;
            }

            // Running visitor against the PSI
            var elementProcessor = new MakeEnumComparisonTypeSafeFinderElementProcessor(myDaemonProcess);

            file.ProcessDescendants(elementProcessor);

            // Checking if the daemon is interrupted by user activity
            if (myDaemonProcess.InterruptFlag)
            {
                throw new ProcessCancelledException();
            }

            // Fill in the result
            DaemonStageResult result = new DaemonStageResult(elementProcessor.Highlightings);

            commiter(result);
        }
        public static IPsiFile GetPsiFile(IPsiSourceFile sourceFile)
        {
            PsiManager manager = PsiManager.GetInstance(sourceFile.GetSolution());

            manager.AssertAllDocumentAreCommited();
            return(manager.GetPsiFile <PsiLanguage>(new DocumentRange(sourceFile.Document, 0)) as IPsiFile);
        }
Пример #7
0
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            IRangeMarker marker = PsiManager.GetInstance(solution).CreatePsiRangeMarker(this.DocumentRange);

            file.ArrangeThisQualifier(marker);
        }
Пример #8
0
        public override IDeclaredElement GetDeclaredElement()
        {
            var solution                         = GetSolution();
            var module                           = PsiModuleManager.GetInstance(solution).GetPsiModule(GetProject().ProjectFile);
            IDeclarationsScope scope             = DeclarationsScopeFactory.ModuleScope(module, false);
            IDeclarationsCache declarationsCache = PsiManager.GetInstance(solution).GetDeclarationsCache(scope, true);

            return(declarationsCache.GetTypeElementByCLRName(GetTypeClrName()));
        }
Пример #9
0
        private static bool ExecuteTransaction([NotNull] IPsiModule module, [NotNull] Action action)
        {
            PsiManager psiManager = PsiManager.GetInstance(module.GetSolution());

            if (psiManager.HasActiveTransaction)
            {
                action();
                return(true);
            }
            return(psiManager.DoTransaction(action, "T4 Assembly Reference").Succeded);
        }
Пример #10
0
        public void Process(
            IPsiSourceFile sourceFile,
            IRangeMarker rangeMarkerMarker,
            CodeCleanupProfile profile,
            IProgressIndicator progressIndicator)
        {
            ISolution solution = sourceFile.GetSolution();

            if (!profile.GetSetting(OurDescriptor))
            {
                return;
            }

            INTriplesFile[] files = sourceFile.GetPsiFiles <NTriplesLanguage>().Cast <INTriplesFile>().ToArray();
            using (progressIndicator.SafeTotal("Reformat Psi", files.Length))
            {
                foreach (INTriplesFile file in files)
                {
                    using (IProgressIndicator pi = progressIndicator.CreateSubProgress(1))
                    {
                        using (WriteLockCookie.Create())
                        {
                            var languageService = file.Language.LanguageService();
                            Assertion.Assert(languageService != null, "languageService != null");
                            var formatter = languageService.CodeFormatter;
                            Assertion.Assert(formatter != null, "formatter != null");

                            PsiManager.GetInstance(sourceFile.GetSolution()).DoTransaction(
                                delegate
                            {
                                if (rangeMarkerMarker != null && rangeMarkerMarker.IsValid)
                                {
                                    formatter.Format(
                                        solution,
                                        rangeMarkerMarker.DocumentRange,
                                        CodeFormatProfile.DEFAULT,
                                        true,
                                        false,
                                        pi);
                                }
                                else
                                {
                                    formatter.FormatFile(
                                        file,
                                        CodeFormatProfile.DEFAULT,
                                        pi);
                                }
                            },
                                "Code cleanup");
                        }
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Performs the QuickFix, ensures the file is both writable and creates a transaction.
        /// </summary>
        /// <param name="solution">
        /// Current Solution.
        /// </param>
        /// <param name="progress">
        /// Progress Indicator for the fix.
        /// </param>
        /// <returns>
        /// The execute transaction.
        /// </returns>
        protected override Action <ITextControl> ExecuteTransaction(ISolution solution, JB::JetBrains.Application.Progress.IProgressIndicator progress)
        {
            return(delegate(ITextControl textControl)
            {
                DocumentManager.GetInstance(solution).SaveAllDocuments();

                using (DocumentManager.GetInstance(solution).EnsureWritable())
                {
                    PsiManager.GetInstance(solution).DoTransaction(() => this.ExecuteWriteLockableTransaction(solution, textControl));
                }
            });
        }
        private ICSharpFile GetCodeFile(string fileName)
        {
            PsiManager   manager     = PsiManager.GetInstance(Solution);
            IProjectFile projectFile = Project.GetAllProjectFiles(file => file.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (projectFile != null)
            {
                return(manager.GetPsiFile(projectFile.ToSourceFile(), CSharpLanguage.Instance) as ICSharpFile);
            }

            return(null);
        }
Пример #13
0
        private void UpdateUI()
        {
            Shell.Instance.Invocator.ReentrancyGuard.ExecuteOrQueue("AddDependencyPage.UpdateUI", delegate
            {
                if (IsDisposed)
                {
                    return;
                }
                using (ReadLockCookie.Create())
                    PsiManager.GetInstance(_solution).CommitAllDocuments();

                FormValidator.GetInstance(this).Update();
            });
        }
Пример #14
0
        /// <summary>
        /// Performs the QuickFix, ensures the file is both writable and creates a transaction.
        /// </summary>
        /// <param name="solution">
        /// Current Solution.
        /// </param>
        /// <param name="progress">
        /// Progress Indicator for the fix.
        /// </param>
        /// <returns>
        /// The execute transaction.
        /// </returns>
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, JB::JetBrains.Application.Progress.IProgressIndicator progress)
        {
            return(delegate(ITextControl textControl)
            {
                solution.GetComponent <DocumentManagerOperations>().SaveAllDocuments();

                using (
                    JB::JetBrains.Util.ITransactionCookie documentTransaction =
                        solution.GetComponent <DocumentTransactionManager>().CreateTransactionCookie(JB::JetBrains.Util.DefaultAction.Commit, "action name"))
                {
                    PsiManager.GetInstance(solution).DoTransaction(() => this.ExecuteWriteLockableTransaction(solution, textControl), "Code cleanup");
                }
            });
        }
        public override void SetUp()
        {
            base.SetUp();
            WrapperAssert.SupportsSpecialFeatures            = false;
            WrapperAssert.SupportsSpecialName                = false;
            WrapperAssert.SupportsCallingConventions         = false;
            WrapperAssert.SupportsReturnAttributes           = false;
            WrapperAssert.SupportsEventFields                = false;
            WrapperAssert.SupportsGenericParameterAttributes = false;
            WrapperAssert.SupportsFinalizers         = false;
            WrapperAssert.SupportsStaticConstructors = false; // compiler generated static constructors introduced by static readonly fields are not supported

            PsiManager manager = PsiManager.GetInstance(SolutionManager.Instance.CurrentSolution);

            reflectionPolicy = new PsiReflectionPolicy(manager);
        }
        protected ITypeElement GetDeclaredType()
        {
            IProject project = GetProject();

            if (project == null)
            {
                return(null);
            }
            PsiManager manager = PsiManager.GetInstance(project.GetSolution());

            using (ReadLockCookie.Create())
            {
                IDeclarationsCache declarationsCache = manager.GetDeclarationsCache(DeclarationsScopeFactory.ModuleScope(PsiModuleManager.GetInstance(project.GetSolution()).GetPrimaryPsiModule(project), true), true);
                return(declarationsCache.GetTypeElementByCLRName(myTypeName));
            }
        }
Пример #17
0
        protected ITypeElement GetDeclaredType()
        {
            ISolution solution = GetSolution();

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

            using (ReadLockCookie.Create())
            {
                IDeclarationsScope scope = DeclarationsScopeFactory.SolutionScope(solution, false);
                IDeclarationsCache cache = PsiManager.GetInstance(solution).GetDeclarationsCache(scope, true);
                return(cache.GetTypeElementByCLRName(_declaringTypeName));
            }
        }
Пример #18
0
        public override IDeclaredElement GetDeclaredElement()
        {
            ISolution solution = GetSolution();

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

            using (ReadLockCookie.Create())
            {
                DeclarationsCacheScope scope = DeclarationsCacheScope.SolutionScope(solution, false);
                IDeclarationsCache     cache = PsiManager.GetInstance(solution).GetDeclarationsCache(scope, true);
                return(cache.GetTypeElementByCLRName(GetTypeClrName()));
            }
        }
        public void Execute(ISolution solution, ITextControl textControl)
        {
            using (ReadLockCookie.Create())
            {
                var manager = PsiManager.GetInstance(solution);
                manager.CommitAllDocuments();

                IProjectItem parentFolder = GetParentFolder(_sourceTypeDeclaration);
                MoveToOuterFile();

                IProjectItem sourceFile = GetSourceFile(parentFolder, _sourceTypeDeclaration);
                IProjectFile newFile    = MoveFileToProject(sourceFile);
                OpenFileInEditor(solution, newFile);
                sourceFile.Remove();
            }
        }
Пример #20
0
        private void UpdateUI()
        {
            var shellLocks = Shell.Instance.GetComponent <IShellLocks>();

            shellLocks.ReentrancyGuard.ExecuteOrQueue(
                "AddDependencyPage.UpdateUI",
                delegate
            {
                if (IsDisposed)
                {
                    return;
                }
                using (ReadLockCookie.Create())
                    PsiManager.GetInstance(_solution).CommitAllDocuments();

                Shell.Instance.GetComponent <FormValidators>().GetOrCreate(this).Update();
            });
        }
Пример #21
0
        protected ITypeElement GetDeclaredType()
        {
            IProject project = GetProject();

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

            using (ReadLockCookie.Create())
            {
                var solution                         = GetSolution();
                var module                           = PsiModuleManager.GetInstance(solution).GetPsiModule(GetProject().ProjectFile);
                IDeclarationsScope scope             = DeclarationsScopeFactory.ModuleScope(module, true);
                IDeclarationsCache declarationsCache = PsiManager.GetInstance(solution).GetDeclarationsCache(scope, true);

                return(declarationsCache.GetTypeElementByCLRName(myTypeName));
            }
        }
Пример #22
0
        /// <summary>
        /// Executes the process.
        /// The process should check for <see cref="P:JetBrains.ReSharper.Daemon.IDaemonProcess.InterruptFlag"/> periodically (with intervals less than 100 ms)
        /// and throw <see cref="T:JetBrains.Application.Progress.ProcessCancelledException"/> if it is true.
        /// Failing to do so may cause the program to prevent user from typing while analysing the code.
        /// Stage results should be passed to <param name="commiter"/>. If DaemonStageResult is <c>null</c>, it means that no highlightings available
        /// </summary>
        public void Execute(Action <DaemonStageResult> commiter)
        {
            if (DaemonProcess.InterruptFlag)
            {
                return;
            }

            PsiManager manager    = PsiManager.GetInstance(DaemonProcess.Solution);
            var        sourceFile = manager.GetPsiFile(DaemonProcess.SourceFile, CSharpLanguage.Instance) as ICSharpFile;

            if (sourceFile != null)
            {
                List <INamingConsistencyChecker> list =
                    LanguageManager.Instance.GetServices <INamingConsistencyChecker>(sourceFile.Language).Where(x => x.IsApplicable(DaemonProcess.SourceFile)).ToList();

                list.ForEach(Console.WriteLine);

                var highlights = new List <HighlightingInfo>();

                // highlight field declarations
                var processor = new RecursiveElementProcessor <IFieldDeclaration>(
                    declaration =>
                {
                    DocumentRange docRange = declaration.GetNameDocumentRange();

                    highlights.Add(new HighlightingInfo(docRange, new NameInfoHighlighting(declaration)));
                });
                sourceFile.ProcessDescendants(processor);

                // highlight local var declarations
                var localVarsProcessor = new RecursiveElementProcessor <ILocalVariableDeclaration>(
                    declaration =>
                {
                    DocumentRange docRange = declaration.GetNameDocumentRange();

                    highlights.Add(new HighlightingInfo(docRange, new NameInfoHighlighting(declaration)));
                });
                sourceFile.ProcessDescendants(localVarsProcessor);

                commiter(new DaemonStageResult(highlights));
            }
        }
Пример #23
0
        private bool FileIsValid()
        {
            PsiManager manager = PsiManager.GetInstance(this.daemonProcess.Solution);

            if (!this.daemonProcess.SourceFile.ToProjectFile().IsValid())
            {
                return(false);
            }

            IFile file = this.daemonProcess.SourceFile.GetPsiFile(CSharpLanguage.Instance);

            if (file == null)
            {
                return(false);
            }

            bool hasErrorElements = new RecursiveElementCollector <ErrorElement>().ProcessElement(file).GetResults().Any();

            return(!hasErrorElements);
        }
Пример #24
0
        public void ExecuteTemplate()
        {
            IDeclaration newDeclaration = myDeclaration;

            newDeclaration.AssertIsValid();

            ISolution solution = newDeclaration.GetPsiModule().GetSolution();

            Shell.Instance.Invocator.Dispatcher.AssertAccess();

            Assertion.Assert(!PsiManager.GetInstance(solution).HasActiveTransaction, "PSI transaction is active");
            solution.GetComponent <SolutionDocumentTransactionManager>().AssertNotUnderTransaction();

            IFile file = myAnchor.GetContainingFile();

            Assertion.Assert(file != null, "file!= null");
            var item = file.GetSourceFile().ToProjectFile();

            var infos = GetFieldInfos(newDeclaration, myHolders);

            var textControl = EditorManager.GetInstance(solution).OpenProjectFile(item, true, TabOptions.DefaultTab);

            if (textControl == null)
            {
                if (Shell.Instance.IsInInternalMode || Shell.Instance.IsTestShell)
                {
                    Logger.Fail("textControl != null");
                }
                return;
            }

            if (infos.Length > 0)
            {
                HotspotSession hotspotSession = LiveTemplatesManager.Instance.CreateHotspotSessionAtopExistingText(solution,
                                                                                                                   TextRange.InvalidRange, textControl, LiveTemplatesManager.EscapeAction.LeaveTextAndCaret, infos);
                hotspotSession.Execute();
            }

            Shell.Instance.GetComponent <PsiIntentionResultBehavior>().OnHotspotSessionExecutionStarted(this, textControl);
        }
Пример #25
0
        private bool ReferenceModuleImpl([NotNull] IPsiModule module, [NotNull] IPsiModule moduleToReference, [CanBeNull] string ns)
        {
            if (!CanReferenceModule(module, moduleToReference))
            {
                return(false);
            }

            var t4PsiModule = (T4PsiModule)module;
            var assembly    = (IAssembly)moduleToReference.ContainingProjectModule;

            Assertion.AssertNotNull(assembly, "assembly != null");

            var t4File = t4PsiModule.SourceFile.GetNonInjectedPsiFile <T4Language>() as IT4File;

            if (t4File == null)
            {
                return(false);
            }

            Action action = () => {
                // add assembly directive
                AddDirective(t4File, _directiveInfoManager.Assembly.CreateDirective(assembly.FullAssemblyName));

                // add import directive if necessary
                if (!String.IsNullOrEmpty(ns) &&
                    !t4File.GetDirectives(_directiveInfoManager.Import).Any(d => String.Equals(ns, d.GetAttributeValue(_directiveInfoManager.Import.NamespaceAttribute.Name), StringComparison.Ordinal)))
                {
                    AddDirective(t4File, _directiveInfoManager.Import.CreateDirective(ns));
                }
            };

            PsiManager psiManager = PsiManager.GetInstance(module.GetSolution());

            if (psiManager.HasActiveTransaction)
            {
                action();
                return(true);
            }
            return(psiManager.DoTransaction(action, "T4 Assembly Reference").Succeded);
        }
Пример #26
0
        public bool Execute(IProgressIndicator progressIndicator)
        {
            var ctor = _ctor.FindDeclaredElement();

            if (ctor == null)
            {
                return(false);
            }
            var definingClass = _class.FindDeclaredElement();

            if (definingClass == null)
            {
                return(false);
            }
            if (ctor.Module == null)
            {
                return(false);
            }
            var factory  = CSharpElementFactory.GetInstance(ctor.Module);
            var ctorDecl = ctor.GetDeclarations().FirstOrDefault();

            if (ctorDecl == null)
            {
                var typeDecl = definingClass.GetDeclarations().FirstOrDefault() as IClassLikeDeclarationNode;
                if (typeDecl == null)
                {
                    return(false);
                }
                var typeBody = typeDecl.Body;
                ctorDecl = factory.CreateTypeMemberDeclaration("public $0() {}", typeDecl.DeclaredName);
                if (typeBody.FirstChild == null)
                {
                    return(false);
                }
                if (ctorDecl == null)
                {
                    return(false);
                }

                ctorDecl = ModificationUtil.AddChildBefore(
                    typeBody,
                    typeBody.FirstChild.NextSibling,
                    ctorDecl.ToTreeNode()).GetContainingElement <IConstructorDeclaration>(true);
            }
            if (ctorDecl == null)
            {
                return(false);
            }
            var type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.ToTreeNode());

            if (!type.IsResolved)
            {
                type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.GetPsiModule());
            }
            string recommendedName = null;
            var    naming          = PsiManager.GetInstance(_solution).Naming;

            if (!type.IsResolved)
            {
                var presentableName = type.GetPresentableName(CSharpLanguageService.CSHARP);
                var indexOfGeneric  = presentableName.IndexOf('<');
                if (indexOfGeneric != -1)
                {
                    var interfaceName   = presentableName.Substring(1, indexOfGeneric - 1);
                    var genericArgument = presentableName.Substring(indexOfGeneric).Trim('<', '>');
                    recommendedName = naming.Suggestion.GetDerivedName(
                        genericArgument + interfaceName,
                        NamedElementKinds.Parameters,
                        ScopeKind.Common,
                        CSharpLanguageService.CSHARP,
                        new SuggestionOptions());
                }
                var interfaceDecl = factory.CreateTypeMemberDeclaration("public interface IFoo {}");
                if (interfaceDecl == null)
                {
                    return(false);
                }
                interfaceDecl.SetName(presentableName);
                interfaceDecl.LanguageService.CodeFormatter.Format(interfaceDecl.ToTreeNode(), CodeFormatProfile.GENERATOR);
                var containingType = ctor.GetContainingType();
                if (containingType == null)
                {
                    return(false);
                }
                var containingTypeDecl = containingType.GetDeclarations().First();
                ModificationUtil.AddChildBefore(containingTypeDecl.ToTreeNode(), interfaceDecl.ToTreeNode());
            }
            type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.ToTreeNode());
            if (recommendedName == null)
            {
                var suggestionOptions = new SuggestionOptions();
                recommendedName = naming.Suggestion.GetDerivedName(
                    type.GetPresentableName(CSharpLanguageService.CSHARP),
                    NamedElementKinds.Parameters, ScopeKind.Common,
                    CSharpLanguageService.CSHARP, suggestionOptions);
            }
            var parametersOwner = ctorDecl as ICSharpParametersOwnerDeclaration;
            var references      = FindReferences(parametersOwner, progressIndicator);

            if (parametersOwner == null)
            {
                return(false);
            }
            parametersOwner.AddParameterDeclarationAfter(
                ParameterKind.VALUE, type, recommendedName,
                parametersOwner.ParameterDeclarations.LastOrDefault());

            foreach (var reference in references)
            {
                ChangeReference(reference, recommendedName, type);
            }

            return(true);
        }
Пример #27
0
        /// <summary>
        /// This code changes PSI documents. It is executed usder PSI transaction, Command cookies, Reentrancy guard ets.
        /// All documents are committed (PSI is valid).
        /// </summary>
        public override bool Execute(IProgressIndicator pi)
        {
            pi.Start(6);

            //check if data stored in workflow is valid...
            Method    = Workflow.MethodPointer.FindDeclaredElement();
            Parameter = Workflow.ParameterPointer.FindDeclaredElement();

            if (Method == null || Parameter == null)
            {
                return(false);
            }

            IPsiServices services = Parameter.GetPsiServices();

            IReference[] referencesToParameter;
            IReference[] referencesToRootOverrides;

            // search for method overrides (OverridesFinder is util class that
            // allows to find all overrides and problems with quasi implementations)
            OverridesFinder overridesFinder = OverridesFinder.CreateInstance(Method);

            using (var subPi = new SubProgressIndicator(pi, 1))
                overridesFinder.Find(subPi);

            JetHashSet <HierarchyMember> hierarchyMembers = overridesFinder.Overrides;

            List <IMethod>    methods    = ScanHierarchyConflicts(hierarchyMembers).ToList();
            List <IParameter> parameters = GetAllParameters(methods).ToList();

            // find parameters and methods usages...
            using (var subPi = new SubProgressIndicator(pi, 1))
            {
                subPi.TaskName = "Searching parameter usages:";
                IEnumerable <IPsiSourceFile> projectFiles = from param in parameters
                                                            let projectFilesOfOneParameter = param.GetSourceFiles()
                                                                                             from projectFile in projectFilesOfOneParameter
                                                                                             select projectFile;
                ISearchDomain searchDomain = mySearchDomainFactory.CreateSearchDomain(projectFiles.ToList());
                referencesToParameter = services.Finder.FindReferences(parameters, searchDomain, subPi);
            }

            using (var subPi = new SubProgressIndicator(pi, 1))
            {
                subPi.TaskName            = "Searching method usages:";
                referencesToRootOverrides = services.Finder.FindReferences(methods,
                                                                           mySearchDomainFactory.CreateSearchDomain(Solution,
                                                                                                                    false), subPi);
            }

            // this step processes method usages, removes argument and stores reference specific data to the 'MethodInvocation'.
            List <MethodInvocation> usages;

            using (var subPi = new SubProgressIndicator(pi, 1))
                usages = PreProcessMethodUsages(referencesToRootOverrides, subPi).ToList();

            // replace usages of parameters with typeof(TNewTypeParameter) expression.
            using (var subPi = new SubProgressIndicator(pi, 1))
                ProcessParameterUsages(referencesToParameter, subPi);

            // Remove parameters from method declarations and insert new type parmeter. Map contains method -> new type parameter relation.
            Dictionary <IMethod, ITypeParameter> map = UpdateDeclarations(methods);

            // We have changed declarations. cashes should be updated)
            PsiManager.GetInstance(Solution).UpdateCaches();

            // Process method usages one more time to insert correct type arguments to the call.
            using (var subPi = new SubProgressIndicator(pi, 1))
                BindUsages(usages, map, subPi);

            return(true);
        }
Пример #28
0
        private void DoSmartIndentOnEnter(ITextControl textControl)
        {
            var originalOffset = textControl.Caret.Offset();

            var offset     = TextControlToLexer(textControl, originalOffset);
            var mixedLexer = GetCachingLexer(textControl);

            // if there is something on that line, then use existing text
            if (offset <= 0 || !mixedLexer.FindTokenAt(offset - 1))
            {
                return;
            }

            if (mixedLexer.TokenType == PsiTokenType.C_STYLE_COMMENT || mixedLexer.TokenType == PsiTokenType.STRING_LITERAL)
            {
                return;
            }

            if (offset <= 0 || !mixedLexer.FindTokenAt(offset))
            {
                return;
            }

            while (mixedLexer.TokenType == PsiTokenType.WHITE_SPACE)
            {
                mixedLexer.Advance();
            }

            offset = mixedLexer.TokenType == null ? offset : mixedLexer.TokenStart;
            var extraText = (mixedLexer.TokenType == PsiTokenType.NEW_LINE || mixedLexer.TokenType == null) ? "foo " : String.Empty;

            var projectItem = textControl.Document.GetPsiSourceFile(Solution);

            if (projectItem == null || !projectItem.IsValid())
            {
                return;
            }

            using (PsiManager.GetInstance(Solution).DocumentTransactionManager.CreateTransactionCookie(DefaultAction.Commit, "Typing assist"))
            {
                // If the new line is empty, the do default indentation
                int lexerOffset = offset;
                if (extraText.Length > 0)
                {
                    textControl.Document.InsertText(lexerOffset, extraText);
                }

                PsiServices.PsiManager.CommitAllDocuments();
                var file = projectItem.GetPsiFile <PsiLanguage>(new DocumentRange(textControl.Document, offset));

                if (file == null)
                {
                    return;
                }

                var rangeInJsTree = file.Translate(new DocumentOffset(textControl.Document, offset));

                if (!rangeInJsTree.IsValid())
                {
                    if (extraText.Length > 0)
                    {
                        textControl.Document.DeleteText(new TextRange(lexerOffset, lexerOffset + extraText.Length));
                    }
                    return;
                }

                var tokenNode = file.FindTokenAt(rangeInJsTree) as ITokenNode;
                if (tokenNode == null)
                {
                    if (extraText.Length > 0)
                    {
                        textControl.Document.DeleteText(new TextRange(lexerOffset, lexerOffset + extraText.Length));
                    }
                    return;
                }

                PsiCodeFormatter codeFormatter = GetCodeFormatter(file);
                int offsetInToken = rangeInJsTree.Offset - tokenNode.GetTreeStartOffset().Offset;

                using (PsiTransactionCookie.CreateAutoCommitCookieWithCachesUpdate(PsiServices, "Typing assist"))
                {
                    Lifetimes.Using(
                        lifetime =>
                    {
                        var boundSettingsStore = SettingsStore.CreateNestedTransaction(lifetime, "PsiTypingAssist").BindToContextTransient(textControl.ToContextRange());
                        var prevToken          = tokenNode.GetPrevToken();
                        if (prevToken == null)
                        {
                            return;
                        }

                        if (tokenNode.Parent is IParenExpression || prevToken.Parent is IParenExpression)
                        {
                            var node = tokenNode.Parent;
                            if (prevToken.Parent is IParenExpression)
                            {
                                node = prevToken.Parent;
                            }
                            codeFormatter.Format(node.FirstChild, node.LastChild,
                                                 CodeFormatProfile.DEFAULT, NullProgressIndicator.Instance, boundSettingsStore);
                        }
                        else
                        {
                            codeFormatter.Format(prevToken, tokenNode,
                                                 CodeFormatProfile.INDENT, NullProgressIndicator.Instance, boundSettingsStore);
                        }
                    });
                    offset = file.GetDocumentRange(tokenNode.GetTreeStartOffset()).TextRange.StartOffset +
                             offsetInToken;
                }

                if (extraText.Length > 0)
                {
                    lexerOffset = offset;
                    textControl.Document.DeleteText(new TextRange(lexerOffset, lexerOffset + extraText.Length));
                }
            }

            textControl.Caret.MoveTo(offset, CaretVisualPlacement.DontScrollIfVisible);
        }