Skip to content

Commit c77d0ce

Browse files
authored
Make switch statement report correct error position when it fails to evaluate the condition (#7151)
1 parent 53e6ec6 commit c77d0ce

File tree

2 files changed

+52
-4
lines changed

2 files changed

+52
-4
lines changed

src/System.Management.Automation/engine/parser/Compiler.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4189,10 +4189,7 @@ private Expression GenerateIteratorStatement(VariablePath iteratorVariablePath,
41894189
// $foreach/$switch = GetEnumerator $enumerable
41904190
var enumerable = NewTemp(typeof(object), "enumerable");
41914191
temps.Add(enumerable);
4192-
if (generatingForeach)
4193-
{
4194-
exprs.Add(UpdatePosition(stmt.Condition));
4195-
}
4192+
exprs.Add(UpdatePosition(stmt.Condition));
41964193
exprs.Add(
41974194
Expression.Assign(enumerable,
41984195
GetRangeEnumerator(stmt.Condition.GetPureExpression())
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
Describe "Error position Tests" -Tags "CI" {
5+
It "switch condition evaluation failure should report correct error position" {
6+
$testFile = Join-Path $TestDrive "SwitchError1.ps1"
7+
Set-Content -Path $testFile -Encoding Ascii -Value @'
8+
$test = 1
9+
switch ($null[0]) {
10+
"a" {};
11+
}
12+
'@
13+
try { & $testFile } catch { $errorRecord = $_ }
14+
$errorRecord | Should -Not -BeNullOrEmpty
15+
$errorRecord.ScriptStackTrace | Should -Match "SwitchError1.ps1: line 2"
16+
}
17+
18+
It "switch condition MoveNext failure should report correct error position" {
19+
$code = @'
20+
using System;
21+
using System.Collections.Generic;
22+
namespace SwitchTest
23+
{
24+
public class Test
25+
{
26+
public static IEnumerable<string> GetName()
27+
{
28+
yield return "Hello world";
29+
throw new ArgumentException();
30+
}
31+
}
32+
}
33+
'@
34+
$testFile = Join-Path $TestDrive "SwitchError2.ps1"
35+
Set-Content -Path $testFile -Encoding Ascii -Value @'
36+
$test = 1
37+
$enumerable = [SwitchTest.Test]::GetName()
38+
switch ($enumerable) {
39+
"hello world" { $test = 1; $_ }
40+
"Yay" { $test = 2; $_ }
41+
}
42+
'@
43+
if (-not ("SwitchTest.Test" -as [type])) {
44+
Add-Type -TypeDefinition $code
45+
}
46+
47+
try { & $testFile > $null } catch { $errorRecord = $_ }
48+
$errorRecord | Should -Not -BeNullOrEmpty
49+
$errorRecord.ScriptStackTrace | Should -Match "SwitchError2.ps1: line 3"
50+
}
51+
}

0 commit comments

Comments
 (0)