public DiagnosticService()
 {
     // we use registry service rather than doing MEF import since MEF import method can have race issue where
     // update source gets created before aggregator - diagnostic service - is created and we will lose events fired before
     // the aggregator is created.
     _updateSources = ImmutableHashSet<IDiagnosticUpdateSource>.Empty;
 }
Esempio n. 2
0
        public EEAssemblyBuilder(
            SourceAssemblySymbol sourceAssembly,
            EmitOptions emitOptions,
            ImmutableArray<MethodSymbol> methods,
            ModulePropertiesForSerialization serializationProperties,
            ImmutableArray<NamedTypeSymbol> additionalTypes,
            NamedTypeSymbol dynamicOperationContextType,
            CompilationTestData testData) :
            base(
                  sourceAssembly,
                  emitOptions,
                  outputKind: OutputKind.DynamicallyLinkedLibrary,
                  serializationProperties: serializationProperties,
                  manifestResources: SpecializedCollections.EmptyEnumerable<ResourceDescription>(),
                  additionalTypes: additionalTypes)
        {
            Methods = ImmutableHashSet.CreateRange(methods);
            _dynamicOperationContextType = dynamicOperationContextType;

            if (testData != null)
            {
                this.SetMethodTestData(testData.Methods);
                testData.Module = this;
            }
        }
        public ClusterRouterGroupSettings(int totalInstances, bool allowLocalRoutees, string useRole, ImmutableHashSet<string> routeesPaths) : base(totalInstances, allowLocalRoutees, useRole)
        {
            RouteesPaths = routeesPaths;
            if(routeesPaths == null || routeesPaths.IsEmpty || string.IsNullOrEmpty(routeesPaths.First())) throw new ArgumentException("routeesPaths must be defined", "routeesPaths");

            //todo add relative actor path validation
        }
 protected override void OnReceive(object message)
 {
     var state = message as ClusterEvent.CurrentClusterState;
     if (state != null)
     {
         _clusterNodes =
             state.Members.Select(m => m.Address).Where(a => a != _cluster.SelfAddress).ToImmutableHashSet();
         foreach(var node in _clusterNodes) TakeOverResponsibility(node);
         Unreachable.ExceptWith(_clusterNodes);
         return;
     }
     var memberUp = message as ClusterEvent.MemberUp;
     if (memberUp != null)
     {
         MemberUp(memberUp);
         return;
     }
     var memberRemoved = message as ClusterEvent.MemberRemoved;
     if (memberRemoved != null)
     {
         MemberRemoved(memberRemoved);
         return;
     }
     if (message is ClusterEvent.IMemberEvent) return; // not interesting
     base.OnReceive(message);
 }
        private readonly MultiDictionary<ISentenceForm, Fact> _sentencesByForm; //TODO: Immutable

        #endregion Fields

        #region Constructors

        private ImmutableConstantChecker(ImmutableSentenceFormModel sentenceModel, MultiDictionary<ISentenceForm, Fact> sentencesByForm)
        {
            Debug.Assert(sentenceModel.ConstantSentenceForms.IsSupersetOf(sentencesByForm.Keys));
            _sentenceModel = sentenceModel;
            _sentencesByForm = sentencesByForm;
            _allSentences = sentencesByForm.SelectMany(s => s.Value).ToImmutableHashSet();
        }
        protected ImmutableArray<CompletionProvider> GetProviders(ImmutableHashSet<string> roles)
        {
            roles = roles ?? ImmutableHashSet<string>.Empty;

            RoleProviders providers;
            if (!_roleProviders.TryGetValue(roles, out providers))
            {
                providers = _roleProviders.GetValue(roles, _ =>
                {
                    var builtin = GetBuiltInProviders();
                    var imported = GetImportedProviders()
                        .Where(lz => lz.Metadata.Roles == null || lz.Metadata.Roles.Length == 0 || roles.Overlaps(lz.Metadata.Roles))
                        .Select(lz => lz.Value);
                    return new RoleProviders { Providers = builtin.Concat(imported).ToImmutableArray() };
                });
            }

            if (_testProviders.Length > 0)
            {
                return providers.Providers.Concat(_testProviders);
            }
            else
            {
                return providers.Providers;
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Gets the completions available at the caret position.
 /// </summary>
 /// <param name="document">The document that completion is occuring within.</param>
 /// <param name="caretPosition">The position of the caret after the triggering action.</param>
 /// <param name="trigger">The triggering action.</param>
 /// <param name="roles">Optional set of roles associated with the editor state.</param>
 /// <param name="options">Optional options that override the default options.</param>
 /// <param name="cancellationToken"></param>
 public abstract Task<CompletionList> GetCompletionsAsync(
     Document document,
     int caretPosition,
     CompletionTrigger trigger = default(CompletionTrigger),
     ImmutableHashSet<string> roles = null,
     OptionSet options = null,
     CancellationToken cancellationToken = default(CancellationToken));
Esempio n. 8
0
		static async Task<SyntaxNode> GetNewRootWithAddedNamespaces(Document document, SyntaxNode relativeToNode,
			CancellationToken cancellationToken, ImmutableHashSet<string> namespaceQualifiedStrings)
		{
			var namespaceWithUsings = relativeToNode
				.GetAncestorsOrThis<NamespaceDeclarationSyntax>()
				.FirstOrDefault(ns => ns.DescendantNodes().OfType<UsingDirectiveSyntax>().Any());

			var root = await document.GetSyntaxRootAsync(cancellationToken);
			SyntaxNode newRoot;

			var usings = namespaceQualifiedStrings
				.Select(ns => UsingDirective(ParseName(ns).WithAdditionalAnnotations(Simplifier.Annotation)));

			if (namespaceWithUsings != null)
			{
				var newNamespaceDeclaration = namespaceWithUsings.WithUsings(namespaceWithUsings.Usings.AddRange(usings));
				newRoot = root.ReplaceNode(namespaceWithUsings, newNamespaceDeclaration);
			}
			else
			{
				var compilationUnit = (CompilationUnitSyntax)root;
				newRoot = compilationUnit.WithUsings(compilationUnit.Usings.AddRange(usings));
			}
			return newRoot;
		}
        private async Task<Solution> GetFix(TextDocument publicSurfaceAreaDocument, string newSymbolName, ImmutableHashSet<string> siblingSymbolNamesToRemove, CancellationToken cancellationToken)
        {
            SourceText sourceText = await publicSurfaceAreaDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
            SourceText newSourceText = AddSymbolNamesToSourceText(sourceText, new[] { newSymbolName });
            newSourceText = RemoveSymbolNamesFromSourceText(newSourceText, siblingSymbolNamesToRemove);

            return publicSurfaceAreaDocument.Project.Solution.WithAdditionalDocumentText(publicSurfaceAreaDocument.Id, newSourceText);
        }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TradeGood"/> class.
 /// </summary>
 public TradeGood()
 {
     m_AvailabilityList = ImmutableHashSet<string>.Empty;
     DetailRoll = "2D6";
     Legal = true;
     m_PurchaseDMs = new List<TradeGoodPurchase>();
     m_SaleDMs = new List<TradeGoodSale>();
 }
Esempio n. 11
0
        /// <summary>
        /// Creates a member from internal Akka method
        /// </summary>
        /// <returns>The new member</returns>
        public static Member MemberCreate(UniqueAddress uniqueAddress, int upNumber, MemberStatus status, ImmutableHashSet<string> roles)
        {
            var createMethod =
                typeof(Member).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
                .First(m => m.Name == "Create" && m.GetParameters().Length == 4);

            return (Member)createMethod.Invoke(null, new object[] { uniqueAddress, upNumber, status, roles });
        }
Esempio n. 12
0
 /// <summary>
 /// Returns true if the character recently inserted or deleted in the text should trigger completion.
 /// </summary>
 /// <param name="text">The document text to trigger completion within </param>
 /// <param name="caretPosition">The position of the caret after the triggering action.</param>
 /// <param name="trigger">The potential triggering action.</param>
 /// <param name="roles">Optional set of roles associated with the editor state.</param>
 /// <param name="options">Optional options that override the default options.</param>
 /// <remarks>
 /// This API uses SourceText instead of Document so implementations can only be based on text, not syntax or semantics.
 /// </remarks>
 public virtual bool ShouldTriggerCompletion(
     SourceText text,
     int caretPosition,
     CompletionTrigger trigger,
     ImmutableHashSet<string> roles = null,
     OptionSet options = null)
 {
     return false;
 }
 public FixAllDiagnosticProvider(
     ImmutableHashSet<string> diagnosticIds,
     Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync,
     Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync)
 {
     this.diagnosticIds = diagnosticIds;
     this.getDocumentDiagnosticsAsync = getDocumentDiagnosticsAsync;
     this.getProjectDiagnosticsAsync = getProjectDiagnosticsAsync;
 }
Esempio n. 14
0
 /// <summary>
 /// Contant sentences are those that do not have a dependency on 'true' or 'does' facts
 /// </summary>
 /// <param name="sentenceForms"></param>
 /// <param name="dependencyGraph"></param>
 /// <returns></returns>
 private static ImmutableHashSet<ISentenceForm> GetConstantSentenceForms(ImmutableHashSet<ISentenceForm> sentenceForms,
     MultiDictionary<ISentenceForm, ISentenceForm> dependencyGraph)
 {
     MultiDictionary<ISentenceForm, ISentenceForm> augmentedGraph = AugmentGraphWithLanguageRules(dependencyGraph, sentenceForms);
     ImmutableHashSet<ISentenceForm> changingSentenceForms =
         DependencyGraphs.GetMatchingAndDownstream(sentenceForms, augmentedGraph,
                                                     d => SentenceForms.TruePred(d) || SentenceForms.DoesPred(d));
     return sentenceForms.SymmetricExcept(changingSentenceForms).ToImmutableHashSet();
 }
Esempio n. 15
0
 /// <summary>
 /// 
 /// </summary>
 public RendererState()
 {
     _panX = 0.0;
     _panY = 0.0;
     _zoom = 1.0;
     _enableAutofit = true;
     _drawShapeState = ShapeState.Create(ShapeStateFlags.Visible | ShapeStateFlags.Printable);
     _selectedShape = default(BaseShape);
     _selectedShapes = default(ImmutableHashSet<BaseShape>);
 }
Esempio n. 16
0
 public AnalyzerData(
     ImmutableHashSet<ExpandedType> usedTypes, ImmutableHashSet<ExpandedMethod> analyzedMethods,
     ImmutableHashSet<VirtualMethod> virtualMethodsToAnalyze,
     ImmutableHashSet<VirtualMethod> analyzedVirtualMethods
     )
 {
     this.usedTypes = usedTypes;
       this.analyzedMethods = analyzedMethods;
       this.virtualMethodsToAnalyze = virtualMethodsToAnalyze;
       this.analyzedVirtualMethods = analyzedVirtualMethods;
 }
Esempio n. 17
0
        public ParallelWorker(int workerCount)
        {
            if (workerCount < 1) throw new ArgumentException(nameof(workerCount));

            this.syncRoot = new object();
            this.capacity = workerCount;
            this.idleWorkers = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(0, workerCount));
            this.busyWorkers = ImmutableHashSet<int>.Empty;

            this.waitingWorkItems = new CancellableQueue<WaitingWorkItem>();
        }
Esempio n. 18
0
 private FixMultipleContext(
     Project triggerProject,
     CodeFixProvider codeFixProvider,
     string codeActionEquivalenceKey,
     ImmutableHashSet<string> diagnosticIds,
     FixMultipleDiagnosticProvider diagnosticProvider,
     CancellationToken cancellationToken)
     : base(triggerProject, codeFixProvider, FixAllScope.Custom, codeActionEquivalenceKey, diagnosticIds, diagnosticProvider, cancellationToken)
 {
     _diagnosticProvider = diagnosticProvider;
 }
Esempio n. 19
0
 public Map(int id, bool[,] filled, PositionedUnit unit, ImmutableStack<Unit> nextUnits, ImmutableHashSet<PositionedUnit> usedPositions, Scores scores, bool died = false)
 {
     Id = id;
     NextUnits = nextUnits;
     Width = filled.GetLength(0);
     Height = filled.GetLength(1);
     Filled = filled;
     Unit = IsValidPosition(unit) ? unit : PositionedUnit.Null;
     UsedPositions = usedPositions.Add(Unit);
     Scores = scores;
     Died = died;
 }
Esempio n. 20
0
 public CurrentClusterState(
     ImmutableSortedSet<Member> members,
     ImmutableHashSet<Member> unreachable,
     ImmutableHashSet<Address> seenBy,
     Address leader,
     ImmutableDictionary<string, Address> roleLeaderMap)
 {
     _members = members;
     _unreachable = unreachable;
     _seenBy = seenBy;
     _leader = leader;
     _roleLeaderMap = roleLeaderMap;
 }
        public void Register(IDiagnosticUpdateSource source)
        {
            lock (_gate)
            {
                if (_updateSources.Contains(source))
                {
                    return;
                }

                _updateSources = _updateSources.Add(source);
                source.DiagnosticsUpdated += OnDiagnosticsUpdated;
            }
        }
 private FixAllCodeActionContext(
     Project project,
     FixAllProviderInfo fixAllProviderInfo,
     CodeFixProvider originalFixProvider,
     IEnumerable<Diagnostic> originalFixDiagnostics,
     ImmutableHashSet<string> diagnosticIds,
     FixAllDiagnosticProvider diagnosticProvider,
     CancellationToken cancellationToken)
     : base(project, originalFixProvider, FixAllScope.Project, null, diagnosticIds, diagnosticProvider, cancellationToken)
 {
     _fixAllProviderInfo = fixAllProviderInfo;
     _originalFixDiagnostics = originalFixDiagnostics;
     _diagnosticProvider = diagnosticProvider;
 }
Esempio n. 23
0
		static ImmutableList<string> GetNamespacesToReallyAdd(SyntaxNode relativeToNode, SemanticModel semanticModel,
			ImmutableHashSet<string> namespaceQualifiedStrings)
		{
			var alreadyInScope = semanticModel
				.GetUsingNamespacesInScope(relativeToNode)
				.Select(ns => ns.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))
				.ToImmutableHashSet();

			var toReallyAdd = namespaceQualifiedStrings
				.Where(ns => !alreadyInScope.Contains(ns))
				.ToImmutableList();

			return toReallyAdd;
		}
Esempio n. 24
0
        public ClusterReadView(Cluster cluster)
        {
            _cluster = cluster;
            _state = new ClusterEvent.CurrentClusterState();
            _reachability = Reachability.Empty;
            _latestStats = new ClusterEvent.CurrentInternalStats(new GossipStats(), new VectorClockStats());
            _clusterMetrics = ImmutableHashSet.Create<NodeMetrics>();
            _selfAddress = cluster.SelfAddress;

            _eventBusListener =
                cluster.System.SystemActorOf(
                    Props.Create(() => new EventBusListener(cluster, this))
                        .WithDispatcher(cluster.Settings.UseDispatcher)
                        .WithDeploy(Deploy.Local), "clusterEventBusListener");
        }
        private static SourceText RemoveSymbolNamesFromSourceText(SourceText sourceText, ImmutableHashSet<string> linesToRemove)
        {
            if (linesToRemove.IsEmpty)
            {
                return sourceText;
            }

            HashSet<string> lines = GetLinesFromSourceText(sourceText);
            var newLines = lines.Where(line => !linesToRemove.Contains(line));

            IOrderedEnumerable<string> sortedLines = newLines.OrderBy(s => s, StringComparer.Ordinal);

            SourceText newSourceText = sourceText.Replace(new TextSpan(0, sourceText.Length), string.Join(Environment.NewLine, sortedLines));
            return newSourceText;
        }
        public CSharpEditorFormattingService()
        {
            _autoFormattingTriggerChars = ImmutableHashSet.CreateRange<char>(";}");

            // add all auto formatting trigger to supported char
            _supportedChars = _autoFormattingTriggerChars.Union("{}#nte:)");

            // set up multi words map
            _multiWordsMap = ImmutableDictionary.CreateRange(new[]
            {
                KeyValuePair.Create('n', ImmutableHashSet.Create(SyntaxKind.RegionKeyword, SyntaxKind.EndRegionKeyword)),
                KeyValuePair.Create('t', ImmutableHashSet.Create(SyntaxKind.SelectKeyword)),
                KeyValuePair.Create('e', ImmutableHashSet.Create(SyntaxKind.WhereKeyword)),
            });
        }
            public void ComputeModel(
                CompletionService completionService,
                CompletionTrigger trigger,
                ImmutableHashSet<string> roles,
                OptionSet options)
            {
                AssertIsForeground();

                // If we've already computed a model then we can just ignore this request and not
                // generate any tasks.
                if (this.Computation.InitialUnfilteredModel != null)
                {
                    return;
                }

                new ModelComputer(this, completionService, trigger, roles, options).Do();
            }
Esempio n. 28
0
        public ClusterSettings(Config config, string systemName)
        {
            //TODO: Requiring!
            var cc = config.GetConfig("akka.cluster");
            _logInfo = cc.GetBoolean("log-info");
            _failureDetectorConfig = cc.GetConfig("failure-detector");
            _failureDetectorImplementationClass = _failureDetectorConfig.GetString("implementation-class");
            _heartbeatInterval = _failureDetectorConfig.GetTimeSpan("heartbeat-interval");
            _heartbeatExpectedResponseAfter = _failureDetectorConfig.GetTimeSpan("expected-response-after");
            _monitoredByNrOfMembers = _failureDetectorConfig.GetInt("monitored-by-nr-of-members");

            _seedNodes = cc.GetStringList("seed-nodes").Select(Address.Parse).ToImmutableList();
            _seedNodeTimeout = cc.GetTimeSpan("seed-node-timeout");
            _retryUnsuccessfulJoinAfter = cc.GetTimeSpanWithOffSwitch("retry-unsuccessful-join-after");
            _periodicTasksInitialDelay = cc.GetTimeSpan("periodic-tasks-initial-delay");
            _gossipInterval = cc.GetTimeSpan("gossip-interval");
            _gossipTimeToLive = cc.GetTimeSpan("gossip-time-to-live");
            _leaderActionsInterval = cc.GetTimeSpan("leader-actions-interval");
            _unreachableNodesReaperInterval = cc.GetTimeSpan("unreachable-nodes-reaper-interval");
            _publishStatsInterval = cc.GetTimeSpanWithOffSwitch("publish-stats-interval");
            _downRemovalMargin = cc.GetTimeSpan("down-removal-margin");

            _autoDownUnreachableAfter = cc.GetTimeSpanWithOffSwitch("auto-down-unreachable-after");

            _roles = cc.GetStringList("roles").ToImmutableHashSet();
            _minNrOfMembers = cc.GetInt("min-nr-of-members");
            //TODO:
            //_minNrOfMembersOfRole = cc.GetConfig("role").Root.GetArray().ToImmutableDictionary(o => o. )
            //TODO: Ignored jmx
            _useDispatcher = cc.GetString("use-dispatcher");
            if (String.IsNullOrEmpty(_useDispatcher)) _useDispatcher = Dispatchers.DefaultDispatcherId;
            _gossipDifferentViewProbability = cc.GetDouble("gossip-different-view-probability");
            _reduceGossipDifferentViewProbability = cc.GetInt("reduce-gossip-different-view-probability");
            _schedulerTickDuration = cc.GetTimeSpan("scheduler.tick-duration");
            _schedulerTicksPerWheel = cc.GetInt("scheduler.ticks-per-wheel");
            _metricsEnabled = cc.GetBoolean("metrics.enabled");
            _metricsCollectorClass = cc.GetString("metrics.collector-class");
            _metricsInterval = cc.GetTimeSpan("metrics.collect-interval");
            _metricsGossipInterval = cc.GetTimeSpan("metrics.gossip-interval");
            _metricsMovingAverageHalfLife = cc.GetTimeSpan("metrics.moving-average-half-life");

            _minNrOfMembersOfRole = cc.GetConfig("role").Root.GetObject().Items
                .ToImmutableDictionary(kv => kv.Key, kv => kv.Value.GetObject().GetKey("min-nr-of-members").GetInt());

            _verboseHeartbeatLogging = cc.GetBoolean("debug.verbose-heartbeat-logging");
        }
Esempio n. 29
0
    public Server(StringManager stringManager, Ide.Config config, IServiceProvider serviceProvider)
    {
      Contract.Requires(ServiceProvider != null);

      ServiceProvider = serviceProvider;

      var client = new NitraClient(stringManager);
      client.Send(new ClientMessage.CheckVersion(M.Constants.AssemblyVersionGuid));
      var responseMap = client.ResponseMap;
      responseMap[-1] = Response;
      _config = config;
      Client = client;

      var builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase);
      foreach (var lang in config.Languages)
        builder.UnionWith(lang.Extensions);
      Extensions = builder.ToImmutable();
    }
        /// <summary>
        /// Constructor
        /// </summary>
        internal AssemblyFoldersFromConfigCache(AssemblyFoldersFromConfig assemblyFoldersFromConfig, FileExists fileExists)
        {
            AssemblyFoldersFromConfig = assemblyFoldersFromConfig;
            _fileExists = fileExists;

            if (Environment.GetEnvironmentVariable("MSBUILDDISABLEASSEMBLYFOLDERSEXCACHE") != null)
            {
                _useOriginalFileExists = true;
            }
            else
            {
                _filesInDirectories = assemblyFoldersFromConfig.AsParallel()
                    .Where(assemblyFolder => FileUtilities.DirectoryExistsNoThrow(assemblyFolder.DirectoryPath))
                    .SelectMany(
                        assemblyFolder =>
                            Directory.GetFiles(assemblyFolder.DirectoryPath, "*.*", SearchOption.TopDirectoryOnly))
                    .ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
            }
        }
Esempio n. 31
0
 protected abstract void GetSyntaxAnalyzer(CodeBlockStartAnalysisContext <TLanguageKindEnum> context, ImmutableHashSet <ISymbol> symbols);
 public LWW_SetWithVC(ImmutableHashSet <LWW_SetWithVCElement <T> > adds, ImmutableHashSet <LWW_SetWithVCElement <T> > removes)
     : base(adds, removes)
 {
 }
 public Builder(ProjectId projectId, VersionStamp version, ImmutableHashSet <DocumentId> documentIds = null)
 {
     _projectId   = projectId;
     _version     = version;
     _documentIds = documentIds;
 }
Esempio n. 34
0
 public CompositeValidator(ImmutableHashSet <IValidator> validators) => this.validators = validators;
Esempio n. 35
0
        public override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, ImmutableHashSet <string> roles = null, OptionSet options = null)
        {
            options = options ?? _workspace.Options;
            if (!options.GetOption(CompletionOptions.TriggerOnTyping, this.Language))
            {
                return(false);
            }

            var providers = this.GetProviders(roles, CompletionTrigger.Default);

            return(providers.Any(p => p.ShouldTriggerCompletion(text, caretPosition, trigger, options)));
        }
Esempio n. 36
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <param name="node">TBD</param>
 /// <returns>TBD</returns>
 internal static Member Removed(UniqueAddress node)
 {
     return(new Member(node, int.MaxValue, MemberStatus.Removed, ImmutableHashSet.Create <string>()));
 }
 static IImmutableSet <string> GetNativeTypes()
 {
     return(ImmutableHashSet.Create("string", "int", "float"));
 }
Esempio n. 38
0
        private static async Task <Solution> GetFix(TextDocument publicSurfaceAreaDocument, string newSymbolName, ImmutableHashSet <string> siblingSymbolNamesToRemove, CancellationToken cancellationToken)
        {
            SourceText sourceText = await publicSurfaceAreaDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);

            SourceText newSourceText = AddSymbolNamesToSourceText(sourceText, new[] { newSymbolName });

            newSourceText = RemoveSymbolNamesFromSourceText(newSourceText, siblingSymbolNamesToRemove);

            return(publicSurfaceAreaDocument.Project.Solution.WithAdditionalDocumentText(publicSurfaceAreaDocument.Id, newSourceText));
        }
Esempio n. 39
0
 /// <summary>
 /// Creates a new <see cref="Member"/>.
 /// </summary>
 /// <param name="uniqueAddress">The address of the member.</param>
 /// <param name="upNumber">The upNumber of the member, as assigned by the leader at the time the node joined the cluster.</param>
 /// <param name="status">The status of this member.</param>
 /// <param name="roles">The roles for this member. Can be empty.</param>
 internal Member(UniqueAddress uniqueAddress, int upNumber, MemberStatus status, ImmutableHashSet <string> roles)
 {
     UniqueAddress = uniqueAddress;
     UpNumber      = upNumber;
     Status        = status;
     Roles         = roles;
 }
Esempio n. 40
0
        private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet <string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
        {
            try
            {
                if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
                {
                    return;
                }

                var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);

                var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);

                var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

                var versions = new VersionArgument(textVersion, dataVersion, projectVersion);
                if (bodyOpt == null)
                {
                    await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    // only open file can go this route
                    await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (Exception e) when(FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }
 protected abstract void EscapeValueForParameterPointsToLocationOnExit(IParameterSymbol parameter, AnalysisEntity analysisEntity, ImmutableHashSet <AbstractLocation> escapedLocations);
Esempio n. 42
0
 public Action(int index, IEnumerable <string> inputVariables)
 {
     _index = index;
     //JAVA version: this.inputVariables = Collections.unmodifiableSet(new HashSet<>(inputVariables));
     _inputVariables = ImmutableHashSet.CreateRange(inputVariables);
 }
Esempio n. 43
0
 public AbstractCodeBlockStartedAnalyzer(ImmutableHashSet <ISymbol> symbols)
 {
     _symbols = symbols;
 }
Esempio n. 44
0
        internal static Options Create(string[] args)
        {
            string analyzerPath                = null;
            string solutionPath                = null;
            var    builder                     = ImmutableHashSet.CreateBuilder <string>();
            var    refactoringBuilder          = ImmutableHashSet.CreateBuilder <string>();
            bool   runConcurrent               = false;
            bool   reportSuppressedDiagnostics = false;
            bool   applyChanges                = false;
            bool   showStats                   = false;
            bool   showCompilerDiagnostics     = false;
            bool   useAll        = false;
            int    iterations    = 1;
            bool   testDocuments = false;
            Func <string, bool> testDocumentMatch = _ => true;
            int    testDocumentIterations         = 10;
            string logFileName              = null;
            string profileRoot              = null;
            var    usePersistentStorage     = false;
            var    fullSolutionAnalysis     = false;
            var    incrementalAnalyzerNames = ImmutableArray.CreateBuilder <string>();

            int i = 0;

            while (i < args.Length)
            {
                var arg = args[i++];
                string ReadValue() => (i < args.Length) ? args[i++] : throw new InvalidDataException($"Missing value for option {arg}");

                switch (arg)
                {
                case "/all":
                    useAll = true;
                    break;

                case "/stats":
                    showStats = true;
                    break;

                case "/compilerStats":
                    showCompilerDiagnostics = true;
                    break;

                case "/concurrent":
                    runConcurrent = true;
                    break;

                case "/editperf":
                    testDocuments = true;
                    break;

                case var _ when arg.StartsWith("/editperf:"):
                    testDocuments = true;

                    var expression = new Regex(arg.Substring("/editperf:".Length), RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    testDocumentMatch = documentPath => expression.IsMatch(documentPath);
                    break;

                case var _ when arg.StartsWith("/edititer:"):
                    testDocumentIterations = int.Parse(arg.Substring("/edititer:".Length));

                    break;

                case var _ when arg.StartsWith("/iter:"):
                    iterations = int.Parse(arg.Substring("/iter:".Length));

                    break;

                case "/suppressed":
                    reportSuppressedDiagnostics = true;
                    break;

                case "/apply":
                    applyChanges = true;
                    break;

                case "/a":
                    builder.Add(ReadValue());
                    break;

                case "/refactor":
                    refactoringBuilder.Add(ReadValue());
                    break;

                case "/log":
                    logFileName = ReadValue();
                    break;

                case "/profileroot":
                    profileRoot = ReadValue();
                    break;

                case "/persist":
                    usePersistentStorage = true;
                    break;

                case "/fsa":
                    fullSolutionAnalysis = true;
                    break;

                case "/ia":
                    incrementalAnalyzerNames.Add(ReadValue());
                    break;

                default:
                    if (analyzerPath == null)
                    {
                        analyzerPath = arg;
                    }
                    else if (solutionPath == null)
                    {
                        solutionPath = arg;
                    }
                    else
                    {
                        throw new InvalidDataException((arg.StartsWith("/", StringComparison.Ordinal) ?
                                                        "Unrecognized option " + arg :
                                                        "Unrecognized parameter " + arg));
                    }
                    break;
                }
            }

            if (analyzerPath == null)
            {
                throw new InvalidDataException("Missing analyzer path");
            }

            if (solutionPath == null)
            {
                throw new InvalidDataException("Missing solution path");
            }

            return(new Options(
                       analyzerPath: analyzerPath,
                       solutionPath: solutionPath,
                       analyzerIds: builder.ToImmutableHashSet(),
                       refactoringNodes: refactoringBuilder.ToImmutableHashSet(),
                       runConcurrent: runConcurrent,
                       reportSuppressedDiagnostics: reportSuppressedDiagnostics,
                       applyChanges: applyChanges,
                       showStats: showStats,
                       showCompilerDiagnostics: showCompilerDiagnostics,
                       useAll: useAll,
                       iterations: iterations,
                       testDocuments: testDocuments,
                       testDocumentMatch: testDocumentMatch,
                       testDocumentIterations: testDocumentIterations,
                       logFileName: logFileName,
                       profileRoot: profileRoot,
                       usePersistentStorage: usePersistentStorage,
                       fullSolutionAnalysis: fullSolutionAnalysis,
                       incrementalAnalyzerNames: incrementalAnalyzerNames.ToImmutable()));
        }
Esempio n. 45
0
 protected abstract AbstractCodeBlockStartedAnalyzer GetCodeBlockStartedAnalyzer(ImmutableHashSet <ISymbol> symbols);
Esempio n. 46
0
        private static SourceText RemoveSymbolNamesFromSourceText(SourceText sourceText, ImmutableHashSet <string> linesToRemove)
        {
            if (linesToRemove.IsEmpty)
            {
                return(sourceText);
            }

            List <string>        lines    = GetLinesFromSourceText(sourceText);
            IEnumerable <string> newLines = lines.Where(line => !linesToRemove.Contains(line));

            SourceText newSourceText = sourceText.Replace(new TextSpan(0, sourceText.Length), string.Join(Environment.NewLine, newLines) + GetEndOfFileText(sourceText));

            return(newSourceText);
        }
Esempio n. 47
0
 /// <summary>
 /// Creates a new <see cref="Member"/>.
 /// </summary>
 /// <param name="uniqueAddress">The address of the member.</param>
 /// <param name="upNumber">The upNumber of the member, as assigned by the leader at the time the node joined the cluster.</param>
 /// <param name="status">The status of this member.</param>
 /// <param name="roles">The roles for this member. Can be empty.</param>
 /// <returns>A new member instance.</returns>
 internal static Member Create(UniqueAddress uniqueAddress, int upNumber, MemberStatus status, ImmutableHashSet <string> roles)
 {
     return(new Member(uniqueAddress, upNumber, status, roles));
 }
Esempio n. 48
0
 public OutputCompletionSource(Resource?resource)
 {
     _resources            = resource == null ? ImmutableHashSet <Resource> .Empty : ImmutableHashSet.Create(resource);
     _taskCompletionSource = new TaskCompletionSource <OutputData <T> >();
     Output = new Output <T>(_taskCompletionSource.Task);
 }
Esempio n. 49
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <param name="uniqueAddress">TBD</param>
 /// <param name="roles">TBD</param>
 /// <returns>TBD</returns>
 internal static Member Create(UniqueAddress uniqueAddress, ImmutableHashSet <string> roles)
 {
     return(new Member(uniqueAddress, int.MaxValue, MemberStatus.Joining, roles));
 }
Esempio n. 50
0
        public void ClusterClient_must_report_events()
        {
            Within(15.Seconds(), () =>
            {
                RunOn(() =>
                {
                    var c = Sys.ActorSelection("/user/client").ResolveOne(Dilated(1.Seconds())).Result;
                    var l = Sys.ActorOf(
                        Props.Create(() => new ClusterClientSpecConfig.TestClientListener(c)),
                        "reporter-client-listener");

                    var expectedContacts = ImmutableHashSet.Create(_config.First, _config.Second, _config.Third, _config.Fourth)
                                           .Select(_ => Node(_) / "system" / "receptionist");

                    Within(10.Seconds(), () =>
                    {
                        AwaitAssert(() =>
                        {
                            var probe = CreateTestProbe();
                            l.Tell(ClusterClientSpecConfig.TestClientListener.GetLatestContactPoints.Instance, probe.Ref);
                            probe.ExpectMsg <ClusterClientSpecConfig.TestClientListener.LatestContactPoints>()
                            .ContactPoints.Should()
                            .BeEquivalentTo(expectedContacts);
                        });
                    });
                }, _config.Client);


                EnterBarrier("reporter-client-listener-tested");

                RunOn(() =>
                {
                    // Only run this test on a node that knows about our client. It could be that no node knows
                    // but there isn't a means of expressing that at least one of the nodes needs to pass the test.
                    var r = ClusterClientReceptionist.Get(Sys).Underlying;
                    r.Tell(GetClusterClients.Instance);
                    var cps = ExpectMsg <ClusterClients>();
                    if (cps.ClusterClientsList.Any(c => c.Path.Name.Equals("client")))
                    {
                        Log.Info("Testing that the receptionist has just one client");
                        var l = Sys.ActorOf(
                            Props.Create(() => new ClusterClientSpecConfig.TestReceptionistListener(r)),
                            "reporter-receptionist-listener");

                        var c = Sys
                                .ActorSelection(Node(_config.Client) / "user" / "client")
                                .ResolveOne(Dilated(2.Seconds())).Result;

                        var expectedClients = ImmutableHashSet.Create(c);
                        Within(10.Seconds(), () =>
                        {
                            AwaitAssert(() =>
                            {
                                var probe = CreateTestProbe();
                                l.Tell(ClusterClientSpecConfig.TestReceptionistListener.GetLatestClusterClients.Instance, probe.Ref);

                                // "ask-client" might still be around, filter
                                probe.ExpectMsg <ClusterClientSpecConfig.TestReceptionistListener.LatestClusterClients>()
                                .ClusterClients.Should()
                                .Contain(expectedClients);
                            });
                        });
                    }
                }, _config.First, _config.Second, _config.Third);

                EnterBarrier("after-5");
            });
        }
Esempio n. 51
0
 protected ClusterClientSpec(ClusterClientSpecConfig config) : base(config, typeof(ClusterClientSpec))
 {
     _config = config;
     _remainingServerRoleNames = ImmutableHashSet.Create(_config.First, _config.Second, _config.Third, _config.Fourth);
 }
        public void ReplicatedDataSerializer_should_serialize_ORMultiDictionary()
        {
            CheckSerialization(ORMultiDictionary <string, string> .Empty);
            CheckSerialization(ORMultiDictionary <string, string> .Empty.AddItem(_address1, "a", "A"));
            CheckSerialization(ORMultiDictionary <string, string> .Empty
                               .AddItem(_address1, "a", "A1")
                               .SetItems(_address2, "b", ImmutableHashSet.CreateRange(new[] { "B1", "B2", "B3" }))
                               .AddItem(_address2, "a", "A2"));

            var m1 = ORMultiDictionary <string, string> .Empty.AddItem(_address1, "a", "A1").AddItem(_address2, "a", "A2");

            var m2 = ORMultiDictionary <string, string> .Empty.SetItems(_address2, "b", ImmutableHashSet.CreateRange(new[] { "B1", "B2", "B3" }));

            CheckSameContent(m1.Merge(m2), m2.Merge(m1));
        }
Esempio n. 53
0
        private static bool IsCheckedSymbolUpdated(ExpressionSyntax expression, ImmutableHashSet <ISymbol> checkedSymbols, SemanticModel semanticModel)
        {
            var symbol = semanticModel.GetSymbolInfo(expression).Symbol;

            return(symbol != null && checkedSymbols.Contains(symbol));
        }
Esempio n. 54
0
        public static void ArrayAsRootObject()
        {
            const string ExpectedJson         = @"[1,true,{""City"":""MyCity""},null,""foo""]";
            const string ReversedExpectedJson = @"[""foo"",null,{""City"":""MyCity""},true,1]";

            string[] expectedObjects = { @"""foo""", @"null", @"{""City"":""MyCity""}", @"true", @"1" };

            var address = new Address();

            address.Initialize();

            var    array = new object[] { 1, true, address, null, "foo" };
            string json  = JsonSerializer.Serialize(array);

            Assert.Equal(ExpectedJson, json);

            var dictionary = new Dictionary <string, string> {
                { "City", "MyCity" }
            };
            var arrayWithDictionary = new object[] { 1, true, dictionary, null, "foo" };

            json = JsonSerializer.Serialize(arrayWithDictionary);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(array);
            Assert.Equal(ExpectedJson, json);

            List <object> list = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(list);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(list);
            Assert.Equal(ExpectedJson, json);

            IEnumerable ienumerable = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(ienumerable);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(ienumerable);
            Assert.Equal(ExpectedJson, json);

            IList ilist = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(ilist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(ilist);
            Assert.Equal(ExpectedJson, json);

            ICollection icollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(icollection);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(icollection);
            Assert.Equal(ExpectedJson, json);

            IEnumerable <object> genericIEnumerable = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIEnumerable);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIEnumerable);
            Assert.Equal(ExpectedJson, json);

            IList <object> genericIList = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIList);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIList);
            Assert.Equal(ExpectedJson, json);

            ICollection <object> genericICollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericICollection);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericICollection);
            Assert.Equal(ExpectedJson, json);

            IReadOnlyCollection <object> genericIReadOnlyCollection = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIReadOnlyCollection);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIReadOnlyCollection);
            Assert.Equal(ExpectedJson, json);

            IReadOnlyList <object> genericIReadonlyList = new List <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(genericIReadonlyList);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(genericIReadonlyList);
            Assert.Equal(ExpectedJson, json);

            ISet <object> iset = new HashSet <object> {
                1, true, address, null, "foo"
            };

            json = JsonSerializer.Serialize(iset);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iset);
            Assert.Equal(ExpectedJson, json);

            Stack <object> stack = new Stack <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(stack);
            Assert.Equal(ReversedExpectedJson, json);

            json = JsonSerializer.Serialize <object>(stack);
            Assert.Equal(ReversedExpectedJson, json);

            Queue <object> queue = new Queue <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(queue);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(queue);
            Assert.Equal(ExpectedJson, json);

            HashSet <object> hashset = new HashSet <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(hashset);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(hashset);
            Assert.Equal(ExpectedJson, json);

            LinkedList <object> linkedlist = new LinkedList <object>(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(linkedlist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(linkedlist);
            Assert.Equal(ExpectedJson, json);

            ImmutableArray <object> immutablearray = ImmutableArray.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablearray);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablearray);
            Assert.Equal(ExpectedJson, json);

            IImmutableList <object> iimmutablelist = ImmutableList.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutablelist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iimmutablelist);
            Assert.Equal(ExpectedJson, json);

            IImmutableStack <object> iimmutablestack = ImmutableStack.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iimmutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            IImmutableQueue <object> iimmutablequeue = ImmutableQueue.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutablequeue);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(iimmutablequeue);
            Assert.Equal(ExpectedJson, json);

            IImmutableSet <object> iimmutableset = ImmutableHashSet.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(iimmutableset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            json = JsonSerializer.Serialize <object>(iimmutableset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            ImmutableHashSet <object> immutablehashset = ImmutableHashSet.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablehashset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            json = JsonSerializer.Serialize <object>(immutablehashset);
            foreach (string obj in expectedObjects)
            {
                Assert.Contains(obj, json);
            }

            ImmutableList <object> immutablelist = ImmutableList.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablelist);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablelist);
            Assert.Equal(ExpectedJson, json);

            ImmutableStack <object> immutablestack = ImmutableStack.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablestack);
            Assert.Equal(ReversedExpectedJson, json);

            ImmutableQueue <object> immutablequeue = ImmutableQueue.CreateRange(new List <object> {
                1, true, address, null, "foo"
            });

            json = JsonSerializer.Serialize(immutablequeue);
            Assert.Equal(ExpectedJson, json);

            json = JsonSerializer.Serialize <object>(immutablequeue);
            Assert.Equal(ExpectedJson, json);
        }
Esempio n. 55
0
        public override async Task <CompletionList> GetCompletionsAsync(
            Document document,
            int caretPosition,
            CompletionTrigger trigger,
            ImmutableHashSet <string> roles,
            OptionSet options,
            CancellationToken cancellationToken)
        {
            var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

            var defaultItemSpan = this.GetDefaultItemSpan(text, caretPosition);

            options = options ?? document.Project.Solution.Workspace.Options;
            var providers = GetProviders(roles, trigger);

            var completionProviderToIndex = GetCompletionProviderToIndex(providers);
            var completionRules           = this.GetRules();

            var triggeredProviders = ImmutableArray <CompletionProvider> .Empty;

            switch (trigger.Kind)
            {
            case CompletionTriggerKind.Insertion:
            case CompletionTriggerKind.Deletion:
                if (this.ShouldTriggerCompletion(text, caretPosition, trigger, roles, options))
                {
                    triggeredProviders = providers.Where(p => p.ShouldTriggerCompletion(text, caretPosition, trigger, options)).ToImmutableArrayOrEmpty();
                    if (triggeredProviders.Length == 0)
                    {
                        triggeredProviders = providers;
                    }
                }
                break;

            default:
                triggeredProviders = providers;
                break;
            }

            // Now, ask all the triggered providers if they can provide a group.
            var completionLists = new List <CompletionContext>();

            foreach (var provider in triggeredProviders)
            {
                var completionList = await GetProviderCompletionsAsync(provider, document, caretPosition, defaultItemSpan, trigger, options, cancellationToken).ConfigureAwait(false);

                if (completionList != null)
                {
                    completionLists.Add(completionList);
                }
            }

            // See if there was a group provided that was exclusive and had items in it.  If so, then
            // that's all we'll return.
            var firstExclusiveList = completionLists.FirstOrDefault(t => t.IsExclusive && t.Items.Any());

            if (firstExclusiveList != null)
            {
                return(MergeAndPruneCompletionLists(SpecializedCollections.SingletonEnumerable(firstExclusiveList), defaultItemSpan));
            }

            // If no exclusive providers provided anything, then go through the remaining
            // triggered list and see if any provide items.
            var nonExclusiveLists = completionLists.Where(t => !t.IsExclusive).ToList();

            // If we still don't have any items, then we're definitely done.
            if (!nonExclusiveLists.Any(g => g.Items.Any()))
            {
                return(null);
            }

            // If we do have items, then ask all the other (non exclusive providers) if they
            // want to augment the items.
            var usedProviders            = nonExclusiveLists.Select(g => g.Provider);
            var nonUsedProviders         = providers.Except(usedProviders);
            var nonUsedNonExclusiveLists = new List <CompletionContext>();

            foreach (var provider in nonUsedProviders)
            {
                var completionList = await GetProviderCompletionsAsync(provider, document, caretPosition, defaultItemSpan, trigger, options, cancellationToken).ConfigureAwait(false);

                if (completionList != null && !completionList.IsExclusive)
                {
                    nonUsedNonExclusiveLists.Add(completionList);
                }
            }

            var allProvidersAndLists = nonExclusiveLists.Concat(nonUsedNonExclusiveLists).ToList();

            if (allProvidersAndLists.Count == 0)
            {
                return(null);
            }

            // Providers are ordered, but we processed them in our own order.  Ensure that the
            // groups are properly ordered based on the original providers.
            allProvidersAndLists.Sort((p1, p2) => completionProviderToIndex[p1.Provider] - completionProviderToIndex[p2.Provider]);

            return(MergeAndPruneCompletionLists(allProvidersAndLists, defaultItemSpan));
        }
Esempio n. 56
0
 /// <summary>
 /// Prevents a default instance of the <see cref="TypeCollection"/> class from being created.
 /// </summary>
 private TypeCollection()
 {
     this.TypeSet = ImmutableHashSet.Create <Type>();
 }
Esempio n. 57
0
 private static void CategorizeLines(string line, int lineNumber, ImmutableHashSet <int> .Builder noSonar, ImmutableHashSet <int> .Builder nonBlank)
 {
     if (line.Contains("NOSONAR"))
     {
         nonBlank.Remove(lineNumber);
         noSonar.Add(lineNumber);
     }
     else
     {
         if (HasValidCommentContent(line) &&
             !noSonar.Contains(lineNumber))
         {
             nonBlank.Add(lineNumber);
         }
     }
 }
Esempio n. 58
0
 public AbstractSyntaxAnalyzer(ImmutableHashSet <ISymbol> symbols)
 {
     _symbols = symbols;
 }
Esempio n. 59
0
        //TODO: Logging receive?
        protected override void OnReceive(object message)
        {
            var createServerFSM = message as CreateServerFSM;

            if (createServerFSM != null)
            {
                var channel = createServerFSM.Channel;
                var host    = channel.RemoteHost;
                var name    = host.ToEndPoint() + ":" + host.Port + "-server" + _generation++;
                Sender.Tell(
                    Context.ActorOf(
                        new Props(typeof(ServerFSM), new object[] { Self, channel }).WithDeploy(Deploy.Local), name));
                return;
            }
            var nodeInfo = message as NodeInfo;

            if (nodeInfo != null)
            {
                _barrier.Forward(nodeInfo);
                if (_nodes.ContainsKey(nodeInfo.Name))
                {
                    if (_initialParticipants > 0)
                    {
                        foreach (var ni in _nodes.Values)
                        {
                            ni.FSM.Tell(new ToClient <BarrierResult>(new BarrierResult("initial startup", false)));
                        }
                        _initialParticipants = 0;
                    }
                    nodeInfo.FSM.Tell(new ToClient <BarrierResult>(new BarrierResult("initial startup", false)));
                }
                else
                {
                    _nodes = _nodes.Add(nodeInfo.Name, nodeInfo);
                    if (_initialParticipants <= 0)
                    {
                        nodeInfo.FSM.Tell(new ToClient <Done>(Done.Instance));
                    }
                    else if (_nodes.Count == _initialParticipants)
                    {
                        foreach (var ni in _nodes.Values)
                        {
                            ni.FSM.Tell(new ToClient <Done>(Done.Instance));
                        }
                        _initialParticipants = 0;
                    }
                    if (_addrInterest.ContainsKey(nodeInfo.Name))
                    {
                        foreach (var a in _addrInterest[nodeInfo.Name])
                        {
                            a.Tell(new ToClient <AddressReply>(new AddressReply(nodeInfo.Name, nodeInfo.Addr)));
                        }
                        _addrInterest = _addrInterest.Remove(nodeInfo.Name);
                    }
                }
            }
            var clientDisconnected = message as ClientDisconnected;

            if (clientDisconnected != null && clientDisconnected.Name != null)
            {
                _nodes = _nodes.Remove(clientDisconnected.Name);
                _barrier.Forward(clientDisconnected);
                return;
            }
            if (message is IServerOp)
            {
                if (message is EnterBarrier)
                {
                    _barrier.Forward(message);
                    return;
                }
                if (message is FailBarrier)
                {
                    _barrier.Forward(message);
                    return;
                }
                var getAddress = message as GetAddress;
                if (getAddress != null)
                {
                    var node = getAddress.Node;
                    if (_nodes.ContainsKey(node))
                    {
                        Sender.Tell(new ToClient <AddressReply>(new AddressReply(node, _nodes[node].Addr)));
                    }
                    else
                    {
                        ImmutableHashSet <IActorRef> existing;
                        _addrInterest = _addrInterest.SetItem(node,
                                                              (_addrInterest.TryGetValue(node, out existing)
                                ? existing
                                : ImmutableHashSet.Create <IActorRef>()
                                                              ).Add(Sender));
                    }
                    return;
                }
                if (message is Done)
                {
                    return;                  //FIXME what should happen?
                }
            }
            if (message is ICommandOp)
            {
                var throttle = message as Throttle;
                if (throttle != null)
                {
                    var t = _nodes[throttle.Target];
                    _nodes[throttle.Node].FSM.Forward(new ToClient <ThrottleMsg>(new ThrottleMsg(t.Addr, throttle.Direction, throttle.RateMBit)));
                    return;
                }
                var disconnect = message as Disconnect;
                if (disconnect != null)
                {
                    var t = _nodes[disconnect.Target];
                    _nodes[disconnect.Node].FSM.Forward((new ToClient <DisconnectMsg>(new DisconnectMsg(t.Addr, disconnect.Abort))));
                    return;
                }
                var terminate = message as Terminate;
                if (terminate != null)
                {
                    _barrier.Tell(new BarrierCoordinator.RemoveClient(terminate.Node));
                    _nodes[terminate.Node].FSM.Forward(new ToClient <TerminateMsg>(new TerminateMsg(terminate.ShutdownOrExit)));
                    _nodes = _nodes.Remove(terminate.Node);
                    return;
                }
                var remove = message as Remove;
                if (remove != null)
                {
                    _barrier.Tell(new BarrierCoordinator.RemoveClient(remove.Node));
                    return;
                }
            }
            if (message is GetNodes)
            {
                Sender.Tell(_nodes.Keys);
                return;
            }
            if (message is GetSockAddr)
            {
                Sender.Tell(_connection.Local);
                return;
            }
        }
 public MemberOverrideReflectedGenHandler(IReadOnlyList <ReflectedGenMemberOverride> memberOverrides)
 {
     _memberOverrides     = memberOverrides;
     _memberPathOverrides = ImmutableHashSet.Create(_memberOverrides.Select(x => x.Path).ToArray());
 }