private static async Task <ImmutableArray <DependentProject> > GetDependentProjectsCoreAsync( ISymbol symbol, Solution solution, Project sourceProject, SymbolVisibility visibility, CancellationToken cancellationToken) { var dependentProjects = new HashSet <DependentProject>(); // If a symbol was defined in source, then it is always visible to the project it // was defined in. if (sourceProject != null) { dependentProjects.Add(new DependentProject(sourceProject.Id, hasInternalsAccess: true)); } cancellationToken.ThrowIfCancellationRequested(); // If it's not private, then we need to find possible references. if (visibility != SymbolVisibility.Private) { await AddNonSubmissionDependentProjectsAsync(symbol.ContainingAssembly, solution, sourceProject, dependentProjects, cancellationToken).ConfigureAwait(false); } // submission projects are special here. The fields generated inside the Script object // is private, but further submissions can bind to them. await AddSubmissionDependentProjectsAsync(solution, sourceProject, dependentProjects, cancellationToken).ConfigureAwait(false); return(dependentProjects.ToImmutableArray()); }
/// <summary> /// Gets pending events for given set of analyzers for the given syntax tree. /// </summary> private ImmutableArray <CompilationEvent> GetPendingEvents_NoLock(ImmutableArray <DiagnosticAnalyzer> analyzers, SyntaxTree tree) { HashSet <CompilationEvent> compilationEventsForTree; if (_pendingSourceEvents.TryGetValue(tree, out compilationEventsForTree)) { if (compilationEventsForTree?.Count > 0) { HashSet <CompilationEvent> pendingEvents = null; try { pendingEvents = GetPendingEvents_NoLock(analyzers); if (pendingEvents.Count > 0) { pendingEvents.IntersectWith(compilationEventsForTree); return(pendingEvents.ToImmutableArray()); } } finally { Free(pendingEvents); } } } return(ImmutableArray <CompilationEvent> .Empty); }
protected override ImmutableArray <UsingDirectiveSyntax> GetUnnecessaryImports( SemanticModel model, SyntaxNode root, Func <SyntaxNode, bool> predicate, CancellationToken cancellationToken) { predicate ??= Functions <SyntaxNode> .True; var diagnostics = model.GetDiagnostics(cancellationToken: cancellationToken); if (!diagnostics.Any()) { return(ImmutableArray <UsingDirectiveSyntax> .Empty); } var unnecessaryImports = new HashSet <UsingDirectiveSyntax>(); foreach (var diagnostic in diagnostics) { if (diagnostic.Id == "CS8019") { if (root.FindNode(diagnostic.Location.SourceSpan) is UsingDirectiveSyntax node && predicate(node)) { unnecessaryImports.Add(node); } } } return(unnecessaryImports.ToImmutableArray()); }
public void RemovePage(WorkbookPage workbookPage) { if (workbookPage == null) { throw new ArgumentNullException(nameof(workbookPage)); } workbookPage.PropertyChanged -= WorkbookPage_PropertyChanged; pages.Remove(workbookPage); if (pages.Count == 0) { PlatformTargets = ImmutableArray <AgentType> .Empty; } else { PlatformTargets = pages [0].PlatformTargets; if (pages.Count > 1) { var intersection = new HashSet <AgentType> (PlatformTargets); foreach (var page in pages.Skip(1)) { intersection.IntersectWith(page.PlatformTargets); } PlatformTargets = intersection.ToImmutableArray(); } } }
/// <summary> /// Constructs a new OpenCL accelerator reference. /// </summary> /// <param name="platformId">The OpenCL platform id.</param> /// <param name="deviceId">The OpenCL device id.</param> public CLAcceleratorId(IntPtr platformId, IntPtr deviceId) : base(AcceleratorType.OpenCL) { if (platformId == IntPtr.Zero) { throw new ArgumentOutOfRangeException(nameof(platformId)); } if (deviceId == IntPtr.Zero) { throw new ArgumentOutOfRangeException(nameof(deviceId)); } PlatformId = platformId; DeviceId = deviceId; DeviceType = (CLDeviceType)CLAPI.GetDeviceInfo <long>( deviceId, CLDeviceInfoType.CL_DEVICE_TYPE); // Resolve extensions var extensionString = CLAPI.GetDeviceInfo( DeviceId, CLDeviceInfoType.CL_DEVICE_EXTENSIONS); extensionSet = new HashSet <string>( extensionString.ToLower().Split(' ')); Extensions = extensionSet.ToImmutableArray(); // Resolve extension method getKernelSubGroupInfo = CLAPI.GetExtension <clGetKernelSubGroupInfoKHR>(platformId); }
private static async Task <ImmutableArray <ISymbol> > FindSourceImplementationsAsync( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var builder = new HashSet <ISymbol>(SymbolEquivalenceComparer.Instance); // If we're in a linked file, try to find all the symbols this links to, and find all the implementations of // each of those linked symbols. De-dupe the results so the user only gets unique results. var linkedSymbols = await SymbolFinder.FindLinkedSymbolsAsync( symbol, solution, cancellationToken).ConfigureAwait(false); // Because we're searching linked files, we may get many symbols that are conceptually // 'duplicates' to the user. Specifically, any symbols that would navigate to the same // location do not provide value to the user as selecting any from that set of items // would navigate them to the exact same location. For this, we use file-paths and spans // as those will be the same regardless of how a file is linked or used in shared project // scenarios. var seenLocations = new HashSet <(string filePath, TextSpan span)>(); foreach (var linkedSymbol in linkedSymbols) { var implementations = await FindImplementationsWorkerAsync( solution, linkedSymbol, cancellationToken).ConfigureAwait(false); foreach (var implementation in implementations) { if (AddedAllLocations(implementation, seenLocations)) { builder.Add(implementation); } } } return(builder.ToImmutableArray());
/// <summary> /// Возвращает список уникальных идентификаторов объектов, используемых в тексте <see cref="text"/>. /// Идентификаторы объектов имеют длину 8байт и представлены в тексте в виде ¶X:Y¶, где X - старшие 4 байта, а Y - младшие 4 байта. /// Текст <see cref="text"/> так же содержит строчные (//) и блоковые (/**/) комментарии, которые нужно игнорировать. /// Т.е. в комментариях идентификаторы объектов искать не нужно. И, кстати, блоковые комментарии могут быть многострочными. /// </summary> public static IImmutableList <long> GetUsedObjects(this string text) { /* * Задача на поиграться с регулярками - вся сложность в том, чтобы аккуратно игнорировать комментарии. * Экспериментировать онлайн можно, например, здесь: http://regexstorm.net/tester и https://regexr.com/ */ /* * * Непонятно условие - как именно записаны байты идентификатора в тексте? * Здесь предполагается что идентификаторы записаны в тексте так: * * ``` * Never gonna 31b9:6f8c you up * Never gonna let you a3ba:188a * Never gonna run around and 14hh:00b5 you * Never gonna make you 58f4:7cdc * // Never gonna say 4dd9:00a0 * Never gonna tell 6aac:2f9c and 31b9:6f8c you * ``` * */ HashSet <long> objectIDs = new HashSet <long>(); MatchCollection matches = Regex.Matches(text, @"(?<!\n[^\n]*\/\/((?!\/\/).)*)(?<!\/\*((?!\*\/)([^$]))*)([\da-f]{4}:[\da-f]{4})"); foreach (Match m in matches) { string hex = m.ToString().Substring(0, 4) + m.ToString().Substring(5); objectIDs.Add(long.Parse(hex, System.Globalization.NumberStyles.HexNumber)); } return(objectIDs.ToImmutableArray()); }
public override ImmutableArray <Symbol> GetMembers() { if (_lazyMembers.IsDefault) { HashSet <Symbol> symbols = new HashSet <Symbol>(); try { foreach (var model in _module.Models) { foreach (var ms in model.Objects) { if (ms.MParent == null) { var symbol = MetaSymbolMap.GetSymbol(ms); symbols.Add(symbol); } } } } finally { ImmutableInterlocked.InterlockedInitialize(ref _lazyMembers, symbols.ToImmutableArray()); } } return(_lazyMembers); }
public MarkupResult Render(MarkdownDocument document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var filePath = document.GetData("filePath") as string; if (filePath == null) { throw new ArgumentNullException("file path can't be found in AST."); } var context = CreateContext(null, filePath); var dependency = new HashSet <string>(); var engine = CreateEngine(dependency); return(new MarkupResult { Html = engine.Render(document, context, _parameters), Dependency = dependency.ToImmutableArray() }); }
public ImmutableArray <TypeParameterType> GetAllConstraints() { var visited = new HashSet <TypeParameterType>(); var allConstraints = new HashSet <TypeParameterType>(); var queue = new Queue <TypeParameterType>(); visited.Add(this); queue.Enqueue(this); while (queue.Any()) { var next = queue.Dequeue(); allConstraints.Add(next); foreach (var constraint in next.Constraints) { if (!visited.Contains(constraint.Value)) { visited.Add(constraint.Value); queue.Enqueue(constraint.Value); } } } return(allConstraints.ToImmutableArray()); }
internal static async Task <ImmutableArray <ISymbol> > FindLinkedSymbolsAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken ) { // Add the original symbol to the result set. var linkedSymbols = new HashSet <ISymbol> { symbol }; foreach (var location in symbol.DeclaringSyntaxReferences) { var originalDocument = solution.GetDocument(location.SyntaxTree); // 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 (originalDocument == null) { Debug.Assert( solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles ); continue; } 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.Add(linkedSymbol); } } } return(linkedSymbols.ToImmutableArray()); }
private static async Task <(ImmutableArray <ISymbol> implementations, string?message)> FindSourceImplementationsAsync( Solution solution, ISymbol symbol, CancellationToken cancellationToken ) { var builder = new HashSet <ISymbol>(SymbolEquivalenceComparer.Instance); // If we're in a linked file, try to find all the symbols this links to, and find all the implementations of // each of those linked symbols. De-dupe the results so the user only gets unique results. var linkedSymbols = await SymbolFinder .FindLinkedSymbolsAsync(symbol, solution, cancellationToken) .ConfigureAwait(false); foreach (var linkedSymbol in linkedSymbols) { builder.AddRange( await FindSourceImplementationsWorkerAsync( solution, linkedSymbol, cancellationToken ) .ConfigureAwait((bool)false) ); } var result = builder.ToImmutableArray(); var message = result.IsEmpty ? EditorFeaturesResources.The_symbol_has_no_implementations : null; return(result, message); }
public IEnumerable <IMarketDataEntity> GetAll() { if (!_fileContentLoaded) { Load(); } return(_entities.ToImmutableArray()); }
public static ImmutableArray <string> PopDependencies() { lock (_locker) { var array = SharedDependencies.ToImmutableArray(); SharedDependencies.Clear(); return(array); } }
private static async Task <ImmutableArray <ISymbol> > FindImplementationsWorkerAsync( ISymbol symbol, Project project, CancellationToken cancellationToken) { var solution = project.Solution; if (symbol.IsInterfaceType() || symbol.IsImplementableMember()) { var implementations = await SymbolFinder.FindImplementationsAsync( symbol, solution, cancellationToken : cancellationToken).ConfigureAwait(false); // It's important we use a HashSet here -- we may have cases in an inheritence hierarchy where more than one method // in an overrides chain implements the same interface method, and we want to duplicate those. The easiest way to do it // is to just use a HashSet. var implementationsAndOverrides = new HashSet <ISymbol>(); foreach (var implementation in implementations) { implementationsAndOverrides.Add(implementation); // FindImplementationsAsync will only return the base virtual/abstract method, not that method and the overrides // of the method. We should also include those. if (implementation.IsOverridable()) { var overrides = await SymbolFinder.FindOverridesAsync( implementation, solution, cancellationToken : cancellationToken).ConfigureAwait(false); implementationsAndOverrides.AddRange(overrides); } } return(implementationsAndOverrides.ToImmutableArray()); } else if ((symbol as INamedTypeSymbol)?.TypeKind == TypeKind.Class) { var derivedClasses = await SymbolFinder.FindDerivedClassesAsync( (INamedTypeSymbol)symbol, solution, cancellationToken : cancellationToken).ConfigureAwait(false); var implementations = derivedClasses.Concat(symbol); return(implementations.ToImmutableArray()); } else if (symbol.IsOverridable()) { var overrides = await SymbolFinder.FindOverridesAsync( symbol, solution, cancellationToken : cancellationToken).ConfigureAwait(false); var implementations = overrides.Concat(symbol); return(implementations.ToImmutableArray()); } else { // This is something boring like a regular method or type, so we'll just go there directly return(ImmutableArray.Create(symbol)); } }
public async Task <ImmutableArray <SymbolAndProjectId> > DetermineCascadedSymbolsAsync( SymbolAndProjectId symbolAndProjectId, Solution solution, IImmutableSet <Project> projects, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var linkedSymbols = new HashSet <SymbolAndProjectId>(); var symbol = symbolAndProjectId.Symbol; foreach (var location in symbol.DeclaringSyntaxReferences) { var originalDocument = solution.GetDocument(location.SyntaxTree); // 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. // TODO: the assert is also commented out becase generated syntax trees won't // have a document until https://github.com/dotnet/roslyn/issues/42823 is fixed if (originalDocument == null) { // Debug.Assert(solution.Workspace.Kind == WorkspaceKind.Interactive || solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles); continue; } foreach (var linkedDocumentId in originalDocument.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var linkedSyntaxRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Defend against constructed solutions with inconsistent linked documents if (!linkedSyntaxRoot.FullSpan.Contains(location.Span)) { continue; } 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) { var linkedSymbolAndProjectId = SymbolAndProjectId.Create(linkedSymbol, linkedDocument.Project.Id); if (!linkedSymbols.Contains(linkedSymbolAndProjectId)) { linkedSymbols.Add(linkedSymbolAndProjectId); } } } } return(linkedSymbols.ToImmutableArray()); }
public void Build(FileModel model, IHostService host) { model.File = Path.ChangeExtension(model.File, ".json"); var toc = (TocViewModel)model.Content; HashSet<string> links = new HashSet<string>(); Dictionary<string, HashSet<string>> tocMap = new Dictionary<string, HashSet<string>>(); UpdateRelativePathAndAddTocMap(toc, model, links, tocMap, host); model.Properties.LinkToFiles = links.ToImmutableArray(); model.Properties.TocMap = tocMap.ToImmutableDictionary(); // todo : metadata. }
public SaveResult Save(FileModel model) { HashSet <string> linkToFiles = CollectLinksAndFixDocument(model); return(new SaveResult { DocumentType = "Conceptual", ModelFile = model.File, LinkToFiles = linkToFiles.ToImmutableArray(), }); }
public SuppressionDiffResult(string path, string assembly, HashSet <SuppressMessage> addedMessages, HashSet <SuppressMessage> deletedMessages) { path.ThrowOnNull(nameof(path)); assembly.ThrowOnNull(nameof(assembly)); addedMessages.ThrowOnNull(nameof(addedMessages)); deletedMessages.ThrowOnNull(nameof(deletedMessages)); Path = path; Assembly = assembly; AddedMessages = addedMessages.ToImmutableArray(); DeletedMessages = deletedMessages.ToImmutableArray(); }
public override void Build(FileModel model, IHostService host) { model.File = Path.ChangeExtension(model.File, ".json"); var toc = (TocViewModel)model.Content; HashSet <string> links = new HashSet <string>(); Dictionary <string, HashSet <string> > tocMap = new Dictionary <string, HashSet <string> >(); UpdateRelativePathAndAddTocMap(toc, model, links, tocMap, host); model.Properties.LinkToFiles = links.ToImmutableArray(); model.Properties.TocMap = tocMap.ToImmutableDictionary(); // todo : metadata. }
/// <summary> /// Init general OpenCL extensions. /// </summary> private void InitExtensions() { // Resolve extensions var extensionString = CurrentAPI.GetDeviceInfo( DeviceId, CLDeviceInfoType.CL_DEVICE_EXTENSIONS); foreach (var extension in extensionString.ToLower().Split(' ')) { extensionSet.Add(extension); } Extensions = extensionSet.ToImmutableArray(); }
public MarkupResult Markup(string src, string path) { var dependency = new HashSet<string>(); var html = _builder.CreateDfmEngine(new DfmRenderer() { Tokens = _tokens }).Markup(src, path, dependency); var result = new MarkupResult { Html = html, }; if (dependency.Count > 0) { result.Dependency = dependency.ToImmutableArray(); } return result; }
public async Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsAsync( SymbolAndProjectId symbolAndProjectId, Solution solution, IImmutableSet<Project> projects = null, CancellationToken cancellationToken = default(CancellationToken)) { var linkedSymbols = new HashSet<SymbolAndProjectId>(); var symbol = symbolAndProjectId.Symbol; foreach (var location in symbol.DeclaringSyntaxReferences) { var originalDocument = solution.GetDocument(location.SyntaxTree); // 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 (originalDocument == null) { Debug.Assert(solution.Workspace.Kind == "Interactive"); continue; } foreach (var linkedDocumentId in originalDocument.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var linkedSyntaxRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Defend against constructed solutions with inconsistent linked documents if (!linkedSyntaxRoot.FullSpan.Contains(location.Span)) { continue; } 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) { var linkedSymbolAndProjectId = SymbolAndProjectId.Create(linkedSymbol, linkedDocument.Project.Id); if (!linkedSymbols.Contains(linkedSymbolAndProjectId)) { linkedSymbols.Add(linkedSymbolAndProjectId); } } } } return linkedSymbols.ToImmutableArray(); }
public static ILogger AddOrReplace( ILogger newLogger, ILogger oldLogger, Func <ILogger, bool> predicate ) { if (newLogger == null) { return(oldLogger); } if (oldLogger == null) { return(newLogger); } var aggregateLogger = oldLogger as AggregateLogger; if (aggregateLogger == null) { // replace old logger with new logger if (predicate(oldLogger)) { // this might not aggregate logger return(newLogger); } // merge two return(new AggregateLogger(ImmutableArray.Create(newLogger, oldLogger))); } var set = new HashSet <ILogger>(); foreach (var logger in aggregateLogger._loggers) { // replace this logger with new logger if (predicate(logger)) { set.Add(newLogger); continue; } // add old one back set.Add(logger); } // add new logger. if we already added one, this will be ignored. set.Add(newLogger); return(new AggregateLogger(set.ToImmutableArray())); }
public async Task <ImmutableArray <ISymbol> > FindMemberDependentsAsync() { var tasks = _member.DeclaringSyntaxReferences.Select(@ref => @ref.GetSyntaxAsync(_cancellationToken)); var syntaxes = await Task.WhenAll(tasks).ConfigureAwait(false); var compilation = await _project.GetCompilationAsync(_cancellationToken).ConfigureAwait(false); foreach (var syntax in syntaxes) { Visit(compilation.GetSemanticModel(syntax.SyntaxTree).GetOperation(syntax, _cancellationToken)); } return(_dependents.ToImmutableArray()); }
private void ClearReportedRunModeDiagnostics() { // clear diagnostics reported during run mode: ImmutableArray <DocumentId> documentsToReanalyze; lock (_documentsWithReportedDiagnosticsDuringRunModeGuard) { documentsToReanalyze = _documentsWithReportedDiagnosticsDuringRunMode.ToImmutableArray(); _documentsWithReportedDiagnosticsDuringRunMode.Clear(); } // clear all reported run mode diagnostics: _diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); }
public MarkupResult Markup(string src, string path) { var dependency = new HashSet <string>(); var html = Builder.CreateDfmEngine(Renderer).Markup(src, path, dependency); var result = new MarkupResult { Html = html, }; if (dependency.Count > 0) { result.Dependency = dependency.ToImmutableArray(); } return(result); }
private ImmutableArray <TypeDefinition> GetAllInterfaces() { var interfaces = new HashSet <TypeDefinition>(); var t = this; do { foreach (var @interface in t.Interfaces) { interfaces.Add(@interface); } t = t.BaseType; } while (t != null); return(interfaces.ToImmutableArray()); }
internal static ImmutableArray <AttributeInfo> GetAttributesIncludingInherited(this INamedTypeSymbol namedType, Func <ISymbol, AttributeData, bool> predicate = null) { HashSet <AttributeInfo> attributes = null; foreach (AttributeData attributeData in namedType.GetAttributes()) { if (predicate == null || predicate(namedType, attributeData)) { (attributes ??= new HashSet <AttributeInfo>(AttributeInfo.AttributeClassComparer)).Add(new AttributeInfo(namedType, attributeData)); } } INamedTypeSymbol baseType = namedType.BaseType; while (baseType != null && baseType.SpecialType != SpecialType.System_Object) { foreach (AttributeData attributeData in baseType.GetAttributes()) { AttributeData attributeUsage = attributeData.AttributeClass.GetAttribute(MetadataNames.System_AttributeUsageAttribute); if (attributeUsage != null) { TypedConstant typedConstant = attributeUsage.NamedArguments.FirstOrDefault(f => f.Key == "Inherited").Value; if (typedConstant.Kind != TypedConstantKind.Error && typedConstant.Type?.SpecialType == SpecialType.System_Boolean && (!(bool)typedConstant.Value)) { continue; } } if (predicate == null || predicate(baseType, attributeData)) { (attributes ??= new HashSet <AttributeInfo>(AttributeInfo.AttributeClassComparer)).Add(new AttributeInfo(baseType, attributeData)); } } baseType = baseType.BaseType; } return((attributes != null) ? attributes.ToImmutableArray() : ImmutableArray <AttributeInfo> .Empty); }
public static ImmutableArray <ITypeSymbol> DetermineParameterTypes( ArgumentSyntax argument, SemanticModel semanticModel, CancellationToken cancellationToken = default) { if (argument.Parent is BaseArgumentListSyntax argumentList) { SyntaxNode parent = argumentList.Parent; if (parent != null) { SymbolInfo symbolInfo = GetSymbolInfo(parent, semanticModel, cancellationToken); ISymbol symbol = symbolInfo.Symbol; if (symbol != null) { ITypeSymbol typeSymbol = DetermineParameterType(symbol, argument, argumentList); if (typeSymbol?.IsErrorType() == false) { return(ImmutableArray.Create(typeSymbol)); } } else { HashSet <ITypeSymbol> typeSymbols = null; foreach (ISymbol candidateSymbol in symbolInfo.CandidateSymbols) { ITypeSymbol typeSymbol = DetermineParameterType(candidateSymbol, argument, argumentList); if (typeSymbol?.IsErrorType() == false) { (typeSymbols ??= new HashSet <ITypeSymbol>()).Add(typeSymbol); } } if (typeSymbols != null) { return(typeSymbols.ToImmutableArray()); } } } } return(ImmutableArray <ITypeSymbol> .Empty); }
private static async Task <ImmutableArray <SymbolAndProjectId> > FindSourceAndMetadataImplementationsAsync( Solution solution, SymbolAndProjectId symbolAndProjectId, CancellationToken cancellationToken) { if (symbolAndProjectId.Symbol.IsInterfaceType() || symbolAndProjectId.Symbol.IsImplementableMember()) { var implementations = await SymbolFinder.FindImplementationsAsync( symbolAndProjectId, solution, cancellationToken : cancellationToken).ConfigureAwait(false); // It's important we use a HashSet here -- we may have cases in an inheritance hierarchy where more than one method // in an overrides chain implements the same interface method, and we want to duplicate those. The easiest way to do it // is to just use a HashSet. var implementationsAndOverrides = new HashSet <SymbolAndProjectId>(); foreach (var implementation in implementations) { implementationsAndOverrides.Add(implementation); // FindImplementationsAsync will only return the base virtual/abstract method, not that method and the overrides // of the method. We should also include those. if (implementation.Symbol.IsOverridable()) { var overrides = await SymbolFinder.FindOverridesAsync( implementation, solution, cancellationToken : cancellationToken).ConfigureAwait(false); implementationsAndOverrides.AddRange(overrides); } } if (!symbolAndProjectId.Symbol.IsInterfaceType() && !symbolAndProjectId.Symbol.IsAbstract) { implementationsAndOverrides.Add(symbolAndProjectId); } return(implementationsAndOverrides.ToImmutableArray()); } else if (symbolAndProjectId.Symbol is INamedTypeSymbol { TypeKind : TypeKind.Class } namedType) { var derivedClasses = await SymbolFinder.FindDerivedClassesAsync( symbolAndProjectId.WithSymbol(namedType), solution, cancellationToken : cancellationToken).ConfigureAwait(false); return(derivedClasses.SelectAsArray(s => (SymbolAndProjectId)s).Concat(symbolAndProjectId)); }
public static ILogger AddOrReplace(ILogger newLogger, ILogger oldLogger, Func<ILogger, bool> predicate) { if (newLogger == null) { return oldLogger; } if (oldLogger == null) { return newLogger; } var aggregateLogger = oldLogger as AggregateLogger; if (aggregateLogger == null) { // replace old logger with new logger if (predicate(oldLogger)) { // this might not aggregate logger return newLogger; } // merge two return new AggregateLogger(ImmutableArray.Create(newLogger, oldLogger)); } var set = new HashSet<ILogger>(); foreach (var logger in aggregateLogger._loggers) { // replace this logger with new logger if (predicate(logger)) { set.Add(newLogger); continue; } // add old one back set.Add(logger); } // add new logger. if we already added one, this will be ignored. set.Add(newLogger); return new AggregateLogger(set.ToImmutableArray()); }
public static AggregateLogger Create(params ILogger[] loggers) { var set = new HashSet <ILogger>(); // flatten loggers foreach (var logger in loggers.WhereNotNull()) { if (logger is AggregateLogger aggregateLogger) { set.UnionWith(aggregateLogger._loggers); continue; } set.Add(logger); } return(new AggregateLogger(set.ToImmutableArray())); }
public Task <IEnumerable <string> > GetAllMessagesToCancellAsync() { _readWriterLockSlim.EnterReadLock(); try { var enumerator = _operationsToCancel.ToImmutableArray(); return(Task.FromResult((IEnumerable <string>)enumerator)); } finally { if (_readWriterLockSlim.IsReadLockHeld) { _readWriterLockSlim.ExitReadLock(); } } }
public static AggregateLogger Create(params ILogger[] loggers) { var set = new HashSet<ILogger>(); // flatten loggers foreach (var logger in loggers.WhereNotNull()) { var aggregateLogger = logger as AggregateLogger; if (aggregateLogger != null) { set.UnionWith(aggregateLogger.loggers); continue; } set.Add(logger); } return new AggregateLogger(set.ToImmutableArray()); }
public MarkupResult Markup(string src, string path) { var dependency = new HashSet<string>(); var json = _builder.CreateDfmEngine(new DfmJsonTokenTreeRender()).Markup(src, path, dependency); if (json.Length != 0 && json.EndsWith(",")) { json = json.Remove(json.Length - 1); } var result = new MarkupResult { // TODO: rename Html = $"{{\"name\":\"0>0>markdown\",\"children\":[{json}]}}", }; if (dependency.Count > 0) { result.Dependency = dependency.ToImmutableArray(); } return result; }
public MarkupResult MarkupCore(string markdown, FileAndType ft) { var html = DocfxFlavoredMarked.Markup(markdown, Path.Combine(ft.BaseDir, ft.File)); var doc = new HtmlDocument(); doc.LoadHtml(html); var result = new MarkupResult(); // TODO: how to get TITLE // InnerText in HtmlAgilityPack is not decoded, should be a bug var headerNode = doc.DocumentNode.SelectSingleNode("//h1|//h2|//h3"); result.Title = StringHelper.HtmlDecode(headerNode?.InnerText); var node = doc.DocumentNode.SelectSingleNode("//yamlheader"); if (node != null) { using (var sr = new StringReader(StringHelper.HtmlDecode(node.InnerHtml))) { result.YamlHeader = YamlUtility.Deserialize<Dictionary<string, object>>(sr).ToImmutableDictionary(); } node.Remove(); } var linkToFiles = new HashSet<string>(); foreach (var link in from n in doc.DocumentNode.Descendants() where !string.Equals(n.Name, "xref", StringComparison.OrdinalIgnoreCase) from attr in n.Attributes where string.Equals(attr.Name, "src", StringComparison.OrdinalIgnoreCase) || string.Equals(attr.Name, "href", StringComparison.OrdinalIgnoreCase) where !string.IsNullOrWhiteSpace(attr.Value) select attr) { string linkFile; string anchor = null; if (PathUtility.IsRelativePath(link.Value)) { var index = link.Value.IndexOf('#'); if (index == -1) { linkFile = link.Value; } else if (index == 0) { continue; } else { linkFile = link.Value.Remove(index); anchor = link.Value.Substring(index); } var path = (RelativePath)ft.File + (RelativePath)linkFile; if (path.ParentDirectoryCount > 0) { Logger.LogError($"Cannot refer path: \"{path}\" out of project.", file: ft.File); throw new DocumentException($"Cannot refer path \"{path}\" out of project in file \"{ft.File}\"."); } var file = path.GetPathFromWorkingFolder(); link.Value = file + anchor; linkToFiles.Add(HttpUtility.UrlDecode(file)); } } result.LinkToFiles = linkToFiles.ToImmutableArray(); result.LinkToUids = (from n in doc.DocumentNode.Descendants() where string.Equals(n.Name, "xref", StringComparison.OrdinalIgnoreCase) from attr in n.Attributes where string.Equals(attr.Name, "href", StringComparison.OrdinalIgnoreCase) where !string.IsNullOrWhiteSpace(attr.Value) select attr.Value).ToImmutableArray(); using (var sw = new StringWriter()) { doc.Save(sw); result.Html = sw.ToString(); } return result; }
private async Task<ImmutableArray<PackageWithAssemblyResult>> FindMatchingPackagesAsync( PackageSource source, ISymbolSearchService searchService, IPackageInstallerService installerService, ISet<string> assemblyNames, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var result = new HashSet<PackageWithAssemblyResult>(); foreach (var assemblyName in assemblyNames) { var packagesWithAssembly = await searchService.FindPackagesWithAssemblyAsync( source.Name, assemblyName, cancellationToken).ConfigureAwait(false); result.AddRange(packagesWithAssembly); } // Ensure the packages are sorted by rank. var sortedPackages = result.ToImmutableArray().Sort(); return sortedPackages; }
private MarkupResult MarkupCore(string markdown, FileAndType ft) { var html = _engine.CreateDfmEngine(DocfxFlavoredMarked.Renderer).Markup(markdown, Path.Combine(ft.BaseDir, ft.File)); var doc = new HtmlDocument(); doc.LoadHtml(html); var result = new MarkupResult(); var node = doc.DocumentNode.SelectSingleNode("//yamlheader"); if (node != null) { using (var sr = new StringReader(StringHelper.HtmlDecode(node.InnerHtml))) { result.YamlHeader = YamlUtility.Deserialize<Dictionary<string, object>>(sr).ToImmutableDictionary(); } node.Remove(); } var linkToFiles = new HashSet<string>(); foreach (var link in from n in doc.DocumentNode.Descendants() where !string.Equals(n.Name, "xref", StringComparison.OrdinalIgnoreCase) from attr in n.Attributes where string.Equals(attr.Name, "src", StringComparison.OrdinalIgnoreCase) || string.Equals(attr.Name, "href", StringComparison.OrdinalIgnoreCase) where !string.IsNullOrWhiteSpace(attr.Value) select attr) { string linkFile; string anchor = null; if (PathUtility.IsRelativePath(link.Value)) { var index = link.Value.IndexOf('#'); if (index == -1) { linkFile = link.Value; } else if (index == 0) { continue; } else { linkFile = link.Value.Remove(index); anchor = link.Value.Substring(index); } var path = (RelativePath)ft.File + (RelativePath)linkFile; var file = path.GetPathFromWorkingFolder(); link.Value = file + anchor; linkToFiles.Add(HttpUtility.UrlDecode(file)); } } result.LinkToFiles = linkToFiles.ToImmutableArray(); result.LinkToUids = (from n in doc.DocumentNode.Descendants() where string.Equals(n.Name, "xref", StringComparison.OrdinalIgnoreCase) from attr in n.Attributes where string.Equals(attr.Name, "href", StringComparison.OrdinalIgnoreCase) where !string.IsNullOrWhiteSpace(attr.Value) select attr.Value).ToImmutableHashSet(); using (var sw = new StringWriter()) { doc.Save(sw); result.Html = sw.ToString(); } return result; }