From 03a120ab063075b5f484fe4e26cad235ce26f3f6 Mon Sep 17 00:00:00 2001 From: Glenn Sarti Date: Thu, 2 Aug 2018 14:25:45 +0800 Subject: [PATCH] (GH-1459) Folding provider should not crash with mismatched region tokens Previously the folding provider would crash with an error if the document contained mismatched begin and end region comments e.g. If the document started with `# endregion`. This was due to the token stack code always assuming there was at least one element in the stack. This commit modifies the end region detection to only trigger if there was a previous begin region. --- src/features/Folding.ts | 2 +- test/features/folding.test.ts | 14 ++++++++++++++ test/fixtures/folding-mismatch.ps1 | 7 +++++++ 3 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/folding-mismatch.ps1 diff --git a/src/features/Folding.ts b/src/features/Folding.ts index 00e1001765..c8f7e621a7 100644 --- a/src/features/Folding.ts +++ b/src/features/Folding.ts @@ -283,7 +283,7 @@ export class FoldingProvider implements vscode.FoldingRangeProvider { if (token.scopes.indexOf(startScopeName) !== -1) { tokenStack.push(token); } - if (token.scopes.indexOf(endScopeName) !== -1) { + if ((tokenStack.length > 0) && (token.scopes.indexOf(endScopeName) !== -1)) { result.unshift((new LineNumberRange(matchType)).fromTokenPair(tokenStack.pop(), token, document)); } }); diff --git a/test/features/folding.test.ts b/test/features/folding.test.ts index 404b12e968..e4744a9329 100644 --- a/test/features/folding.test.ts +++ b/test/features/folding.test.ts @@ -82,6 +82,20 @@ suite("Features", () => { assertFoldingRegions(result, expectedFoldingRegions); }); + + test("Can detect all of the foldable regions in a document with mismatched regions", async () => { + const expectedMismatchedFoldingRegions = [ + { start: 2, end: 4, kind: 3 }, + ]; + + // Integration test against the test fixture 'folding-mismatch.ps1' that contains + // comment regions with mismatched beginning and end + const uri = vscode.Uri.file(path.join(fixturePath, "folding-mismatch.ps1")); + const document = await vscode.workspace.openTextDocument(uri); + const result = await provider.provideFoldingRanges(document, null, null); + + assertFoldingRegions(result, expectedMismatchedFoldingRegions); + }); }); }); }); diff --git a/test/fixtures/folding-mismatch.ps1 b/test/fixtures/folding-mismatch.ps1 new file mode 100644 index 0000000000..181001b3f2 --- /dev/null +++ b/test/fixtures/folding-mismatch.ps1 @@ -0,0 +1,7 @@ +#endregion should not fold - mismatched + +#region This should fold +$something = 'foldable' +#endregion + +#region should not fold - mismatched