public override async Task RunRemoteAsync(string targetName, Solution?solution, IReadOnlyList <object?> arguments, CancellationToken cancellationToken) { if (solution != null) { using var scope = await _remotableDataService.CreatePinnedRemotableDataScopeAsync(solution, cancellationToken).ConfigureAwait(false); using var _ = ArrayBuilder <object?> .GetInstance(arguments.Count + 1, out var argumentsBuilder); argumentsBuilder.Add(scope.SolutionInfo); argumentsBuilder.AddRange(arguments); await _serviceEndPoint.InvokeAsync(targetName, argumentsBuilder, cancellationToken).ConfigureAwait(false); } else { await _serviceEndPoint.InvokeAsync(targetName, arguments, cancellationToken).ConfigureAwait(false); } }
public async ValueTask DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } _pendingUpdatedSolution = null; try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when(FatalError.ReportAndCatch(e)) { _disabled = true; } }
protected override IChecksummedPersistentStorage?TryOpenDatabase( SolutionKey solutionKey, Solution?bulkLoadSnapshot, string workingFolderPath, string databaseFilePath) { if (!TryInitializeLibraries()) { // SQLite is not supported on the current platform return(null); } // try to get db ownership lock. if someone else already has the lock. it will throw var dbOwnershipLock = TryGetDatabaseOwnership(databaseFilePath); if (dbOwnershipLock == null) { return(null); } SQLitePersistentStorage?sqlStorage = null; try { sqlStorage = new SQLitePersistentStorage( workingFolderPath, solutionKey.FilePath, databaseFilePath, dbOwnershipLock, _faultInjector); sqlStorage.Initialize(bulkLoadSnapshot); return(sqlStorage); } catch (Exception) { if (sqlStorage != null) { // Dispose of the storage, releasing the ownership lock. sqlStorage.Dispose(); } else { // The storage was not created so nothing owns the lock. // Dispose the lock to allow reuse. dbOwnershipLock.Dispose(); } throw; } }
private Task <bool> RenameAsync(string oldFilePath, string newFilePath, bool isCaseSensitive, string oldName, string newName, ISymbol?symbol, string renameOperationName, CancellationToken token) { token.ThrowIfCancellationRequested(); return(_unconfiguredProjectTasksService.LoadedProjectAsync(async() => { // Perform the rename operation Solution?renamedSolution = await GetRenamedSolutionAsync(oldName, oldFilePath, newFilePath, isCaseSensitive, GetCurrentProject, token); if (renamedSolution is null) { return false; } string rqName = RQName.From(symbol); Solution?solution = GetCurrentProject()?.Solution; if (solution is null) { return false; } IEnumerable <ProjectChanges> changes = renamedSolution.GetChanges(solution).GetProjectChanges(); DTE?dte = _dte.Value; Assumes.NotNull(dte); using var undo = UndoScope.Create(dte, renameOperationName); // Notify other VS features that symbol is about to be renamed NotifyBeforeRename(newName, rqName, changes); // Try and apply the changes to the current solution token.ThrowIfCancellationRequested(); if (!_roslynServices.ApplyChangesToSolution(renamedSolution.Workspace, renamedSolution)) { return false; } // Notify other VS features that symbol has been renamed NotifyAfterRename(newName, rqName, changes); return true; })); }
public RequestContext( Solution? solution, Action<string> traceInformation, ClientCapabilities clientCapabilities, string? clientName, Document? document, IDocumentChangeTracker documentChangeTracker, ImmutableArray<string> supportedLanguages, IGlobalOptionService globalOptions) { Document = document; Solution = solution; ClientCapabilities = clientCapabilities; ClientName = clientName; SupportedLanguages = supportedLanguages; GlobalOptions = globalOptions; _documentChangeTracker = documentChangeTracker; _traceInformation = traceInformation; }
private void RaiseDiagnosticsRemoved( ProjectId projectId, Solution?solution, StateSet stateSet, Action <DiagnosticsUpdatedArgs> raiseEvents ) { Contract.ThrowIfFalse(solution == null || solution.Workspace == Workspace); raiseEvents( DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateId(stateSet, projectId, AnalysisKind.NonLocal), Workspace, solution, projectId, documentId: null ) ); }
public async ValueTask <ManagedHotReloadUpdates> GetHotReloadUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return(new ManagedHotReloadUpdates(ImmutableArray <ManagedHotReloadUpdate> .Empty, ImmutableArray <ManagedHotReloadDiagnostic> .Empty)); } var workspace = WorkspaceProvider.Value.Workspace; var solution = GetCurrentCompileTimeSolution(_pendingUpdatedDesignTimeSolution = workspace.CurrentSolution); var(moduleUpdates, diagnosticData, rudeEdits, syntaxError) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, s_noActiveStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); var updates = moduleUpdates.Updates.SelectAsArray( update => new ManagedHotReloadUpdate(update.Module, update.ILDelta, update.MetadataDelta, update.PdbDelta, update.UpdatedTypes)); var diagnostics = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, syntaxError, cancellationToken).ConfigureAwait(false); return(new ManagedHotReloadUpdates(updates, diagnostics.FromContract())); }
private void OnRemoveUnusedReferencesForSelectedProject(object sender, EventArgs args) { if (VisualStudioCommandHandlerHelpers.TryGetSelectedProjectHierarchy(_serviceProvider, out var hierarchy)) { Solution?solution = null; string? projectFilePath = null; ImmutableArray <ReferenceUpdate> referenceUpdates = default; var status = _threadOperationExecutor.Execute(ServicesVSResources.Remove_Unused_References, ServicesVSResources.Analyzing_project_references, allowCancellation: true, showProgress: true, (operationContext) => { (solution, projectFilePath, referenceUpdates) = GetUnusedReferencesForProjectHierarchy(hierarchy, operationContext.UserCancellationToken); }); if (status == UIThreadOperationStatus.Canceled) { return; } if (solution is null || projectFilePath is not string { Length : > 0 } ||
public static DiagnosticsUpdatedArgs DiagnosticsCreated( object id, Workspace workspace, Solution?solution, ProjectId?projectId, DocumentId?documentId, ImmutableArray <DiagnosticData> diagnostics ) { return(new DiagnosticsUpdatedArgs( id, workspace, solution, projectId, documentId, diagnostics, DiagnosticsUpdatedKind.DiagnosticsCreated )); }
private DiagnosticsUpdatedArgs( object id, Workspace workspace, Solution?solution, ProjectId?projectId, DocumentId?documentId, ImmutableArray <DiagnosticData> diagnostics, DiagnosticsUpdatedKind kind ) : base(id, workspace, projectId, documentId) { // TODO: This assert fails for EditAndContinueDiagnosticUpdateSource. See https://github.com/dotnet/roslyn/issues/36246. // Debug.Assert(diagnostics.All(d => d.ProjectId == projectId && d.DocumentId == documentId)); Debug.Assert(kind != DiagnosticsUpdatedKind.DiagnosticsRemoved || diagnostics.IsEmpty); Solution = solution; Kind = kind; _diagnostics = diagnostics; }
private async Task <Solution?> GetRenamedSolutionAsync(string oldName, string oldFileName, string newFileName, bool isCaseSensitive, Project?project, CancellationToken token = default) { if (project is null) { return(null); } ISymbol?symbolToRename = await TryGetSymbolToRename(oldName, oldFileName, newFileName, isCaseSensitive, project, token); if (symbolToRename is null) { return(null); } string newName = Path.GetFileNameWithoutExtension(newFileName); Solution?renamedSolution = await _roslynServices.RenameSymbolAsync(project.Solution, symbolToRename, newName, token); return(renamedSolution); }
protected override async Task <Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { SyntaxNode?root = await this.document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var methodDeclaration = (MethodDeclarationSyntax)root.FindNode(this.diagnostic.Location.SourceSpan); SemanticModel?semanticModel = await this.document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); IMethodSymbol?methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, cancellationToken); Solution?solution = this.document.Project.Solution; Solution?updatedSolution = await Renamer.RenameSymbolAsync( solution, methodSymbol, this.NewName, solution.Workspace.Options, cancellationToken).ConfigureAwait(false); return(updatedSolution); }
private void DiagnosticService_DiagnosticsUpdated(Solution?solution, DocumentId?documentId) { // LSP doesn't support diagnostics without a document. So if we get project level diagnostics without a document, ignore them. if (documentId != null && solution != null) { var document = solution.GetDocument(documentId); if (document == null || document.FilePath == null) { return; } // Only publish document diagnostics for the languages this provider supports. if (!_supportedLanguages.Contains(document.Project.Language)) { return; } _diagnosticsWorkQueue.AddWork(document.Id); } }
// legacy services: public async Task RunRemoteAsync( RemoteServiceName serviceName, string targetName, Solution?solution, IReadOnlyList <object?> arguments, object?callbackTarget, CancellationToken cancellationToken ) { using var connection = await CreateConnectionAsync( serviceName, callbackTarget, cancellationToken ) .ConfigureAwait(false); await connection .RunRemoteAsync(targetName, solution, arguments, cancellationToken) .ConfigureAwait(false); }
public void ReactionEntity(IEntity entity, ReactionMethod method, ReagentPrototype reagent, ReagentUnit reactVolume, Solution?source) { if (entity == null || entity.Deleted || !entity.TryGetComponent(out ReactiveComponent? reactive)) { return; } foreach (var reaction in reactive.Reactions) { // If we have a source solution, use the reagent quantity we have left. Otherwise, use the reaction volume specified. reaction.React(method, entity, reagent, source?.GetReagentQuantity(reagent.ID) ?? reactVolume, source); // Make sure we still have enough reagent to go... if (source != null && !source.ContainsReagent(reagent.ID)) { break; } } }
public RequestContext( Solution?solution, ILspLogger logger, ClientCapabilities clientCapabilities, string?clientName, Document?document, IDocumentChangeTracker documentChangeTracker, ImmutableDictionary <Uri, SourceText> trackedDocuments, ImmutableArray <string> supportedLanguages, IGlobalOptionService globalOptions) { Document = document; Solution = solution; ClientCapabilities = clientCapabilities; ClientName = clientName; SupportedLanguages = supportedLanguages; GlobalOptions = globalOptions; _documentChangeTracker = documentChangeTracker; _logger = logger; _trackedDocuments = trackedDocuments; }
public async Task <T> RunRemoteAsync <T>( RemoteServiceName serviceName, string targetName, Solution?solution, IReadOnlyList <object?> arguments, object?callbackTarget, Func <Stream, CancellationToken, Task <T> >?dataReader, CancellationToken cancellationToken ) { using var connection = await CreateConnectionAsync( serviceName, callbackTarget, cancellationToken ) .ConfigureAwait(false); return(await connection .RunRemoteAsync(targetName, solution, arguments, dataReader, cancellationToken) .ConfigureAwait(false)); }
private async Task <Solution?> GetRenamedSolutionAsync(string oldName, string oldFileName, string newFileName, bool isCaseSensitive, Func <Project?> getProject, CancellationToken token) { ISymbol?symbolToRename = await TryGetSymbolToRename(oldName, oldFileName, newFileName, isCaseSensitive, getProject, token); if (symbolToRename is null) { return(null); } string newName = Path.GetFileNameWithoutExtension(newFileName); Solution?solution = getProject()?.Solution; if (solution is null) { return(null); } Solution?renamedSolution = await _roslynServices.RenameSymbolAsync(solution, symbolToRename, newName, token); return(renamedSolution); }
public async ValueTask EndSessionAsync(CancellationToken cancellationToken) { IsSessionActive = false; if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; _committedDesignTimeSolution = null; _pendingUpdatedDesignTimeSolution = null; } catch (Exception e) when(FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } }
public async ValueTask CommitUpdatesAsync(CancellationToken cancellationToken) { try { var committedDesignTimeSolution = Interlocked.Exchange(ref _pendingUpdatedDesignTimeSolution, null); Contract.ThrowIfNull(committedDesignTimeSolution); SolutionCommitted?.Invoke(committedDesignTimeSolution); _committedDesignTimeSolution = committedDesignTimeSolution; } catch (Exception e) when(FatalError.ReportAndCatch(e)) { } try { Contract.ThrowIfTrue(_disabled); await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when(FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } }
public RequestContext( Solution?solution, ILspLogger logger, ClientCapabilities clientCapabilities, WellKnownLspServerKinds serverKind, Document?document, IDocumentChangeTracker documentChangeTracker, ImmutableDictionary <Uri, SourceText> trackedDocuments, ImmutableArray <string> supportedLanguages, LspServices lspServices, CancellationToken queueCancellationToken) { Document = document; Solution = solution; ClientCapabilities = clientCapabilities; ServerKind = serverKind; SupportedLanguages = supportedLanguages; _documentChangeTracker = documentChangeTracker; _logger = logger; _trackedDocuments = trackedDocuments; _lspServices = lspServices; QueueCancellationToken = queueCancellationToken; }
public abstract Task <T> RunRemoteAsync <T>(string targetName, Solution?solution, IReadOnlyList <object?> arguments, Func <Stream, CancellationToken, Task <T> >?dataReader, CancellationToken cancellationToken);
public Task <T> RunRemoteAsync <T>(string targetName, Solution?solution, IReadOnlyList <object?> arguments, CancellationToken cancellationToken) => RunRemoteAsync <T>(targetName, solution, arguments, dataReader: null, cancellationToken);
public async Task <Optional <T> > TryRunRemoteAsync <T>(string targetName, Solution?solution, IReadOnlyList <object?> arguments, CancellationToken cancellationToken) => await _client.RunRemoteAsync <T>(WellKnownServiceHubService.Razor, targetName, solution, arguments, callbackTarget : null, cancellationToken).ConfigureAwait(false);
public abstract Task RunRemoteAsync(string targetName, Solution?solution, IReadOnlyList <object?> arguments, CancellationToken cancellationToken);
public SolutionPreviewResult?GetSolutionPreviews(Solution oldSolution, Solution?newSolution, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: The order in which previews are added to the below list is significant. // Preview for a changed document is preferred over preview for changed references and so on. var previewItems = new List <SolutionPreviewItem>(); SolutionChangeSummary?changeSummary = null; if (newSolution != null) { var solutionChanges = newSolution.GetChanges(oldSolution); var ignoreUnchangeableDocuments = oldSolution.Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges; foreach (var projectChanges in solutionChanges.GetProjectChanges()) { cancellationToken.ThrowIfCancellationRequested(); var projectId = projectChanges.ProjectId; var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // Exclude changes to unchangeable documents if they will be ignored when applied to workspace. foreach (var documentId in projectChanges.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true, ignoreUnchangeableDocuments)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, async c => await CreateChangedDocumentPreviewViewAsync(oldSolution.GetRequiredDocument(documentId), newSolution.GetRequiredDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetAddedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, async c => await CreateAddedDocumentPreviewViewAsync(newSolution.GetRequiredDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetRemovedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, async c => await CreateRemovedDocumentPreviewViewAsync(oldSolution.GetRequiredDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetChangedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, async c => await CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetRequiredAdditionalDocument(documentId), newSolution.GetRequiredAdditionalDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetAddedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, async c => await CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetRequiredAdditionalDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, async c => await CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetRequiredAdditionalDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetChangedAnalyzerConfigDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, async c => await CreateChangedAnalyzerConfigDocumentPreviewViewAsync(oldSolution.GetRequiredAnalyzerConfigDocument(documentId), newSolution.GetRequiredAnalyzerConfigDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetAddedAnalyzerConfigDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, async c => await CreateAddedAnalyzerConfigDocumentPreviewViewAsync(newSolution.GetRequiredAnalyzerConfigDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var documentId in projectChanges.GetRemovedAnalyzerConfigDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, async c => await CreateRemovedAnalyzerConfigDocumentPreviewViewAsync(oldSolution.GetRequiredAnalyzerConfigDocument(documentId), zoomLevel, c).ConfigureAwaitRunInline())); } foreach (var metadataReference in projectChanges.GetAddedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_reference_0_to_1, metadataReference.Display, oldProject.Name))); } foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_reference_0_from_1, metadataReference.Display, oldProject.Name))); } foreach (var projectReference in projectChanges.GetAddedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_reference_0_to_1, newSolution.GetRequiredProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var projectReference in projectChanges.GetRemovedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_reference_0_from_1, oldSolution.GetRequiredProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_analyzer_reference_0_to_1, analyzer.Display, oldProject.Name))); } foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_analyzer_reference_0_from_1, analyzer.Display, oldProject.Name))); } } foreach (var project in solutionChanges.GetAddedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.Adding_project_0, project.Name))); } foreach (var project in solutionChanges.GetRemovedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.Removing_project_0, project.Name))); } foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(ProjectReferencesChanged)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null, string.Format(EditorFeaturesResources.Changing_project_references_for_0, projectChanges.OldProject.Name))); } changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges); } return(new SolutionPreviewResult(ThreadingContext, previewItems, changeSummary)); }
public SolutionPreviewResult?GetSolutionPreviews(Solution oldSolution, Solution?newSolution, CancellationToken cancellationToken) => GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken);
/// <summary> /// Converts a synchronous method to be asynchronous, if it is not already async. /// </summary> /// <param name="method">The method to convert.</param> /// <param name="document">The document.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The new Document and method syntax, or the original if it was already async. /// </returns> /// <exception cref="System.ArgumentNullException"> /// <para>If <paramref name="method"/> is null.</para> /// <para>-or-</para> /// <para>If <paramref name="document"/> is null.</para> /// </exception> internal static async Task <Tuple <Document, MethodDeclarationSyntax> > MakeMethodAsync(this MethodDeclarationSyntax method, Document document, CancellationToken cancellationToken = default(CancellationToken)) { if (method is null) { throw new ArgumentNullException(nameof(method)); } if (document is null) { throw new ArgumentNullException(nameof(document)); } if (method.Modifiers.Any(SyntaxKind.AsyncKeyword)) { // Already asynchronous. return(Tuple.Create(document, method)); } DocumentId documentId = document.Id; SemanticModel?semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); IMethodSymbol?methodSymbol = semanticModel.GetDeclaredSymbol(method, cancellationToken); bool hasReturnValue; TypeSyntax returnType = method.ReturnType; if (!Utils.HasAsyncCompatibleReturnType(methodSymbol)) { hasReturnValue = (method.ReturnType as PredefinedTypeSyntax)?.Keyword.Kind() != SyntaxKind.VoidKeyword; // Determine new return type. returnType = hasReturnValue ? QualifyName( Namespaces.SystemThreadingTasks, SyntaxFactory.GenericName(SyntaxFactory.Identifier(nameof(Task))) .AddTypeArgumentListArguments(method.ReturnType)) : SyntaxFactory.ParseTypeName(typeof(Task).FullName); returnType = returnType .WithAdditionalAnnotations(Simplifier.Annotation) .WithTrailingTrivia(method.ReturnType.GetTrailingTrivia()); } else { TypeSyntax t = method.ReturnType; while (t is QualifiedNameSyntax q) { t = q.Right; } hasReturnValue = t is GenericNameSyntax; } // Fix up any return statements to await on the Task it would have returned. bool returnTypeChanged = method.ReturnType != returnType; BlockSyntax updatedBody = UpdateStatementsForAsyncMethod( method.Body, semanticModel, hasReturnValue, returnTypeChanged, cancellationToken); // Apply the changes to the document, and null out stale data. SyntaxAnnotation methodBookmark; (document, method, methodBookmark) = await UpdateDocumentAsync( document, method, m => m .WithBody(updatedBody) .AddModifiers(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)) .WithReturnType(returnType), cancellationToken).ConfigureAwait(false); semanticModel = null; methodSymbol = null; // Rename the method to have an Async suffix if we changed the return type, // and it doesn't already have that suffix. if (returnTypeChanged && !method.Identifier.ValueText.EndsWith(VSTHRD200UseAsyncNamingConventionAnalyzer.MandatoryAsyncSuffix, StringComparison.Ordinal)) { string newName = method.Identifier.ValueText + VSTHRD200UseAsyncNamingConventionAnalyzer.MandatoryAsyncSuffix; semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); methodSymbol = semanticModel.GetDeclaredSymbol(method, cancellationToken); // Don't rename entrypoint (i.e. "Main") methods. if (!Utils.IsEntrypointMethod(methodSymbol, semanticModel, cancellationToken)) { Solution?solution = await Renamer.RenameSymbolAsync( document.Project.Solution, methodSymbol, newName, document.Project.Solution.Workspace.Options, cancellationToken).ConfigureAwait(false); document = solution.GetDocument(document.Id); semanticModel = null; methodSymbol = null; SyntaxNode?root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); method = (MethodDeclarationSyntax)root.GetAnnotatedNodes(methodBookmark).Single(); } } // Update callers to await calls to this method if we made it awaitable. if (returnTypeChanged) { semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); methodSymbol = semanticModel.GetDeclaredSymbol(method, cancellationToken); SyntaxAnnotation callerAnnotation; Solution solution = document.Project.Solution; List <DocumentId> annotatedDocumentIds; (solution, callerAnnotation, annotatedDocumentIds) = await AnnotateAllCallersAsync(solution, methodSymbol, cancellationToken).ConfigureAwait(false); foreach (DocumentId docId in annotatedDocumentIds) { document = solution.GetDocument(docId); SyntaxTree?tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); SyntaxNode?root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var rewriter = new AwaitCallRewriter(callerAnnotation); root = rewriter.Visit(root); solution = solution.GetDocument(tree).WithSyntaxRoot(root).Project.Solution; } foreach (DocumentId docId in annotatedDocumentIds) { document = solution.GetDocument(docId); SyntaxTree?tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); SyntaxNode?root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); for (SyntaxNode?node = root.GetAnnotatedNodes(callerAnnotation).FirstOrDefault(); node is object; node = root.GetAnnotatedNodes(callerAnnotation).FirstOrDefault()) { MethodDeclarationSyntax?callingMethod = node.FirstAncestorOrSelf <MethodDeclarationSyntax>(); if (callingMethod is object) { (document, callingMethod) = await MakeMethodAsync(callingMethod, document, cancellationToken).ConfigureAwait(false); // Clear all annotations of callers from this method so we don't revisit it. root = await callingMethod.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var annotationRemover = new RemoveAnnotationRewriter(callerAnnotation); root = root.ReplaceNode(callingMethod, annotationRemover.Visit(callingMethod)); document = document.WithSyntaxRoot(root); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } else { // Clear all annotations of callers from this method so we don't revisit it. root = await node.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); root = root.ReplaceNode(node, node.WithoutAnnotations(callerAnnotation)); document = document.WithSyntaxRoot(root); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } } solution = document.Project.Solution; } // Make sure we return the latest of everything. document = solution.GetDocument(documentId); SyntaxTree?finalTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); SyntaxNode?finalRoot = await finalTree.GetRootAsync(cancellationToken).ConfigureAwait(false); method = (MethodDeclarationSyntax)finalRoot.GetAnnotatedNodes(methodBookmark).Single(); } return(Tuple.Create(document, method)); }
private void TryMetabolize(EntityUid uid, MetabolizerComponent?meta = null, MechanismComponent?mech = null) { if (!Resolve(uid, ref meta)) { return; } Resolve(uid, ref mech, false); // First step is get the solution we actually care about Solution? solution = null; EntityUid?solutionEntityUid = null; EntityUid?bodyEntityUid = mech?.Body?.Owner; SolutionContainerManagerComponent?manager = null; if (meta.SolutionOnBody) { if (mech != null) { var body = mech.Body; if (body != null) { if (!Resolve((body).Owner, ref manager, false)) { return; } _solutionContainerSystem.TryGetSolution((body).Owner, meta.SolutionName, out solution, manager); solutionEntityUid = body.Owner; } } } else { if (!Resolve(uid, ref manager, false)) { return; } _solutionContainerSystem.TryGetSolution(uid, meta.SolutionName, out solution, manager); solutionEntityUid = uid; } if (solutionEntityUid == null || solution == null) { return; } // randomize the reagent list so we don't have any weird quirks // like alphabetical order or insertion order mattering for processing var list = solution.Contents.ToArray(); _random.Shuffle(list); int reagents = 0; foreach (var reagent in list) { if (!_prototypeManager.TryIndex <ReagentPrototype>(reagent.ReagentId, out var proto)) { continue; } FixedPoint2 mostToRemove = FixedPoint2.Zero; if (proto.Metabolisms == null) { if (meta.RemoveEmpty) { _solutionContainerSystem.TryRemoveReagent(solutionEntityUid.Value, solution, reagent.ReagentId, FixedPoint2.New(1)); } continue; } // we're done here entirely if this is true if (reagents >= meta.MaxReagentsProcessable) { return; } reagents += 1; // loop over all our groups and see which ones apply if (meta.MetabolismGroups == null) { continue; } foreach (var group in meta.MetabolismGroups) { if (!proto.Metabolisms.Keys.Contains(group.Id)) { continue; } var entry = proto.Metabolisms[group.Id]; // we don't remove reagent for every group, just whichever had the biggest rate if (entry.MetabolismRate > mostToRemove) { mostToRemove = entry.MetabolismRate; } mostToRemove *= group.MetabolismRateModifier; mostToRemove = FixedPoint2.Clamp(mostToRemove, 0, reagent.Quantity); // if it's possible for them to be dead, and they are, // then we shouldn't process any effects, but should probably // still remove reagents if (EntityManager.TryGetComponent <MobStateComponent>(solutionEntityUid.Value, out var state)) { if (state.IsDead()) { continue; } } var actualEntity = bodyEntityUid != null ? bodyEntityUid.Value : solutionEntityUid.Value; var args = new ReagentEffectArgs(actualEntity, (meta).Owner, solution, proto, mostToRemove, EntityManager, null); // do all effects, if conditions apply foreach (var effect in entry.Effects) { if (!effect.ShouldApply(args, _random)) { continue; } if (effect.ShouldLog) { _adminLogger.Add(LogType.ReagentEffect, effect.LogImpact, $"Metabolism effect {effect.GetType().Name:effect} of reagent {args.Reagent.LocalizedName:reagent} applied on entity {actualEntity:entity} at {Transform(actualEntity).Coordinates:coordinates}"); } effect.Effect(args); } } // remove a certain amount of reagent if (mostToRemove > FixedPoint2.Zero) { _solutionContainerSystem.TryRemoveReagent(solutionEntityUid.Value, solution, reagent.ReagentId, mostToRemove); } } }
public async Task <bool> TryRunRemoteAsync(string serviceName, string targetName, IReadOnlyList <object> arguments, Solution?solution, object?callbackTarget, CancellationToken cancellationToken) { // TODO: revisit solution handling - see https://github.com/dotnet/roslyn/issues/24836 if (solution == null) { using var connection = await TryCreateConnectionAsync(serviceName, callbackTarget, cancellationToken).ConfigureAwait(false); if (connection == null) { return(false); } await connection.InvokeAsync(targetName, arguments, cancellationToken).ConfigureAwait(false); } else { using var session = await TryCreateSessionAsync(serviceName, solution, callbackTarget, cancellationToken).ConfigureAwait(false); if (session == null) { return(false); } await session.Connection.InvokeAsync(targetName, arguments, cancellationToken).ConfigureAwait(false); } return(true); }