public void Execute(ISolution solution, ITextControl textControl) { if (!_literalExpression.IsValid()) { return; } var containingFile = _literalExpression.GetContainingFile(); var psiModule = _literalExpression.GetPsiModule(); var elementFactory = CSharpElementFactory.GetInstance(_literalExpression); IExpression newExpression = null; _literalExpression.GetPsiServices().Transactions.Execute(GetType().Name, () => { using (solution.GetComponent <IShellLocks>().UsingWriteLock()) newExpression = ModificationUtil.ReplaceChild( _literalExpression.Task, elementFactory.CreateExpression("$0.ConfigureAwait($1)", _literalExpression.Task, elementFactory.CreateExpressionByConstantValue(CSharpConstantValueFactory.CreateBoolValue(_value, psiModule)))); }); if (newExpression != null) { IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>()); containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Create()); } }
private void ProcessBehaviorContainer(IDeclaredElement element) { var solution = element.GetSolution(); var finder = solution.GetPsiServices().Finder; var searchDomain = _searchDomainFactory.CreateSearchDomain(solution, false); var consumer = new SearchResultsConsumer(); var progress = NullProgressIndicator.Create(); finder.Find(new[] { element }, searchDomain, consumer, SearchPattern.FIND_USAGES, progress); var contexts = consumer.GetOccurrences() .OfType <ReferenceOccurrence>() .Select(x => x.GetTypeElement().GetValidDeclaredElement()) .OfType <IClass>() .Where(x => x.IsContext()); foreach (var context in contexts) { var type = context.AsTypeInfo(); var declaration = context.GetDeclarations().FirstOrDefault(); if (declaration != null) { ProcessContext(type, declaration, false); foreach (var field in type.GetFields()) { ProcessField(declaration.GetProject(), field); } } } }
public IEnumerable <ITypeElement> GetLinkedTypes(IReadOnlyList <ITypeElement> allSourceTypes, IPsiServices services) { foreach (var sourceType in allSourceTypes) { foreach (var linkedType in GetLinkedTypes(sourceType)) { yield return(linkedType); if (!ReferenceEquals(sourceType, allSourceTypes[index: 0])) { continue; } var derivedLinkedTypes = new List <ITypeElement>(); services.Finder.FindInheritors(linkedType, new FindResultConsumer(x => { var typeElement = (x as FindResultDeclaredElement)?.DeclaredElement as ITypeElement; if (typeElement != null) { derivedLinkedTypes.Add(typeElement); } return(FindExecution.Continue); }), NullProgressIndicator.Create()); foreach (var derivedLinkedType in derivedLinkedTypes) { yield return(derivedLinkedType); } } } }
public static IReadOnlyCollection <ITypeElement> GetLinkedTypes(ITypeElement source) { var sources = new[] { source } .Concat(source.GetAllSuperTypes() .Select(x => x.GetTypeElement()) .WhereNotNull() .Where(x => !x.IsObjectClass())); var linkedTypes = sources.SelectMany(GetLinkedTypesInternal).ToList(); // TODO move to Internal method var services = source.GetPsiServices(); linkedTypes.ForEach(x => services.Finder.FindInheritors(x, new FindResultConsumer(y => { if ((y as FindResultDeclaredElement)?.DeclaredElement is ITypeElement typeElement) { linkedTypes.Add(typeElement); } return(FindExecution.Continue); }), NullProgressIndicator.Create())); return(linkedTypes); }
public void TestNullProgressIndicatorUpdate() { NullProgressIndicator np = new NullProgressIndicator(); np.UpdateProgress(50, 100, "description"); Assert.AreEqual("", standardOut.ToString()); }
public void Execute(ISolution solution, ITextControl textControl) { Shell.Instance.GetComponent <UITaskExecutor>().SingleThreaded.ExecuteTask("Cleanup file", TaskCancelable.No, progress => { progress.TaskName = _profile.Name; progress.Start(1); using (Shell.Instance.GetComponent <ICommandProcessor>().UsingBatchTextChange("Code Cleanup")) { using (var cookie = solution.GetComponent <SolutionDocumentTransactionManager>().CreateTransactionCookie(DefaultAction.Rollback, "Code cleanup")) { var progressIndicator = NullProgressIndicator.Create(); CodeCleanup instance = CodeCleanup.GetInstance(solution); int caret = -1; instance.Run(this._dataProvider.SourceFile, DocumentRange.InvalidRange, ref caret, _profile, NullProgressIndicator.Create()); cookie.Commit(progressIndicator); } } progress.Stop(); }); }
public static void OrginizeUsingsAndFormatFile(ISolution solution, IDocument document) { IPsiSourceFile sourceFile = document.GetPsiSourceFile(solution); IPsiServices psiServices = solution.GetPsiServices(); psiServices.Files.CommitAllDocuments(); PsiTransactionCookie.ExecuteConditionally( psiServices, () => { if (sourceFile?.GetPsiFile(CSharpLanguage.Instance, new DocumentRange(document, 0)) is ICSharpFile psiFile) { SortImports(psiFile); psiFile.OptimizeImportsAndRefs( new RangeMarker(document.ToPointer(), new TextRange(0, document.DocumentRange.Length)), true /* optimizeUsings */, true /* shortenReferences */, NullProgressIndicator.Create() ); psiFile.FormatNode(); } return(true); }, "Format T4 Generated File" ); }
public void Execute(IDataContext context, DelegateExecute nextExecute) { var solution = context.GetData(ProjectModelDataConstants.SOLUTION); if (solution == null) { return; } var workflow = new ConvertWebFormsToRazorRefactoringWorkflow( solution, nameof(ConvertWebFormsToRazorAction), context.GetComponent <RazorConverterSettingsStore>(), Shell.Instance.GetComponent <IMainWindowPopupWindowContext>()); if (!workflow.IsAvailable(context) || !workflow.Initialize(context)) { return; } using (var pi = NullProgressIndicator.Create()) { workflow.PreExecute(pi); workflow.Execute(pi); workflow.PostExecute(pi); } }
public void TestNullProgressIndicatorComplete() { NullProgressIndicator np = new NullProgressIndicator(); np.Complete(); Assert.AreEqual("", standardOut.ToString()); }
static void Analyze([NotNull] ILocalFunctionDeclaration localFunctionDeclaration, [NotNull] IHighlightingConsumer consumer) { if (!localFunctionDeclaration.IsAsync || !localFunctionDeclaration.IsVoidMethodDeclaration()) { return; // not an "async void" local function } var psiServices = localFunctionDeclaration.GetPsiServices(); Debug.Assert(SearchDomainFactory.Instance != null); var solutionSearchDomain = SearchDomainFactory.Instance.CreateSearchDomain(psiServices.Solution, false); var references = psiServices.Finder.FindReferences( localFunctionDeclaration.DeclaredElement, solutionSearchDomain, NullProgressIndicator.Create()); var count = references.Count(reference => !reference.AssertNotNull().IsEventTarget()); if (count > 0) { consumer.AddHighlighting( new AvoidAsyncVoidHighlighting( string.Format( "'async void' local function used {0} time{1} not as a direct event handler.", count.ToString(), count == 1 ? "" : "s"), localFunctionDeclaration)); } }
private Action <ITextControl> ChangeParameters(ISolution solution) { var model = ClrChangeSignatureModel.CreateModel(myMethodDeclaration.DeclaredElement).NotNull(); for (var i = 0; i < myExpectedMethodSignature.Parameters.Length; i++) { var requiredParameter = myExpectedMethodSignature.Parameters[i]; var modelParameter = FindBestMatch(requiredParameter, model, i); if (modelParameter != null) { // If the current index is correct, do nothing. If not, use the original index to find the item to move if (modelParameter.ParameterIndex != i) { model.MoveTo(modelParameter.OriginalParameterIndex, i); } } else { model.Add(i); modelParameter = model.ChangeSignatureParameters[i]; } modelParameter.ParameterName = requiredParameter.Name; modelParameter.ParameterKind = ParameterKind.VALUE; modelParameter.ParameterType = requiredParameter.Type; // Reset everything else modelParameter.IsOptional = false; modelParameter.IsParams = false; modelParameter.IsThis = false; modelParameter.IsVarArg = false; } for (var i = model.ChangeSignatureParameters.Length - 1; i >= myExpectedMethodSignature.Parameters.Length; i--) { model.RemoveAt(i); } var refactoring = new ChangeSignatureRefactoring(model); refactoring.Execute(NullProgressIndicator.Create()); // Ideally, we would now call InplaceRefactoringsManager.Reset to make sure we didn't have // an inplace refactoring highlight. But InplaceRefactoringsManager is internal, so we can't. // We don't want a highlight telling us to "apply signature change refactoring" because we // just have. The only way to remove it is to fire the Escape action return(tc => { var highlightingManager = solution.GetComponent <InplaceRefactoringsHighlightingManager>(); if (highlightingManager.GetHighlightersForTests(tc).Any()) { var actionManager = solution.GetComponent <IActionManager>(); var escapeActionHandler = actionManager.Defs.GetActionDef <EscapeActionHandler>(); escapeActionHandler.EvaluateAndExecute(actionManager); } }); }
private static bool TryGenerateFile( ISolution solution, IProjectFile sourceFile, string filePath, string generatedText, out IProjectFile generatedFile) { using (var progressIndicator = NullProgressIndicator.Create()) { IProjectModelTransactionCookie transaction = solution.CreateTransactionCookie(DefaultAction.Rollback, "T4 Generating file", progressIndicator); using (transaction) { if (!TryCreateFile(filePath, solution, sourceFile, transaction, out generatedFile)) { return(false); } IDocument generatedDocument = generatedFile.GetDocument(); generatedDocument.ReplaceText(generatedDocument.DocumentRange, generatedText); ExecutionHelpers.OrginizeUsingsAndFormatFile(solution, generatedDocument); transaction.Commit(progressIndicator); } } return(true); }
private static bool TryGenerateFiles( ISolution solution, List <FileGeneratorOutput> fileGeneratorOutputs, List <InPlaceGeneratorOutput> inPlaceGeneratorOutputs) { if (!TryProcessFilePaths(solution, fileGeneratorOutputs, out List <FileGeneratorOutput> notFoundProjectFolderOutputs)) { return(false); } using (var progressIndicator = NullProgressIndicator.Create()) { IProjectModelTransactionCookie transaction = solution.CreateTransactionCookie(DefaultAction.Rollback, "T4 Generating files", progressIndicator); using (transaction) { if (!TryCreateProjectFolders(notFoundProjectFolderOutputs, transaction)) { return(false); } if (!TryCreateFiles(fileGeneratorOutputs, transaction)) { return(false); } MakeDocumentChanges(solution, fileGeneratorOutputs, inPlaceGeneratorOutputs); transaction.Commit(progressIndicator); } } return(true); }
public static IEnumerable <IMethod> FindAllHierarchy([NotNull] this IMethod method, [CanBeNull] IProgressIndicator pi = null) { var finder = method .GetPsiServices() .Finder; return(InnerFindAllHierarchy(finder, method, pi ?? NullProgressIndicator.Create())); }
public static IReference[] FindReferences([NotNull] this ITreeNode treeNode, [NotNull] IDeclaredElement declaredElement) { IPsiServices psiServices = treeNode.GetPsiServices(); return(psiServices.Finder.FindReferences( declaredElement, psiServices.SearchDomainFactory.CreateSearchDomain(treeNode), NullProgressIndicator.Create() )); }
private string GetTextAfterFormatting([NotNull] IDocument document, [NotNull] ITextControl textControl) { using (Solution.GetComponent <DocumentTransactionManager>() .CreateTransactionCookie(DefaultAction.Rollback, "Temporary change")) { var file = document.GetPsiSourceFile(Solution); var codeCleanup = CodeCleanup.GetInstance(Solution); var codeCleanupSettings = Shell.Instance.GetComponent <CodeCleanupSettingsComponent>(); var profile = codeCleanupSettings.GetDefaultProfile(CodeCleanup.DefaultProfileType.REFORMAT); var selectionRange = textControl.Selection.OneDocRangeWithCaret(); codeCleanup.Run(file, selectionRange.Length > 0 ? new DocumentRange(textControl.Document, selectionRange) : DocumentRange.InvalidRange, profile, NullProgressIndicator.Create()); return(document.GetText()); } }
private static IReadOnlyCollection <IIssue> RunInspections(ISolution solution, IEnumerable <IPsiSourceFile> sourceFiles) { var issues = new List <IIssue>(); using (var lifetime = Lifetimes.Define(solution.GetLifetime())) using (var nullProgressIndicator = NullProgressIndicator.Create()) { var collectInspectionResults = new CollectInspectionResults(solution, lifetime, nullProgressIndicator); collectInspectionResults.RunLocalInspections( new Stack <IPsiSourceFile>(sourceFiles), issuePointers => issues.AddRange(issuePointers)); } return(issues); }
private bool IsHandlerExists(Lifetime lifetime, int projectId, string className, string methodName) { var indicator = NullProgressIndicator.CreateCancellable(lifetime); using (TryReadLockCookie.Create(indicator, _locks, () => !lifetime.IsAlive || _locks.ContentModelLocks.IsWriteLockRequested)) { var project = _projectModelViewHost.GetItemById <IProject>(projectId); Assertion.AssertNotNull(project, "project instance should not be null"); _logger.Verbose($"Searching handler with name '{className}.{methodName}' in the project {project}..."); var psiModules = project.GetPsiModules(); foreach (var psiModule in psiModules) { using (CompilationContextCookie.OverrideOrCreate(psiModule.GetContextFromModule())) { var scope = _symbolCache.GetSymbolScope(psiModule, false, true); var typeElements = scope.GetElementsByQualifiedName(className).OfType <IClass>(); foreach (var typeElement in typeElements) { InterruptableActivityCookie.CheckAndThrow(indicator); foreach (var method in typeElement.Methods) { if (method.ShortName != methodName) { continue; } if (!LambdaFinder.IsSuitableLambdaMethod(method)) { continue; } return(true); } } } } } return(false); }
protected override bool TryExecute(IInPlaceGenerator generator, GeneratorExecutionHost executionHost) { IDocument document = generator.DataProvider.Document; bool executed = ExecutionHelpers.TryExecuteGenerator( generator, out string generatedText, out TextRange rangeToDelete, out int positionToInsert, out IReadOnlyCollection <IUsingDirective> missingUsingDirectives ); if (!executed) { return(false); } ISolution solution = generator.DataProvider.Solution; using (var progressIndicator = NullProgressIndicator.Create()) { IProjectModelTransactionCookie transaction = solution.CreateTransactionCookie(DefaultAction.Rollback, "T4 Generating file", progressIndicator); using (transaction) { if (!rangeToDelete.IsEmpty) { document.DeleteText(rangeToDelete); } document.InsertText(positionToInsert, generatedText); var treeTextRange = TreeTextRange.FromLength(new TreeOffset(positionToInsert), generatedText.Length); ExecutionHelpers.FormatFileRangeAndAddUsingDirectives(solution, document, treeTextRange, missingUsingDirectives); transaction.Commit(progressIndicator); } } return(true); }
public static IList <TOverridableMember> FindImplementingMembers <TOverridableMember>([NotNull] this TOverridableMember overridableMember, [CanBeNull] IProgressIndicator pi = null) where TOverridableMember : class, IOverridableMember { var found = new List <TOverridableMember>(); overridableMember .GetPsiServices() .Finder .FindImplementingMembers(overridableMember, overridableMember.GetSearchDomain(), new FindResultConsumer(findResult => { var resultOverridableMember = findResult as FindResultOverridableMember; var result = resultOverridableMember?.OverridableMember as TOverridableMember; if (result != null) { found.Add(result); } return(FindExecution.Continue); }), true, pi ?? NullProgressIndicator.Create()); return(found); }
private static void HighlightReferencesInFile(IDeclaredElement declaredElement, IPsiDocumentRangeView psiDocumentRangeView, HighlightingsConsumer consumer) { var searchDomain = SearchDomainFactory.Instance.CreateSearchDomain(psiDocumentRangeView.SortedSourceFiles); var elements = new[] { new DeclaredElementInstance(declaredElement) }; var searchRequest = new SearchSingleFileDeclaredElementRequest(elements, elements, searchDomain); foreach (var occurrence in searchRequest.Search(NullProgressIndicator.Create()) ?? EmptyList <IOccurrence> .InstanceList) { if (!(occurrence is ReferenceOccurrence referenceOccurrence)) { continue; } var primaryReference = referenceOccurrence.PrimaryReference; if (primaryReference == null) { continue; } var documentRange = primaryReference.GetDocumentRange(); consumer.ConsumeHighlighting(HIGHLIGHTING_ID, documentRange); } }
public PsiCodeFormattingContext(PsiCodeFormatter psiCodeFormatter, ITreeNode firstNode, ITreeNode lastNode, NullProgressIndicator instance) : base(psiCodeFormatter, firstNode, lastNode, instance) { }
static void Analyze([NotNull] IMethodDeclaration methodDeclaration, [NotNull] IHighlightingConsumer consumer) { if (!methodDeclaration.IsAsync || !methodDeclaration.IsVoidMethodDeclaration()) { return; // not an "async void" method } var method = methodDeclaration.DeclaredElement; if (method == null) { return; // cannot analyze } if (method.GetImmediateSuperMembers().Any()) { consumer.AddHighlighting( new AvoidAsyncVoidHighlighting("'void' method overridden or implemented as 'async void'.", methodDeclaration)); return; } // find usages var psiServices = method.GetPsiServices(); Debug.Assert(SearchDomainFactory.Instance != null); var solutionSearchDomain = SearchDomainFactory.Instance.CreateSearchDomain(psiServices.Solution, false); var references = psiServices.Finder.FindReferences(method, solutionSearchDomain, NullProgressIndicator.Create()); if (IsPublicSurfaceArea(method)) { if (references.Length > 0) { consumer.AddHighlighting( new AvoidAsyncVoidHighlighting("'async void' public surface area method with detected usages.", methodDeclaration)); } else { var implicitUseAnnotationProvider = psiServices.GetCodeAnnotationsCache().GetProvider <ImplicitUseAnnotationProvider>(); var useKindFlags = implicitUseAnnotationProvider.IsImplicitlyUsed(method); if (useKindFlags == null) { // [UsedImplicitly] annotation not applied consumer.AddHighlighting( new AvoidAsyncVoidHighlighting("'async void' public surface area method without detected usages.", methodDeclaration)); } } } else { var count = references.Count(reference => !reference.AssertNotNull().IsEventTarget()); if (count > 0) { consumer.AddHighlighting( new AvoidAsyncVoidHighlighting( string.Format( "'async void' method used {0} time{1} not as a direct event handler.", count.ToString(), count == 1 ? "" : "s"), methodDeclaration)); } } }
public async void Execute(ISolution solution, ITextControl textControl) { if (this.ExistingProjectFile != null) { await ShowProjectFile(solution, this.ExistingProjectFile, null); return; } using (ReadLockCookie.Create()) { string testClassName; string testNamespace; string testFileName; IProjectFolder testFolder; Template testFileTemplate; using (var cookie = solution.CreateTransactionCookie(DefaultAction.Rollback, this.Text, NullProgressIndicator.Create())) { var declaration = this._provider.GetSelectedElement <ICSharpTypeDeclaration>(); var declaredType = declaration?.DeclaredElement; if (declaredType == null) { return; } var settingsStore = declaration.GetSettingsStore(); var helperSettings = ReSharperHelperSettings.GetSettings(settingsStore); var testProject = this.CachedTestProject ?? this.ResolveTargetTestProject(declaration, solution, helperSettings); if (testProject == null) { return; } var classNamespaceParts = TrimDefaultProjectNamespace(declaration.GetProject().NotNull(), declaredType.GetContainingNamespace().QualifiedName); var testFolderLocation = classNamespaceParts.Aggregate(testProject.Location, (current, part) => current.Combine(part)); testNamespace = StringUtil.MakeFQName(testProject.GetDefaultNamespace(), StringUtil.MakeFQName(classNamespaceParts)); testFolder = testProject.GetOrCreateProjectFolder(testFolderLocation, cookie); if (testFolder == null) { return; } testClassName = declaredType.ShortName + helperSettings.TestClassNameSuffix; testFileName = testClassName + ".cs"; testFileTemplate = StoredTemplatesProvider.Instance.EnumerateTemplates(settingsStore, TemplateApplicability.File).FirstOrDefault(t => t.Description == TemplateDescription); cookie.Commit(NullProgressIndicator.Create()); } if (testFileTemplate != null) { await FileTemplatesManager.Instance.CreateFileFromTemplateAsync(testFileName, new ProjectFolderWithLocation(testFolder), testFileTemplate); return; } var newFile = AddNewItemHelper.AddFile(testFolder, testFileName); if (newFile == null) { return; } int?caretPosition = -1; solution.GetPsiServices() .Transactions.Execute(this.Text, () => { var psiSourceFile = newFile.ToSourceFile(); var csharpFile = psiSourceFile?.GetDominantPsiFile <CSharpLanguage>() as ICSharpFile; if (csharpFile == null) { return; } var elementFactory = CSharpElementFactory.GetInstance(csharpFile); var namespaceDeclaration = elementFactory.CreateNamespaceDeclaration(testNamespace); var addedNs = csharpFile.AddNamespaceDeclarationAfter(namespaceDeclaration, null); var classLikeDeclaration = (IClassLikeDeclaration)elementFactory.CreateTypeMemberDeclaration("public class $0 {}", testClassName); var addedTypeDeclaration = addedNs.AddTypeDeclarationAfter(classLikeDeclaration, null) as IClassDeclaration; caretPosition = addedTypeDeclaration?.Body?.GetDocumentRange().TextRange.StartOffset + 1; }); await ShowProjectFile(solution, newFile, caretPosition); } }
private void DoUnderTransaction(string command, Action action) { // Create a transaction - Rider will hook the file system and cause the VFS to refresh using (WriteLockCookie.Create()) using (myMetaFileTracker.mySolution.CreateTransactionCookie(DefaultAction.Commit, command, NullProgressIndicator.Create())) action(); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var changeSignature = LanguageManager.Instance.TryGetService <ChangeSignature>(myMethodDeclaration.Language); if (changeSignature == null) { return(null); } var model = changeSignature.CreateModel(myMethodDeclaration.DeclaredElement); for (var i = 0; i < myMethodSignature.Parameters.Length; i++) { var requiredParameter = myMethodSignature.Parameters[i]; var modelParameter = FindBestMatch(requiredParameter, model, i); if (modelParameter != null) { model.MoveTo(modelParameter.OriginalParameterIndex, i); } else { model.Add(i); modelParameter = model.ChangeSignatureParameters[i]; } modelParameter.ParameterName = requiredParameter.Name; modelParameter.ParameterKind = ParameterKind.VALUE; modelParameter.ParameterType = requiredParameter.Type; // Reset everything else modelParameter.DefaultValue = null; modelParameter.IsOptional = false; modelParameter.IsParams = false; modelParameter.IsThis = false; modelParameter.IsVarArg = false; } for (var i = model.ChangeSignatureParameters.Length - 1; i >= myMethodSignature.Parameters.Length; i--) { model.Remove(i); } var refactoring = new ChangeSignatureRefactoring(model); refactoring.Execute(NullProgressIndicator.Create()); // Ideally, we would now call InplaceRefactoringsManager.Reset to make sure we didn't have // an inplace refactoring highlight. But InplaceRefactoringsManager is internal, so we can't. // We don't want a highlight telling us to "apply signature change refactoring" because we // just have. The only way to remove it is to fire the Escape action return(tc => { var highlightingManager = solution.GetComponent <InplaceRefactoringsHighlightingManager>(); if (highlightingManager.GetHighlightersForTests(tc).Any()) { var actionManager = solution.GetComponent <IActionManager>(); var escapeActionHandler = actionManager.Defs.GetActionDef <EscapeActionHandler>(); escapeActionHandler.EvaluateAndExecute(actionManager); } }); }