EditAndContinueTestHelpers.cs 17.0 KB
Newer Older
J
Jonathon Marolf 已提交
1 2 3
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
4 5 6 7 8 9 10 11 12 13 14 15 16

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
17
using static Microsoft.CodeAnalysis.EditAndContinue.AbstractEditAndContinueAnalyzer;
18 19 20 21 22 23 24 25 26 27 28 29 30

namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
    internal abstract class EditAndContinueTestHelpers
    {
        public abstract AbstractEditAndContinueAnalyzer Analyzer { get; }
        public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span);
        public abstract SyntaxTree ParseText(string source);
        public abstract Compilation CreateLibraryCompilation(string name, IEnumerable<SyntaxTree> trees);
        public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method);

        internal void VerifyUnchangedDocument(
            string source,
31
            ActiveStatement[] oldActiveStatements,
32 33 34 35 36 37 38 39 40 41 42
            TextSpan?[] trackingSpansOpt,
            TextSpan[] expectedNewActiveStatements,
            ImmutableArray<TextSpan>[] expectedOldExceptionRegions,
            ImmutableArray<TextSpan>[] expectedNewExceptionRegions)
        {
            var text = SourceText.From(source);
            var tree = ParseText(source);
            var root = tree.GetRoot();

            tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();

C
Cyrus Najmabadi 已提交
43
            var documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
44 45 46 47 48 49 50 51 52 53 54

            TestActiveStatementTrackingService trackingService;
            if (trackingSpansOpt != null)
            {
                trackingService = new TestActiveStatementTrackingService(documentId, trackingSpansOpt);
            }
            else
            {
                trackingService = null;
            }

55
            var actualNewActiveStatements = new ActiveStatement[oldActiveStatements.Length];
56 57
            var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];

58
            Analyzer.GetTestAccessor().AnalyzeUnchangedDocument(
59 60 61 62 63 64 65 66 67
                oldActiveStatements.AsImmutable(),
                text,
                root,
                documentId,
                trackingService,
                actualNewActiveStatements,
                actualNewExceptionRegions);

            // check active statements:
68
            AssertSpansEqual(expectedNewActiveStatements, actualNewActiveStatements.Select(s => s.Span), source, text);
69 70 71

            // check new exception regions:
            Assert.Equal(expectedNewExceptionRegions.Length, actualNewExceptionRegions.Length);
C
Cyrus Najmabadi 已提交
72
            for (var i = 0; i < expectedNewExceptionRegions.Length; i++)
73 74 75 76 77 78 79 80 81 82
            {
                AssertSpansEqual(expectedNewExceptionRegions[i], actualNewExceptionRegions[i], source, text);
            }
        }

        internal void VerifyRudeDiagnostics(
            EditScript<SyntaxNode> editScript,
            ActiveStatementsDescription description,
            RudeEditDiagnosticDescription[] expectedDiagnostics)
        {
83
            var oldActiveStatements = description.OldStatements;
84

T
Tomas Matousek 已提交
85
            if (description.OldTrackingSpans != null)
86
            {
T
Tomas Matousek 已提交
87
                Assert.Equal(oldActiveStatements.Length, description.OldTrackingSpans.Length);
88 89
            }

C
Cyrus Najmabadi 已提交
90 91
            var newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
            var oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
92 93 94 95 96

            var oldText = SourceText.From(oldSource);
            var newText = SourceText.From(newSource);

            var diagnostics = new List<RudeEditDiagnostic>();
97
            var actualNewActiveStatements = new ActiveStatement[oldActiveStatements.Length];
98
            var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
99 100
            var updatedActiveMethodMatches = new List<UpdatedMemberInfo>();
            var editMap = BuildEditMap(editScript);
101

C
Cyrus Najmabadi 已提交
102
            var documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
103 104

            TestActiveStatementTrackingService trackingService;
T
Tomas Matousek 已提交
105
            if (description.OldTrackingSpans != null)
106
            {
T
Tomas Matousek 已提交
107
                trackingService = new TestActiveStatementTrackingService(documentId, description.OldTrackingSpans);
108 109 110 111 112 113
            }
            else
            {
                trackingService = null;
            }

114
            Analyzer.GetTestAccessor().AnalyzeSyntax(
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
                editScript,
                editMap,
                oldText,
                newText,
                documentId,
                trackingService,
                oldActiveStatements.AsImmutable(),
                actualNewActiveStatements,
                actualNewExceptionRegions,
                updatedActiveMethodMatches,
                diagnostics);

            diagnostics.Verify(newSource, expectedDiagnostics);

            // check active statements:
130
            AssertSpansEqual(description.NewSpans, actualNewActiveStatements.Select(s => s.Span), newSource, newText);
131 132 133 134

            if (diagnostics.Count == 0)
            {
                // check old exception regions:
C
Cyrus Najmabadi 已提交
135
                for (var i = 0; i < oldActiveStatements.Length; i++)
136 137 138 139 140
                {
                    var actualOldExceptionRegions = Analyzer.GetExceptionRegions(
                        oldText,
                        editScript.Match.OldRoot,
                        oldActiveStatements[i].Span,
141 142
                        isNonLeaf: oldActiveStatements[i].IsNonLeaf,
                        out _);
143 144 145 146 147 148

                    AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText);
                }

                // check new exception regions:
                Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length);
C
Cyrus Najmabadi 已提交
149
                for (var i = 0; i < description.NewRegions.Length; i++)
150 151 152 153 154 155
                {
                    AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText);
                }
            }
            else
            {
C
Cyrus Najmabadi 已提交
156
                for (var i = 0; i < oldActiveStatements.Length; i++)
157 158 159 160 161
                {
                    Assert.Equal(0, description.NewRegions[i].Length);
                }
            }

T
Tomas Matousek 已提交
162
            if (description.OldTrackingSpans != null)
163
            {
T
Tomas Matousek 已提交
164
                // Verify that the new tracking spans are equal to the new active statements.
165 166 167 168 169 170 171 172 173 174
                AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s));
            }
        }

        internal void VerifyLineEdits(
            EditScript<SyntaxNode> editScript,
            IEnumerable<LineChange> expectedLineEdits,
            IEnumerable<string> expectedNodeUpdates,
            RudeEditDiagnosticDescription[] expectedDiagnostics)
        {
C
Cyrus Najmabadi 已提交
175 176
            var newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
            var oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
177 178 179 180 181

            var oldText = SourceText.From(oldSource);
            var newText = SourceText.From(newSource);

            var diagnostics = new List<RudeEditDiagnostic>();
182
            var editMap = BuildEditMap(editScript);
183

184
            var triviaEdits = new List<(SyntaxNode OldNode, SyntaxNode NewNode)>();
185 186
            var actualLineEdits = new List<LineChange>();

187
            Analyzer.GetTestAccessor().AnalyzeTrivia(
188 189 190 191 192 193 194
                oldText,
                newText,
                editScript.Match,
                editMap,
                triviaEdits,
                actualLineEdits,
                diagnostics,
C
Cyrus Najmabadi 已提交
195
                default);
196 197 198 199 200

            diagnostics.Verify(newSource, expectedDiagnostics);

            AssertEx.Equal(expectedLineEdits, actualLineEdits, itemSeparator: ",\r\n");

201
            var actualNodeUpdates = triviaEdits.Select(e => e.NewNode.ToString().ToLines().First());
202 203 204 205 206
            AssertEx.Equal(expectedNodeUpdates, actualNodeUpdates, itemSeparator: ",\r\n");
        }

        internal void VerifySemantics(
            EditScript<SyntaxNode> editScript,
T
Tomáš Matoušek 已提交
207
            ActiveStatementsDescription activeStatements = null,
208 209 210
            IEnumerable<string> additionalOldSources = null,
            IEnumerable<string> additionalNewSources = null,
            SemanticEditDescription[] expectedSemanticEdits = null,
211
            DiagnosticDescription expectedDeclarationError = null,
212
            RudeEditDiagnosticDescription[] expectedDiagnostics = null)
213
        {
T
Tomáš Matoušek 已提交
214 215
            activeStatements ??= ActiveStatementsDescription.Empty;

216
            var editMap = BuildEditMap(editScript);
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

            var oldRoot = editScript.Match.OldRoot;
            var newRoot = editScript.Match.NewRoot;

            var oldSource = oldRoot.SyntaxTree.ToString();
            var newSource = newRoot.SyntaxTree.ToString();

            var oldText = SourceText.From(oldSource);
            var newText = SourceText.From(newSource);

            IEnumerable<SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree };
            IEnumerable<SyntaxTree> newTrees = new[] { newRoot.SyntaxTree };

            if (additionalOldSources != null)
            {
                oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s)));
            }

            if (additionalOldSources != null)
            {
                newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s)));
            }

            var oldCompilation = CreateLibraryCompilation("Old", oldTrees);
            var newCompilation = CreateLibraryCompilation("New", newTrees);

            var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree);
            var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);

246
            var oldActiveStatements = activeStatements.OldStatements.AsImmutable();
247
            var updatedActiveMethodMatches = new List<UpdatedMemberInfo>();
248
            var triviaEdits = new List<(SyntaxNode OldNode, SyntaxNode NewNode)>();
249 250 251 252
            var actualLineEdits = new List<LineChange>();
            var actualSemanticEdits = new List<SemanticEdit>();
            var diagnostics = new List<RudeEditDiagnostic>();

253 254
            var actualNewActiveStatements = new ActiveStatement[activeStatements.OldStatements.Length];
            var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[activeStatements.OldStatements.Length];
255

256
            Analyzer.GetTestAccessor().AnalyzeSyntax(
257 258 259 260 261 262 263 264 265 266 267 268 269 270
                editScript,
                editMap,
                oldText,
                newText,
                null,
                null,
                oldActiveStatements,
                actualNewActiveStatements,
                actualNewExceptionRegions,
                updatedActiveMethodMatches,
                diagnostics);

            diagnostics.Verify(newSource);

271
            Analyzer.GetTestAccessor().AnalyzeTrivia(
272 273 274 275 276 277 278
                oldText,
                newText,
                editScript.Match,
                editMap,
                triviaEdits,
                actualLineEdits,
                diagnostics,
279
                CancellationToken.None);
280 281 282

            diagnostics.Verify(newSource);

283
            Analyzer.GetTestAccessor().AnalyzeSemantics(
284 285 286 287 288 289 290 291 292 293
                editScript,
                editMap,
                oldText,
                oldActiveStatements,
                triviaEdits,
                updatedActiveMethodMatches,
                oldModel,
                newModel,
                actualSemanticEdits,
                diagnostics,
294
                out var firstDeclarationErrorOpt,
295
                CancellationToken.None);
296

297 298 299 300
            var actualDeclarationErrors = (firstDeclarationErrorOpt != null) ? new[] { firstDeclarationErrorOpt } : Array.Empty<Diagnostic>();
            var expectedDeclarationErrors = (expectedDeclarationError != null) ? new[] { expectedDeclarationError } : Array.Empty<DiagnosticDescription>();
            actualDeclarationErrors.Verify(expectedDeclarationErrors);

301 302 303 304 305 306 307 308 309
            diagnostics.Verify(newSource, expectedDiagnostics);

            if (expectedSemanticEdits == null)
            {
                return;
            }

            Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count);

C
Cyrus Najmabadi 已提交
310
            for (var i = 0; i < actualSemanticEdits.Count; i++)
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
            {
                var editKind = expectedSemanticEdits[i].Kind;

                Assert.Equal(editKind, actualSemanticEdits[i].Kind);

                var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null;
                var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation);
                var actualOldSymbol = actualSemanticEdits[i].OldSymbol;
                var actualNewSymbol = actualSemanticEdits[i].NewSymbol;

                Assert.Equal(expectedOldSymbol, actualOldSymbol);
                Assert.Equal(expectedNewSymbol, actualNewSymbol);

                var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap;
                var actualSyntaxMap = actualSemanticEdits[i].SyntaxMap;

                Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables);

                if (expectedSyntaxMap != null)
                {
                    Assert.NotNull(actualSyntaxMap);
                    Assert.True(expectedSemanticEdits[i].PreserveLocalVariables);

                    var newNodes = new List<SyntaxNode>();

                    foreach (var expectedSpanMapping in expectedSyntaxMap)
                    {
                        var newNode = FindNode(newRoot, expectedSpanMapping.Value);
                        var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key);
                        var actualOldNode = actualSyntaxMap(newNode);

                        Assert.Equal(expectedOldNode, actualOldNode);

                        newNodes.Add(newNode);
                    }
                }
347
                else if (!expectedSemanticEdits[i].PreserveLocalVariables)
348 349 350 351 352 353
                {
                    Assert.Null(actualSyntaxMap);
                }
            }
        }

354
        private static void AssertSpansEqual(IEnumerable<TextSpan> expected, IEnumerable<LinePositionSpan> actual, string newSource, SourceText newText)
355 356 357 358 359 360 361 362 363
        {
            AssertEx.Equal(
                expected,
                actual.Select(span => newText.Lines.GetTextSpan(span)),
                itemSeparator: "\r\n",
                itemInspector: s => DisplaySpan(newSource, s));
        }

        private static string DisplaySpan(string source, TextSpan span)
364
            => span + ": [" + source.Substring(span.Start, span.Length).Replace("\r\n", " ") + "]";
365 366 367

        internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch)
        {
368 369
            Dictionary<SyntaxNode, LambdaInfo> lazyActiveOrMatchedLambdas = null;
            var map = analyzer.GetTestAccessor().ComputeMap(bodyMatch, Array.Empty<ActiveNode>(), ref lazyActiveOrMatchedLambdas, new List<RudeEditDiagnostic>());
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

            var result = new Dictionary<SyntaxNode, SyntaxNode>();
            foreach (var pair in map.Forward)
            {
                if (pair.Value == bodyMatch.NewRoot)
                {
                    Assert.Same(pair.Key, bodyMatch.OldRoot);
                    continue;
                }

                result.Add(pair.Key, pair.Value);
            }

            return result;
        }

        public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match)
387
            => ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot));
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

        public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches)
        {
            return new MatchingPairs(matches
                .OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start)
                .ThenByDescending(partners => partners.Key.Span.Length)
                .Select(partners => new MatchingPair
                {
                    Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "),
                    New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ")
                }));
        }

        private static IEnumerable<KeyValuePair<K, V>> ReverseMapping<K, V>(IEnumerable<KeyValuePair<V, K>> mapping)
        {
            foreach (var pair in mapping)
            {
J
Jared Parsons 已提交
405
                yield return KeyValuePairUtil.Create(pair.Value, pair.Key);
406 407
            }
        }
408
    }
409 410 411 412

    internal static class EditScriptTestUtils
    {
        public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected)
413
            => AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n");
414
    }
415
}