public MetadataDefinitionState(MetadataDefinitionName name, IDataType datatype, string regex, IImmutableSet<AllowableValue> allowedValues) : this(name, datatype,regex) { _allowedValues = allowedValues; CreatedUtcDate = DateTime.UtcNow; IsDeleted = false; }
public CommandStatusResult GetCommandStatus(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) { if ((VSConstants.VSStd2KCmdID)commandId == VSConstants.VSStd2KCmdID.EXCLUDEFROMPROJECT && nodes != null && nodes.Count > 0) { return new CommandStatusResult(true, commandText, CommandStatus.NotSupported | CommandStatus.Invisible); } return CommandStatusResult.Unhandled; }
public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) { var workflow = _interactiveWorkflowProvider.GetOrCreate(); if (commandId == RPackageCommandId.icmdCopyRemoteItemPath && nodes.IsSingleNodePath() && workflow.RSession.IsHostRunning && workflow.RSession.IsRemote) { return Task.FromResult(new CommandStatusResult(true, commandText, CommandStatus.Enabled | CommandStatus.Supported)); } return Task.FromResult(CommandStatusResult.Unhandled); }
private static async Task FindReferencesInServiceProcessAsync( SymbolAndProjectId symbolAndProjectId, Solution solution, IStreamingFindReferencesProgress progress, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var client = await solution.Workspace.GetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); if (client == null) { await FindReferencesInCurrentProcessAsync( symbolAndProjectId, solution, progress, documents, cancellationToken).ConfigureAwait(false); return; } // Create a callback that we can pass to the server process to hear about the // results as it finds them. When we hear about results we'll forward them to // the 'progress' parameter which will then upate the UI. var serverCallback = new ServerCallback(solution, progress, cancellationToken); using (var session = await client.CreateCodeAnalysisServiceSessionAsync( solution, serverCallback, cancellationToken).ConfigureAwait(false)) { await session.InvokeAsync( nameof(IRemoteSymbolFinder.FindReferencesAsync), SerializableSymbolAndProjectId.Dehydrate(symbolAndProjectId), documents?.Select(SerializableDocumentId.Dehydrate).ToArray()).ConfigureAwait(false); } }
protected async Task<ImmutableArray<Document>> FindDocumentsAsync(Project project, IImmutableSet<Document> scope, Func<Document, CancellationToken, Task<bool>> predicateAsync, CancellationToken cancellationToken) { // special case for HR if (scope != null && scope.Count == 1) { var document = scope.First(); if (document.Project == project) { return scope.ToImmutableArray(); } return ImmutableArray<Document>.Empty; } var documents = ArrayBuilder<Document>.GetInstance(); foreach (var document in project.Documents) { if (scope != null && !scope.Contains(document)) { continue; } if (await predicateAsync(document, cancellationToken).ConfigureAwait(false)) { documents.Add(document); } } return documents.ToImmutableAndFree(); }
public override IEnumerable<SlideBlock> BuildUp(BuildUpContext context, IImmutableSet<string> filesInProgress) { FillProperties(context); RemovedLabels = RemovedLabels ?? new Label[0]; if (PreludeFile == null) { PreludeFile = context.CourseSettings.GetPrelude(LangId); if (PreludeFile != null) PreludeFile = Path.Combine("..", PreludeFile); } var code = context.FileSystem.GetContent(File); var regionRemover = new RegionRemover(LangId); var extractor = context.GetExtractor(File, LangId, code); var prelude = ""; if (PreludeFile != null) prelude = context.FileSystem.GetContent(PreludeFile); var exerciseCode = regionRemover.Prepare(code); IEnumerable<Label> notRemoved; exerciseCode = regionRemover.Remove(exerciseCode, RemovedLabels, out notRemoved); int index; exerciseCode = regionRemover.RemoveSolution(exerciseCode, SolutionLabel, out index); index += prelude.Length; ExerciseInitialCode = ExerciseInitialCode.RemoveCommonNesting(); ExerciseCode = prelude + exerciseCode; IndexToInsertSolution = index; EthalonSolution = extractor.GetRegion(SolutionLabel); ValidatorName = string.Join(" ", LangId, ValidatorName); yield return this; }
public MetadataDefinitionState(MetadataDefinitionName name, IDataType datatype, IImmutableSet<AllowableValue> allowedValues, bool isDeleted) : this(name, datatype, allowedValues) { IsDeleted = isDeleted; CreatedUtcDate = DateTime.UtcNow; IsDeleted = false; }
private static Task<IEnumerable<INamedTypeSymbol>> FindDerivedClassesAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, bool transitive, CancellationToken cancellationToken) { if (s_isNonSealedClass(type)) { Func<HashSet<INamedTypeSymbol>, INamedTypeSymbol, bool> metadataTypeMatches = (set, metadataType) => TypeDerivesFrom(set, metadataType, transitive); Func<HashSet<INamedTypeSymbol>, INamedTypeSymbol, bool> sourceTypeImmediatelyMatches = (set, metadataType) => set.Contains(metadataType.BaseType?.OriginalDefinition); return FindTypesAsync(type, solution, projects, metadataTypeMatches: metadataTypeMatches, sourceTypeImmediatelyMatches: sourceTypeImmediatelyMatches, shouldContinueSearching: s_isNonSealedClass, transitive: transitive, cancellationToken: cancellationToken); } return SpecializedTasks.EmptyEnumerable<INamedTypeSymbol>(); }
public async Task<IEnumerable<ISymbol>> DetermineCascadedSymbolsAsync(ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default(CancellationToken)) { var linkedSymbols = new HashSet<ISymbol>(); foreach (var location in symbol.DeclaringSyntaxReferences) { var originalDocument = solution.GetDocument(location.SyntaxTree); foreach (var linkedDocumentId in originalDocument.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var linkedSyntaxRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var linkedNode = linkedSyntaxRoot.FindNode(location.Span, getInnermostNodeForTie: true); var semanticModel = await linkedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var linkedSymbol = semanticModel.GetDeclaredSymbol(linkedNode, cancellationToken); if (linkedSymbol != null && linkedSymbol.Kind == symbol.Kind && linkedSymbol.Name == symbol.Name && !linkedSymbols.Contains(linkedSymbol)) { linkedSymbols.Add(linkedSymbol); } } } return linkedSymbols; }
public MetadataDefinitionState(MetadataDefinitionName name, IDataType datatype, string regex, IImmutableSet<AllowableValue> allowedValues, MetadataDefinitionDescription desc, bool isDeleted) : this(name, datatype, regex, allowedValues) { _description = desc; CreatedUtcDate = DateTime.UtcNow; IsDeleted = isDeleted; }
public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { // use speculative semantic model to see whether we are on a symbol we can do HR var span = new TextSpan(position, 0); var solution = document.Project.Solution; var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false); if (symbol == null) { return ImmutableArray<DocumentHighlights>.Empty; } // Get unique tags for referenced symbols return await GetTagsForReferencedSymbolAsync( new SymbolAndProjectId(symbol, document.Project.Id), documentsToSearch, solution, cancellationToken).ConfigureAwait(false); }
public Role(int id, string name, string description, IImmutableSet<IRight> rights = null, PermissionsSource source = PermissionsSource.Manual) { this.Id = id; this.Name = name; this.Description = description; this.Rights = rights.DefaultIfNull(); this.Source = source; }
public static Task<IEnumerable<INamedTypeSymbol>> FindImplementingTypesAsync( this INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken) { return DependentTypeFinder.FindImplementingTypesAsync(type, solution, projects, cancellationToken); }
/// <summary> /// Find symbols for declarations that implement members of the specified interface symbol /// </summary> public static async Task<IEnumerable<ISymbol>> FindImplementedInterfaceMembersAsync( ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default(CancellationToken)) { var result = await FindImplementedInterfaceMembersAsync( SymbolAndProjectId.Create(symbol, projectId: null), solution, projects, cancellationToken).ConfigureAwait(false); return result.SelectAsArray(s => s.Symbol); }
private EntityState(Guid group, EntityName name, IImmutableSet<EntityValueSetState> values, bool deleted) { _group = group; _name = name; _values = values; LastModifiedUtcDate = DateTime.UtcNow; IsDeleted = deleted; }
public CommandStatusResult GetCommandStatus(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) { if (commandId == RPackageCommandId.icmdSetDirectoryHere && nodes.Count == 1) { var session = _interactiveWorkflowProvider.Active?.RSession; bool enabled = session != null && session.IsHostRunning && !session.IsRemote; return new CommandStatusResult(true, commandText, enabled ? CommandStatus.Enabled | CommandStatus.Supported : CommandStatus.Supported); } return CommandStatusResult.Unhandled; }
/// <summary> /// Finds all references to a symbol throughout a solution /// </summary> /// <param name="symbol">The symbol to find references to.</param> /// <param name="solution">The solution to find references within.</param> /// <param name="documents">A set of documents to be searched. If documents is null, then that means "all documents".</param> /// <param name="cancellationToken">A cancellation token.</param> public static Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( ISymbol symbol, Solution solution, IImmutableSet<Document> documents, CancellationToken cancellationToken = default(CancellationToken)) { return FindReferencesAsync(symbol, solution, progress: null, documents: documents, cancellationToken: cancellationToken); }
/// <summary> /// Find symbols for members that override the specified member symbol. /// </summary> public static async Task<IEnumerable<ISymbol>> FindOverridesAsync( ISymbol symbol, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default(CancellationToken)) { var result = await FindOverridesAsync( SymbolAndProjectId.Create(symbol, projectId: null), solution, projects, cancellationToken).ConfigureAwait(false); return result.Select(s => s.Symbol).ToList(); }
/// <summary> /// This is an internal implementation of <see cref="SymbolFinder.FindDerivedClassesAsync"/>, which is a publically callable method. /// </summary> public static Task<IEnumerable<INamedTypeSymbol>> FindTransitivelyDerivedClassesAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken) { return FindDerivedClassesAsync(type, solution, projects, transitive: true, cancellationToken: cancellationToken); }
public bool TryHandleCommand(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut) { if (commandId == RPackageCommandId.icmdPublishSProc) { if (_dacServicesProvider.GetDacPackageServices(showMessage: true) != null) { Handle(); } return true; } return false; }
public static Task<IEnumerable<INamedTypeSymbol>> FindImplementingTypesAsync (this INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default(CancellationToken)) { try { return (Task<IEnumerable<INamedTypeSymbol>>)findImplementingTypesAsync.Invoke(null, new object[] { type, solution, projects, cancellationToken }); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); return null; } }
public MetadataDefinitionState(MetadataDefinitionName name, IDataType datatype) { _name = name; _datatype = datatype; _regex = String.Empty; _allowedValues = ImmutableHashSet.Create<AllowableValue>(); CreatedUtcDate = DateTime.UtcNow; IsDeleted = false; }
public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus status) { if (_session.IsHostRunning && _commandIds.Contains(commandId)) { if (nodes.Any(IsRData)) { status |= CommandStatus.Supported | CommandStatus.Enabled; return Task.FromResult(new CommandStatusResult(true, commandText, status)); } } return Task.FromResult(CommandStatusResult.Unhandled); }
/// <summary> /// This is an internal implementation of <see cref="SymbolFinder.FindDerivedClassesAsync(SymbolAndProjectId{INamedTypeSymbol}, Solution, IImmutableSet{Project}, CancellationToken)"/>, which is a publically callable method. /// </summary> public static Task<ImmutableArray<SymbolAndProjectId<INamedTypeSymbol>>> FindTransitivelyDerivedClassesAsync( INamedTypeSymbol type, Solution solution, IImmutableSet<Project> projects, CancellationToken cancellationToken) { return FindDerivedClassesAsync( SymbolAndProjectId.Create(type, projectId: null), solution, projects, transitive: true, cancellationToken: cancellationToken); }
internal static Task FindReferencesAsync( SymbolAndProjectId symbolAndProjectId, Solution solution, IStreamingFindReferencesProgress progress, IImmutableSet<Document> documents, CancellationToken cancellationToken = default(CancellationToken)) { var engineService = solution.Workspace.Services.GetService<ISymbolFinderEngineService>(); return engineService.FindReferencesAsync(symbolAndProjectId, solution, progress, documents, cancellationToken); }
public PermissionsProvider(Permissions permissions, ContextType? activeDirectoryContextType = null) { this.permissions = permissions; this.requiredRights = ConsolidateRights(permissions.RequiredRights, permissions.RequiredRoles); this.restrictedRights = ConsolidateRights(permissions.RestrictedRights, permissions.RestrictedRoles); this.requiredRoles = GetManualRoles(permissions.RequiredRoles); this.restrictedRoles = GetManualRoles(permissions.RestrictedRoles); this.requiredActiveDirectoryRoles = GetActiveDirectoryRoles(permissions.RequiredRoles); this.restrictedActiveDirectoryRoles = GetActiveDirectoryRoles(permissions.RestrictedRoles); this.activeDirectoryContextType = activeDirectoryContextType; }
public override IEnumerable<SlideBlock> BuildUp(BuildUpContext context, IImmutableSet<string> filesInProgress) { if (filesInProgress.Contains(File)) throw new Exception("Cyclic dependency"); var xmlStream = new StringReader(context.FileSystem.GetContent(File)); var serializer = new XmlSerializer(typeof(SlideBlock[])); var slideBlocks = (SlideBlock[])serializer.Deserialize(xmlStream); var newInProgress = filesInProgress.Add(File); return slideBlocks.SelectMany(b => b.BuildUp(context, newInProgress)); }
public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) { if ((commandId == RPackageCommandId.icmdSourceSelectedFiles || commandId == RPackageCommandId.icmdSourceSelectedFilesWithEcho) && nodes.GetSelectedNodesPaths().Count() > 0) { foreach (var n in nodes) { if (n.IsFolder || !Path.GetExtension(n.FilePath).EqualsIgnoreCase(".r")) { return Task.FromResult(CommandStatusResult.Unhandled); } } return Task.FromResult(new CommandStatusResult(true, commandText, CommandStatus.Enabled | CommandStatus.Supported)); } return Task.FromResult(CommandStatusResult.Unhandled); }
internal static Task FindReferencesInCurrentProcessAsync( SymbolAndProjectId symbolAndProjectId, Solution solution, IStreamingFindReferencesProgress progress, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var finders = ReferenceFinders.DefaultReferenceFinders; progress = progress ?? StreamingFindReferencesProgress.Instance; var engine = new FindReferencesSearchEngine( solution, documents, finders, progress, cancellationToken); return engine.FindReferencesAsync(symbolAndProjectId); }
/// <summary> /// Check if a specific command is supported and enabled. /// </summary> /// <param name="nodes">The project nodes being queried.</param> /// <param name="commandId">The command ID.</param> /// <param name="focused">A value indicating whether <paramref name="nodes"/> or the project have the user focus. /// A value of <c>false</c> indicates this command is being routed through the application in search of command handlers to process a command that the focused UI did not handle.</param> /// <param name="commandText">The default caption of the command that is displayed to the user. <c>null</c> to allow the default caption to be used.</param> /// <param name="progressiveStatus">The query result thus far (as default, or as handed off from previous handler).</param> /// <returns>A value that describes how this command may be handled.</returns> public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) { if (commandId == 0x100) { return Task.FromResult(new CommandStatusResult(true, commandText, CommandStatus.Enabled | CommandStatus.Supported)); } else { return Task.FromResult(CommandStatusResult.Unhandled); } }
public static void ArrayAsRootObject() { const string ExpectedJson = @"[1,true,{""City"":""MyCity""},null,""foo""]"; const string ReversedExpectedJson = @"[""foo"",null,{""City"":""MyCity""},true,1]"; string[] expectedObjects = { @"""foo""", @"null", @"{""City"":""MyCity""}", @"true", @"1" }; var address = new Address(); address.Initialize(); var array = new object[] { 1, true, address, null, "foo" }; string json = JsonSerializer.Serialize(array); Assert.Equal(ExpectedJson, json); var dictionary = new Dictionary <string, string> { { "City", "MyCity" } }; var arrayWithDictionary = new object[] { 1, true, dictionary, null, "foo" }; json = JsonSerializer.Serialize(arrayWithDictionary); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(array); Assert.Equal(ExpectedJson, json); List <object> list = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(list); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(list); Assert.Equal(ExpectedJson, json); IEnumerable ienumerable = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(ienumerable); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(ienumerable); Assert.Equal(ExpectedJson, json); IList ilist = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(ilist); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(ilist); Assert.Equal(ExpectedJson, json); ICollection icollection = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(icollection); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(icollection); Assert.Equal(ExpectedJson, json); IEnumerable <object> genericIEnumerable = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(genericIEnumerable); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(genericIEnumerable); Assert.Equal(ExpectedJson, json); IList <object> genericIList = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(genericIList); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(genericIList); Assert.Equal(ExpectedJson, json); ICollection <object> genericICollection = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(genericICollection); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(genericICollection); Assert.Equal(ExpectedJson, json); IReadOnlyCollection <object> genericIReadOnlyCollection = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(genericIReadOnlyCollection); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(genericIReadOnlyCollection); Assert.Equal(ExpectedJson, json); IReadOnlyList <object> genericIReadonlyList = new List <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(genericIReadonlyList); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(genericIReadonlyList); Assert.Equal(ExpectedJson, json); ISet <object> iset = new HashSet <object> { 1, true, address, null, "foo" }; json = JsonSerializer.Serialize(iset); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(iset); Assert.Equal(ExpectedJson, json); Stack <object> stack = new Stack <object>(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(stack); Assert.Equal(ReversedExpectedJson, json); json = JsonSerializer.Serialize <object>(stack); Assert.Equal(ReversedExpectedJson, json); Queue <object> queue = new Queue <object>(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(queue); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(queue); Assert.Equal(ExpectedJson, json); HashSet <object> hashset = new HashSet <object>(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(hashset); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(hashset); Assert.Equal(ExpectedJson, json); LinkedList <object> linkedlist = new LinkedList <object>(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(linkedlist); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(linkedlist); Assert.Equal(ExpectedJson, json); ImmutableArray <object> immutablearray = ImmutableArray.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(immutablearray); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(immutablearray); Assert.Equal(ExpectedJson, json); IImmutableList <object> iimmutablelist = ImmutableList.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(iimmutablelist); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(iimmutablelist); Assert.Equal(ExpectedJson, json); IImmutableStack <object> iimmutablestack = ImmutableStack.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(iimmutablestack); Assert.Equal(ReversedExpectedJson, json); json = JsonSerializer.Serialize <object>(iimmutablestack); Assert.Equal(ReversedExpectedJson, json); IImmutableQueue <object> iimmutablequeue = ImmutableQueue.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(iimmutablequeue); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(iimmutablequeue); Assert.Equal(ExpectedJson, json); IImmutableSet <object> iimmutableset = ImmutableHashSet.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(iimmutableset); foreach (string obj in expectedObjects) { Assert.Contains(obj, json); } json = JsonSerializer.Serialize <object>(iimmutableset); foreach (string obj in expectedObjects) { Assert.Contains(obj, json); } ImmutableHashSet <object> immutablehashset = ImmutableHashSet.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(immutablehashset); foreach (string obj in expectedObjects) { Assert.Contains(obj, json); } json = JsonSerializer.Serialize <object>(immutablehashset); foreach (string obj in expectedObjects) { Assert.Contains(obj, json); } ImmutableList <object> immutablelist = ImmutableList.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(immutablelist); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(immutablelist); Assert.Equal(ExpectedJson, json); ImmutableStack <object> immutablestack = ImmutableStack.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(immutablestack); Assert.Equal(ReversedExpectedJson, json); json = JsonSerializer.Serialize <object>(immutablestack); Assert.Equal(ReversedExpectedJson, json); ImmutableQueue <object> immutablequeue = ImmutableQueue.CreateRange(new List <object> { 1, true, address, null, "foo" }); json = JsonSerializer.Serialize(immutablequeue); Assert.Equal(ExpectedJson, json); json = JsonSerializer.Serialize <object>(immutablequeue); Assert.Equal(ExpectedJson, json); }
/// <summary> /// TBD /// </summary> /// <param name="currentShardAllocations">TBD</param> /// <param name="rebalanceInProgress">TBD</param> /// <returns>TBD</returns> public Task <IImmutableSet <ShardId> > Rebalance(IImmutableDictionary <IActorRef, IImmutableList <ShardId> > currentShardAllocations, IImmutableSet <ShardId> rebalanceInProgress) { if (rebalanceInProgress.Count < _maxSimultaneousRebalance) { var leastShardsRegion = GetMinBy(currentShardAllocations, kv => kv.Value.Count); var shards = currentShardAllocations.Select(kv => kv.Value.Where(s => !rebalanceInProgress.Contains(s)).ToArray()); var mostShards = GetMaxBy(shards, x => x.Length); if (mostShards.Length - leastShardsRegion.Value.Count >= _rebalanceThreshold) { return(Task.FromResult <IImmutableSet <ShardId> >(mostShards.Take(_maxSimultaneousRebalance - rebalanceInProgress.Count).ToImmutableHashSet())); } } return(Task.FromResult <IImmutableSet <ShardId> >(ImmutableHashSet <ShardId> .Empty)); }
/// <summary> /// Finds all the documents in the provided project that contain the requested string /// values /// </summary> protected Task <ImmutableArray <Document> > FindDocumentsAsync(Project project, IImmutableSet <Document> documents, CancellationToken cancellationToken, params string[] values) { return(FindDocumentsAsync(project, documents, async(d, c) => { var info = await SyntaxTreeIndex.GetIndexAsync(d, c).ConfigureAwait(false); foreach (var value in values) { if (!info.ProbablyContainsIdentifier(value)) { return false; } } return true; }, cancellationToken)); }
/// <summary> /// Deletes items from the project, and optionally from disk. /// Note: Delete and Remove commands are handled via IVsHierarchyDeleteHandler3, not by /// IAsyncCommandGroupHandler and first asks us we CanRemove nodes. If yes then RemoveAsync is called. /// We can remove only nodes that are standard and based on project items, i.e. nodes that /// are created by default IProjectDependenciesSubTreeProvider implementations and have /// DependencyNode.GenericDependencyFlags flags and IRule with Context != null, in order to obtain /// node's itemSpec. ItemSpec then used to remove a project item having same Include. /// </summary> /// <param name="nodes">The nodes that should be deleted.</param> /// <param name="deleteOptions">A value indicating whether the items should be deleted from disk as well as /// from the project file. /// </param> /// <exception cref="InvalidOperationException">Thrown when <see cref="IProjectTreeProvider.CanRemove"/> /// would return <c>false</c> for this operation.</exception> public override async Task RemoveAsync(IImmutableSet <IProjectTree> nodes, DeleteOptions deleteOptions = DeleteOptions.None) { if (deleteOptions.HasFlag(DeleteOptions.DeleteFromStorage)) { throw new NotSupportedException(); } // Get the list of shared import nodes. IEnumerable <IProjectTree> sharedImportNodes = nodes.Where(node => node.Flags.Contains(DependencyTreeFlags.SharedProjectFlags)); // Get the list of normal reference Item Nodes (this excludes any shared import nodes). IEnumerable <IProjectTree> referenceItemNodes = nodes.Except(sharedImportNodes); using (var access = await ProjectLockService.WriteLockAsync()) { var project = await access.GetProjectAsync(ActiveConfiguredProject).ConfigureAwait(true); // Handle the removal of normal reference Item Nodes (this excludes any shared import nodes). foreach (var node in referenceItemNodes) { if (node.BrowseObjectProperties == null || node.BrowseObjectProperties.Context == null) { // if node does not have an IRule with valid ProjectPropertiesContext we can not // get it's itemsSpec. If nodes provided by custom IProjectDependenciesSubTreeProvider // implementation, and have some custom IRule without context, it is not a problem, // since they wouldnot have DependencyNode.GenericDependencyFlags and we would not // end up here, since CanRemove would return false and Remove command would not show // up for those nodes. continue; } var nodeItemContext = node.BrowseObjectProperties.Context; var unresolvedReferenceItem = project.GetItemsByEvaluatedInclude(nodeItemContext.ItemName) .FirstOrDefault(item => string.Equals(item.ItemType, nodeItemContext.ItemType, StringComparison.OrdinalIgnoreCase)); Report.IfNot(unresolvedReferenceItem != null, "Cannot find reference to remove."); if (unresolvedReferenceItem != null) { await access.CheckoutAsync(unresolvedReferenceItem.Xml.ContainingProject.FullPath) .ConfigureAwait(true); project.RemoveItem(unresolvedReferenceItem); } } var snapshot = DependenciesSnapshotProvider.CurrentSnapshot; Requires.NotNull(snapshot, nameof(snapshot)); if (snapshot == null) { return; } // Handle the removal of shared import nodes. var projectXml = await access.GetProjectXmlAsync(UnconfiguredProject.FullPath) .ConfigureAwait(true); foreach (var sharedImportNode in sharedImportNodes) { var sharedFilePath = UnconfiguredProject.GetRelativePath(sharedImportNode.FilePath); if (string.IsNullOrEmpty(sharedFilePath)) { continue; } var sharedProjectDependency = snapshot.FindDependency(sharedFilePath, topLevel: true); if (sharedProjectDependency != null) { sharedFilePath = sharedProjectDependency.Path; } // Find the import that is included in the evaluation of the specified ConfiguredProject that // imports the project file whose full path matches the specified one. var matchingImports = from import in project.Imports where import.ImportingElement.ContainingProject == projectXml where PathHelper.IsSamePath(import.ImportedProject.FullPath, sharedFilePath) select import; foreach (var importToRemove in matchingImports) { var importingElementToRemove = importToRemove.ImportingElement; Report.IfNot(importingElementToRemove != null, "Cannot find shared project reference to remove."); if (importingElementToRemove != null) { await access.CheckoutAsync(importingElementToRemove.ContainingProject.FullPath) .ConfigureAwait(true); importingElementToRemove.Parent.RemoveChild(importingElementToRemove); } } } } }
/// <summary> /// Revoked /// </summary> /// <param name="partitions">List of revoked partitions</param> public Revoked(IImmutableSet <TopicPartition> partitions) { Partitions = partitions; }
/// <summary> /// AssignWithOffset /// </summary> /// <param name="topicPartitionOffsets">Topic partitions with offsets</param> public AssignWithOffset(IImmutableSet <TopicPartitionOffset> topicPartitionOffsets) { TopicPartitionOffsets = topicPartitionOffsets; }
public override Task <ImmutableArray <Project> > DetermineProjectsToSearchAsync(ISymbol symbol, Solution solution, IImmutableSet <Project> projects, CancellationToken cancellationToken) { return(symbol is TSymbol && CanFind((TSymbol)symbol) ? DetermineProjectsToSearchAsync((TSymbol)symbol, solution, projects, cancellationToken) : SpecializedTasks.EmptyImmutableArray <Project>()); }
public async Task <AggregateCrossTargetProjectContext?> TryUpdateCurrentAggregateProjectContextAsync() { AggregateCrossTargetProjectContext?previousContext = Current; // Check if we have already computed the project context. if (previousContext != null) { // For non-cross targeting projects, we can use the current project context if the TargetFramework hasn't changed. // For cross-targeting projects, we need to verify that the current project context matches latest frameworks targeted by the project. // If not, we create a new one and dispose the current one. ConfigurationGeneral projectProperties = await _commonServices.ActiveConfiguredProjectProperties.GetConfigurationGeneralPropertiesAsync(); if (!previousContext.IsCrossTargeting) { string?newTargetFrameworkName = (string?)await projectProperties.TargetFramework.GetValueAsync(); if (string.IsNullOrEmpty(newTargetFrameworkName) && TargetFramework.Empty.Equals(previousContext.ActiveTargetFramework)) { // No change return(null); } ITargetFramework?newTargetFramework = _targetFrameworkProvider.GetTargetFramework(newTargetFrameworkName); if (previousContext.ActiveTargetFramework.Equals(newTargetFramework)) { // No change return(null); } } else { // Check if the current project context is up-to-date for the current active and known project configurations. Assumes.Present(_commonServices.Project.Services.ProjectConfigurationsService); ProjectConfiguration activeProjectConfiguration = _commonServices.ActiveConfiguredProject.ProjectConfiguration; IImmutableSet <ProjectConfiguration> knownProjectConfigurations = await _commonServices.Project.Services.ProjectConfigurationsService.GetKnownProjectConfigurationsAsync(); if (knownProjectConfigurations.All(c => c.IsCrossTargeting()) && HasMatchingTargetFrameworks(activeProjectConfiguration, knownProjectConfigurations)) { // No change return(null); } } } // Force refresh the CPS active project configuration (needs UI thread). await _commonServices.ThreadingService.SwitchToUIThread(); await _activeProjectConfigurationRefreshService.RefreshActiveProjectConfigurationAsync(); // Create new project context. AggregateCrossTargetProjectContext newContext = await _contextProvider.Value.CreateProjectContextAsync(); Current = newContext; return(newContext); bool HasMatchingTargetFrameworks( ProjectConfiguration activeProjectConfiguration, IReadOnlyCollection <ProjectConfiguration> knownProjectConfigurations) { Assumes.NotNull(previousContext); Assumes.True(activeProjectConfiguration.IsCrossTargeting()); ITargetFramework?activeTargetFramework = _targetFrameworkProvider.GetTargetFramework(activeProjectConfiguration.Dimensions[ConfigurationGeneral.TargetFrameworkProperty]); if (!previousContext.ActiveTargetFramework.Equals(activeTargetFramework)) { // Active target framework is different. return(false); } var targetFrameworkMonikers = knownProjectConfigurations .Select(c => c.Dimensions[ConfigurationGeneral.TargetFrameworkProperty]) .Distinct() .ToList(); if (targetFrameworkMonikers.Count != previousContext.TargetFrameworks.Length) { // Different number of target frameworks. return(false); } foreach (string targetFrameworkMoniker in targetFrameworkMonikers) { ITargetFramework?targetFramework = _targetFrameworkProvider.GetTargetFramework(targetFrameworkMoniker); if (targetFramework == null || !previousContext.TargetFrameworks.Contains(targetFramework)) { // Differing TargetFramework return(false); } } return(true); } }
private Task <ImmutableArray <Document> > FindDocumentWithIndexerMemberCrefAsync( Project project, IImmutableSet <Document> documents, CancellationToken cancellationToken) { return(FindDocumentsWithPredicateAsync(project, documents, info => info.ContainsIndexerMemberCref, cancellationToken)); }
/// <summary> /// TBD /// </summary> /// <param name="regions">TBD</param> public CurrentRegions(IImmutableSet <Address> regions) { Regions = regions; }
/// <summary> /// TBD /// </summary> /// <param name="shards">TBD</param> public CurrentShardRegionState(IImmutableSet <ShardState> shards) { Shards = shards; }
/// <summary> /// Commit /// </summary> /// <param name="offsets">List of offsets to commit</param> public Commit(IImmutableSet <TopicPartitionOffset> offsets) { Offsets = offsets; }
/// <summary> /// Seek /// </summary> /// <param name="offsets">Offsets to seek</param> public Seek(IImmutableSet <TopicPartitionOffset> offsets) { Offsets = offsets; }
/// <summary> /// Subscribe /// </summary> public Subscribe(IImmutableSet <string> topics) { Topics = topics; }
protected virtual Task <ImmutableArray <SymbolAndProjectId> > DetermineCascadedSymbolsAsync( SymbolAndProjectId <TSymbol> symbolAndProject, Solution solution, IImmutableSet <Project> projects, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return(SpecializedTasks.EmptyImmutableArray <SymbolAndProjectId>()); }
protected virtual Task <ImmutableArray <Project> > DetermineProjectsToSearchAsync( TSymbol symbol, Solution solution, IImmutableSet <Project> projects, CancellationToken cancellationToken) { return(DependentProjectsFinder.GetDependentProjectsAsync( symbol, solution, projects, cancellationToken)); }
private static async Task <ImmutableArray <DocumentHighlights> > CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable <ReferencedSymbol> references, IEnumerable <Location> additionalReferences, IImmutableSet <Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet <DocumentSpan>(); var tagMap = new MultiDictionary <Document, HighlightSpan>(); bool addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } var list = ArrayBuilder <DocumentHighlights> .GetInstance(tagMap.Count); foreach (var kvp in tagMap) { var spans = ArrayBuilder <HighlightSpan> .GetInstance(kvp.Value.Count); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans.ToImmutableAndFree())); } return(list.ToImmutableAndFree()); }
public abstract Task <ImmutableArray <SymbolAndProjectId> > DetermineCascadedSymbolsAsync( SymbolAndProjectId symbolAndProject, Solution solution, IImmutableSet <Project> projects, FindReferencesSearchOptions options, CancellationToken cancellationToken);
private Task <ImmutableArray <Document> > FindDocumentWithElementAccessExpressionsAsync( Project project, IImmutableSet <Document> documents, CancellationToken cancellationToken) { return(FindDocumentsWithPredicateAsync(project, documents, info => info.ContainsElementAccessExpression, cancellationToken)); }
protected async Task <ImmutableArray <Document> > FindDocumentsAsync(Project project, IImmutableSet <Document> scope, Func <Document, CancellationToken, Task <bool> > predicateAsync, CancellationToken cancellationToken) { // special case for HR if (scope != null && scope.Count == 1) { var document = scope.First(); if (document.Project == project) { return(scope.ToImmutableArray()); } return(ImmutableArray <Document> .Empty); } var documents = ArrayBuilder <Document> .GetInstance(); foreach (var document in project.Documents) { if (scope != null && !scope.Contains(document)) { continue; } if (await predicateAsync(document, cancellationToken).ConfigureAwait(false)) { documents.Add(document); } } return(documents.ToImmutableAndFree()); }
public override Task <ImmutableArray <Document> > DetermineDocumentsToSearchAsync(ISymbol symbol, Project project, IImmutableSet <Document> documents, CancellationToken cancellationToken) { return(symbol is TSymbol && CanFind((TSymbol)symbol) ? DetermineDocumentsToSearchAsync((TSymbol)symbol, project, documents, cancellationToken) : SpecializedTasks.EmptyImmutableArray <Document>()); }
public LatestClusterClients(IImmutableSet <IActorRef> clusterClients) { ClusterClients = clusterClients; }
public abstract Task <ImmutableArray <Document> > DetermineDocumentsToSearchAsync(ISymbol symbol, Project project, IImmutableSet <Document> documents, CancellationToken cancellationToken);
protected abstract Task <ImmutableArray <Document> > DetermineDocumentsToSearchAsync( TSymbol symbol, Project project, IImmutableSet <Document> documents, FindReferencesSearchOptions options, CancellationToken cancellationToken);
/// <summary> /// Finds all the callers of a specified symbol. /// </summary> public static async Task <IEnumerable <SymbolCallerInfo> > FindCallersAsync(ISymbol symbol, Solution solution, IImmutableSet <Document> documents, CancellationToken cancellationToken = default(CancellationToken)) { symbol = symbol.OriginalDefinition; var foundSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false); symbol = foundSymbol ?? symbol; var callReferences = await FindCallReferencesAsync(solution, symbol, documents, cancellationToken).ConfigureAwait(false); var directReferences = callReferences.Where( r => SymbolEquivalenceComparer.Instance.Equals(symbol, r.Definition)).FirstOrDefault(); var indirectReferences = callReferences.WhereAsArray(r => r != directReferences); List <SymbolCallerInfo> results = null; if (directReferences != null) { foreach (var kvp in await directReferences.Locations.FindReferencingSymbolsAsync(cancellationToken).ConfigureAwait(false)) { results = results ?? new List <SymbolCallerInfo>(); results.Add(new SymbolCallerInfo(kvp.Key, symbol, kvp.Value, isDirect: true)); } } { var indirectLocations = indirectReferences.SelectMany(r => r.Locations); foreach (var kvp in await indirectLocations.FindReferencingSymbolsAsync(cancellationToken).ConfigureAwait(false)) { results = results ?? new List <SymbolCallerInfo>(); results.Add(new SymbolCallerInfo(kvp.Key, symbol, kvp.Value, isDirect: false)); } } return(results ?? SpecializedCollections.EmptyEnumerable <SymbolCallerInfo>()); }
internal static async Task <ImmutableArray <SymbolAndProjectId> > FindImplementedInterfaceMembersAsync( SymbolAndProjectId symbolAndProjectId, Solution solution, IImmutableSet <Project> projects = null, CancellationToken cancellationToken = default(CancellationToken)) { // Member can only implement interface members if it is an explicit member, or if it is // public and non static. var symbol = symbolAndProjectId.Symbol; if (symbol != null) { var explicitImplementations = symbol.ExplicitInterfaceImplementations(); if (explicitImplementations.Length > 0) { return(explicitImplementations.SelectAsArray(symbolAndProjectId.WithSymbol)); } else if ( symbol.DeclaredAccessibility == Accessibility.Public && !symbol.IsStatic && (symbol.ContainingType.TypeKind == TypeKind.Class || symbol.ContainingType.TypeKind == TypeKind.Struct)) { // Interface implementation is a tricky thing. A method may implement an interface // method, even if its containing type doesn't state that it implements the // interface. For example: // // interface IFoo { void Foo(); } // // class Base { public void Foo(); } // // class Derived : Base, IFoo { } // // In this case, Base.Foo *does* implement IFoo.Foo in the context of the type // Derived. var containingType = symbolAndProjectId.WithSymbol( symbol.ContainingType.OriginalDefinition); var derivedClasses = await SymbolFinder.FindDerivedClassesAsync( containingType, solution, projects, cancellationToken).ConfigureAwait(false); var allTypes = derivedClasses.Concat(containingType); var builder = ArrayBuilder <SymbolAndProjectId> .GetInstance(); foreach (var type in allTypes.Convert <INamedTypeSymbol, ITypeSymbol>()) { foreach (var interfaceType in GetAllInterfaces(type)) { if (interfaceType.Symbol.MemberNames.Contains(symbol.Name)) { foreach (var m in GetMembers(interfaceType, symbol.Name)) { var sourceMethod = await FindSourceDefinitionAsync(m, solution, cancellationToken).ConfigureAwait(false); var bestMethod = sourceMethod.Symbol != null ? sourceMethod : m; var implementations = type.FindImplementationsForInterfaceMember( bestMethod.Symbol, solution.Workspace, cancellationToken); foreach (var implementation in implementations) { if (implementation.Symbol != null && SymbolEquivalenceComparer.Instance.Equals(implementation.Symbol.OriginalDefinition, symbol.OriginalDefinition)) { builder.Add(bestMethod); } } } } } } var result = builder.Distinct(SymbolAndProjectIdComparer.SymbolEquivalenceInstance) .ToImmutableArray(); builder.Free(); return(result); } } return(ImmutableArray <SymbolAndProjectId> .Empty); }
public LatestContactPoints(IImmutableSet <ActorPath> contactPoints) { ContactPoints = contactPoints; }
internal static Task <ImmutableArray <SymbolAndProjectId <INamedTypeSymbol> > > FindDerivedClassesAsync( SymbolAndProjectId <INamedTypeSymbol> typeAndProjectId, Solution solution, IImmutableSet <Project> projects = null, CancellationToken cancellationToken = default(CancellationToken)) { var type = typeAndProjectId.Symbol; if (type == null) { throw new ArgumentNullException(nameof(type)); } if (solution == null) { throw new ArgumentNullException(nameof(solution)); } return(DependentTypeFinder.FindTransitivelyDerivedClassesAsync(type, solution, projects, cancellationToken)); }
/// <summary> /// Assign /// </summary> /// <param name="topicPartitions">Topic partitions</param> public Assign(IImmutableSet <TopicPartition> topicPartitions) { TopicPartitions = topicPartitions; }
public abstract Task <ImmutableArray <Project> > DetermineProjectsToSearchAsync(ISymbol symbol, Solution solution, IImmutableSet <Project> projects, CancellationToken cancellationToken);