public SymbolImplementation BuildMethod(SourceMethodDefinitionSymbol methodSymbol)
        {
            var methodBody = methodSymbol.Syntax.Body;
            var symbolTable = (ISymbolTable) methodSymbol.Parent;

            _rootScope = new SymbolScope(symbolTable);
            _currentScope = _rootScope;

            var symbolContext = methodSymbol;
            var implementationNode = methodBody;

            var statements = new List<BoundStatement>();
            var statementBuilder = new StatementBinder(this, symbolContext, _diagnostics);

            if (symbolContext.Parameters != null)
            {
                int parameterCount = symbolContext.Parameters.Length;
                for (int paramIndex = 0; paramIndex < parameterCount; paramIndex++)
                    _currentScope.AddSymbol(symbolContext.Parameters[paramIndex]);
            }

            foreach (var statementNode in implementationNode.Statements)
            {
                var statement = statementBuilder.BuildStatement(statementNode);
                if (statement != null)
                    statements.Add(statement);
            }

            return new SymbolImplementation(statements.ToImmutableArray(), _rootScope);
        }
		internal static ImmutableArray<TypeToRemove> GetTypesToRemove(
			this SyntaxNode @this, SemanticModel model, 
			string documentFileNameWithoutExtension)
		{
			var typesToRemove = new List<TypeToRemove>();
			TypeDeclarationSyntax typeToPreserve = null;

			var typeNodes = @this.DescendantNodes(_ => true)
				.OfType<TypeDeclarationSyntax>();

			foreach(var typeNode in typeNodes)
			{
				var type = model.GetDeclaredSymbol(typeNode) as ITypeSymbol;

				if(type.ContainingType == null)
				{
					if(type.Name != documentFileNameWithoutExtension)
					{
						typesToRemove.Add(new TypeToRemove(
							typeNode, type));
					}
					else
					{
						typeToPreserve = typeNode;
					}
				}
			}

			return typesToRemove.ToImmutableArray();
		}
                private ImmutableArray<int> ComputePathFromRoot(SyntaxNode node)
                {
                    var path = new List<int>();
                    var root = _tree.GetRoot();

                    while (node != root)
                    {
                        for (; node.Parent != null; node = node.Parent)
                        {
                            var index = GetChildIndex(node);
                            path.Add(index);
                        }

                        // if we were part of structure trivia, continue searching until we get to the true root
                        if (node.IsStructuredTrivia)
                        {
                            var trivia = node.ParentTrivia;
                            var triviaIndex = GetTriviaIndex(trivia);
                            path.Add(triviaIndex);
                            var tokenIndex = GetChildIndex(trivia.Token);
                            path.Add(tokenIndex);
                            node = trivia.Token.Parent;
                            continue;
                        }
                        else if (node != root)
                        {
                            throw new InvalidOperationException(CSharpWorkspaceResources.Node_does_not_descend_from_root);
                        }
                    }

                    path.Reverse();
                    return path.ToImmutableArray();
                }
Example #4
0
        private ImmutableArray<TodoCommentDescriptor> Parse(string data)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                return ImmutableArray<TodoCommentDescriptor>.Empty;
            }

            var tuples = data.Split('|');
            var result = new List<TodoCommentDescriptor>(tuples.Length);

            foreach (var tuple in tuples)
            {
                if (string.IsNullOrWhiteSpace(tuple))
                {
                    continue;
                }

                var pair = tuple.Split(':');

                if (pair.Length != 2 || string.IsNullOrWhiteSpace(pair[0]))
                {
                    continue;
                }

                int priority;
                if (!int.TryParse(pair[1], NumberStyles.None, CultureInfo.InvariantCulture, out priority))
                {
                    continue;
                }

                result.Add(new TodoCommentDescriptor(pair[0].Trim(), priority));
            }

            return result.ToImmutableArray();
        }
Example #5
0
        public static UInt256 CalculateMerkleRoot(ImmutableArray<Transaction> transactions, out ImmutableArray<ImmutableArray<byte>> merkleTree)
        {
            var workingMerkleTree = new List<ImmutableArray<byte>>();

            var hashes = transactions.Select(tx => tx.Hash.ToByteArray().ToImmutableArray()).ToList();

            workingMerkleTree.AddRange(hashes);
            while (hashes.Count > 1)
            {
                workingMerkleTree.AddRange(hashes);

                // ensure row is even length
                if (hashes.Count % 2 != 0)
                    hashes.Add(hashes.Last());

                // pair up hashes in row ({1, 2, 3, 4} into {{1, 2}, {3, 4}}) and then hash the pairs
                // the result is the next row, which will be half the size of the current row
                hashes =
                    Enumerable.Range(0, hashes.Count / 2)
                    .Select(i => hashes[i * 2].AddRange(hashes[i * 2 + 1]))
                    //.AsParallel().AsOrdered().WithExecutionMode(ParallelExecutionMode.ForceParallelism).WithDegreeOfParallelism(10)
                    .Select(pair => Crypto.DoubleSHA256(pair.ToArray()).ToImmutableArray())
                    .ToList();
            }
            Debug.Assert(hashes.Count == 1);

            merkleTree = workingMerkleTree.ToImmutableArray();
            return new UInt256(hashes[0].ToArray());
        }
Example #6
0
        internal ArenaBehavior(World world, List<Team> teams)
        {
            Requires.NotNull(world, nameof(world));
            Requires.NotNull(teams, nameof(teams));

            this.world = world;
            this.teams = teams.ToImmutableArray();
        }
Example #7
0
        public void ConcurrentAccess()
        {
            var source =
@"class A
{
    B F;
    D P { get; set; }
    void M(A a, B b, S s, I i) { }
    delegate void D(S s);
    class B { }
    struct S { }
    interface I { }
}
class B
{
    A M<T, U>() where T : A where U : T, I { return null; }
    event D E;
    delegate void D(S s);
    struct S { }
    interface I { }
}";

            var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
            var compilation1 = compilation0.WithSource(source);

            var builder = new List<Symbol>();
            var type = compilation1.GetMember<NamedTypeSymbol>("A");
            builder.Add(type);
            builder.AddRange(type.GetMembers());
            type = compilation1.GetMember<NamedTypeSymbol>("B");
            builder.Add(type);
            builder.AddRange(type.GetMembers());
            var members = builder.ToImmutableArray();
            Assert.True(members.Length > 10);

            for (int i = 0; i < 10; i++)
            {
                var matcher = new CSharpSymbolMatcher(
                    null,
                    compilation1.SourceAssembly,
                    default(EmitContext),
                    compilation0.SourceAssembly,
                    default(EmitContext),
                    null);

                var tasks = new Task[10];
                for (int j = 0; j < tasks.Length; j++)
                {
                    int startAt = i + j + 1;
                    tasks[j] = Task.Run(() =>
                    {
                        MatchAll(matcher, members, startAt);
                        Thread.Sleep(10);
                    });
                }
                Task.WaitAll(tasks);
            }
        }
Example #8
0
        /// <summary>
        /// Updates the general options.
        /// </summary>
        /// <param name="disableRuleGroups">
        /// The rules that can be turned off for the formatter.
        /// </param>
        /// <param name="tabSize">
        /// How big in spaces the indents are when you format
        /// </param>
        /// <param name="indentSize">
        /// How big in spaces the indents are when you press tab,
        /// </param>
        /// <param name="usingTabs">
        /// Whether or not Keep Tabs is on or off.
        /// </param>
        public FormattingOptions(
            List<DisableableRules> disableRuleGroups,
            uint tabSize, uint indentSize, bool usingTabs)
        {
            Requires.NotNull(disableRuleGroups, nameof(disableRuleGroups));

            this.TabSize = tabSize;
            this.IndentSize = indentSize;
            this.UsingTabs = usingTabs;
            this.RuleGroupsToDisable = disableRuleGroups.ToImmutableArray();
            this.OptionalRuleMap = new OptionalRuleMap(this.RuleGroupsToDisable);
        }
Example #9
0
        private BoundNode BindTypedefStatement(TypedefStatementSyntax declaration)
        {
            var boundType = Bind(declaration.Type, x => BindType(x, null));

            var boundDeclarations = new List<BoundTypeAlias>();
            foreach (var declarator in declaration.Declarators)
            {
                boundDeclarations.Add(Bind(declarator, x => BindTypeAlias(x, boundType.TypeSymbol)));
            }

            return new BoundTypedefStatement(boundDeclarations.ToImmutableArray());
        }
Example #10
0
        static IntrinsicSemantics()
        {
            var allSemantics = new List<SemanticSymbol>();

            // D3D10
            allSemantics.Add(new SemanticSymbol("SV_ClipDistance", "Clip distance data. SV_ClipDistance values are each assumed to be a float32 signed distance to a plane. Primitive setup only invokes rasterization on pixels for which the interpolated plane distance(s) are >= 0. Multiple clip planes can be implemented simultaneously, by declaring multiple component(s) of one or more vertex elements as the SV_ClipDistance. The combined clip and cull distance values are at most D3D#_CLIP_OR_CULL_DISTANCE_COUNT components in at most D3D#_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT registers.", true, SemanticUsages.AllShaders & ~SemanticUsages.VertexShaderInput, IntrinsicTypes.Float));
            allSemantics.Add(new SemanticSymbol("SV_CullDistance", "Cull distance data. When component(s) of vertex Element(s) are given this label, these values are each assumed to be a float32 signed distance to a plane. Primitives will be completely discarded if the plane distance(s) for all of the vertices in the primitive are < 0. Multiple cull planes can be used simultaneously, by declaring multiple component(s) of one or more vertex elements as the SV_CullDistance. The combined clip and cull distance values are at most D3D#_CLIP_OR_CULL_DISTANCE_COUNT components in at most D3D#_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT registers.", true, SemanticUsages.AllShaders & ~SemanticUsages.VertexShaderInput, IntrinsicTypes.Float));
            allSemantics.Add(new SemanticSymbol("SV_Coverage", "A mask that can be specified on input, output, or both of a pixel shader.\n\nFor SV_Coverage on a pixel shader, OUTPUT is supported on ps_4_1 or higher.\n\nFor SV_Coverage on a pixel shader, INPUT requires ps_5_0 or higher.", false, SemanticUsages.PixelShaderInput | SemanticUsages.PixelShaderOutput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_Depth", "Depth buffer data.", false, SemanticUsages.AllShaders, IntrinsicTypes.Float));
            allSemantics.Add(new SemanticSymbol("SV_DepthGreaterEqual", "Tests whether the value is greater than or equal to the depth data value.", true, SemanticUsages.PixelShaderOutput));
            allSemantics.Add(new SemanticSymbol("SV_DepthLessEqual", "Tests whether the value is less than or equal to the depth data value.", true, SemanticUsages.PixelShaderOutput));
            allSemantics.Add(new SemanticSymbol("SV_DispatchThreadID", "Defines the global thread offset within the Dispatch call, per dimension of the group. (read only)", false, SemanticUsages.ComputeShaderInput, IntrinsicTypes.Uint3));
            allSemantics.Add(new SemanticSymbol("SV_DomainLocation", "Defines the location on the hull of the current domain point being evaluated. (read only)", false, SemanticUsages.DomainShaderInput, IntrinsicTypes.Float2, IntrinsicTypes.Float3));
            allSemantics.Add(new SemanticSymbol("SV_GroupID", "Defines the group offset within a Dispatch call, per dimension of the dispatch call. (read only)", false, SemanticUsages.ComputeShaderInput, IntrinsicTypes.Uint3));
            allSemantics.Add(new SemanticSymbol("SV_GroupIndex", "Provides a flattened index for a given thread within a given group. (read only)", false, SemanticUsages.ComputeShaderInput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_GroupThreadID", "Defines the thread offset within the group, per dimension of the group. (read only)", false, SemanticUsages.ComputeShaderInput, IntrinsicTypes.Uint3));
            allSemantics.Add(new SemanticSymbol("SV_GSInstanceID", "Defines the instance of the geometry shader. The instance is needed as a geometry shader can be invoked up to 32 times on the same geometry primitive.", false, SemanticUsages.GeometryShaderInput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_InnerCoverage", "Represents underestimated conservative rasterization information (i.e. whether a pixel is guaranteed-to-be-fully covered).", false, SemanticUsages.PixelShaderInput | SemanticUsages.PixelShaderOutput));
            allSemantics.Add(new SemanticSymbol("SV_InsideTessFactor", "Defines the tessellation amount within a patch surface.", false, SemanticUsages.HullShaderOutput | SemanticUsages.DomainShaderInput, IntrinsicTypes.Float, IntrinsicTypes.Float2));
            allSemantics.Add(new SemanticSymbol("SV_InstanceID", "Per-instance identifier automatically generated by the runtime.", false, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("SV_IsFrontFace", "Specifies whether a triangle is front facing. For lines and points, IsFrontFace has the value true. The exception is lines drawn out of triangles (wireframe mode), which sets IsFrontFace the same way as rasterizing the triangle in solid mode.", false, SemanticUsages.GeometryShaderOutput | SemanticUsages.PixelShaderInput, IntrinsicTypes.Bool));
            allSemantics.Add(new SemanticSymbol("SV_OutputControlPointID", "Defines the index of the control point ID being operated on by an invocation of the main entry point of the hull shader.", false, SemanticUsages.HullShaderInput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_Position", "When SV_Position is declared for input to a shader, it can have one of two interpolation modes specified: linearNoPerspective or linearNoPerspectiveCentroid, where the latter causes centroid-snapped xyzw values to be provided when multisample antialiasing. When used in a shader, SV_Position describes the pixel location. Available in all shaders to get the pixel center with a 0.5 offset.", false, SemanticUsages.VertexShaderOutput | SemanticUsages.GeometryShaderInput | SemanticUsages.GeometryShaderOutput | SemanticUsages.PixelShaderInput, IntrinsicTypes.Float4));
            allSemantics.Add(new SemanticSymbol("SV_PrimitiveID", "Per-primitive identifier automatically generated by the runtime.", false, SemanticUsages.GeometryShaderOutput | SemanticUsages.PixelShaderOutput | SemanticUsages.GeometryShaderInput | SemanticUsages.PixelShaderInput | SemanticUsages.HullShaderInput | SemanticUsages.DomainShaderInput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_RenderTargetArrayIndex", "Render-target array index. Applied to geometry shader output and indicates the render target array slice that the primitive will be drawn to by the pixel shader. SV_RenderTargetArrayIndex is only valid if the render target is an array resource. This semantic applies only to primitives, if a primitive has more than one vertex the value from the leading vertex will be used.\nThis value also indicates which array slice of a depthstencilview is used for read / write purposes.", false, SemanticUsages.GeometryShaderOutput | SemanticUsages.PixelShaderInput | SemanticUsages.PixelShaderOutput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_SampleIndex", "Sample frequency index data.", false, SemanticUsages.PixelShaderInput | SemanticUsages.PixelShaderOutput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_StencilRef", "Represents the current pixel shader stencil reference value.", false, SemanticUsages.PixelShaderOutput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_Target", "The output value that will be stored in a render target. The index indicates which of the 8 possibly bound render targets to write to.", true, SemanticUsages.PixelShaderOutput, IntrinsicTypes.Float));
            allSemantics.Add(new SemanticSymbol("SV_TessFactor", "Defines the tessellation amount on each edge of a patch. Available for writing in the hull shader and reading in the domain shader.", false, SemanticUsages.HullShaderOutput | SemanticUsages.DomainShaderInput, IntrinsicTypes.Float2, IntrinsicTypes.Float3, IntrinsicTypes.Float4));
            allSemantics.Add(new SemanticSymbol("SV_VertexID", "Per-vertex identifier automatically generated by the runtime.", false, SemanticUsages.VertexShaderInput, IntrinsicTypes.Uint));
            allSemantics.Add(new SemanticSymbol("SV_ViewportArrayIndex", "Viewport array index. Applied to geometry shader output and indicates which viewport to use for the primitive currently being written out. The primitive will be transformed and clipped against the viewport specified by the index before it is passed to the rasterizer. This semantic applies only to primitives, if a primitive has more than one vertex the value from the leading vertex will be used.", false, SemanticUsages.GeometryShaderOutput | SemanticUsages.PixelShaderInput | SemanticUsages.PixelShaderOutput, IntrinsicTypes.Uint));

            // D3D9
            allSemantics.Add(new SemanticSymbol("BINORMAL", "Binormal.", true, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("BLENDINDICES", "Blend indices.", true, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("BLENDWEIGHT", "Blend weights.", true, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("COLOR", "Diffuse or specular color.", true, SemanticUsages.VertexShaderInput | SemanticUsages.VertexShaderOutput | SemanticUsages.PixelShaderInput | SemanticUsages.PixelShaderOutput));
            allSemantics.Add(new SemanticSymbol("NORMAL", "Normal vector.", true, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("POSITION", "Used as input: Vertex position in object space.\nUsed as output: Position of a vertex in homogenous space. Compute position in screen-space by dividing (x,y,z) by w. Every (D3D9) vertex shader must write out a parameter with this semantic.", true, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("POSITIONT", "Transformed vertex position.", false, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("PSIZE", "Point size.", true, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("TANGENT", "Tangent.", true, SemanticUsages.VertexShaderInput));
            allSemantics.Add(new SemanticSymbol("TEXCOORD", "Texture coordinates", true, SemanticUsages.VertexShaderInput | SemanticUsages.VertexShaderOutput | SemanticUsages.PixelShaderInput));
            allSemantics.Add(new SemanticSymbol("FOG", "Vertex fog.", false, SemanticUsages.VertexShaderOutput));
            allSemantics.Add(new SemanticSymbol("PSIZE", "Point size.", true, SemanticUsages.VertexShaderOutput | SemanticUsages.PixelShaderInput));
            allSemantics.Add(new SemanticSymbol("TESSFACTOR", "Tessellation factor.", true, SemanticUsages.VertexShaderOutput));
            allSemantics.Add(new SemanticSymbol("VFACE", "Floating-point scalar that indicates a back-facing primitive. A negative value faces backwards, while a positive value faces the camera.\nNote  This semantic is available in Direct3D 9 Shader Model 3.0. For Direct3D 10 and later, use SV_IsFrontFace instead.", false, SemanticUsages.PixelShaderInput));
            allSemantics.Add(new SemanticSymbol("VPOS", "The pixel location (x,y) in screen space.", false, SemanticUsages.PixelShaderInput));
            allSemantics.Add(new SemanticSymbol("DEPTH", "Depth.", true, SemanticUsages.PixelShaderOutput));

            AllSemantics = allSemantics.ToImmutableArray();
        }
Example #11
0
 public Agent(string assignment, Book book)
     : base("Agent", assignment, book)
 {
     var careers = new List<NormalCareer>
     {
         new Corporate(book),
         new Worker(book),
         new Colonist(book),
         new Thief(book),
         new Enforcer(book),
         new Pirate(book)
     };
     m_Careers = careers.ToImmutableArray();
 }
Example #12
0
		internal static async Task TestProvider(string file, string fileName,
			Func<Solution, ProjectId, Solution> modifySolution,
			Func<ImmutableArray<CodeAction>, Task> handleActions)
		{
			var code = File.ReadAllText(file);
			var document = TestHelpers.CreateDocument(code, fileName, modifySolution);
			var actions = new List<CodeAction>();
			var actionRegistration = new Action<CodeAction>(action => actions.Add(action));
			var context = new CodeRefactoringContext(document, new TextSpan(0, 1),
				actionRegistration, new CancellationToken(false));

			var provider = new ExtractTypesToFilesCodeRefactoringProvider();
			await provider.ComputeRefactoringsAsync(context);
			await handleActions(actions.ToImmutableArray());
		}
            public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken)
            {
                var references = new List<InlineRenameLocation>();

                var renameLocations = await _renameInfo.FindRenameLocationsAsync(
                    renameInStrings: optionSet.GetOption(RenameOptions.RenameInStrings),
                    renameInComments: optionSet.GetOption(RenameOptions.RenameInComments),
                    cancellationToken: cancellationToken).ConfigureAwait(false);

                references.AddRange(renameLocations.Select(
                    ds => new InlineRenameLocation(ds.Document, ds.TextSpan)));

                return new InlineRenameLocationSet(
                    _renameInfo, _document.Project.Solution,
                    references.ToImmutableArray());
            }
Example #14
0
        private static ImmutableArray<Cell> ProcessLine(string line, int x)
        {
            var cells = new List<Cell>();

            for (var y = 0; y < line.Length; y++)
            {
                var value = line[y];

                if (value != ' ')
                {
                    cells.Add(new Cell(new Point(x, y), value));
                }
            }

            return cells.ToImmutableArray();
        }
Example #15
0
        public ImmutableArray<AlaCarteAssignmentModel> GetUnsentEmails()
        {
            if (SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref operating, 1, 0) != 0, TimeSpan.FromSeconds(30)))
            {
                try
                {
                    bool alreadyOpen = Connection.State == ConnectionState.Open;
                    if (!alreadyOpen)
                        Connection.Open();
                    try
                    {
                        IList<Exception> exceptions = null;
                        IList<AlaCarteAssignmentModel> emails = new List<AlaCarteAssignmentModel>();
                        using (var command = CreateCommand(Connection))
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                try
                                {
                                    var email = Load(reader);
                                    emails.Add(email);
                                }
                                catch(Exception ex)
                                {
                                    (exceptions ?? (exceptions = new List<Exception>(1))).Add(ex);
                                }
                            }
                        }

                        return emails.ToImmutableArray();
                    }
                    finally
                    {
                        if (!alreadyOpen && Connection != null)
                            Connection.Close();
                    }
                }
                finally
                {
                    Interlocked.CompareExchange(ref operating, 0, 1);
                }
            }
            return ImmutableArray<AlaCarteAssignmentModel>.Empty;
        }
Example #16
0
        private static ImmutableArray<DiagnosticAnalyzer> GetAllAnalyzers()
        {
            Assembly assembly = typeof(StyleCop.Analyzers.NoCodeFixAttribute).Assembly;

            var diagnosticAnalyzerType = typeof(DiagnosticAnalyzer);

            List<DiagnosticAnalyzer> analyzers = new List<DiagnosticAnalyzer>();

            foreach (var type in assembly.GetTypes())
            {
                if (type.IsSubclassOf(diagnosticAnalyzerType) && !type.IsAbstract)
                {
                    analyzers.Add((DiagnosticAnalyzer)Activator.CreateInstance(type));
                }
            }

            return analyzers.ToImmutableArray();
        }
Example #17
0
 public static ImmutableArray<IMarkdownToken> ParseInlineToken(
     IMarkdownParser parser,
     IMarkdownRule rule,
     ImmutableArray<IMarkdownToken> blockTokens,
     bool wrapParagraph)
 {
     var result = new List<IMarkdownToken>(blockTokens.Length);
     var textContent = StringBuffer.Empty;
     foreach (var token in blockTokens)
     {
         var text = token as MarkdownTextToken;
         if (text != null)
         {
             if (textContent != StringBuffer.Empty)
             {
                 textContent += "\n";
             }
             textContent += text.Content;
             continue;
         }
         var newLine = token as MarkdownNewLineBlockToken;
         if (newLine?.RawMarkdown.Length == 1)
         {
             continue;
         }
         if (textContent != StringBuffer.Empty)
         {
             var rawMarkdown = textContent.ToString();
             result.Add(CreateToken(parser, rule, wrapParagraph, rawMarkdown));
             textContent = StringBuffer.Empty;
         }
         if (newLine != null)
         {
             continue;
         }
         result.Add(token);
     }
     if (textContent != StringBuffer.Empty)
     {
         var rawMarkdown = textContent.ToString();
         result.Add(CreateToken(parser, rule, wrapParagraph, rawMarkdown));
     }
     return result.ToImmutableArray();
 }
Example #18
0
        public ImmutableArray<Cell> Parse()
        {
            var cells = new List<Cell>();

            if (this.lines != null)
            {
                for (var i = 0; i < this.lines.Length; i++)
                {
                    var line = this.lines[i];

                    if (line != null)
                    {
                        cells.AddRange(Parser.ProcessLine(line, i));
                    }
                }
            }

            return cells.ToImmutableArray();
        }
Example #19
0
 public static ImmutableArray<IMarkdownToken> CreateParagraghs(
     IMarkdownParser parser,
     IMarkdownRule rule,
     ImmutableArray<IMarkdownToken> blockTokens,
     bool wrapParagraph,
     SourceInfo sourceInfo)
 {
     var result = new List<IMarkdownToken>(blockTokens.Length);
     var textContent = StringBuffer.Empty;
     var si = sourceInfo;
     foreach (var token in blockTokens)
     {
         var text = token as MarkdownTextToken;
         if (text != null)
         {
             if (textContent == StringBuffer.Empty)
             {
                 si = text.SourceInfo;
             }
             textContent += text.Content;
             continue;
         }
         if (textContent != StringBuffer.Empty)
         {
             result.Add(GroupTextTokens(parser, rule, wrapParagraph, textContent, si));
             textContent = StringBuffer.Empty;
         }
         if (token is MarkdownNewLineBlockToken)
         {
             continue;
         }
         result.Add(token);
     }
     if (textContent != StringBuffer.Empty)
     {
         result.Add(GroupTextTokens(parser, rule, wrapParagraph, textContent, si));
     }
     return result.ToImmutableArray();
 }
Example #20
0
        private BoundInterfaceType BindInterfaceDeclaration(InterfaceTypeSyntax declaration, Symbol parent)
        {
            var interfaceSymbol = new InterfaceSymbol(declaration, parent);
            AddSymbol(interfaceSymbol, declaration.Name.Span);

            var methods = new List<BoundFunction>();
            var interfaceBinder = new Binder(_sharedBinderState, this);
            foreach (var memberSyntax in declaration.Methods)
                methods.Add(interfaceBinder.Bind(memberSyntax, x => interfaceBinder.BindFunctionDeclaration(x, interfaceSymbol)));

            foreach (var member in interfaceBinder.LocalSymbols.Values.SelectMany(x => x))
                interfaceSymbol.AddMember(member);

            return new BoundInterfaceType(interfaceSymbol, methods.ToImmutableArray());
        }
        private async Task<ImmutableArray<CodeAction>> GetOfferedFixesInternalAsync(string language, string source, int? diagnosticIndex, ImmutableArray<DiagnosticAnalyzer> analyzers, CodeFixProvider codeFixProvider, CancellationToken cancellationToken)
        {
            var document = this.CreateDocument(source, language);
            var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzers, new[] { document }, cancellationToken).ConfigureAwait(false);

            var index = diagnosticIndex.HasValue ? diagnosticIndex.Value : 0;

            Assert.True(index < analyzerDiagnostics.Count());

            var actions = new List<CodeAction>();
            var context = new CodeFixContext(document, analyzerDiagnostics[index], (a, d) => actions.Add(a), cancellationToken);
            await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(false);

            return actions.ToImmutableArray();
        }
Example #22
0
        static IntrinsicAttributes()
        {
            var allAttributes = new List<AttributeSymbol>();

            allAttributes.Add(Create("allow_uav_condition", "Allows a compute shader loop termination condition to be based off of a UAV read. The loop must not contain synchronization intrinsics."));
            allAttributes.Add(Create("branch", "When applied to if statements: Evaluate only one side of the if statement depending on the given condition.\nWhen applied to switch statements: Compile the statement as a series of if statements each with the branch attribute."));
            allAttributes.Add(Create("call", "The bodies of the individual cases in the switch will be moved into hardware subroutines and the switch will be a series of subroutine calls."));
            allAttributes.Add(Create("fastopt", "Reduces the compile time but produces less aggressive optimizations. If you use this attribute, the compiler will not unroll loops."));
            allAttributes.Add(Create("flatten", "When applied to if statements: Evaluate both sides of the if statement and choose between the two resulting values.\nWhen applied to switch statements: Compile the statement as a series of if statements, each with the flatten attribute."));
            allAttributes.Add(Create("forcecase", "Force a switch statement in the hardware."));
            allAttributes.Add(Create("loop", "Generate code that uses flow control to execute each iteration of the loop. Not compatible with the [unroll] attribute."));

            allAttributes.Add(Create("unroll", "Unroll the loop until it stops executing. Can optionally specify the maximum number of times the loop is to execute. Not compatible with the [loop] attribute.", a => new[]
            {
                new ParameterSymbol("count", "Maximum number of times the loop is to execute.", a, IntrinsicTypes.Int)
            }));

            allAttributes.Add(Create("clipplanes", "", a => new[]
            {
                new ParameterSymbol("clipPlane1", "", a, IntrinsicTypes.Float4),
                new ParameterSymbol("clipPlane2", "", a, IntrinsicTypes.Float4),
                new ParameterSymbol("clipPlane3", "", a, IntrinsicTypes.Float4),
                new ParameterSymbol("clipPlane4", "", a, IntrinsicTypes.Float4),
                new ParameterSymbol("clipPlane5", "", a, IntrinsicTypes.Float4),
                new ParameterSymbol("clipPlane6", "", a, IntrinsicTypes.Float4)
            }));

            allAttributes.Add(Create("domain", "Defines the patch type used in the HS.", a => new[]
            {
                new ParameterSymbol("domainType", "", a, IntrinsicTypes.String)
            }));

            allAttributes.Add(Create("earlydepthstencil", "Forces depth-stencil testing before a shader executes."));

            allAttributes.Add(Create("instance", "Use this attribute to instance a geometry shader.", a => new[]
            {
                new ParameterSymbol("count", "An integer index that indicates the number of instances to be executed for each drawn item (for example, for each triangle).", a, IntrinsicTypes.Int)
            }));

            allAttributes.Add(Create("maxtessfactor", "Indicates the maximum value that the hull shader would return for any tessellation factor.", a => new[]
            {
                new ParameterSymbol("factor", "Upper bound on the amount of tessellation requested to help a driver determine the maximum amount of resources required for tessellation.", a, IntrinsicTypes.Int)
            }));

            allAttributes.Add(Create("numthreads", "Defines the number of threads to be executed in a single thread group when a compute shader is dispatched.", a => new[]
            {
                new ParameterSymbol("x", "Size of the thread group in the X direction.", a, IntrinsicTypes.Int),
                new ParameterSymbol("y", "Size of the thread group in the Y direction.", a, IntrinsicTypes.Int),
                new ParameterSymbol("z", "Size of the thread group in the Z direction.", a, IntrinsicTypes.Int)
            }));

            allAttributes.Add(Create("outputcontrolpoints", "Defines the number of output control points (per thread) that will be created in the hull shader.", a => new[]
            {
                new ParameterSymbol("count", "", a, IntrinsicTypes.Int)
            }));

            allAttributes.Add(Create("outputtopology", "Defines the output primitive type for the tessellator.", a => new[]
            {
                new ParameterSymbol("topology", "Must be one of \"point\", \"line\", \"triangle_cw\", or \"triangle_ccw\".", a, IntrinsicTypes.String)
            }));

            allAttributes.Add(Create("partioning", "Defines the tesselation scheme to be used in the hull shader.", a => new[]
            {
                new ParameterSymbol("scheme", "Must be one of \"integer\", \"fractional_even\", \"fractional_odd\", or \"pow2\".", a, IntrinsicTypes.String)
            }));

            allAttributes.Add(Create("patchconstantfunc", "Defines the function for computing patch constant data.", a => new[]
            {
                new ParameterSymbol("functionName", "Name of a separate function that outputs the patch-constant data.", a, IntrinsicTypes.String)
            }));

            allAttributes.Add(Create("maxvertexcount", "Declares the maximum number of vertices to create.", a => new[]
            {
                new ParameterSymbol("count", "Maximum number of vertices.", a, IntrinsicTypes.Int)
            }));

            allAttributes.Add(Create("intrinsic", "", a => new[]
            {
                new ParameterSymbol("group", "", a, IntrinsicTypes.String),
                new ParameterSymbol("opcode", "", a, IntrinsicTypes.Int)
            }));

            allAttributes.Add(Create("RootSignature", "Defines the root signature.", a => new[]
            {
                new ParameterSymbol("signature", "", a, IntrinsicTypes.String)
            }));

            AllAttributes = allAttributes.ToImmutableArray();
        }
Example #23
0
        private BoundTypeAlias BindTypeAlias(TypeAliasSyntax syntax, TypeSymbol variableType)
        {
            variableType = BindArrayRankSpecifiers(syntax.ArrayRankSpecifiers, variableType);

            var symbol = new TypeAliasSymbol(syntax, variableType);
            AddSymbol(symbol, syntax.Identifier.Span);

            var boundQualifiers = new List<BoundVariableQualifier>();
            foreach (var qualifier in syntax.Qualifiers)
                boundQualifiers.Add(Bind(qualifier, BindVariableQualifier));

            return new BoundTypeAlias(symbol, variableType, boundQualifiers.ToImmutableArray());
        }
        /// <summary>
        /// Resolves metadata references stored in command line arguments and reports errors for those that can't be resolved.
        /// </summary>
        internal List<MetadataReference> ResolveMetadataReferences(
            List<DiagnosticInfo> diagnostics,
            TouchedFileLogger touchedFiles,
            out MetadataReferenceResolver referenceDirectiveResolver)
        {
            var commandLineReferenceResolver = GetCommandLineMetadataReferenceResolver(touchedFiles);

            List<MetadataReference> resolved = new List<MetadataReference>();
            Arguments.ResolveMetadataReferences(commandLineReferenceResolver, diagnostics, this.MessageProvider, resolved);

            if (Arguments.IsScriptRunner)
            {
                referenceDirectiveResolver = commandLineReferenceResolver;
            }
            else
            {
                // when compiling into an assembly (csc/vbc) we only allow #r that match references given on command line:
                referenceDirectiveResolver = new ExistingReferencesResolver(commandLineReferenceResolver, resolved.ToImmutableArray());
            }

            return resolved;
        }
Example #25
0
        //TODO move into p2p node
        private static ImmutableArray<UInt256> CalculateBlockLocatorHashes(IImmutableList<ChainedBlock> blockHashes)
        {
            var blockLocatorHashes = new List<UInt256>();

            if (blockHashes.Count > 0)
            {
                var step = 1;
                var start = 0;
                for (var i = blockHashes.Count - 1; i > 0; i -= step, start++)
                {
                    if (start >= 10)
                        step *= 2;

                    blockLocatorHashes.Add(blockHashes[i].BlockHash);
                }
                blockLocatorHashes.Add(blockHashes[0].BlockHash);
            }

            return blockLocatorHashes.ToImmutableArray();
        }
            private Model FilterModelInBackgroundWorker(
                Model model,
                int id,
                SnapshotPoint caretPosition,
                bool recheckCaretPosition,
                bool dismissIfEmptyAllowed,
                CompletionFilterReason filterReason)
            {
                if (model == null)
                {
                    return null;
                }

                var filterState = model.FilterState;

                // If all the filters are on, or all the filters are off then we don't actually 
                // need to filter.
                if (filterState != null)
                {
                    if (filterState.Values.All(b => b) ||
                        filterState.Values.All(b => !b))
                    {
                        filterState = null;
                    }
                }

                // We want to dismiss the session if the caret ever moved outside our bounds.
                if (recheckCaretPosition && Controller.IsCaretOutsideAllItemBounds(model, caretPosition))
                {
                    return null;
                }

                if (id != _filterId)
                {
                    return model;
                }

                var textSnapshot = caretPosition.Snapshot;
                var allFilteredItems = new List<PresentationItem>();
                var textSpanToText = new Dictionary<TextSpan, string>();
                var helper = this.Controller.GetCompletionHelper();

                // isUnique tracks if there is a single 
                bool? isUnique = null;
                PresentationItem bestFilterMatch = null;
                bool filterTextIsPotentialIdentifier = false;

                var recentItems = this.Controller.GetRecentItems();

                var itemToFilterText = new Dictionary<CompletionItem, string>();
                model = model.WithCompletionItemToFilterText(itemToFilterText);

                foreach (var currentItem in model.TotalItems)
                {
                    // Check if something new has happened and there's a later on filter operation
                    // in the chain.  If so, there's no need for us to do any more work (as it will
                    // just be superceded by the later work).
                    if (id != _filterId)
                    {
                        return model;
                    }

                    // We may have wrapped some items in the list in DescriptionModifying items,
                    // but we should use the actual underlying items when filtering. That way
                    // our rules can access the underlying item's provider.

                    if (ItemIsFilteredOut(currentItem.Item, filterState))
                    {
                        continue;
                    }

                    var filterText = model.GetCurrentTextInSnapshot(currentItem.Item.Span, textSnapshot, textSpanToText);
                    var matchesFilterText = MatchesFilterText(helper, currentItem.Item, filterText, model.Trigger, filterReason, recentItems);
                    itemToFilterText[currentItem.Item] = filterText;

                    if (matchesFilterText)
                    {
                        allFilteredItems.Add(currentItem);

                        // If we have no best match, or this match is better than the last match,
                        // then the current item is the best filter match.
                        if (bestFilterMatch == null ||
                            IsBetterFilterMatch(helper, currentItem.Item, bestFilterMatch.Item, filterText, model.Trigger, filterReason, recentItems))
                        {
                            bestFilterMatch = currentItem;
                        }

                        // If isUnique is null, then this is the first time we've seen an item that
                        // matches the filter text.  That item is now considered unique.  However, if
                        // isUnique is non-null, then this is the second (or third, or fourth, etc.)
                        // that a provider said to include. It's no longer unique.
                        //
                        // Note: We only want to do this if any filter text was actually provided.
                        // This is so we can handle the following cases properly:
                        //
                        //    Console.WriteLi$$
                        //
                        // If they try to commit unique item there, we want to commit to
                        // "WriteLine".  However, if they just have:
                        //
                        //    Console.$$
                        //
                        // And they try to commit unique item, we won't commit something just
                        // because it was in the MRU list.
                        if (filterText != string.Empty)
                        {
                            isUnique = isUnique == null || false;
                        }
                    }
                    else
                    {
                        if (filterText.Length <= 1)
                        {
                            // Even though the rule provider didn't match this, we'll still include it
                            // since we want to allow a user typing a single character and seeing all
                            // possibly completions.  However, we don't consider it either unique or a
                            // filter match, so we won't select it.
                            allFilteredItems.Add(currentItem);
                        }

                        // We want to dismiss the list if the user is typing a # and nothing matches
                        filterTextIsPotentialIdentifier = filterTextIsPotentialIdentifier ||
                            filterText.Length == 0 ||
                            (!char.IsDigit(filterText[0]) && filterText[0] != '-' && filterText[0] != '.');
                    }
                }

                if (!filterTextIsPotentialIdentifier && bestFilterMatch == null)
                {
                    // We had no matches, and the user is typing a #, dismiss the list
                    return null;
                }

                if (allFilteredItems.Count == 0)
                {
                    if (dismissIfEmptyAllowed &&
                        model.DismissIfEmpty &&
                        filterReason != CompletionFilterReason.BackspaceOrDelete)
                    {
                        return null;
                    }

                    if (model.FilterState != null && model.FilterState.Values.Any(b => b))
                    {
                        // If the user has turned on some filtering states, and we filtered down to 
                        // nothing, then we do want the UI to show that to them.
                        return model.WithFilteredItems(allFilteredItems.ToImmutableArray())
                                    .WithHardSelection(false)
                                    .WithIsUnique(false);
                    }
                    else
                    {
                        // If we are going to filter everything out, then just preserve the existing
                        // model, but switch over to soft selection.  Also, nothing is unique at that
                        // point.
                        return model.WithHardSelection(false)
                                    .WithIsUnique(false);
                    }
                }

                // If we have a best item, then select it.  Otherwise just use the first item
                // in the list.
                var selectedItem = bestFilterMatch ?? allFilteredItems.First();

                // If we have a best item, then we want to hard select it.  Otherwise we want
                // soft selection.  However, no hard selection if there's a builder.
                var hardSelection = IsHardSelection(model, bestFilterMatch, textSnapshot, helper, model.Trigger, filterReason);

                var result = model.WithFilteredItems(allFilteredItems.ToImmutableArray())
                                  .WithSelectedItem(selectedItem)
                                  .WithHardSelection(hardSelection)
                                  .WithIsUnique(isUnique.HasValue && isUnique.Value);

                return result;
            }
Example #27
0
        private VsixData VerifyVsixContentsBeforeSign(BinaryName vsixName, Dictionary<string, BinaryName> checksumToNameMap, ref bool allGood)
        {
            var nestedExternalBinaries = new List<string>();
            var nestedParts = new List<VsixPart>();
            using (var package = Package.Open(vsixName.FullPath, FileMode.Open, FileAccess.Read))
            {
                foreach (var part in package.GetParts())
                {
                    var relativeName = GetPartRelativeFileName(part);
                    var name = Path.GetFileName(relativeName);
                    if (!IsVsix(name) && !IsAssembly(name))
                    {
                        continue;
                    }

                    if (_signData.ExternalBinaryNames.Contains(name))
                    {
                        nestedExternalBinaries.Add(name);
                        continue;
                    }

                    if (!_signData.BinaryNames.Any(x => FilePathComparer.Equals(x.Name, name)))
                    {
                        allGood = false;
                        Console.WriteLine($"VSIX {vsixName} has part {name} which is not listed in the sign or external list");
                        continue;
                    }

                    // This represents a binary that we need to sign.  Ensure the content in the VSIX is the same as the 
                    // content in the binaries directory by doing a chekcsum match.
                    using (var stream = part.GetStream())
                    {
                        string checksum = _contentUtil.GetChecksum(stream);
                        BinaryName checksumName;
                        if (!checksumToNameMap.TryGetValue(checksum, out checksumName))
                        {
                            allGood = false;
                            Console.WriteLine($"{vsixName} has part {name} which does not match the content in the binaries directory");
                            continue;
                        }

                        if (!FilePathComparer.Equals(checksumName.Name, name))
                        {
                            allGood = false;
                            Console.WriteLine($"{vsixName} has part {name} with a different name in the binaries directory: {checksumName}");
                            continue;
                        }

                        nestedParts.Add(new VsixPart(relativeName, checksumName));
                    }
                }
            }

            return new VsixData(vsixName, nestedParts.ToImmutableArray(), nestedExternalBinaries.ToImmutableArray());
        }
Example #28
0
        public static async Task<ImmutableArray<ISymbol>> GetSymbolsAsync(CompletionItem item, Document document, CancellationToken cancellationToken)
        {
            string symbolIds;
            if (item.Properties.TryGetValue("Symbols", out symbolIds))
            {
                var idList = symbolIds.Split(s_symbolSplitters, StringSplitOptions.RemoveEmptyEntries).ToList();
                var symbols = new List<ISymbol>();

                var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
                DecodeSymbols(idList, compilation, symbols);

                // merge in symbols from other linked documents
                if (idList.Count > 0)
                {
                    var linkedIds = document.GetLinkedDocumentIds();
                    if (linkedIds.Length > 0)
                    {
                        foreach (var id in linkedIds)
                        {
                            var linkedDoc = document.Project.Solution.GetDocument(id);
                            var linkedCompilation = await linkedDoc.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
                            DecodeSymbols(idList, linkedCompilation, symbols);
                        }
                    }
                }

                return symbols.ToImmutableArray();
            }

            return ImmutableArray<ISymbol>.Empty;
        }
        private async Task TestFixAllWithMultipleEncodingsAsync(FixAllScope scope)
        {
            string[] testCode = new[] { "class Foo { }", "class Bar { }" };

            this.fileEncoding = Encoding.Unicode;

            // Create a project using the specified encoding
            Project project = this.CreateProject(testCode);

            project = project.AddDocument("Test2.cs", SourceText.From("class FooBar { }", Encoding.UTF7)).Project;

            Project oldProject = project;

            Workspace workspace = project.Solution.Workspace;

            var codeFixer = this.GetCSharpCodeFixProvider();
            var fixAllProvider = codeFixer.GetFixAllProvider();
            var diagnostics = new List<Diagnostic>();
            var descriptor = this.GetCSharpDiagnosticAnalyzers().First().SupportedDiagnostics.First();
            foreach (var document in project.Documents)
            {
                // Create a diagnostic for the document to fix
                var properties = ImmutableDictionary<string, string>.Empty.SetItem(SA1412StoreFilesAsUtf8.EncodingProperty, (await document.GetTextAsync().ConfigureAwait(false)).Encoding.WebName);
                var diagnostic = Diagnostic.Create(
                    descriptor,
                    Location.Create(await document.GetSyntaxTreeAsync().ConfigureAwait(false), TextSpan.FromBounds(0, 0)),
                    properties);
                diagnostics.Add(diagnostic);
            }

            FixAllContext fixAllContext = new FixAllContext(
                project.Documents.First(),
                codeFixer,
                scope,
                nameof(SA1412CodeFixProvider) + "." + this.fileEncoding.WebName,
                new[] { SA1412StoreFilesAsUtf8.DiagnosticId },
                TestDiagnosticProvider.Create(diagnostics.ToImmutableArray()),
                CancellationToken.None);

            CodeAction codeAction = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(false);
            var operation = codeAction.GetOperationsAsync(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()[0];

            operation.Apply(workspace, CancellationToken.None);

            // project should now have the "fixed document" in it.
            // Because of limitations in Roslyn the fixed document should
            // have a different DocumentId then the broken document
            project = workspace.CurrentSolution.Projects.First();

            Assert.Equal(3, project.DocumentIds.Count);

            // The order of the document ids is now different from the order before.
            for (int i = 1; i < 3; i++)
            {
                DocumentId documentId = project.DocumentIds[i];
                SourceText sourceText = await project.GetDocument(documentId).GetTextAsync().ConfigureAwait(false);

                Assert.Equal(testCode[i - 1], sourceText.ToString());

                Assert.Equal(Encoding.UTF8, sourceText.Encoding);
                Assert.NotEqual(oldProject.DocumentIds[i - 1], project.DocumentIds[i]);
            }

            // Check that Test2.cs was not changed
            DocumentId otherDocumentId = project.DocumentIds[0];
            var otherDocument = project.GetDocument(otherDocumentId);

            Assert.Equal("Test2.cs", otherDocument.Name);

            SourceText otherDocumentText = await otherDocument.GetTextAsync().ConfigureAwait(false);

            Assert.Equal("class FooBar { }", otherDocumentText.ToString());

            Assert.Equal(Encoding.UTF7, otherDocumentText.Encoding);
            Assert.Equal(oldProject.DocumentIds[2], project.DocumentIds[0]);
        }
        private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics(
            AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics,
            SyntaxTree tree, SyntaxNode member, int memberId)
        {
            // get old span
            var oldSpan = range[memberId];

            // get old diagnostics
            var diagnostics = existingData.Items;

            // check quick exit cases
            if (diagnostics.Length == 0 && memberDiagnostics.Length == 0)
            {
                return diagnostics;
            }

            // simple case
            if (diagnostics.Length == 0 && memberDiagnostics.Length > 0)
            {
                return memberDiagnostics;
            }

            // regular case
            var result = new List<DiagnosticData>();

            // update member location
            Contract.Requires(member.FullSpan.Start == oldSpan.Start);
            var delta = member.FullSpan.End - oldSpan.End;

            var replaced = false;
            foreach (var diagnostic in diagnostics)
            {
                if (diagnostic.TextSpan.Start < oldSpan.Start)
                {
                    result.Add(diagnostic);
                    continue;
                }

                if (!replaced)
                {
                    result.AddRange(memberDiagnostics);
                    replaced = true;
                }

                if (oldSpan.End <= diagnostic.TextSpan.Start)
                {
                    result.Add(UpdatePosition(diagnostic, tree, delta));
                    continue;
                }
            }

            // if it haven't replaced, replace it now
            if (!replaced)
            {
                result.AddRange(memberDiagnostics);
                replaced = true;
            }

            return result.ToImmutableArray();
        }