Fix a crash in the type inference code (#19400)

This commit is contained in:
MartinGC94
2023-03-23 14:40:50 -07:00
committed by GitHub
parent 48c9d68356
commit 25651ef6e9
2 changed files with 25 additions and 7 deletions
@@ -739,19 +739,28 @@ namespace System.Management.Automation
object ICustomAstVisitor.VisitErrorStatement(ErrorStatementAst errorStatementAst)
{
var inferredTypes = new List<PSTypeName>();
foreach (var ast in errorStatementAst.Conditions)
if (errorStatementAst.Conditions is not null)
{
inferredTypes.AddRange(InferTypes(ast));
foreach (var ast in errorStatementAst.Conditions)
{
inferredTypes.AddRange(InferTypes(ast));
}
}
foreach (var ast in errorStatementAst.Bodies)
if (errorStatementAst.Bodies is not null)
{
inferredTypes.AddRange(InferTypes(ast));
foreach (var ast in errorStatementAst.Bodies)
{
inferredTypes.AddRange(InferTypes(ast));
}
}
foreach (var ast in errorStatementAst.NestedAst)
if (errorStatementAst.NestedAst is not null)
{
inferredTypes.AddRange(InferTypes(ast));
foreach (var ast in errorStatementAst.NestedAst)
{
inferredTypes.AddRange(InferTypes(ast));
}
}
return inferredTypes;
@@ -1944,7 +1953,8 @@ namespace System.Management.Automation
{
break;
}
else if (parent is SwitchStatementAst switchStatement)
else if (parent is SwitchStatementAst switchStatement
&& switchStatement.Condition.Extent.EndOffset < variableExpressionAst.Extent.StartOffset)
{
parent = switchStatement.Condition;
break;
@@ -1406,6 +1406,14 @@ Describe "Type inference Tests" -tags "CI" {
$res = [AstTypeInference]::InferTypeOf( { pwsh }.Ast)
$res.Name | Should -Be 'System.String'
}
It 'Should not throw when inferring $_ in switch condition' {
$FoundAst = { switch($_){default{}} }.Ast.Find(
{param($Ast) $Ast -is [Language.VariableExpressionAst]},
$true
)
$null = [AstTypeInference]::InferTypeOf($FoundAst)
}
}
Describe "AstTypeInference tests" -Tags CI {