示例#1
0
        public void Init()
        {
            var fakeHeaders = new FakeHeaders();
            this.chainedHeader0 = fakeHeaders.GenesisChained();
            this.chainedHeader1 = fakeHeaders.NextChained();

            var fakeHeadersA = new FakeHeaders(fakeHeaders);
            this.chainedHeaderA2 = fakeHeadersA.NextChained();
            this.chainedHeaderA3 = fakeHeadersA.NextChained();
            this.chainedHeaderA4 = fakeHeadersA.NextChained();

            var fakeHeadersB = new FakeHeaders(fakeHeaders);
            this.chainedHeaderB2 = fakeHeadersB.NextChained();
            this.chainedHeaderB3 = fakeHeadersB.NextChained();
            this.chainedHeaderB4 = fakeHeadersB.NextChained();

            var fakeHeadersX = new FakeHeaders();
            this.chainedHeaderX0 = fakeHeadersX.GenesisChained();
            this.chainedHeaderX1 = fakeHeadersX.NextChained();

            this.chain = ImmutableDictionary.CreateRange(
                new[] { chainedHeader0, chainedHeader1, chainedHeaderA2, chainedHeaderA3, chainedHeaderA4, chainedHeaderB2, chainedHeaderB3, chainedHeaderB4, chainedHeaderX0, chainedHeaderX1 }
                .Select(x => new KeyValuePair<UInt256, ChainedHeader>(x.Hash, x)));

            this.getChainedHeader = blockHash => this.chain[blockHash];
        }
 protected internal DocumentationSettings()
 {
     this.companyName = DefaultCompanyName;
     this.copyrightText = DefaultCopyrightText;
     this.variables = ImmutableDictionary<string, string>.Empty;
     this.xmlHeader = true;
 }
示例#3
0
        internal override async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
            FixAllState fixAllState, CancellationToken cancellationToken)
        {
            if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any())
            {
                FixAllLogger.LogDiagnosticsStats(documentsAndDiagnosticsToFixMap);

                var fixesBag = new ConcurrentBag<(Diagnostic diagnostic, CodeAction action)>();

                using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Fixes, cancellationToken))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var documents = documentsAndDiagnosticsToFixMap.Keys;
                    var tasks = documents.Select(d => AddDocumentFixesAsync(
                        d, documentsAndDiagnosticsToFixMap[d], fixesBag, fixAllState, cancellationToken)).ToArray();
                    await Task.WhenAll(tasks).ConfigureAwait(false);
                }

                if (fixesBag.Count > 0)
                {
                    using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, cancellationToken))
                    {
                        FixAllLogger.LogFixesToMergeStats(fixesBag.Count);
                        return await TryGetMergedFixAsync(
                            fixesBag.ToImmutableArray(), fixAllState, cancellationToken).ConfigureAwait(false);
                    }
                }
            }

            return null;
        }
示例#4
0
        private Solution(
            BranchId branchId,
            int workspaceVersion,
            SolutionServices solutionServices,
            SolutionId id,
            string filePath,
            ImmutableList<ProjectId> projectIds,
            ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
            ImmutableDictionary<ProjectId, CompilationTracker> projectIdToTrackerMap,
            ProjectDependencyGraph dependencyGraph,
            VersionStamp version,
            Lazy<VersionStamp> lazyLatestProjectVersion)
        {
            this.branchId = branchId;
            this.workspaceVersion = workspaceVersion;
            this.id = id;
            this.filePath = filePath;
            this.solutionServices = solutionServices;
            this.projectIds = projectIds;
            this.projectIdToProjectStateMap = idToProjectStateMap;
            this.projectIdToTrackerMap = projectIdToTrackerMap;
            this.dependencyGraph = dependencyGraph;
            this.projectIdToProjectMap = ImmutableHashMap<ProjectId, Project>.Empty;
            this.version = version;
            this.lazyLatestProjectVersion = lazyLatestProjectVersion;

            CheckInvariants();
        }
示例#5
0
        /// <summary>
        /// Change the NuGet dependencies in the file to match the new packages.
        /// </summary>
        internal static bool ChangeDependencies(string filePath, ImmutableDictionary<NuGetPackage, NuGetPackage> changeMap)
        {
            var obj = JObject.Parse(File.ReadAllText(filePath), new JsonLoadSettings() { CommentHandling = CommentHandling.Load });
            var dependencies = (JObject)obj["dependencies"];
            if (dependencies == null)
            {
                return false;
            }

            var changed = false;
            foreach (var prop in dependencies.Properties())
            {
                var currentPackage = ParseDependency(prop);
                NuGetPackage newPackage;
                if (!changeMap.TryGetValue(currentPackage, out newPackage))
                {
                    continue;
                }

                ChangeDependency(prop, newPackage.Version);
                changed = true;
            }

            if (!changed)
            {
                return false;
            }

            var data = JsonConvert.SerializeObject(obj, Formatting.Indented);
            File.WriteAllText(filePath, data);
            return true;
        }
 protected AbstractOutliningService(
     ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxNodeOutliner>> defaultNodeOutlinerMap,
     ImmutableDictionary<int, ImmutableArray<AbstractSyntaxTriviaOutliner>> defaultTriviaOutlinerMap)
 {
     _nodeOutlinerMap = defaultNodeOutlinerMap;
     _triviaOutlinerMap = defaultTriviaOutlinerMap;
 }
            public void FilterModel(
                CompletionFilterReason filterReason,
                bool recheckCaretPosition = false,
                bool dismissIfEmptyAllowed = true,
                ImmutableDictionary<CompletionItemFilter, bool> filterState = null)
            {
                AssertIsForeground();

                var caretPosition = GetCaretPointInViewBuffer();

                // Use an interlocked increment so that reads by existing filter tasks will see the
                // change.
                Interlocked.Increment(ref _filterId);
                var localId = _filterId;
                Computation.ChainTaskAndNotifyControllerWhenFinished(
                    model =>
                    {
                        if (model != null && filterState != null)
                        {
                            // If the UI specified an updated filter state, then incorporate that 
                            // into our model.
                            model = model.WithFilterState(filterState);
                        }

                        return FilterModelInBackground(
                            model, localId, caretPosition, recheckCaretPosition, dismissIfEmptyAllowed, filterReason);
                    });
            }
示例#8
0
 public static CompletionItem Create(
     string displayText,
     TextSpan span,
     ISymbol symbol,
     int contextPosition = -1,
     int descriptionPosition = -1,
     string sortText = null,
     string insertionText = null,
     Glyph? glyph = null,
     string filterText = null,
     bool preselect = false,
     SupportedPlatformData supportedPlatforms = null,
     bool isArgumentName = false,
     ImmutableDictionary<string, string> properties = null,
     CompletionItemRules rules = null)
 {
     return Create(
         displayText: displayText,
         span: span,
         symbols: ImmutableArray.Create(symbol),
         contextPosition: contextPosition,
         descriptionPosition: descriptionPosition,
         sortText: sortText,
         insertionText: insertionText,
         glyph: glyph,
         filterText: filterText,
         preselect: preselect,
         supportedPlatforms: supportedPlatforms,
         isArgumentName: isArgumentName,
         properties: properties,
         rules: rules);
 }
            private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable<Location> additionalLocations,
                object[] messageArgs,
                ImmutableDictionary<string, string> properties,
                bool isSuppressed)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException(nameof(warningLevel));
                }

                if (descriptor == null)
                {
                    throw new ArgumentNullException(nameof(descriptor));
                }

                _descriptor = descriptor;
                _severity = severity;
                _warningLevel = warningLevel;
                _location = location ?? Location.None;
                _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList<Location>();
                _messageArgs = messageArgs ?? Array.Empty<object>();
                _properties = properties ?? ImmutableDictionary<string, string>.Empty;
                _isSuppressed = isSuppressed;
            }
        public virtual async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
            FixAllContext fixAllContext)
        {
            if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any())
            {
                fixAllContext.CancellationToken.ThrowIfCancellationRequested();

                var documents = documentsAndDiagnosticsToFixMap.Keys.ToImmutableArray();
                var fixesBag = new List<CodeAction>[documents.Length];
                var options = new ParallelOptions() { CancellationToken = fixAllContext.CancellationToken };
                Parallel.ForEach(documents, options, (document, state, index) =>
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                    fixesBag[index] = new List<CodeAction>();
                    this.AddDocumentFixesAsync(document, documentsAndDiagnosticsToFixMap[document], fixesBag[index].Add, fixAllContext).Wait(fixAllContext.CancellationToken);
                });

                if (fixesBag.Any(fixes => fixes.Count > 0))
                {
                    return await this.TryGetMergedFixAsync(fixesBag.SelectMany(i => i), fixAllContext).ConfigureAwait(false);
                }
            }

            return null;
        }
示例#11
0
        private SolutionState(
            BranchId branchId,
            int workspaceVersion,
            SolutionServices solutionServices,
            SolutionId id,
            string filePath,
            IEnumerable<ProjectId> projectIds,
            ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
            ImmutableDictionary<ProjectId, CompilationTracker> projectIdToTrackerMap,
            ImmutableDictionary<string, ImmutableArray<DocumentId>> linkedFilesMap,
            ProjectDependencyGraph dependencyGraph,
            VersionStamp version,
            Lazy<VersionStamp> lazyLatestProjectVersion)
        {
            _branchId = branchId;
            _workspaceVersion = workspaceVersion;
            _id = id;
            _filePath = filePath;
            _solutionServices = solutionServices;
            _projectIds = projectIds.ToImmutableReadOnlyListOrEmpty();
            _projectIdToProjectStateMap = idToProjectStateMap;
            _projectIdToTrackerMap = projectIdToTrackerMap;
            _linkedFilesMap = linkedFilesMap;
            _dependencyGraph = dependencyGraph;
            _version = version;
            _lazyLatestProjectVersion = lazyLatestProjectVersion;

            CheckInvariants();
        }
 public ParseResult(string input, string output, int? position, ImmutableDictionary<string, ImmutableArray<TextSpan>> spanMap)
 {
     this.input = input;
     this.output = output;
     this.position = position;
     this.spanMap = spanMap;
 }
示例#13
0
 private MSBuildWorkspace(
     HostServices hostServices,
     ImmutableDictionary<string, string> properties)
     : base(hostServices, "MSBuildWorkspace")
 {
     _loader = new MSBuildProjectLoader(this, properties);
 }
        internal ProjectState(ProjectInfo projectInfo, HostLanguageServices languageServices, SolutionServices solutionServices)
        {
            Contract.ThrowIfNull(projectInfo);
            Contract.ThrowIfNull(languageServices);
            Contract.ThrowIfNull(solutionServices);

            _languageServices = languageServices;
            _solutionServices = solutionServices;

            _projectInfo = FixProjectInfo(projectInfo);

            _documentIds = _projectInfo.Documents.Select(d => d.Id).ToImmutableArray();
            _additionalDocumentIds = this.ProjectInfo.AdditionalDocuments.Select(d => d.Id).ToImmutableArray();

            var docStates = ImmutableDictionary.CreateRange<DocumentId, DocumentState>(
                _projectInfo.Documents.Select(d =>
                    new KeyValuePair<DocumentId, DocumentState>(d.Id,
                        CreateDocument(this.ProjectInfo, d, languageServices, solutionServices))));

            _documentStates = docStates;

            var additionalDocStates = ImmutableDictionary.CreateRange<DocumentId, TextDocumentState>(
                    _projectInfo.AdditionalDocuments.Select(d =>
                        new KeyValuePair<DocumentId, TextDocumentState>(d.Id, TextDocumentState.Create(d, solutionServices))));

            _additionalDocumentStates = additionalDocStates;

            _lazyLatestDocumentVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentVersionAsync(docStates, additionalDocStates, c), cacheResult: true);
            _lazyLatestDocumentTopLevelChangeVersion = new AsyncLazy<VersionStamp>(c => ComputeLatestDocumentTopLevelChangeVersionAsync(docStates, additionalDocStates, c), cacheResult: true);
        }
        internal sealed override async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap, 
            FixAllState fixAllState, 
            CancellationToken cancellationToken)
        {
            // Process all documents in parallel.
            var updatedDocumentTasks = documentsAndDiagnosticsToFixMap.Select(
                kvp => FixDocumentAsync(kvp.Key, kvp.Value, cancellationToken));

            await Task.WhenAll(updatedDocumentTasks).ConfigureAwait(false);

            var currentSolution = fixAllState.Solution;
            foreach (var task in updatedDocumentTasks)
            {
                // 'await' the tasks so that if any completed in a cancelled manner then we'll
                // throw the right exception here.  Calling .Result on the tasks might end up
                // with AggregateExceptions being thrown instead.
                var updatedDocument = await task.ConfigureAwait(false);
                currentSolution = currentSolution.WithDocumentSyntaxRoot(
                    updatedDocument.Id,
                    await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false));
            }

            var title = fixAllState.GetDefaultFixAllTitle();
            return new CodeAction.SolutionChangeAction(title, _ => Task.FromResult(currentSolution));
        }
        public override async Task SynchronizeWithBuildAsync(Workspace workspace, ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>> map)
        {
            if (!PreferBuildErrors(workspace))
            {
                // prefer live errors over build errors
                return;
            }

            var solution = workspace.CurrentSolution;
            foreach (var projectEntry in map)
            {
                var project = solution.GetProject(projectEntry.Key);
                if (project == null)
                {
                    continue;
                }

                var stateSets = _stateManager.CreateBuildOnlyProjectStateSet(project);
                var lookup = projectEntry.Value.ToLookup(d => d.DocumentId);

                // do project one first
                await SynchronizeWithBuildAsync(project, stateSets, lookup[null]).ConfigureAwait(false);

                foreach (var document in project.Documents)
                {
                    await SynchronizeWithBuildAsync(document, stateSets, lookup[document.Id]).ConfigureAwait(false);
                }
            }
        }
示例#17
0
        public virtual async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
            FixAllContext fixAllContext)
        {
            if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any())
            {
                FixAllLogger.LogDiagnosticsStats(documentsAndDiagnosticsToFixMap);

                var fixesBag = new ConcurrentBag<CodeAction>();

                using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Fixes, fixAllContext.CancellationToken))
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();

                    var documents = documentsAndDiagnosticsToFixMap.Keys.ToImmutableArray();
                    var options = new ParallelOptions() { CancellationToken = fixAllContext.CancellationToken };
                    Parallel.ForEach(documents, options, document =>
                    {
                        fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                        AddDocumentFixesAsync(document, documentsAndDiagnosticsToFixMap[document], fixesBag.Add, fixAllContext).Wait(fixAllContext.CancellationToken);
                    });
                }

                if (fixesBag.Any())
                {
                    using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, fixAllContext.CancellationToken))
                    {
                        FixAllLogger.LogFixesToMergeStats(fixesBag);
                        return await TryGetMergedFixAsync(fixesBag, fixAllContext).ConfigureAwait(false);
                    }
                }
            }

            return null;
        }
示例#18
0
        internal PlaceholderLocalBinder(
            CSharpSyntaxNode syntax,
            ImmutableArray<Alias> aliases,
            MethodSymbol containingMethod,
            EETypeNameDecoder typeNameDecoder,
            Binder next) :
            base(next)
        {
            _syntax = syntax;
            _containingMethod = containingMethod;

            var compilation = next.Compilation;
            var sourceAssembly = compilation.SourceAssembly;

            var aliasesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(aliases.Length);
            var lowercaseBuilder = ImmutableDictionary.CreateBuilder<string, LocalSymbol>();
            foreach (Alias alias in aliases)
            {
                var local = PlaceholderLocalSymbol.Create(
                    typeNameDecoder,
                    containingMethod,
                    sourceAssembly,
                    alias);
                aliasesBuilder.Add(local);

                if (alias.Kind == DkmClrAliasKind.ReturnValue)
                {
                    lowercaseBuilder.Add(local.Name.ToLower(), local);
                }
            }
            _lowercaseReturnValueAliases = lowercaseBuilder.ToImmutableDictionary();
            _aliases = aliasesBuilder.ToImmutableAndFree();
        }
 public void Setup()
 {
     _dictionary = Enumerable.Range(1, Size).ToDictionary(_ => "test " + _, _ => _);
     _readonlyDictionary = new ReadonlyDictionary<string, int>(_dictionary);
     _concurrentDictionary = new ConcurrentDictionary<string, int>(_dictionary);
     _immutableDictionary = _dictionary.ToImmutableDictionary();
 }
示例#20
0
 internal ProjectDependencyGraph(
     ImmutableArray<ProjectId> projectIds,
     ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> referencesMap)
 {
     _projectIds = projectIds;
     _referencesMap = referencesMap;
 }
 protected AbstractBlockStructureProvider(
     ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> defaultNodeOutlinerMap,
     ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> defaultTriviaOutlinerMap)
 {
     _nodeProviderMap = defaultNodeOutlinerMap;
     _triviaProviderMap = defaultTriviaOutlinerMap;
 }
示例#22
0
 internal ProjectDependencyGraph(
     ImmutableList<ProjectId> projectIds,
     ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> referencesMap)
 {
     this.projectIds = projectIds;
     this.referencesMap = referencesMap;
 }
示例#23
0
 public TestNetwork() {
   _message = String.Empty;
   _address = String.Empty;
   _fingerprint = String.Empty;
   _addresses = ImmutableDictionary<string, string>.Empty;
   _fingerprints = ImmutableDictionary<string, string>.Empty;
 }
        public virtual async Task<CodeAction> GetFixAsync(
            ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
            FixAllContext fixAllContext)
        {
            if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any())
            {
                FixAllLogger.LogDiagnosticsStats(documentsAndDiagnosticsToFixMap);

                var fixesBag = new ConcurrentBag<CodeAction>();

                using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Fixes, fixAllContext.CancellationToken))
                {
                    fixAllContext.CancellationToken.ThrowIfCancellationRequested();

                    var documents = documentsAndDiagnosticsToFixMap.Keys;
                    var tasks = documents.Select(d => AddDocumentFixesAsync(d, documentsAndDiagnosticsToFixMap[d], fixesBag.Add, fixAllContext))
                                         .ToArray();
                    await Task.WhenAll(tasks).ConfigureAwait(false);
                }

                if (fixesBag.Any())
                {
                    using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, fixAllContext.CancellationToken))
                    {
                        FixAllLogger.LogFixesToMergeStats(fixesBag);
                        return await TryGetMergedFixAsync(fixesBag, fixAllContext).ConfigureAwait(false);
                    }
                }
            }

            return null;
        }
 public ImmutableSentenceDomainModel(ISentenceFormModel formModel, IDictionary<ISentenceForm, ISentenceFormDomain> domains)
     : base(ImmutableSentenceFormModel.CopyOf(formModel))
 {
     //if (!formModel.SentenceForms.SetEquals(domains.Keys))
     //    throw new Exception();
     _domains = domains.ToImmutableDictionary();
 }
示例#26
0
        private SolutionState(
            BranchId branchId,
            int workspaceVersion,
            SolutionServices solutionServices,
            SolutionInfo solutionInfo,
            IEnumerable<ProjectId> projectIds,
            ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
            ImmutableDictionary<ProjectId, CompilationTracker> projectIdToTrackerMap,
            ImmutableDictionary<string, ImmutableArray<DocumentId>> linkedFilesMap,
            ProjectDependencyGraph dependencyGraph,
            Lazy<VersionStamp> lazyLatestProjectVersion)
        {
            _branchId = branchId;
            _workspaceVersion = workspaceVersion;
            _solutionServices = solutionServices;
            _solutionInfo = solutionInfo;
            _projectIds = projectIds.ToImmutableReadOnlyListOrEmpty();
            _projectIdToProjectStateMap = idToProjectStateMap;
            _projectIdToTrackerMap = projectIdToTrackerMap;
            _linkedFilesMap = linkedFilesMap;
            _dependencyGraph = dependencyGraph;
            _lazyLatestProjectVersion = lazyLatestProjectVersion;

            // when solution state is changed, we re-calcuate its checksum
            _lazyChecksums = new AsyncLazy<SolutionStateChecksums>(ComputeChecksumsAsync, cacheResult: true);

            CheckInvariants();
        }
示例#27
0
        internal MemoryStorageManager(ChainedHeader chainTip = null, int? unspentTxCount = null, int? unspentOutputCount = null, int? totalTxCount = null, int? totalInputCount = null, int? totalOutputCount = null, ImmutableSortedDictionary<UInt256, ChainedHeader> headers = null, ImmutableSortedDictionary<UInt256, UnspentTx> unspentTransactions = null, ImmutableDictionary<int, BlockSpentTxes> spentTransactions = null)
        {
            blockStorage = new MemoryBlockStorage();
            blockTxesStorage = new MemoryBlockTxesStorage();
            chainStateStorage = new MemoryChainStateStorage(chainTip, unspentTxCount, unspentOutputCount, totalTxCount, totalInputCount, totalOutputCount, headers, unspentTransactions, spentTransactions);
            unconfirmedTxesStorage = new MemoryUnconfirmedTxesStorage();

            chainStateCursorCache = new DisposableCache<IChainStateCursor>(1024,
                createFunc: () => new MemoryChainStateCursor(chainStateStorage),
                prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                        cursor.RollbackTransaction();
                });

            unconfirmedTxesCursorCache = new DisposableCache<IUnconfirmedTxesCursor>(1024,
                createFunc: () => new MemoryUnconfirmedTxesCursor(unconfirmedTxesStorage),
                prepareAction: cursor =>
                {
                    // rollback any open transaction before returning the cursor to the cache
                    if (cursor.InTransaction)
                        cursor.RollbackTransaction();
                });
        }
        public override FileModel Load(FileAndType file, ImmutableDictionary<string, object> metadata)
        {
            if (file.Type != DocumentType.Article)
            {
                throw new NotSupportedException();
            }
            var content = MarkdownReader.ReadMarkdownAsConceptual(file.BaseDir, file.File);
            foreach (var item in metadata)
            {
                if (!content.ContainsKey(item.Key))
                {
                    content[item.Key] = item.Value;
                }
            }

            var displayLocalPath = PathUtility.MakeRelativePath(EnvironmentContext.BaseDirectory, file.FullPath);

            return new FileModel(
                file,
                content,
                serializer: Environment.Is64BitProcess ? null : new BinaryFormatter())
            {
                LocalPathFromRepoRoot = (content["source"] as SourceDetail)?.Remote?.RelativePath,
                LocalPathFromRoot = displayLocalPath
            };
        }
示例#29
0
 public CompilerAnalysisResult(
     ImmutableDictionary<DiagnosticAnalyzer, AnalysisResult> analysisResult,
     ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> telemetryInfo)
 {
     AnalysisResult = analysisResult;
     TelemetryInfo = telemetryInfo;
 }
示例#30
0
 /// <summary>
 /// Create a RuleSet.
 /// </summary>
 public RuleSet(string filePath, ReportDiagnostic generalOption, ImmutableDictionary<string, ReportDiagnostic> specificOptions, ImmutableArray<RuleSetInclude> includes)
 {
     _filePath = filePath;
     _generalDiagnosticOption = generalOption;
     _specificDiagnosticOptions = specificOptions == null ? ImmutableDictionary<string, ReportDiagnostic>.Empty : specificOptions;
     _includes = includes.IsDefault ? ImmutableArray<RuleSetInclude>.Empty : includes;
 }
示例#31
0
 public Task <(string id, object state)> NewResourceAsync(string type, string name, ImmutableDictionary <string, object> inputs, string?provider, string?id)
 {
     Assert.Equal("aws:ec2/instance:Instance", type);
     return(Task.FromResult <(string, object)>(("i-1234567890abcdef0", new Dictionary <string, object> {
         { "publicIp", "203.0.113.12" },
     })));
 }
示例#32
0
 internal DataFlowAnalysisResult(
     ImmutableDictionary <BasicBlock, TBlockAnalysisResult> basicBlockStateMap,
     ImmutableDictionary <IOperation, TAbstractAnalysisValue> operationStateMap,
     ImmutableDictionary <IOperation, PredicateValueKind> predicateValueKindMap,
     (TAbstractAnalysisValue, PredicateValueKind)?returnValueAndPredicateKindOpt,
示例#33
0
        public async Task <long> GetInstallationId(string repositoryUrl)
        {
            string[] segments = new Uri(repositoryUrl, UriKind.Absolute).Segments;
            string   org      = segments[segments.Length - 2].TrimEnd('/').ToLowerInvariant();

            if (HasCachedValue(org, out long installation))
            {
                return(installation);
            }

            await _sem.WaitAsync();

            try
            {
                if (HasCachedValue(org, out installation))
                {
                    return(installation);
                }

                _log.LogInformation("No cached installation token found for {org}", org);

                ImmutableDictionary <string, long> .Builder newCache = ImmutableDictionary.CreateBuilder <string, long>();
                string appToken = _tokens.GetAppToken();
                var    client   = new GitHubAppsClient(
                    new ApiConnection(
                        new Connection(_options.Value.ProductHeader)
                {
                    Credentials = new Credentials(appToken, AuthenticationType.Bearer)
                }
                        )
                    );

                foreach (Installation i in await client.GetAllInstallationsForCurrent())
                {
                    string installedOrg = i.Account.Login.ToLowerInvariant();
                    _log.LogInformation("Found installation token for {org}, with id {id}", installedOrg, i.Id);
                    newCache.Add(installedOrg, i.Id);
                }

                foreach (string key in _cache.Keys)
                {
                    // Anything we had before but don't have now has been uninstalled, remove it
                    if (newCache.TryAdd(key, 0))
                    {
                        _log.LogInformation("Removed uninstalled org {org}", key);
                    }
                }

                // If the current thing wasn't in this list, it's not installed, record that so when they ask again in
                // a few seconds, we don't have to re-query GitHub
                if (newCache.TryAdd(org, 0))
                {
                    _log.LogInformation("Removed uninstalled, but requested org {org}", org);
                }

                Interlocked.Exchange(ref _cache, newCache.ToImmutable());
                _lastCached = DateTimeOffset.UtcNow;

                return(_cache[org]);
            }
            finally
            {
                _sem.Release();
            }
        }
示例#34
0
 // Хотел этот метод вынести в расширения, но была ошибка связанная с generic
 private static ImmutableDictionary <TKey, TValue> AddOrSet <TKey, TValue>(
     ImmutableDictionary <TKey, TValue> dictionary,
     TKey key, TValue value)
 {
     return(dictionary.ContainsKey(key) ? dictionary.SetItem(key, value) : dictionary.Add(key, value));
 }
示例#35
0
        public static int ParseChineseDynastyYear(string yearStr, Regex dynastyYearRegex, string dynastyStartYear, ImmutableDictionary <string, int> dynastyYearMap, IExtractor integerExtractor, IParser numberParser)
        {
            int year             = -1;
            var regionTitleMatch = dynastyYearRegex.MatchExact(yearStr, trim: true);

            if (regionTitleMatch.Success)
            {
                // handle "康熙元年" refer to https://zh.wikipedia.org/wiki/%E5%B9%B4%E5%8F%B7
                string dynastyYearStr = regionTitleMatch.Groups["dynasty"].Value;
                string biasYearStr    = regionTitleMatch.Groups["biasYear"].Value;
                int    basicYear      = dynastyYearMap[dynastyYearStr];
                int    biasYear       = 1;
                if (biasYearStr != dynastyStartYear)
                {
                    biasYear = Convert.ToInt32((double)(numberParser.Parse(integerExtractor.Extract(biasYearStr)[0]).Value ?? 0));
                }

                year = basicYear + biasYear - 1;
            }

            return(year);
        }
示例#36
0
 internal PersistentVolume(string name, ImmutableDictionary <string, object?> dictionary, CustomResourceOptions?options = null)
     : base("kubernetes:core/v1:PersistentVolume", name, dictionary, options)
 {
 }
示例#37
0
 public MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary <string, string> map)
 {
     _map = map;
 }
示例#38
0
 internal CustomResourceDefinitionList(string name, ImmutableDictionary <string, object?> dictionary, CustomResourceOptions?options = null)
     : base("kubernetes:apiextensions.k8s.io/v1:CustomResourceDefinitionList", name, dictionary, options)
 {
 }
示例#39
0
 /// <summary>
 /// Creates a new options instance with the specified diagnostic-specific options.
 /// </summary>
 public CompilationOptions WithSpecificDiagnosticOptions(ImmutableDictionary <string, ReportDiagnostic> value)
 {
     return(CommonWithSpecificDiagnosticOptions(value));
 }
示例#40
0
 public Task <object> CallAsync(string token, ImmutableDictionary <string, object> args, string?provider)
 {
     return(Task.FromResult <object>(args));
 }
示例#41
0
        private GetServerResult(
            string?administratorLogin,

            string?administratorLoginPassword,

            string?availabilityZone,

            string byokEnforcement,

            string?createMode,

            Outputs.ServerPropertiesResponseDelegatedSubnetArguments?delegatedSubnetArguments,

            string?displayName,

            string fullyQualifiedDomainName,

            string?haEnabled,

            string haState,

            string id,

            Outputs.IdentityResponse?identity,

            string location,

            Outputs.MaintenanceWindowResponse?maintenanceWindow,

            string name,

            string?pointInTimeUTC,

            string publicNetworkAccess,

            Outputs.SkuResponse?sku,

            string?sourceServerName,

            string standbyAvailabilityZone,

            string state,

            Outputs.StorageProfileResponse?storageProfile,

            ImmutableDictionary <string, string>?tags,

            string type,

            string?version)
        {
            AdministratorLogin         = administratorLogin;
            AdministratorLoginPassword = administratorLoginPassword;
            AvailabilityZone           = availabilityZone;
            ByokEnforcement            = byokEnforcement;
            CreateMode = createMode;
            DelegatedSubnetArguments = delegatedSubnetArguments;
            DisplayName = displayName;
            FullyQualifiedDomainName = fullyQualifiedDomainName;
            HaEnabled               = haEnabled;
            HaState                 = haState;
            Id                      = id;
            Identity                = identity;
            Location                = location;
            MaintenanceWindow       = maintenanceWindow;
            Name                    = name;
            PointInTimeUTC          = pointInTimeUTC;
            PublicNetworkAccess     = publicNetworkAccess;
            Sku                     = sku;
            SourceServerName        = sourceServerName;
            StandbyAvailabilityZone = standbyAvailabilityZone;
            State                   = state;
            StorageProfile          = storageProfile;
            Tags                    = tags;
            Type                    = type;
            Version                 = version;
        }
示例#42
0
 protected abstract CompilationOptions CommonWithSpecificDiagnosticOptions(ImmutableDictionary <string, ReportDiagnostic> specificDiagnosticOptions);
示例#43
0
 internal ClusterRole(string name, ImmutableDictionary <string, object?> dictionary, CustomResourceOptions?options = null)
     : base("kubernetes:rbac.authorization.k8s.io/v1beta1:ClusterRole", name, dictionary, options)
 {
 }
示例#44
0
        // Expects correct arguments.
        internal CompilationOptions(
            OutputKind outputKind,
            bool reportSuppressedDiagnostics,
            string moduleName,
            string mainTypeName,
            string scriptClassName,
            string cryptoKeyContainer,
            string cryptoKeyFile,
            ImmutableArray <byte> cryptoPublicKey,
            bool?delaySign,
            bool publicSign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary <string, ReportDiagnostic> specificDiagnosticOptions,
            bool concurrentBuild,
            bool deterministic,
            DateTime currentLocalTime,
            bool debugPlusMode,
            XmlReferenceResolver xmlReferenceResolver,
            SourceReferenceResolver sourceReferenceResolver,
            MetadataReferenceResolver metadataReferenceResolver,
            AssemblyIdentityComparer assemblyIdentityComparer,
            StrongNameProvider strongNameProvider,
            MetadataImportOptions metadataImportOptions,
            bool referencesSupersedeLowerVersions)
        {
            this.OutputKind                       = outputKind;
            this.ModuleName                       = moduleName;
            this.MainTypeName                     = mainTypeName;
            this.ScriptClassName                  = scriptClassName ?? WellKnownMemberNames.DefaultScriptClassName;
            this.CryptoKeyContainer               = cryptoKeyContainer;
            this.CryptoKeyFile                    = string.IsNullOrEmpty(cryptoKeyFile) ? null : cryptoKeyFile;
            this.CryptoPublicKey                  = cryptoPublicKey.NullToEmpty();
            this.DelaySign                        = delaySign;
            this.CheckOverflow                    = checkOverflow;
            this.Platform                         = platform;
            this.GeneralDiagnosticOption          = generalDiagnosticOption;
            this.WarningLevel                     = warningLevel;
            this.SpecificDiagnosticOptions        = specificDiagnosticOptions;
            this.ReportSuppressedDiagnostics      = reportSuppressedDiagnostics;
            this.OptimizationLevel                = optimizationLevel;
            this.ConcurrentBuild                  = concurrentBuild;
            this.Deterministic                    = deterministic;
            this.CurrentLocalTime                 = currentLocalTime;
            this.DebugPlusMode                    = debugPlusMode;
            this.XmlReferenceResolver             = xmlReferenceResolver;
            this.SourceReferenceResolver          = sourceReferenceResolver;
            this.MetadataReferenceResolver        = metadataReferenceResolver;
            this.StrongNameProvider               = strongNameProvider;
            this.AssemblyIdentityComparer         = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions            = metadataImportOptions;
            this.ReferencesSupersedeLowerVersions = referencesSupersedeLowerVersions;
            this.PublicSign                       = publicSign;

            _lazyErrors = new Lazy <ImmutableArray <Diagnostic> >(() =>
            {
                var builder = ArrayBuilder <Diagnostic> .GetInstance();
                ValidateOptions(builder);
                return(builder.ToImmutableAndFree());
            });
        }
示例#45
0
        public async Task SynchronizeWithBuildAsync(
            ImmutableDictionary <ProjectId,
                                 ImmutableArray <DiagnosticData> > buildDiagnostics,
            TaskQueue postBuildAndErrorListRefreshTaskQueue,
            bool onBuildCompleted,
            CancellationToken cancellationToken)
        {
            var options = Workspace.Options;

            using (Logger.LogBlock(FunctionId.DiagnosticIncrementalAnalyzer_SynchronizeWithBuildAsync, LogSynchronizeWithBuild, options, buildDiagnostics, cancellationToken))
            {
                DebugVerifyDiagnosticLocations(buildDiagnostics);

                if (!PreferBuildErrors(options))
                {
                    // Prefer live errors over build errors
                    return;
                }

                var solution = Workspace.CurrentSolution;

                foreach (var(projectId, diagnostics) in buildDiagnostics)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var project = solution.GetProject(projectId);
                    if (project == null)
                    {
                        continue;
                    }

                    var stateSets = _stateManager.CreateBuildOnlyProjectStateSet(project);
                    var newResult = CreateAnalysisResults(project, stateSets, diagnostics);

                    // PERF: Save the diagnostics into in-memory cache on the main thread.
                    //       Saving them into persistent storage is expensive, so we invoke that operation on a separate task queue
                    //       to ensure faster error list refresh.
                    foreach (var stateSet in stateSets)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        var state  = stateSet.GetOrCreateProjectState(project.Id);
                        var result = GetResultOrEmpty(newResult, stateSet.Analyzer, project.Id, VersionStamp.Default);

                        // Save into in-memory cache.
                        await state.SaveInMemoryCacheAsync(project, result).ConfigureAwait(false);

                        // Save into persistent storage on a separate post-build and post error list refresh task queue.
                        _ = postBuildAndErrorListRefreshTaskQueue.ScheduleTask(
                            nameof(SynchronizeWithBuildAsync),
                            () => state.SaveAsync(PersistentStorageService, project, result),
                            cancellationToken);
                    }

                    // Raise diagnostic updated events after the new diagnostics have been stored into the in-memory cache.
                    if (diagnostics.IsEmpty)
                    {
                        ClearAllDiagnostics(stateSets, projectId);
                    }
                    else
                    {
                        RaiseProjectDiagnosticsIfNeeded(project, stateSets, newResult);
                    }
                }

                // Refresh live diagnostics after solution build completes.
                if (onBuildCompleted && PreferLiveErrorsOnOpenedFiles(options))
                {
                    // Enqueue re-analysis of active document with high-priority right away.
                    if (_documentTrackingService.GetActiveDocument(solution) is { } activeDocument)
                    {
                        AnalyzerService.Reanalyze(Workspace, documentIds: ImmutableArray.Create(activeDocument.Id), highPriority: true);
                    }

                    // Enqueue remaining re-analysis with normal priority on a separate task queue
                    // that will execute at the end of all the post build and error list refresh tasks.
                    _ = postBuildAndErrorListRefreshTaskQueue.ScheduleTask(nameof(SynchronizeWithBuildAsync), () =>
                    {
                        // Enqueue re-analysis of open documents.
                        AnalyzerService.Reanalyze(Workspace, documentIds: Workspace.GetOpenDocumentIds());

                        // Enqueue re-analysis of projects, if required.
                        foreach (var projectsByLanguage in solution.Projects.GroupBy(p => p.Language))
                        {
                            if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(Workspace.Options, projectsByLanguage.Key) == BackgroundAnalysisScope.FullSolution)
                            {
                                AnalyzerService.Reanalyze(Workspace, projectsByLanguage.Select(p => p.Id));
                            }
                        }
                    }, cancellationToken);
                }
            }
        }
示例#46
0
 public static string Elect(ImmutableDictionary <string, ClusterTopologyNotification> memberState) => memberState
 .Values
 .Where(m => memberState.ContainsKey(m.LeaderId))
 .GroupBy(m => m.LeaderId)
 .Select(g => (Id: g.Key, Score: g.Count()))
        public override ImmutableDictionary <string, ITypeSpecBuilder> Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification, ImmutableDictionary <string, ITypeSpecBuilder> metamodel)
        {
            if (BooleanValueSemanticsProvider.IsAdaptedType(type))
            {
                var result = reflector.LoadSpecification(BooleanValueSemanticsProvider.AdaptedType, metamodel);

                metamodel = result.Item2;
                var spec = result.Item1 as IObjectSpecImmutable;
                AddValueFacets(new BooleanValueSemanticsProvider(spec, specification), specification);
            }
            return(metamodel);
        }
示例#48
0
 internal PriorityClass(string name, ImmutableDictionary <string, object?> dictionary, CustomResourceOptions?options = null)
     : base("kubernetes:scheduling.k8s.io/v1alpha1:PriorityClass", name, dictionary, options)
 {
 }
        private GetEndpointResult(
            ImmutableArray <string> contentTypesToCompress,

            Outputs.ResourceReferenceResponse?defaultOriginGroup,

            Outputs.EndpointPropertiesUpdateParametersResponseDeliveryPolicy?deliveryPolicy,

            ImmutableArray <Outputs.GeoFilterResponse> geoFilters,

            string hostName,

            bool?isCompressionEnabled,

            bool?isHttpAllowed,

            bool?isHttpsAllowed,

            string location,

            string name,

            string?optimizationType,

            ImmutableArray <Outputs.DeepCreatedOriginGroupResponse> originGroups,

            string?originHostHeader,

            string?originPath,

            ImmutableArray <Outputs.DeepCreatedOriginResponse> origins,

            string?probePath,

            string provisioningState,

            string?queryStringCachingBehavior,

            string resourceState,

            ImmutableDictionary <string, string>?tags,

            string type,

            ImmutableArray <Outputs.UrlSigningKeyResponse> urlSigningKeys,

            Outputs.EndpointPropertiesUpdateParametersResponseWebApplicationFirewallPolicyLink?webApplicationFirewallPolicyLink)
        {
            ContentTypesToCompress = contentTypesToCompress;
            DefaultOriginGroup     = defaultOriginGroup;
            DeliveryPolicy         = deliveryPolicy;
            GeoFilters             = geoFilters;
            HostName             = hostName;
            IsCompressionEnabled = isCompressionEnabled;
            IsHttpAllowed        = isHttpAllowed;
            IsHttpsAllowed       = isHttpsAllowed;
            Location             = location;
            Name                             = name;
            OptimizationType                 = optimizationType;
            OriginGroups                     = originGroups;
            OriginHostHeader                 = originHostHeader;
            OriginPath                       = originPath;
            Origins                          = origins;
            ProbePath                        = probePath;
            ProvisioningState                = provisioningState;
            QueryStringCachingBehavior       = queryStringCachingBehavior;
            ResourceState                    = resourceState;
            Tags                             = tags;
            Type                             = type;
            UrlSigningKeys                   = urlSigningKeys;
            WebApplicationFirewallPolicyLink = webApplicationFirewallPolicyLink;
        }
        // Given the ordered list of all pragma warning directives in the syntax tree, return a list of mapping entries,
        // containing the cumulative set of warnings that are disabled for that point in the source.
        // This mapping also contains a global warning option, accumulated of all #pragma up to the current line position.
        private static WarningStateMapEntry[] CreatePragmaWarningStateEntries(ImmutableArray <PragmaWarningDirectiveTriviaSyntax> directiveList)
        {
            var entries = new WarningStateMapEntry[directiveList.Length + 1];
            var current = new WarningStateMapEntry(0, ReportDiagnostic.Default, null);
            var index   = 0;

            entries[index] = current;

            // Captures the general reporting option, accumulated of all #pragma up to the current directive.
            var accumulatedGeneralWarningState = ReportDiagnostic.Default;

            // Captures the mapping of a warning number to the reporting option, accumulated of all #pragma up to the current directive.
            var accumulatedSpecificWarningState = ImmutableDictionary.Create <string, ReportDiagnostic>();

            while (index < directiveList.Length)
            {
                var currentDirective = directiveList[index];

                // Compute the directive state (either Disable or Restore)
                var directiveState = currentDirective.DisableOrRestoreKeyword.Kind() == SyntaxKind.DisableKeyword ? ReportDiagnostic.Suppress : ReportDiagnostic.Default;

                // Check if this directive applies for all (e.g., #pragma warning disable)
                if (currentDirective.ErrorCodes.Count == 0)
                {
                    // Update the warning state and reset the specific one
                    accumulatedGeneralWarningState  = directiveState;
                    accumulatedSpecificWarningState = ImmutableDictionary.Create <string, ReportDiagnostic>();
                }
                else
                {
                    // Compute warning numbers from the current directive's codes
                    for (int x = 0; x < currentDirective.ErrorCodes.Count; x++)
                    {
                        var currentErrorCode = currentDirective.ErrorCodes[x];
                        if (currentErrorCode.IsMissing || currentErrorCode.ContainsDiagnostics)
                        {
                            continue;
                        }

                        var errorId = string.Empty;
                        if (currentErrorCode.Kind() == SyntaxKind.NumericLiteralExpression)
                        {
                            var token = ((LiteralExpressionSyntax)currentErrorCode).Token;
                            errorId = MessageProvider.Instance.GetIdForErrorCode((int)token.Value);
                        }
                        else if (currentErrorCode.Kind() == SyntaxKind.IdentifierName)
                        {
                            errorId = ((IdentifierNameSyntax)currentErrorCode).Identifier.ValueText;
                        }

                        if (!string.IsNullOrWhiteSpace(errorId))
                        {
                            // Update the state of this error code with the current directive state
                            accumulatedSpecificWarningState = accumulatedSpecificWarningState.SetItem(errorId, directiveState);
                        }
                    }
                }

                current = new WarningStateMapEntry(currentDirective.Location.SourceSpan.End, accumulatedGeneralWarningState, accumulatedSpecificWarningState);
                ++index;
                entries[index] = current;
            }

#if DEBUG
            // Make sure the entries array is correctly sorted.
            for (int i = 1; i < entries.Length - 1; ++i)
            {
                Debug.Assert(entries[i].CompareTo(entries[i + 1]) < 0);
            }
#endif

            return(entries);
        }
 internal CustomResourceDefinition(string name, ImmutableDictionary<string, object?> dictionary, CustomResourceOptions? options = null)
     : base("kubernetes:apiextensions.k8s.io/v1:CustomResourceDefinition", name, new DictionaryResourceArgs(dictionary), MakeResourceOptions(options, ""))
 {
 }
示例#52
0
 /// <summary>
 /// Returns a new tree whose <see cref="DiagnosticOptions" /> are the specifed value and other properties are copied
 /// from the current tree.
 /// </summary>
 /// <param name="options">
 /// A mapping from diagnostic id to diagnostic reporting level. The diagnostic ID may be case-sensitive depending
 /// on the language.
 /// </param>
 public virtual SyntaxTree WithDiagnosticOptions(ImmutableDictionary <string, ReportDiagnostic> options)
 {
     throw new NotImplementedException();
 }
 private static ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> FilterAnalyzers(ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Options options)
 {
     return analyzers.ToImmutableDictionary(
         pair => pair.Key,
         pair => FilterAnalyzers(pair.Value, options).ToImmutableArray());
 }
        private GetWebTestResult(
            Outputs.WebTestPropertiesResponseConfiguration?configuration,

            Outputs.WebTestPropertiesResponseContentValidation?contentValidation,

            string?description,

            bool?enabled,

            int?expectedHttpStatusCode,

            int?frequency,

            bool?ignoreHttpsStatusCode,

            string?kind,

            string location,

            ImmutableArray <Outputs.WebTestGeolocationResponse> locations,

            string name,

            string provisioningState,

            Outputs.WebTestPropertiesResponseRequest?request,

            bool?retryEnabled,

            int?sSLCertRemainingLifetimeCheck,

            bool?sSLCheck,

            string syntheticMonitorId,

            ImmutableDictionary <string, string>?tags,

            int?timeout,

            string type,

            string webTestKind,

            string webTestName)
        {
            Configuration          = configuration;
            ContentValidation      = contentValidation;
            Description            = description;
            Enabled                = enabled;
            ExpectedHttpStatusCode = expectedHttpStatusCode;
            Frequency              = frequency;
            IgnoreHttpsStatusCode  = ignoreHttpsStatusCode;
            Kind                          = kind;
            Location                      = location;
            Locations                     = locations;
            Name                          = name;
            ProvisioningState             = provisioningState;
            Request                       = request;
            RetryEnabled                  = retryEnabled;
            SSLCertRemainingLifetimeCheck = sSLCertRemainingLifetimeCheck;
            SSLCheck                      = sSLCheck;
            SyntheticMonitorId            = syntheticMonitorId;
            Tags                          = tags;
            Timeout                       = timeout;
            Type                          = type;
            WebTestKind                   = webTestKind;
            WebTestName                   = webTestName;
        }
示例#55
0
        private Dictionary <string, object> ParseScope(Scope scope,
                                                       ImmutableDictionary <Scope, Dictionary <string, object> > symbols = null)
        {
            if (symbols == null)
            {
                symbols = ImmutableDictionary.CreateBuilder <Scope, Dictionary <string, object> >().ToImmutable();
            }

            var dict = new Dictionary <string, object>();

            symbols = symbols.Add(scope, dict);

            // parse tokens in this scope
            foreach (Scope.Node node in scope)
            {
                Token token = node.Token;
                if (node.HasInnerScope)
                {
                    switch (token)
                    {
                    case ListToken list:
                        ParseListToken(list, node, scope, symbols, dict);
                        break;

                    case InlineListToken _:
                        ParseInlineListToken(node, symbols, dict);
                        break;

                    case NamedToken named when named.HasReferencedVariable:
                        ParseVariableNameToken(named, node, symbols, dict);
                        break;

                    default:
                        throw new ParserException("Invalid token encountered during scope iteration " +
                                                  "on a node with an inner scope:\n{token}");
                    }
                }
                else
                {
                    switch (token)
                    {
                    case NamedToken named when !named.HasReferencedVariable:
                        ParseNamedToken(named, dict);
                        break;

                    case LiteralToken literal:
                        ParseLiteralToken(literal);
                        break;

                    case RegExToken regex:
                        // TODO: do not ignore the regex result
                        ParseRegExToken(regex, out _);
                        break;

                    case NewLineToken _:
                        NextNewLineToken();
                        break;

                    default:
                        throw new ParserException("Invalid token encountered during scope iteration:\n{{token}}");
                    }
                }
            }

            // remove hidden tokens once they are not needed anymore
            foreach (NamedToken named in scope.Select(n => n.Token).OfType <NamedToken>().Where(t => t.Hidden))
            {
                dict.Remove(named.Name);
            }

            return(dict);
        }
示例#56
0
 public MemorySnapshot(ConcurrentDictionary <byte[], byte[]> innerData)
 {
     this.innerData     = innerData;
     this.immutableData = innerData.ToImmutableDictionary(ByteArrayEqualityComparer.Default);
     this.writeBatch    = new ConcurrentDictionary <byte[], byte[]>(ByteArrayEqualityComparer.Default);
 }
示例#57
0
        protected override ComposablePartDefinition CreatePart(Type partType, bool typeExplicitlyRequested)
        {
            Requires.NotNull(partType, nameof(partType));

            var partTypeInfo = partType.GetTypeInfo();

            // We want to ignore abstract classes, but we want to consider static classes.
            // Static classes claim to be both abstract and sealed. So to ignore just abstract
            // ones, we check that they are not sealed.
            if (partTypeInfo.IsAbstract && !partTypeInfo.IsSealed)
            {
                return(null);
            }

            BindingFlags everythingLocal = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
            BindingFlags instanceLocal   = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            // If the type is abstract only find local static exports
            var exportBindingFlags = everythingLocal;

            if (partTypeInfo.IsAbstract)
            {
                exportBindingFlags &= ~BindingFlags.Instance;
            }

            var declaredMethods    = partType.GetMethods(exportBindingFlags); // methods can only export, not import
            var declaredProperties = partType.GetProperties(everythingLocal);
            var declaredFields     = partType.GetFields(everythingLocal);

            var allLocalMembers  = declaredMethods.Concat <MemberInfo>(declaredProperties).Concat(declaredFields);
            var exportingMembers = from member in allLocalMembers
                                   from export in member.GetAttributes <ExportAttribute>()
                                   select new KeyValuePair <MemberInfo, ExportAttribute>(member, export);
            var exportedTypes = from export in partTypeInfo.GetAttributes <ExportAttribute>()
                                select new KeyValuePair <MemberInfo, ExportAttribute>(partTypeInfo, export);
            var inheritedExportedTypes = from baseTypeOrInterface in partType.GetInterfaces().Concat(partType.EnumTypeAndBaseTypes().Skip(1))
                                         where baseTypeOrInterface != typeof(object)
                                         from export in baseTypeOrInterface.GetTypeInfo().GetAttributes <InheritedExportAttribute>()
                                         select new KeyValuePair <MemberInfo, ExportAttribute>(baseTypeOrInterface.GetTypeInfo(), export);

            var exportsByMember = (from export in exportingMembers.Concat(exportedTypes).Concat(inheritedExportedTypes)
                                   group export.Value by export.Key into exportsByType
                                   select exportsByType).Select(g => new KeyValuePair <MemberInfo, ExportAttribute[]>(g.Key, g.ToArray())).ToArray();

            if (exportsByMember.Length == 0)
            {
                return(null);
            }

            // Check for PartNotDiscoverable only after we've established it's an interesting part.
            // This optimizes for the fact that most types have no exports, in which case it's not a discoverable
            // part anyway. Checking for the PartNotDiscoverableAttribute first, which is rarely defined,
            // doesn't usually pay for itself in terms of short-circuiting. But it does add an extra
            // attribute to look for that we don't need to find for all the types that have no export attributes either.
            if (!typeExplicitlyRequested && partTypeInfo.IsAttributeDefined <PartNotDiscoverableAttribute>())
            {
                return(null);
            }

            foreach (var exportingMember in exportsByMember)
            {
                this.ThrowOnInvalidExportingMember(exportingMember.Key);
            }

            TypeRef partTypeRef = TypeRef.Get(partType, this.Resolver);
            Type    partTypeAsGenericTypeDefinition = partTypeInfo.IsGenericType ? partType.GetGenericTypeDefinition() : null;

            // Collect information for all imports.
            var imports = ImmutableList.CreateBuilder <ImportDefinitionBinding>();

            this.AddImportsFromMembers(declaredProperties, declaredFields, partTypeRef, imports);
            Type baseType = partTypeInfo.BaseType;

            while (baseType != null && baseType != typeof(object))
            {
                this.AddImportsFromMembers(baseType.GetProperties(instanceLocal), baseType.GetFields(instanceLocal), partTypeRef, imports);
                baseType = baseType.GetTypeInfo().BaseType;
            }

            var partCreationPolicy          = CreationPolicy.Any;
            var partCreationPolicyAttribute = partTypeInfo.GetFirstAttribute <PartCreationPolicyAttribute>();

            if (partCreationPolicyAttribute != null)
            {
                partCreationPolicy = (CreationPolicy)partCreationPolicyAttribute.CreationPolicy;
            }

            var allExportsMetadata = ImmutableDictionary.CreateRange(PartCreationPolicyConstraint.GetExportMetadata(partCreationPolicy));
            var inheritedExportContractNamesFromNonInterfaces = ImmutableHashSet.CreateBuilder <string>();
            var exportDefinitions = ImmutableList.CreateBuilder <KeyValuePair <MemberInfo, ExportDefinition> >();

            foreach (var export in exportsByMember)
            {
                var memberExportMetadata = allExportsMetadata.AddRange(GetExportMetadata(export.Key));

                if (export.Key is MethodInfo)
                {
                    var method           = export.Key as MethodInfo;
                    var exportAttributes = export.Value;
                    if (exportAttributes.Any())
                    {
                        foreach (var exportAttribute in exportAttributes)
                        {
                            Type   exportedType   = exportAttribute.ContractType ?? ReflectionHelpers.GetContractTypeForDelegate(method);
                            string contractName   = string.IsNullOrEmpty(exportAttribute.ContractName) ? GetContractName(exportedType) : exportAttribute.ContractName;
                            var    exportMetadata = memberExportMetadata
                                                    .Add(CompositionConstants.ExportTypeIdentityMetadataName, ContractNameServices.GetTypeIdentity(exportedType));
                            var exportDefinition = new ExportDefinition(contractName, exportMetadata);
                            exportDefinitions.Add(new KeyValuePair <MemberInfo, ExportDefinition>(export.Key, exportDefinition));
                        }
                    }
                }
                else
                {
                    MemberInfo exportingTypeOrPropertyOrField = export.Key;
                    Verify.Operation(export.Key is TypeInfo || !partTypeInfo.IsGenericTypeDefinition, Strings.ExportsOnMembersNotAllowedWhenDeclaringTypeGeneric);
                    Type exportSiteType = ReflectionHelpers.GetMemberType(exportingTypeOrPropertyOrField);
                    foreach (var exportAttribute in export.Value)
                    {
                        Type   exportedType = exportAttribute.ContractType ?? partTypeAsGenericTypeDefinition ?? exportSiteType;
                        string contractName = string.IsNullOrEmpty(exportAttribute.ContractName) ? GetContractName(exportedType) : exportAttribute.ContractName;
                        if (export.Key is TypeInfo && exportAttribute is InheritedExportAttribute)
                        {
                            if (inheritedExportContractNamesFromNonInterfaces.Contains(contractName))
                            {
                                // We already have an export with this contract name on this type (from a more derived type)
                                // using InheritedExportAttribute.
                                continue;
                            }

                            if (!((TypeInfo)export.Key).IsInterface)
                            {
                                inheritedExportContractNamesFromNonInterfaces.Add(contractName);
                            }
                        }

                        var exportMetadata = memberExportMetadata
                                             .Add(CompositionConstants.ExportTypeIdentityMetadataName, ContractNameServices.GetTypeIdentity(exportedType));
                        var exportDefinition = new ExportDefinition(contractName, exportMetadata);
                        exportDefinitions.Add(new KeyValuePair <MemberInfo, ExportDefinition>(export.Key, exportDefinition));
                    }
                }
            }

            MethodInfo onImportsSatisfied = null;

            if (typeof(IPartImportsSatisfiedNotification).IsAssignableFrom(partType))
            {
                onImportsSatisfied = OnImportsSatisfiedMethodInfo;
            }

            var importingConstructorParameters = ImmutableList.CreateBuilder <ImportDefinitionBinding>();
            var importingCtor = GetImportingConstructor <ImportingConstructorAttribute>(partType, publicOnly: false);

            if (importingCtor != null) // some parts have exports merely for metadata -- they can't be instantiated
            {
                foreach (var parameter in importingCtor.GetParameters())
                {
                    var import = this.CreateImport(parameter);
                    if (import.ImportDefinition.Cardinality == ImportCardinality.ZeroOrMore)
                    {
                        Verify.Operation(PartDiscovery.IsImportManyCollectionTypeCreateable(import), Strings.CollectionMustBePublicAndPublicCtorWhenUsingImportingCtor);
                    }

                    importingConstructorParameters.Add(import);
                }
            }

            var partMetadata = ImmutableDictionary.CreateBuilder <string, object>();

            foreach (var partMetadataAttribute in partTypeInfo.GetAttributes <PartMetadataAttribute>())
            {
                partMetadata[partMetadataAttribute.Name] = partMetadataAttribute.Value;
            }

            var exportsOnType    = exportDefinitions.Where(kv => kv.Key is TypeInfo).Select(kv => kv.Value).ToArray();
            var exportsOnMembers = (from kv in exportDefinitions
                                    where !(kv.Key is TypeInfo)
                                    group kv.Value by kv.Key into byMember
                                    select byMember).ToDictionary(g => MemberRef.Get(g.Key, this.Resolver), g => (IReadOnlyCollection <ExportDefinition>)g.ToArray());

            var assemblyNamesForMetadataAttributes = ImmutableHashSet.CreateBuilder <AssemblyName>(ByValueEquality.AssemblyName);

            foreach (var export in exportsByMember)
            {
                GetAssemblyNamesFromMetadataAttributes <MetadataAttributeAttribute>(export.Key, assemblyNamesForMetadataAttributes);
            }

            return(new ComposablePartDefinition(
                       TypeRef.Get(partType, this.Resolver),
                       partMetadata.ToImmutable(),
                       exportsOnType,
                       exportsOnMembers,
                       imports.ToImmutable(),
                       partCreationPolicy != CreationPolicy.NonShared ? string.Empty : null,
                       MethodRef.Get(onImportsSatisfied, this.Resolver),
                       MethodRef.Get(importingCtor, this.Resolver),
                       importingCtor != null ? importingConstructorParameters.ToImmutable() : null, // some MEF parts are only for metadata
                       partCreationPolicy,
                       assemblyNamesForMetadataAttributes,
                       partCreationPolicy != CreationPolicy.NonShared));
        }
        private static async Task<DocumentAnalyzerPerformance> TestDocumentPerformanceAsync(ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Project project, DocumentId documentId, Options analyzerOptionsInternal, CancellationToken cancellationToken)
        {
            // update the project compilation options
            var modifiedSpecificDiagnosticOptions = project.CompilationOptions.SpecificDiagnosticOptions
                .Add("AD0001", ReportDiagnostic.Error)
                .Add("AD0002", ReportDiagnostic.Error);
            // Report exceptions during the analysis process as errors
            var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions);
            var processedProject = project.WithCompilationOptions(modifiedCompilationOptions);

            if (!analyzers.TryGetValue(project.Language, out var languageAnalyzers))
            {
                languageAnalyzers = ImmutableArray<DiagnosticAnalyzer>.Empty;
            }

            var stopwatch = Stopwatch.StartNew();
            for (int i = 0; i < analyzerOptionsInternal.TestDocumentIterations; i++)
            {
                Compilation compilation = await processedProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                var workspaceAnalyzerOptions = new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution.Options, project.Solution);
                CompilationWithAnalyzers compilationWithAnalyzers = compilation.WithAnalyzers(languageAnalyzers, new CompilationWithAnalyzersOptions(workspaceAnalyzerOptions, null, analyzerOptionsInternal.RunConcurrent, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: analyzerOptionsInternal.ReportSuppressedDiagnostics));

                SyntaxTree tree = await project.GetDocument(documentId).GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                await compilationWithAnalyzers.GetAnalyzerSyntaxDiagnosticsAsync(tree, cancellationToken).ConfigureAwait(false);
                await compilationWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(compilation.GetSemanticModel(tree), null, cancellationToken).ConfigureAwait(false);
            }

            return new DocumentAnalyzerPerformance(analyzerOptionsInternal.TestDocumentIterations / stopwatch.Elapsed.TotalSeconds);
        }
示例#59
0
 internal Service(string name, ImmutableDictionary <string, object?> dictionary, CustomResourceOptions?options = null)
     : base("kubernetes:core/v1:Service", name, dictionary, options)
 {
 }
示例#60
0
        private void ParseListToken(ListToken listToken, Scope.Node node, Scope scope,
                                    ImmutableDictionary <Scope, Dictionary <string, object> > symbolTable, IDictionary <string, object> dict)
        {
            if (listToken.Delimiters != null)
            {
                throw new NotImplementedException("List delimiters are not supported yet.");
            }

            // get the number of iterations needed
            var repetitions = 0;

            switch (listToken.Range)
            {
            // automatic
            case AutomaticRange automaticRange:
                throw new NotImplementedException("Automatic range notation is not supported yet.");

            // fixed number
            case NumericRange numericRange:
                repetitions = numericRange.Repetitions;
                break;

            // value of some named token
            case TokenRange tokenRange:
                object referencedValue = FindNamedTokenValue(tokenRange.ReferencedName, scope, symbolTable);
                if (referencedValue is int value)
                {
                    repetitions = value;
                }
                else
                {
                    throw new ParserException($"Could not use the non-numeric value '{referencedValue}' " +
                                              $"of token '{tokenRange.ReferencedName}' as an repetition number.");
                }

                break;
            }

            // parse the inner scope a number of times
            var expandedList = new List <object>();

            for (var i = 0; i < repetitions; i++)
            {
                Dictionary <string, object> innerRepeatedDict = ParseScope(node.InnerScope, symbolTable);
                expandedList.Add(innerRepeatedDict.First().Value);
            }

            // find a name
            Scope.Node innerNode = node;
            while (innerNode.HasInnerScope)
            {
                innerNode = innerNode.InnerScope.First();
            }

            string name = "listToken";

            if (innerNode.Token is NamedToken named)
            {
                name = named.Name + "s";
            }

            dict.Add(name, expandedList);
        }